From 1d4866ec350235c05f4150acaf675e862370e0ae Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 18 Feb 2021 22:44:32 +0100 Subject: [PATCH 0001/1068] implement Unmerge citations for Openoffice integration --- .../org/jabref/gui/openoffice/OOBibBase.java | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 076c2ce2360..0f2dd130ce6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1268,23 +1268,24 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException, BibEntryNotFoundException { XNameAccess nameAccess = getReferenceMarks(); + // TODO: doesn't work for citations in footnotes/tables List names = getSortedReferenceMarks(nameAccess); final XTextRangeCompare compare = UnoRuntime.queryInterface(XTextRangeCompare.class, text); - int pivot = 0; + int piv = 0; boolean madeModifications = false; - while (pivot < (names.size())) { - XTextRange range1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(pivot))) + while (piv < (names.size())) { + XTextRange range1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv))) .getAnchor(); - XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); - + XTextCursor mxDocCursor = range1.getText().createTextCursorByRange(range1); + // // If we are supposed to set character format for citations, test this before // making any changes. This way we can throw an exception before any reference // marks are removed, preventing damage to the user's document: if (style.isFormatCitations()) { - XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, textCursor); + XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, mxDocCursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); @@ -1296,26 +1297,26 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) } } - List keys = parseRefMarkName(names.get(pivot)); + List keys = parseRefMarkName(names.get(piv)); if (keys.size() > 1) { - removeReferenceMark(names.get(pivot)); - + removeReferenceMark(names.get(piv)); + // // Insert bookmark for each key int last = keys.size() - 1; int i = 0; for (String key : keys) { - String newName = getUniqueReferenceMarkName(key, OOBibBase.AUTHORYEAR_PAR); - insertReferenceMark(newName, "tmp", textCursor, true, style); - textCursor.collapseToEnd(); + String bName = getUniqueReferenceMarkName(key, OOBibBase.AUTHORYEAR_PAR); + insertReferenceMark(bName, "tmp", mxDocCursor, true, style); + mxDocCursor.collapseToEnd(); if (i != last) { - textCursor.setString(" "); - textCursor.collapseToEnd(); + mxDocCursor.setString(" "); + mxDocCursor.collapseToEnd(); } i++; } madeModifications = true; } - pivot++; + piv++; } if (madeModifications) { updateSortedReferenceMarks(); From 9f248736770f626026ded8bd2f4847da02aa60f3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 19 Feb 2021 22:31:22 +0100 Subject: [PATCH 0002/1068] simplify --- .../org/jabref/gui/openoffice/OOBibBase.java | 216 +++++++++++------- 1 file changed, 138 insertions(+), 78 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0f2dd130ce6..98b9fb37153 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -56,6 +56,7 @@ import com.sun.star.frame.XController; import com.sun.star.frame.XDesktop; import com.sun.star.frame.XModel; +import com.sun.star.frame.XFrame; import com.sun.star.lang.DisposedException; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.Locale; @@ -85,67 +86,90 @@ import org.slf4j.LoggerFactory; /** - * Class for manipulating the Bibliography of the currently start document in OpenOffice. + * Class for manipulating the Bibliography of the currently started + * document in OpenOffice. */ @AllowedToUseAwt("Requires AWT for italics and bold") class OOBibBase { private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); - private static final String BIB_SECTION_NAME = "JR_bib"; + private static final String BIB_SECTION_NAME = "JR_bib"; private static final String BIB_SECTION_END_NAME = "JR_bib_end"; + private static final String BIB_CITATION = "JR_cite"; - private static final Pattern CITE_PATTERN = Pattern.compile(OOBibBase.BIB_CITATION + "\\d*_(\\d*)_(.*)"); + private static final Pattern CITE_PATTERN = + Pattern.compile(BIB_CITATION + "\\d*_(\\d*)_(.*)"); private static final String CHAR_STYLE_NAME = "CharStyleName"; - private static final int AUTHORYEAR_PAR = 1; + private static final int AUTHORYEAR_PAR = 1; private static final int AUTHORYEAR_INTEXT = 2; - private static final int INVISIBLE_CIT = 3; + private static final int INVISIBLE_CIT = 3; + + private static final Logger LOGGER = + LoggerFactory.getLogger(OOBibBase.class); - private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); - private XMultiServiceFactory mxDocFactory; - private XTextDocument mxDoc; - private XText text; - private final XDesktop xDesktop; + private XMultiServiceFactory mxDocFactory; + private XTextDocument mxDoc; + private XText text; + private final XDesktop xDesktop; private XTextViewCursorSupplier xViewCursorSupplier; - private XComponent xCurrentComponent; - private XPropertySet propertySet; + private XComponent xCurrentComponent; + private XPropertySet propertySet; + private XPropertyContainer userProperties; - private XPropertyContainer userProperties; private final boolean atEnd; + private final Comparator entryComparator; private final Comparator yearAuthorTitleComparator; - private final FieldComparator authComp = new FieldComparator(StandardField.AUTHOR); - private final FieldComparator yearComp = new FieldComparator(StandardField.YEAR); - private final FieldComparator titleComp = new FieldComparator(StandardField.TITLE); - private final List> authorYearTitleList = new ArrayList<>(3); + // private final FieldComparator authComp = new FieldComparator(StandardField.AUTHOR); + // private final FieldComparator yearComp = new FieldComparator(StandardField.YEAR); + // private final FieldComparator titleComp = new FieldComparator(StandardField.TITLE); + + // private final List> authorYearTitleList = new ArrayList<>(3); + // private final List> yearAuthorTitleList = new ArrayList<>(3); - private final List> yearAuthorTitleList = new ArrayList<>(3); private final Map uniquefiers = new HashMap<>(); + private List sortedReferenceMarks; private final DialogService dialogService; - public OOBibBase(Path loPath, boolean atEnd, DialogService dialogService) throws IllegalAccessException, InvocationTargetException, BootstrapException, CreationException, IOException, ClassNotFoundException { - + public OOBibBase(Path loPath, + boolean atEnd, + DialogService dialogService + ) throws IllegalAccessException, + InvocationTargetException, + BootstrapException, + CreationException, + IOException, + ClassNotFoundException + { this.dialogService = dialogService; - - authorYearTitleList.add(authComp); - authorYearTitleList.add(yearComp); - authorYearTitleList.add(titleComp); - - yearAuthorTitleList.add(yearComp); - yearAuthorTitleList.add(authComp); - yearAuthorTitleList.add(titleComp); - - entryComparator = new FieldComparatorStack<>(authorYearTitleList); - yearAuthorTitleComparator = new FieldComparatorStack<>(yearAuthorTitleList); - - this.atEnd = atEnd; - - xDesktop = simpleBootstrap(loPath); + { + FieldComparator a = new FieldComparator(StandardField.AUTHOR); + FieldComparator y = new FieldComparator(StandardField.YEAR); + FieldComparator t = new FieldComparator(StandardField.TITLE); + + { + List> ayt = new ArrayList<>(3); + ayt.add(a); + ayt.add(y); + ayt.add(t); + this.entryComparator= new FieldComparatorStack<>(ayt); + } + { + List> yat = new ArrayList<>(3); + yat.add(y); + yat.add(a); + yat.add(t); + this.yearAuthorTitleComparator = new FieldComparatorStack<>(yat); + } + } + this.atEnd = atEnd; + this.xDesktop = simpleBootstrap(loPath); } public boolean isConnectedToDocument() { @@ -153,10 +177,27 @@ public boolean isConnectedToDocument() { } public XTextDocument selectComponent(List list) { - List viewModel = list.stream().map(DocumentTitleViewModel::new).collect(Collectors.toList()); - // this whole method is part of a background task when auto-detecting instances, so we need to show dialog in FX thread - Optional selectedDocument = dialogService.showChoiceDialogAndWait(Localization.lang("Select document"), Localization.lang("Found documents:"), Localization.lang("Use selected document"), viewModel); - return selectedDocument.map(DocumentTitleViewModel::getXtextDocument).orElse(null); + List viewModel = + list + .stream() + .map(DocumentTitleViewModel::new) + .collect(Collectors.toList()); + + // This whole method is part of a background task when + // auto-detecting instances, so we need to show dialog in FX + // thread + Optional selectedDocument = + dialogService + .showChoiceDialogAndWait( + Localization.lang("Select document"), + Localization.lang("Found documents:"), + Localization.lang("Use selected document"), + viewModel + ); + return + selectedDocument + .map(DocumentTitleViewModel::getXtextDocument) + .orElse(null); } public Optional getCurrentDocumentTitle() { @@ -166,41 +207,55 @@ public Optional getCurrentDocumentTitle() { private Optional getDocumentTitle(XTextDocument doc) { if (doc == null) { return Optional.empty(); - } else { - try { - return Optional.of(String.valueOf(OOUtil.getProperty(doc.getCurrentController().getFrame(), "Title"))); - } catch (UnknownPropertyException | WrappedTargetException e) { - LOGGER.warn("Could not get document title", e); - return Optional.empty(); - } } - } - public void selectDocument() throws NoDocumentException, NoSuchElementException, WrappedTargetException { - List textDocumentList = getTextDocuments(); - XTextDocument selected; - if (textDocumentList.isEmpty()) { - // No text documents found. - throw new NoDocumentException("No Writer documents found"); - } else if (textDocumentList.size() == 1) { - // Get the only one - selected = textDocumentList.get(0); - } else { - // Bring up a dialog - selected = selectComponent(textDocumentList); - } - - if (selected == null) { - return; - } - xCurrentComponent = UnoRuntime.queryInterface(XComponent.class, selected); - mxDoc = selected; - - UnoRuntime.queryInterface(XDocumentIndexesSupplier.class, xCurrentComponent); + try { + XFrame frame = doc.getCurrentController().getFrame(); + Object frame_title_obj = OOUtil.getProperty( frame , "Title"); + String frame_title_str = String.valueOf(frame_title_obj); + return Optional.of(frame_title_str); + } catch (UnknownPropertyException | WrappedTargetException e) { + LOGGER.warn("Could not get document title", e); + return Optional.empty(); + } + } - XModel xModel = UnoRuntime.queryInterface(XModel.class, xCurrentComponent); - XController xController = xModel.getCurrentController(); - xViewCursorSupplier = UnoRuntime.queryInterface(XTextViewCursorSupplier.class, xController); + public void selectDocument() + throws NoDocumentException, + NoSuchElementException, + WrappedTargetException + { + { + XTextDocument selected; + List textDocumentList = getTextDocuments(); + if (textDocumentList.isEmpty()) { + // No text documents found. + throw new NoDocumentException("No Writer documents found"); + } else if (textDocumentList.size() == 1) { + // Get the only one + selected = textDocumentList.get(0); + } else { + // Bring up a dialog + selected = selectComponent(textDocumentList); + } + + if (selected == null) { + return; + } + xCurrentComponent = UnoRuntime.queryInterface(XComponent.class, selected); + mxDoc = selected; + } + + + // TODO: what is the point of the next line? Does it have a side effect? + // + // UnoRuntime.queryInterface(XDocumentIndexesSupplier.class, xCurrentComponent); + + { + XModel xModel = UnoRuntime.queryInterface(XModel.class, xCurrentComponent); + XController xController = xModel.getCurrentController(); + xViewCursorSupplier = UnoRuntime.queryInterface(XTextViewCursorSupplier.class, xController); + } // get a reference to the body text of the document text = mxDoc.getText(); @@ -208,8 +263,11 @@ public void selectDocument() throws NoDocumentException, NoSuchElementException, // Access the text document's multi service factory: mxDocFactory = UnoRuntime.queryInterface(XMultiServiceFactory.class, mxDoc); - XDocumentPropertiesSupplier supp = UnoRuntime.queryInterface(XDocumentPropertiesSupplier.class, mxDoc); - userProperties = supp.getDocumentProperties().getUserDefinedProperties(); + { + XDocumentPropertiesSupplier supp = + UnoRuntime.queryInterface(XDocumentPropertiesSupplier.class, mxDoc); + userProperties = supp.getDocumentProperties().getUserDefinedProperties(); + } propertySet = UnoRuntime.queryInterface(XPropertySet.class, userProperties); } @@ -232,8 +290,9 @@ private List getTextDocuments() throws NoSuchElementException, Wr } private XDesktop simpleBootstrap(Path loPath) - throws CreationException, BootstrapException { - + throws CreationException, + BootstrapException + { // Get the office component context: XComponentContext xContext = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); // Get the office service manager: @@ -248,7 +307,8 @@ private XDesktop simpleBootstrap(Path loPath) } XDesktop resultDesktop = UnoRuntime.queryInterface(XDesktop.class, desktop); - UnoRuntime.queryInterface(XComponentLoader.class, desktop); + // TODO: useless call? + // UnoRuntime.queryInterface(XComponentLoader.class, desktop); return resultDesktop; } @@ -769,9 +829,9 @@ public XNameAccess getReferenceMarks() { private String getUniqueReferenceMarkName(String bibtexKey, int type) { XNameAccess xNamedRefMarks = getReferenceMarks(); int i = 0; - String name = OOBibBase.BIB_CITATION + '_' + type + '_' + bibtexKey; + String name = BIB_CITATION + '_' + type + '_' + bibtexKey; while (xNamedRefMarks.hasByName(name)) { - name = OOBibBase.BIB_CITATION + i + '_' + type + '_' + bibtexKey; + name = BIB_CITATION + i + '_' + type + '_' + bibtexKey; i++; } return name; From 820aa5c19317d0e4fd8490ce79a1049b34f6cfb9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 19 Feb 2021 23:02:11 +0100 Subject: [PATCH 0003/1068] text renamed xtext --- .../org/jabref/gui/openoffice/OOBibBase.java | 136 +++++++++--------- 1 file changed, 71 insertions(+), 65 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 98b9fb37153..1e1402ea8d2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -112,7 +112,7 @@ class OOBibBase { private XMultiServiceFactory mxDocFactory; private XTextDocument mxDoc; - private XText text; + private XText xtext; private final XDesktop xDesktop; private XTextViewCursorSupplier xViewCursorSupplier; private XComponent xCurrentComponent; @@ -137,6 +137,12 @@ class OOBibBase { private final DialogService dialogService; + private static T unoQI(Class zInterface, + Object object) + { + return UnoRuntime.queryInterface( zInterface, object ); + } + public OOBibBase(Path loPath, boolean atEnd, DialogService dialogService @@ -187,7 +193,7 @@ public XTextDocument selectComponent(List list) { // auto-detecting instances, so we need to show dialog in FX // thread Optional selectedDocument = - dialogService + this.dialogService .showChoiceDialogAndWait( Localization.lang("Select document"), Localization.lang("Found documents:"), @@ -201,7 +207,7 @@ public XTextDocument selectComponent(List list) { } public Optional getCurrentDocumentTitle() { - return getDocumentTitle(mxDoc); + return getDocumentTitle( this.mxDoc ); } private Optional getDocumentTitle(XTextDocument doc) { @@ -210,7 +216,7 @@ private Optional getDocumentTitle(XTextDocument doc) { } try { - XFrame frame = doc.getCurrentController().getFrame(); + XFrame frame = doc.getCurrentController().getFrame(); Object frame_title_obj = OOUtil.getProperty( frame , "Title"); String frame_title_str = String.valueOf(frame_title_obj); return Optional.of(frame_title_str); @@ -242,33 +248,33 @@ public void selectDocument() if (selected == null) { return; } - xCurrentComponent = UnoRuntime.queryInterface(XComponent.class, selected); - mxDoc = selected; + this.xCurrentComponent = unoQI(XComponent.class, selected); + this.mxDoc = selected; } // TODO: what is the point of the next line? Does it have a side effect? // - // UnoRuntime.queryInterface(XDocumentIndexesSupplier.class, xCurrentComponent); + // unoQI(XDocumentIndexesSupplier.class, xCurrentComponent); { - XModel xModel = UnoRuntime.queryInterface(XModel.class, xCurrentComponent); - XController xController = xModel.getCurrentController(); - xViewCursorSupplier = UnoRuntime.queryInterface(XTextViewCursorSupplier.class, xController); + XModel mo = unoQI(XModel.class, this.xCurrentComponent); + XController co = mo.getCurrentController(); + xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); } // get a reference to the body text of the document - text = mxDoc.getText(); + this.xtext = this.mxDoc.getText(); // Access the text document's multi service factory: - mxDocFactory = UnoRuntime.queryInterface(XMultiServiceFactory.class, mxDoc); + this.mxDocFactory = unoQI(XMultiServiceFactory.class, this.mxDoc); { XDocumentPropertiesSupplier supp = - UnoRuntime.queryInterface(XDocumentPropertiesSupplier.class, mxDoc); + unoQI(XDocumentPropertiesSupplier.class, this.mxDoc); userProperties = supp.getDocumentProperties().getUserDefinedProperties(); } - propertySet = UnoRuntime.queryInterface(XPropertySet.class, userProperties); + propertySet = unoQI(XPropertySet.class, userProperties); } private List getTextDocuments() throws NoSuchElementException, WrappedTargetException { @@ -280,8 +286,8 @@ private List getTextDocuments() throws NoSuchElementException, Wr while (componentEnumeration.hasMoreElements()) { Object nextElement = componentEnumeration.nextElement(); - XComponent component = UnoRuntime.queryInterface(XComponent.class, nextElement); - XTextDocument document = UnoRuntime.queryInterface(XTextDocument.class, component); + XComponent component = unoQI(XComponent.class, nextElement); + XTextDocument document = unoQI(XTextDocument.class, component); if (document != null) { result.add(document); } @@ -305,10 +311,10 @@ private XDesktop simpleBootstrap(Path loPath) } catch (Exception e) { throw new CreationException(e.getMessage()); } - XDesktop resultDesktop = UnoRuntime.queryInterface(XDesktop.class, desktop); + XDesktop resultDesktop = unoQI(XDesktop.class, desktop); // TODO: useless call? - // UnoRuntime.queryInterface(XComponentLoader.class, desktop); + // unoQI(XComponentLoader.class, desktop); return resultDesktop; } @@ -391,7 +397,7 @@ public void insertEntry(List entries, BibDatabase database, xViewCursor.getText().insertString(xViewCursor, " ", false); if (style.isFormatCitations()) { - XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, xViewCursor); + XPropertySet xCursorProps = unoQI(XPropertySet.class, xViewCursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); @@ -741,7 +747,7 @@ private List refreshCiteMarkersInternal(List databases, OOB boolean mustTestCharFormat = style.isFormatCitations(); for (int i = 0; i < names.size(); i++) { Object referenceMark = xReferenceMarks.getByName(names.get(i)); - XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark); + XTextContent bookmark = unoQI(XTextContent.class, referenceMark); XTextCursor cursor = bookmark.getAnchor().getText().createTextCursorByRange(bookmark.getAnchor()); @@ -751,7 +757,7 @@ private List refreshCiteMarkersInternal(List databases, OOB // exist, we end up deleting the markers before the process crashes due to a the missing // format, with catastrophic consequences for the user. mustTestCharFormat = false; // need to do this only once - XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); + XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); @@ -761,14 +767,14 @@ private List refreshCiteMarkersInternal(List databases, OOB } } - text.removeTextContent(bookmark); + this.xtext.removeTextContent(bookmark); insertReferenceMark(names.get(i), citMarkers[i], cursor, types[i] != OOBibBase.INVISIBLE_CIT, style); if (hadBibSection && (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { // We have overwritten the marker for the start of the reference list. // We need to add it again. cursor.collapseToEnd(); - OOUtil.insertParagraphBreak(text, cursor); + OOUtil.insertParagraphBreak(this.xtext, cursor); insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); } } @@ -787,20 +793,20 @@ private List refreshCiteMarkersInternal(List databases, OOB private List getSortedReferenceMarks(final XNameAccess nameAccess) throws WrappedTargetException, NoSuchElementException { - XTextViewCursorSupplier cursorSupplier = UnoRuntime.queryInterface(XTextViewCursorSupplier.class, - mxDoc.getCurrentController()); + XTextViewCursorSupplier cursorSupplier = unoQI(XTextViewCursorSupplier.class, + this.mxDoc.getCurrentController()); XTextViewCursor viewCursor = cursorSupplier.getViewCursor(); XTextRange initialPos = viewCursor.getStart(); List names = Arrays.asList(nameAccess.getElementNames()); List positions = new ArrayList<>(names.size()); for (String name : names) { - XTextContent textContent = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(name)); + XTextContent textContent = unoQI(XTextContent.class, nameAccess.getByName(name)); XTextRange range = textContent.getAnchor(); // Check if we are inside a footnote: - if (UnoRuntime.queryInterface(XFootnote.class, range.getText()) != null) { + if (unoQI(XFootnote.class, range.getText()) != null) { // Find the linking footnote marker: - XFootnote footer = UnoRuntime.queryInterface(XFootnote.class, range.getText()); + XFootnote footer = unoQI(XFootnote.class, range.getText()); // The footnote's anchor gives the correct position in the text: range = footer.getAnchor(); } @@ -822,7 +828,7 @@ private List getSortedReferenceMarks(final XNameAccess nameAccess) } public XNameAccess getReferenceMarks() { - XReferenceMarksSupplier supplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, xCurrentComponent); + XReferenceMarksSupplier supplier = unoQI(XReferenceMarksSupplier.class, xCurrentComponent); return supplier.getReferenceMarks(); } @@ -867,7 +873,7 @@ private List findCitedKeys() throws NoSuchElementException, WrappedTarge List keys = new ArrayList<>(); for (String name1 : names) { Object bookmark = xNamedMarks.getByName(name1); - UnoRuntime.queryInterface(XTextContent.class, bookmark); + unoQI(XTextContent.class, bookmark); List newKeys = parseRefMarkName(name1); for (String key : newKeys) { @@ -983,7 +989,7 @@ public String getCitationContext(XNameAccess nameAccess, String refMarkName, int boolean htmlMarkup) throws NoSuchElementException, WrappedTargetException { Object referenceMark = nameAccess.getByName(refMarkName); - XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark); + XTextContent bookmark = unoQI(XTextContent.class, referenceMark); XTextCursor cursor = bookmark.getAnchor().getText().createTextCursorByRange(bookmark.getAnchor()); String citPart = cursor.getString(); @@ -1042,15 +1048,15 @@ private void insertFullReferenceAtCursor(XTextCursor cursor, Map entries, OOBibStyle style) throws NoSuchElementException, WrappedTargetException, PropertyVetoException, UnknownPropertyException, UndefinedParagraphFormatException, IllegalArgumentException, CreationException { - XTextSectionsSupplier supplier = UnoRuntime.queryInterface(XTextSectionsSupplier.class, mxDoc); + XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, this.mxDoc); XTextSection section = (XTextSection) ((Any) supplier.getTextSections().getByName(OOBibBase.BIB_SECTION_NAME)) .getObject(); - XTextCursor cursor = text.createTextCursorByRange(section.getAnchor()); - OOUtil.insertTextAtCurrentLocation(text, cursor, (String) style.getProperty(OOBibStyle.TITLE), + XTextCursor cursor = this.xtext.createTextCursorByRange(section.getAnchor()); + OOUtil.insertTextAtCurrentLocation(this.xtext, cursor, (String) style.getProperty(OOBibStyle.TITLE), (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT)); insertFullReferenceAtCursor(cursor, entries, style, (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT)); @@ -1113,18 +1119,18 @@ private XTextContent insertBookMark(String name, XTextCursor position) throws IllegalArgumentException, CreationException { Object bookmark; try { - bookmark = mxDocFactory.createInstance("com.sun.star.text.Bookmark"); + bookmark = this.mxDocFactory.createInstance("com.sun.star.text.Bookmark"); } catch (Exception e) { throw new CreationException(e.getMessage()); } // name the bookmark - XNamed xNamed = UnoRuntime.queryInterface(XNamed.class, bookmark); + XNamed xNamed = unoQI(XNamed.class, bookmark); xNamed.setName(name); // get XTextContent interface - XTextContent xTextContent = UnoRuntime.queryInterface(XTextContent.class, bookmark); + XTextContent xTextContent = unoQI(XTextContent.class, bookmark); // insert bookmark at the end of the document // instead of mxDocText.getEnd you could use a text cursor's XTextRange interface or any XTextRange - text.insertTextContent(position, xTextContent, true); + this.xtext.insertTextContent(position, xTextContent, true); position.collapseToEnd(); return xTextContent; } @@ -1146,17 +1152,17 @@ private void insertReferenceMark(String name, String citationText, XTextCursor p Object bookmark; try { - bookmark = mxDocFactory.createInstance("com.sun.star.text.ReferenceMark"); + bookmark = this.mxDocFactory.createInstance("com.sun.star.text.ReferenceMark"); } catch (Exception e) { throw new CreationException(e.getMessage()); } // Name the reference - XNamed xNamed = UnoRuntime.queryInterface(XNamed.class, bookmark); + XNamed xNamed = unoQI(XNamed.class, bookmark); xNamed.setName(name); if (withText) { position.setString(citText); - XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, position); + XPropertySet xCursorProps = unoQI(XPropertySet.class, position); // Set language to [None]: xCursorProps.setPropertyValue("CharLocale", new Locale("zxx", "", "")); @@ -1174,7 +1180,7 @@ private void insertReferenceMark(String name, String citationText, XTextCursor p } // get XTextContent interface - XTextContent xTextContent = UnoRuntime.queryInterface(XTextContent.class, bookmark); + XTextContent xTextContent = unoQI(XTextContent.class, bookmark); position.getText().insertTextContent(position, xTextContent, true); @@ -1195,8 +1201,8 @@ private void removeReferenceMark(String name) throws NoSuchElementException, Wra XNameAccess xReferenceMarks = getReferenceMarks(); if (xReferenceMarks.hasByName(name)) { Object referenceMark = xReferenceMarks.getByName(name); - XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark); - text.removeTextContent(bookmark); + XTextContent bookmark = unoQI(XTextContent.class, referenceMark); + this.xtext.removeTextContent(bookmark); } } @@ -1216,13 +1222,13 @@ private XTextRange getBookmarkRange(String name) throws NoSuchElementException, return null; } Object foundBookmark = xNamedBookmarks.getByName(name); - XTextContent xFoundBookmark = UnoRuntime.queryInterface(XTextContent.class, foundBookmark); + XTextContent xFoundBookmark = unoQI(XTextContent.class, foundBookmark); return xFoundBookmark.getAnchor(); } private XNameAccess getBookmarks() { // query XBookmarksSupplier from document model and get bookmarks collection - XBookmarksSupplier xBookmarksSupplier = UnoRuntime.queryInterface(XBookmarksSupplier.class, xCurrentComponent); + XBookmarksSupplier xBookmarksSupplier = unoQI(XBookmarksSupplier.class, xCurrentComponent); XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks(); return xNamedBookmarks; } @@ -1233,7 +1239,7 @@ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, XTextCursor cursor = position.getText().createTextCursorByRange(range); cursor.goRight((short) start, false); cursor.goRight((short) (end - start), true); - XPropertySet xcp = UnoRuntime.queryInterface(XPropertySet.class, cursor); + XPropertySet xcp = unoQI(XPropertySet.class, cursor); if (italicize) { xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); } else { @@ -1249,14 +1255,14 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // TODO: doesn't work for citations in footnotes/tables List names = getSortedReferenceMarks(nameAccess); - final XTextRangeCompare compare = UnoRuntime.queryInterface(XTextRangeCompare.class, text); + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, this.xtext); int piv = 0; boolean madeModifications = false; while (piv < (names.size() - 1)) { - XTextRange range1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv))) + XTextRange range1 = unoQI(XTextContent.class, nameAccess.getByName(names.get(piv))) .getAnchor().getEnd(); - XTextRange range2 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv + 1))) + XTextRange range2 = unoQI(XTextContent.class, nameAccess.getByName(names.get(piv + 1))) .getAnchor().getStart(); if (range1.getText() != range2.getText()) { piv++; @@ -1276,7 +1282,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // making any changes. This way we can throw an exception before any reference // marks are removed, preventing damage to the user's document: if (style.isFormatCitations()) { - XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, mxDocCursor); + XPropertySet xCursorProps = unoQI(XPropertySet.class, mxDocCursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); @@ -1331,12 +1337,12 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) // TODO: doesn't work for citations in footnotes/tables List names = getSortedReferenceMarks(nameAccess); - final XTextRangeCompare compare = UnoRuntime.queryInterface(XTextRangeCompare.class, text); + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, this.xtext); int piv = 0; boolean madeModifications = false; while (piv < (names.size())) { - XTextRange range1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv))) + XTextRange range1 = unoQI(XTextContent.class, nameAccess.getByName(names.get(piv))) .getAnchor(); XTextCursor mxDocCursor = range1.getText().createTextCursorByRange(range1); @@ -1345,7 +1351,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) // making any changes. This way we can throw an exception before any reference // marks are removed, preventing damage to the user's document: if (style.isFormatCitations()) { - XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, mxDocCursor); + XPropertySet xCursorProps = unoQI(XPropertySet.class, mxDocCursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); From f67683891df78565a1e83bbf1514771b744971a7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 00:04:20 +0100 Subject: [PATCH 0004/1068] XPropertySetInfo --- .../org/jabref/gui/openoffice/OOBibBase.java | 125 ++++++++++++------ 1 file changed, 82 insertions(+), 43 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1e1402ea8d2..6a83c8e1ca2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -45,6 +45,7 @@ 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.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XEnumeration; @@ -235,7 +236,6 @@ public void selectDocument() XTextDocument selected; List textDocumentList = getTextDocuments(); if (textDocumentList.isEmpty()) { - // No text documents found. throw new NoDocumentException("No Writer documents found"); } else if (textDocumentList.size() == 1) { // Get the only one @@ -260,7 +260,7 @@ public void selectDocument() { XModel mo = unoQI(XModel.class, this.xCurrentComponent); XController co = mo.getCurrentController(); - xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); + this.xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); } // get a reference to the body text of the document @@ -272,24 +272,28 @@ public void selectDocument() { XDocumentPropertiesSupplier supp = unoQI(XDocumentPropertiesSupplier.class, this.mxDoc); - userProperties = supp.getDocumentProperties().getUserDefinedProperties(); + this.userProperties = supp.getDocumentProperties().getUserDefinedProperties(); } - propertySet = unoQI(XPropertySet.class, userProperties); + this.propertySet = unoQI(XPropertySet.class, this.userProperties); } - private List getTextDocuments() throws NoSuchElementException, WrappedTargetException { + private List getTextDocuments() + throws NoSuchElementException, + WrappedTargetException + { List result = new ArrayList<>(); - XEnumerationAccess enumAccess = xDesktop.getComponents(); - XEnumeration componentEnumeration = enumAccess.createEnumeration(); + + XEnumerationAccess enumAccess = xDesktop.getComponents(); + XEnumeration compEnum = enumAccess.createEnumeration(); // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies - while (componentEnumeration.hasMoreElements()) { - Object nextElement = componentEnumeration.nextElement(); - XComponent component = unoQI(XComponent.class, nextElement); - XTextDocument document = unoQI(XTextDocument.class, component); - if (document != null) { - result.add(document); + while (compEnum.hasMoreElements()) { + Object next = compEnum.nextElement(); + XComponent comp = unoQI(XComponent.class , next); + XTextDocument doc = unoQI(XTextDocument.class, comp); + if (doc != null) { + result.add(doc); } } return result; @@ -300,55 +304,75 @@ private XDesktop simpleBootstrap(Path loPath) BootstrapException { // Get the office component context: - XComponentContext xContext = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); - // Get the office service manager: - XMultiComponentFactory xServiceManager = xContext.getServiceManager(); + XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); + XMultiComponentFactory sem = context.getServiceManager(); + // Create the desktop, which is the root frame of the // hierarchy of frames that contain viewable components: Object desktop; try { - desktop = xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext); + desktop = sem.createInstanceWithContext("com.sun.star.frame.Desktop", context); } catch (Exception e) { throw new CreationException(e.getMessage()); } - XDesktop resultDesktop = unoQI(XDesktop.class, desktop); + XDesktop result = unoQI(XDesktop.class, desktop); // TODO: useless call? // unoQI(XComponentLoader.class, desktop); - return resultDesktop; + return result; } - public Optional getCustomProperty(String property) throws UnknownPropertyException, WrappedTargetException { - if (propertySet.getPropertySetInfo().hasPropertyByName(property)) { - return Optional.ofNullable(propertySet.getPropertyValue(property).toString()); + public Optional getCustomProperty(String property) + throws UnknownPropertyException, + WrappedTargetException + { + XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + if (psi.hasPropertyByName(property)) { + String v = this.propertySet.getPropertyValue(property).toString(); + return Optional.ofNullable(v); } return Optional.empty(); } - public void updateSortedReferenceMarks() throws WrappedTargetException, NoSuchElementException { - sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks()); + public void updateSortedReferenceMarks() + throws WrappedTargetException, + NoSuchElementException + { + this.sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks()); } - public void setCustomProperty(String property, String value) throws UnknownPropertyException, - NotRemoveableException, PropertyExistException, IllegalTypeException, IllegalArgumentException { - if (propertySet.getPropertySetInfo().hasPropertyByName(property)) { - userProperties.removeProperty(property); + public void setCustomProperty(String property, String value) + throws UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException + { + XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + if (psi.hasPropertyByName(property)) { + this.userProperties.removeProperty(property); } if (value != null) { - userProperties.addProperty(property, com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value)); + this.userProperties.addProperty(property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value) + ); } } /** - * This method inserts a cite marker in the text for the given BibEntry, and may refresh the bibliography. + * This method inserts a cite marker in the text (at the cursor) for the given + * BibEntry, and may refresh the bibliography. * * @param entries The entries to cite. * @param database The database the entry belongs to. * @param style The bibliography style we are using. - * @param inParenthesis Indicates whether it is an in-text citation or a citation in parenthesis. This is not relevant if numbered citations are used. - * @param withText Indicates whether this should be a normal citation (true) or an empty (invisible) citation (false). + * @param inParenthesis Indicates whether it is an in-text citation + * or a citation in parenthesis. + * This is not relevant if numbered citations are used. + * @param withText Indicates whether this should be a normal citation (true) + * or an empty (invisible) citation (false). * @param sync Indicates whether the reference list should be refreshed. * @throws IllegalTypeException * @throws PropertyExistException @@ -363,17 +387,32 @@ public void setCustomProperty(String property, String value) throws UnknownPrope * @throws BibEntryNotFoundException * @throws UndefinedParagraphFormatException */ - public void insertEntry(List entries, BibDatabase database, - List allBases, OOBibStyle style, - boolean inParenthesis, boolean withText, String pageInfo, boolean sync) - throws IllegalArgumentException, - UnknownPropertyException, NotRemoveableException, PropertyExistException, IllegalTypeException, - UndefinedCharacterFormatException, WrappedTargetException, NoSuchElementException, PropertyVetoException, - IOException, CreationException, BibEntryNotFoundException, UndefinedParagraphFormatException { - + public void insertEntry(List entries, + BibDatabase database, + List allBases, + OOBibStyle style, + boolean inParenthesis, + boolean withText, + String pageInfo, + boolean sync + ) + throws IllegalArgumentException, + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + UndefinedCharacterFormatException, + WrappedTargetException, + NoSuchElementException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException, + UndefinedParagraphFormatException + { try { - - XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor(); + // Get the cursor positioned by the user. + XTextViewCursor xViewCursor = this.xViewCursorSupplier.getViewCursor(); if (entries.size() > 1) { if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { From d201f52dfda28edeba16875434d8b1721c0091bb Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 00:09:00 +0100 Subject: [PATCH 0005/1068] sortBibEntryList --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6a83c8e1ca2..bde6c8d2131 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -361,6 +361,15 @@ public void setCustomProperty(String property, String value) } } + private void sortBibEntryList( List entries, OOBibStyle style ){ + if (entries.size() > 1) { + if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { + entries.sort(this.yearAuthorTitleComparator); + } else { + entries.sort(this.entryComparator); + } + } + } /** * This method inserts a cite marker in the text (at the cursor) for the given * BibEntry, and may refresh the bibliography. @@ -414,6 +423,8 @@ public void insertEntry(List entries, // Get the cursor positioned by the user. XTextViewCursor xViewCursor = this.xViewCursorSupplier.getViewCursor(); + sortBibEntryList( entries, style ); + /* if (entries.size() > 1) { if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { entries.sort(yearAuthorTitleComparator); @@ -421,6 +432,7 @@ public void insertEntry(List entries, entries.sort(entryComparator); } } + */ String keyString = String.join(",", entries.stream().map(entry -> entry.getCitationKey().orElse("")).collect(Collectors.toList())); From a63ecff80df5e726d24154bcf79c61f0cad2c1e4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 09:58:11 +0100 Subject: [PATCH 0006/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 81 +++++++++++++------ 1 file changed, 58 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index bde6c8d2131..cb5006b75a7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -185,8 +185,7 @@ public boolean isConnectedToDocument() { public XTextDocument selectComponent(List list) { List viewModel = - list - .stream() + list.stream() .map(DocumentTitleViewModel::new) .collect(Collectors.toList()); @@ -424,21 +423,34 @@ public void insertEntry(List entries, XTextViewCursor xViewCursor = this.xViewCursorSupplier.getViewCursor(); sortBibEntryList( entries, style ); - /* - if (entries.size() > 1) { - if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { - entries.sort(yearAuthorTitleComparator); - } else { - entries.sort(entryComparator); - } - } - */ + // if (entries.size() > 1) { + // if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { + // entries.sort(yearAuthorTitleComparator); + // } else { + // entries.sort(entryComparator); + // } + // } + String keyString = String.join(",", - entries.stream().map(entry -> entry.getCitationKey().orElse("")).collect(Collectors.toList())); + entries + .stream() + .map(entry -> + entry + .getCitationKey() + .orElse("") + ) + .collect(Collectors.toList()) + ); // Insert bookmark: - String bName = getUniqueReferenceMarkName(keyString, - withText ? inParenthesis ? OOBibBase.AUTHORYEAR_PAR : OOBibBase.AUTHORYEAR_INTEXT : OOBibBase.INVISIBLE_CIT); + String bName = getUniqueReferenceMarkName( + keyString, + withText + ? ( inParenthesis + ? OOBibBase.AUTHORYEAR_PAR + : OOBibBase.AUTHORYEAR_INTEXT ) + : OOBibBase.INVISIBLE_CIT + ); // If we should store metadata for page info, do that now: if (pageInfo != null) { @@ -800,7 +812,11 @@ private List refreshCiteMarkersInternal(List databases, OOB Object referenceMark = xReferenceMarks.getByName(names.get(i)); XTextContent bookmark = unoQI(XTextContent.class, referenceMark); - XTextCursor cursor = bookmark.getAnchor().getText().createTextCursorByRange(bookmark.getAnchor()); + XTextCursor cursor = + bookmark + .getAnchor() + .getText() + .createTextCursorByRange(bookmark.getAnchor()); if (mustTestCharFormat) { // If we are supposed to set character format for citations, must run a test before we @@ -852,7 +868,8 @@ private List getSortedReferenceMarks(final XNameAccess nameAccess) List names = Arrays.asList(nameAccess.getElementNames()); List positions = new ArrayList<>(names.size()); for (String name : names) { - XTextContent textContent = unoQI(XTextContent.class, nameAccess.getByName(name)); + XTextContent textContent = + unoQI(XTextContent.class, nameAccess.getByName(name)); XTextRange range = textContent.getAnchor(); // Check if we are inside a footnote: if (unoQI(XFootnote.class, range.getText()) != null) { @@ -879,10 +896,18 @@ private List getSortedReferenceMarks(final XNameAccess nameAccess) } public XNameAccess getReferenceMarks() { - XReferenceMarksSupplier supplier = unoQI(XReferenceMarksSupplier.class, xCurrentComponent); + XReferenceMarksSupplier supplier = + unoQI(XReferenceMarksSupplier.class, xCurrentComponent); return supplier.getReferenceMarks(); } + /* + * The first occurrence of bibtexKey gets no serial number, the + * second gets 0, the third 1 ... + * + * Or the first unused in this series, after removals. + * + */ private String getUniqueReferenceMarkName(String bibtexKey, int type) { XNameAccess xNamedRefMarks = getReferenceMarks(); int i = 0; @@ -894,12 +919,22 @@ private String getUniqueReferenceMarkName(String bibtexKey, int type) { return name; } - public void rebuildBibTextSection(List databases, OOBibStyle style) - throws NoSuchElementException, WrappedTargetException, IllegalArgumentException, - CreationException, PropertyVetoException, UnknownPropertyException, UndefinedParagraphFormatException { - List cited = findCitedKeys(); - Map linkSourceBase = new HashMap<>(); - Map entries = findCitedEntries(databases, cited, linkSourceBase); // Although entries are redefined without use, this also updates linkSourceBase + public void rebuildBibTextSection(List databases, + OOBibStyle style) + throws NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException + { + List cited = findCitedKeys(); + Map linkSourceBase = new HashMap<>(); + Map entries = + // Although entries are redefined without use, this also + // updates linkSourceBase + findCitedEntries(databases, cited, linkSourceBase); List names = sortedReferenceMarks; From 4be69920f1d3401552d45bc53af96d344e7b7486 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 10:00:26 +0100 Subject: [PATCH 0007/1068] entries2 --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index cb5006b75a7..56b7afbfd77 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -942,11 +942,15 @@ public void rebuildBibTextSection(List databases, // We need to sort the entries according to their order of appearance: entries = getSortedEntriesFromSortedRefMarks(names, linkSourceBase); } else { + // Find them again? Why? + Map entries2 = + findCitedEntries(databases, cited, linkSourceBase); + SortedMap newMap = new TreeMap<>(entryComparator); - for (Map.Entry bibtexEntryBibtexDatabaseEntry : findCitedEntries(databases, cited, - linkSourceBase).entrySet()) { - newMap.put(bibtexEntryBibtexDatabaseEntry.getKey(), bibtexEntryBibtexDatabaseEntry.getValue()); - } + for (Map.Entry kv : entries2.entrySet()) { + newMap.put(kv.getKey(), + kv.getValue()); + } entries = newMap; } clearBibTextSectionContent2(); From dc81ef327b2eeccfac6d4408fb7d5cba1daa95c9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 10:09:27 +0100 Subject: [PATCH 0008/1068] scope --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 56b7afbfd77..64d5b52168b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -936,10 +936,9 @@ public void rebuildBibTextSection(List databases, // updates linkSourceBase findCitedEntries(databases, cited, linkSourceBase); - List names = sortedReferenceMarks; - if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: + List names = sortedReferenceMarks; entries = getSortedEntriesFromSortedRefMarks(names, linkSourceBase); } else { // Find them again? Why? From caf6a2c5a5d349e3e49fd03b716533a1c62f2daf Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 10:14:32 +0100 Subject: [PATCH 0009/1068] this --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 64d5b52168b..a17e36c9be9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -180,7 +180,7 @@ public OOBibBase(Path loPath, } public boolean isConnectedToDocument() { - return xCurrentComponent != null; + return this.xCurrentComponent != null; } public XTextDocument selectComponent(List list) { From 332965a16c660f9e879fa1db8445a487f612497a Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 10:14:48 +0100 Subject: [PATCH 0010/1068] static getDocumentTitle --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a17e36c9be9..549a00be532 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -210,7 +210,7 @@ public Optional getCurrentDocumentTitle() { return getDocumentTitle( this.mxDoc ); } - private Optional getDocumentTitle(XTextDocument doc) { + private static Optional getDocumentTitle(XTextDocument doc) { if (doc == null) { return Optional.empty(); } From 5ca2a8b7d05f44b594f0e6de5755ea2a68466e94 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 10:20:30 +0100 Subject: [PATCH 0011/1068] getTextDocuments is static --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 549a00be532..784b2b6c32e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -233,7 +233,7 @@ public void selectDocument() { { XTextDocument selected; - List textDocumentList = getTextDocuments(); + List textDocumentList = getTextDocuments(this.xDesktop); if (textDocumentList.isEmpty()) { throw new NoDocumentException("No Writer documents found"); } else if (textDocumentList.size() == 1) { @@ -276,13 +276,13 @@ public void selectDocument() this.propertySet = unoQI(XPropertySet.class, this.userProperties); } - private List getTextDocuments() + private static List getTextDocuments( XDesktop desktop ) throws NoSuchElementException, WrappedTargetException { List result = new ArrayList<>(); - XEnumerationAccess enumAccess = xDesktop.getComponents(); + XEnumerationAccess enumAccess = desktop.getComponents(); XEnumeration compEnum = enumAccess.createEnumeration(); // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies From 732f6f7b1c1689ab699d91a8a6d72111b2133a6d Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 10:38:44 +0100 Subject: [PATCH 0012/1068] reorder fields --- .../org/jabref/gui/openoffice/OOBibBase.java | 23 ++++++++----------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 784b2b6c32e..8f9b9cdbcea 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -111,33 +111,28 @@ class OOBibBase { private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); + /* variables */ + private final DialogService dialogService; + private final XDesktop xDesktop; + private final boolean atEnd; + private final Comparator entryComparator; + private final Comparator yearAuthorTitleComparator; + + /* document-related */ private XMultiServiceFactory mxDocFactory; private XTextDocument mxDoc; private XText xtext; - private final XDesktop xDesktop; private XTextViewCursorSupplier xViewCursorSupplier; private XComponent xCurrentComponent; private XPropertySet propertySet; private XPropertyContainer userProperties; - private final boolean atEnd; - - private final Comparator entryComparator; - private final Comparator yearAuthorTitleComparator; - - // private final FieldComparator authComp = new FieldComparator(StandardField.AUTHOR); - // private final FieldComparator yearComp = new FieldComparator(StandardField.YEAR); - // private final FieldComparator titleComp = new FieldComparator(StandardField.TITLE); - - // private final List> authorYearTitleList = new ArrayList<>(3); - // private final List> yearAuthorTitleList = new ArrayList<>(3); private final Map uniquefiers = new HashMap<>(); private List sortedReferenceMarks; - private final DialogService dialogService; - + // unoQI : short for UnoRuntime.queryInterface private static T unoQI(Class zInterface, Object object) { From 71ca96ab4096fadfc38c278e5c7b4d227f0e83e3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 11:13:23 +0100 Subject: [PATCH 0013/1068] DocumentTitleViewModel moved into selectComponent --- .../org/jabref/gui/openoffice/OOBibBase.java | 50 ++++++++++--------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8f9b9cdbcea..707a806cc20 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -178,17 +178,38 @@ public boolean isConnectedToDocument() { return this.xCurrentComponent != null; } - public XTextDocument selectComponent(List list) { + private XTextDocument selectComponent(List list, + DialogService dialogService) + { + class DocumentTitleViewModel { + + private final XTextDocument xTextDocument; + private final String description; + + public DocumentTitleViewModel(XTextDocument xTextDocument) { + this.xTextDocument = xTextDocument; + this.description = getDocumentTitle(xTextDocument).orElse(""); + } + + public XTextDocument getXtextDocument() { + return xTextDocument; + } + + @Override + public String toString() { + return description; + } + } List viewModel = list.stream() - .map(DocumentTitleViewModel::new) + .map( DocumentTitleViewModel::new ) .collect(Collectors.toList()); // This whole method is part of a background task when // auto-detecting instances, so we need to show dialog in FX // thread Optional selectedDocument = - this.dialogService + dialogService .showChoiceDialogAndWait( Localization.lang("Select document"), Localization.lang("Found documents:"), @@ -197,7 +218,7 @@ public XTextDocument selectComponent(List list) { ); return selectedDocument - .map(DocumentTitleViewModel::getXtextDocument) + .map( DocumentTitleViewModel::getXtextDocument ) .orElse(null); } @@ -236,7 +257,7 @@ public void selectDocument() selected = textDocumentList.get(0); } else { // Bring up a dialog - selected = selectComponent(textDocumentList); + selected = selectComponent(textDocumentList, this.dialogService); } if (selected == null) { @@ -1551,23 +1572,4 @@ public int hashCode() { } } - private class DocumentTitleViewModel { - - private final XTextDocument xTextDocument; - private final String description; - - public DocumentTitleViewModel(XTextDocument xTextDocument) { - this.xTextDocument = xTextDocument; - this.description = getDocumentTitle(xTextDocument).orElse(""); - } - - public XTextDocument getXtextDocument() { - return xTextDocument; - } - - @Override - public String toString() { - return description; - } - } } From 85a6b0b4c00714c49526424031bc77372bb9ad3c Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 11:17:40 +0100 Subject: [PATCH 0014/1068] explicit OOBibBase.getDocumentTitle --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 707a806cc20..e8b54627e5f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -184,11 +184,11 @@ private XTextDocument selectComponent(List list, class DocumentTitleViewModel { private final XTextDocument xTextDocument; - private final String description; + private final String description; public DocumentTitleViewModel(XTextDocument xTextDocument) { this.xTextDocument = xTextDocument; - this.description = getDocumentTitle(xTextDocument).orElse(""); + this.description = OOBibBase.getDocumentTitle(xTextDocument).orElse(""); } public XTextDocument getXtextDocument() { From f6f38b813789a5429eb885f4b3bff481995b4470 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 11:19:29 +0100 Subject: [PATCH 0015/1068] selectComponent is static --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e8b54627e5f..9f99b1aeaeb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -178,8 +178,8 @@ public boolean isConnectedToDocument() { return this.xCurrentComponent != null; } - private XTextDocument selectComponent(List list, - DialogService dialogService) + private static XTextDocument selectComponent(List list, + DialogService dialogService) { class DocumentTitleViewModel { From 5d6d301df8e6d9b900966684f960c46e0022655c Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 11:20:53 +0100 Subject: [PATCH 0016/1068] selectComponent renamed to selectDocumentDialog --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9f99b1aeaeb..2264eef92a4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -178,8 +178,8 @@ public boolean isConnectedToDocument() { return this.xCurrentComponent != null; } - private static XTextDocument selectComponent(List list, - DialogService dialogService) + private static XTextDocument selectDocumentDialog(List list, + DialogService dialogService) { class DocumentTitleViewModel { @@ -257,7 +257,7 @@ public void selectDocument() selected = textDocumentList.get(0); } else { // Bring up a dialog - selected = selectComponent(textDocumentList, this.dialogService); + selected = selectDocumentDialog(textDocumentList, this.dialogService); } if (selected == null) { From 22f8babcbcdca4bdc232df9b9dc576c42b590bce Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 11:29:26 +0100 Subject: [PATCH 0017/1068] getDocumentTitle before its use --- .../org/jabref/gui/openoffice/OOBibBase.java | 44 ++++++++++++------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2264eef92a4..1df8f17a228 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -178,6 +178,22 @@ public boolean isConnectedToDocument() { return this.xCurrentComponent != null; } + private static Optional getDocumentTitle(XTextDocument doc) { + if (doc == null) { + return Optional.empty(); + } + + try { + XFrame frame = doc.getCurrentController().getFrame(); + Object frame_title_obj = OOUtil.getProperty( frame , "Title"); + String frame_title_str = String.valueOf(frame_title_obj); + return Optional.of(frame_title_str); + } catch (UnknownPropertyException | WrappedTargetException e) { + LOGGER.warn("Could not get document title", e); + return Optional.empty(); + } + } + private static XTextDocument selectDocumentDialog(List list, DialogService dialogService) { @@ -226,22 +242,18 @@ public Optional getCurrentDocumentTitle() { return getDocumentTitle( this.mxDoc ); } - private static Optional getDocumentTitle(XTextDocument doc) { - if (doc == null) { - return Optional.empty(); - } - - try { - XFrame frame = doc.getCurrentController().getFrame(); - Object frame_title_obj = OOUtil.getProperty( frame , "Title"); - String frame_title_str = String.valueOf(frame_title_obj); - return Optional.of(frame_title_str); - } catch (UnknownPropertyException | WrappedTargetException e) { - LOGGER.warn("Could not get document title", e); - return Optional.empty(); - } - } - + /** Choose a document to work with. + * + * inititalized fields: + * - this.xCurrentComponent + * - this.mxDoc + * - this.xViewCursorSupplier + * - this.xtext + * - this.mxDocFactory + * - this.userProperties + * - this.propertySet + * + */ public void selectDocument() throws NoDocumentException, NoSuchElementException, From d9f740d9c405222fef6ce0168e336ef9a83f7685 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 11:34:13 +0100 Subject: [PATCH 0018/1068] OOBibBase prefix for static method --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1df8f17a228..361a32869e0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -269,7 +269,9 @@ public void selectDocument() selected = textDocumentList.get(0); } else { // Bring up a dialog - selected = selectDocumentDialog(textDocumentList, this.dialogService); + selected = + OOBibBase.selectDocumentDialog(textDocumentList, + this.dialogService); } if (selected == null) { From 4ffbcc764ffe1ad298873ccb6dfd5f3e0f9448e8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 11:34:31 +0100 Subject: [PATCH 0019/1068] move getCurrentDocumentTitle --- .../org/jabref/gui/openoffice/OOBibBase.java | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 361a32869e0..843159293c8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -238,10 +238,27 @@ public String toString() { .orElse(null); } - public Optional getCurrentDocumentTitle() { - return getDocumentTitle( this.mxDoc ); - } + private static List getTextDocuments( XDesktop desktop ) + throws NoSuchElementException, + WrappedTargetException + { + List result = new ArrayList<>(); + + XEnumerationAccess enumAccess = desktop.getComponents(); + XEnumeration compEnum = enumAccess.createEnumeration(); + + // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies + while (compEnum.hasMoreElements()) { + Object next = compEnum.nextElement(); + XComponent comp = unoQI(XComponent.class , next); + XTextDocument doc = unoQI(XTextDocument.class, comp); + if (doc != null) { + result.add(doc); + } + } + return result; + } /** Choose a document to work with. * * inititalized fields: @@ -306,28 +323,11 @@ public void selectDocument() this.propertySet = unoQI(XPropertySet.class, this.userProperties); } - private static List getTextDocuments( XDesktop desktop ) - throws NoSuchElementException, - WrappedTargetException - { - List result = new ArrayList<>(); - - XEnumerationAccess enumAccess = desktop.getComponents(); - XEnumeration compEnum = enumAccess.createEnumeration(); - - // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies - - while (compEnum.hasMoreElements()) { - Object next = compEnum.nextElement(); - XComponent comp = unoQI(XComponent.class , next); - XTextDocument doc = unoQI(XTextDocument.class, comp); - if (doc != null) { - result.add(doc); - } - } - return result; + public Optional getCurrentDocumentTitle() { + return OOBibBase.getDocumentTitle( this.mxDoc ); } + private XDesktop simpleBootstrap(Path loPath) throws CreationException, BootstrapException From 67a6c795aa40d4591bb97f589cf881333f2df052 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 14:35:38 +0100 Subject: [PATCH 0020/1068] try to use XTextCursor --- .../org/jabref/gui/openoffice/OOBibBase.java | 281 +++++++++++------- 1 file changed, 172 insertions(+), 109 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 843159293c8..1804ffc14f6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -104,6 +104,9 @@ class OOBibBase { private static final String CHAR_STYLE_NAME = "CharStyleName"; + /* Types of in-text citation. + * Their numeric values are used in reference mark names. + */ private static final int AUTHORYEAR_PAR = 1; private static final int AUTHORYEAR_INTEXT = 2; private static final int INVISIBLE_CIT = 3; @@ -139,6 +142,34 @@ private static T unoQI(Class zInterface, return UnoRuntime.queryInterface( zInterface, object ); } + /* + * Constructor + */ + + private XDesktop simpleBootstrap(Path loPath) + throws CreationException, + BootstrapException + { + // Get the office component context: + XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); + XMultiComponentFactory sem = context.getServiceManager(); + + // Create the desktop, which is the root frame of the + // hierarchy of frames that contain viewable components: + Object desktop; + try { + desktop = sem.createInstanceWithContext("com.sun.star.frame.Desktop", context); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + XDesktop result = unoQI(XDesktop.class, desktop); + + // TODO: useless call? + // unoQI(XComponentLoader.class, desktop); + + return result; + } + public OOBibBase(Path loPath, boolean atEnd, DialogService dialogService @@ -178,6 +209,32 @@ public boolean isConnectedToDocument() { return this.xCurrentComponent != null; } + /* + * section: selectDocument() + */ + + private static List getTextDocuments( XDesktop desktop ) + throws NoSuchElementException, + WrappedTargetException + { + List result = new ArrayList<>(); + + XEnumerationAccess enumAccess = desktop.getComponents(); + XEnumeration compEnum = enumAccess.createEnumeration(); + + // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies + + while (compEnum.hasMoreElements()) { + Object next = compEnum.nextElement(); + XComponent comp = unoQI(XComponent.class , next); + XTextDocument doc = unoQI(XTextDocument.class, comp); + if (doc != null) { + result.add(doc); + } + } + return result; + } + private static Optional getDocumentTitle(XTextDocument doc) { if (doc == null) { return Optional.empty(); @@ -238,27 +295,6 @@ public String toString() { .orElse(null); } - private static List getTextDocuments( XDesktop desktop ) - throws NoSuchElementException, - WrappedTargetException - { - List result = new ArrayList<>(); - - XEnumerationAccess enumAccess = desktop.getComponents(); - XEnumeration compEnum = enumAccess.createEnumeration(); - - // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies - - while (compEnum.hasMoreElements()) { - Object next = compEnum.nextElement(); - XComponent comp = unoQI(XComponent.class , next); - XTextDocument doc = unoQI(XTextDocument.class, comp); - if (doc != null) { - result.add(doc); - } - } - return result; - } /** Choose a document to work with. * * inititalized fields: @@ -323,52 +359,38 @@ public void selectDocument() this.propertySet = unoQI(XPropertySet.class, this.userProperties); } + /* + * Getters useful after selectDocument() + */ + public Optional getCurrentDocumentTitle() { return OOBibBase.getDocumentTitle( this.mxDoc ); } - private XDesktop simpleBootstrap(Path loPath) - throws CreationException, - BootstrapException - { - // Get the office component context: - XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); - XMultiComponentFactory sem = context.getServiceManager(); - - // Create the desktop, which is the root frame of the - // hierarchy of frames that contain viewable components: - Object desktop; - try { - desktop = sem.createInstanceWithContext("com.sun.star.frame.Desktop", context); - } catch (Exception e) { - throw new CreationException(e.getMessage()); - } - XDesktop result = unoQI(XDesktop.class, desktop); - - // TODO: useless call? - // unoQI(XComponentLoader.class, desktop); - - return result; - } - public Optional getCustomProperty(String property) throws UnknownPropertyException, WrappedTargetException { - XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + assert (this.propertySet != null); + XPropertySetInfo psi = + this.propertySet + .getPropertySetInfo(); if (psi.hasPropertyByName(property)) { - String v = this.propertySet.getPropertyValue(property).toString(); + String v = + this.propertySet + .getPropertyValue(property) + .toString(); return Optional.ofNullable(v); } return Optional.empty(); } - public void updateSortedReferenceMarks() - throws WrappedTargetException, - NoSuchElementException - { - this.sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks()); + public XNameAccess getReferenceMarks() { + XReferenceMarksSupplier supplier = + unoQI(XReferenceMarksSupplier.class, + this.xCurrentComponent); + return supplier.getReferenceMarks(); } public void setCustomProperty(String property, String value) @@ -378,27 +400,41 @@ public void setCustomProperty(String property, String value) IllegalTypeException, IllegalArgumentException { - XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + XPropertySetInfo psi = + this.propertySet + .getPropertySetInfo(); if (psi.hasPropertyByName(property)) { this.userProperties.removeProperty(property); } if (value != null) { - this.userProperties.addProperty(property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value) - ); + this.userProperties + .addProperty(property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value) + ); } } - private void sortBibEntryList( List entries, OOBibStyle style ){ - if (entries.size() > 1) { - if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { - entries.sort(this.yearAuthorTitleComparator); - } else { - entries.sort(this.entryComparator); - } + private void sortBibEntryList( List entries, + OOBibStyle style ) + { + if (entries.size() <= 1){ + return; + } + if (style.getBooleanCitProperty( OOBibStyle.MULTI_CITE_CHRONOLOGICAL )) { + entries.sort(this.yearAuthorTitleComparator); + } else { + entries.sort(this.entryComparator); } } + + private static int citationTypeFromOptions( boolean withText, boolean inParenthesis ){ + if ( !withText ){ return OOBibBase.INVISIBLE_CIT ; } + return ( inParenthesis + ? OOBibBase.AUTHORYEAR_PAR + : OOBibBase.AUTHORYEAR_INTEXT ); + } + /** * This method inserts a cite marker in the text (at the cursor) for the given * BibEntry, and may refresh the bibliography. @@ -412,6 +448,7 @@ private void sortBibEntryList( List entries, OOBibStyle styl * @param withText Indicates whether this should be a normal citation (true) * or an empty (invisible) citation (false). * @param sync Indicates whether the reference list should be refreshed. + * * @throws IllegalTypeException * @throws PropertyExistException * @throws NotRemoveableException @@ -449,8 +486,27 @@ public void insertEntry(List entries, UndefinedParagraphFormatException { try { - // Get the cursor positioned by the user. - XTextViewCursor xViewCursor = this.xViewCursorSupplier.getViewCursor(); + XTextCursor cursor; + { + // Get the cursor positioned by the user. + XTextViewCursor xViewCursor = + this.xViewCursorSupplier + .getViewCursor(); + // + // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Example:_Visible_Cursor_Position + // + // We create a model cursor at the current view cursor + // position with the following steps: we get the Text + // service from the TextViewCursor, the cursor is an + // XTextRange and has therefore a method getText() + // + XText xDocumentText = xViewCursor.getText(); + // the text creates a model cursor from the viewcursor + XTextCursor xModelCursor = + xDocumentText.createTextCursorByRange(xViewCursor.getStart()); + // use the xModelCursor + cursor = xModelCursor; + } sortBibEntryList( entries, style ); // if (entries.size() > 1) { @@ -462,25 +518,15 @@ public void insertEntry(List entries, // } - String keyString = String.join(",", - entries - .stream() - .map(entry -> - entry - .getCitationKey() - .orElse("") - ) - .collect(Collectors.toList()) - ); + String keyString = + String.join(",", + entries.stream() + .map( entry -> entry.getCitationKey().orElse("") ) + .collect( Collectors.toList() ) + ); // Insert bookmark: - String bName = getUniqueReferenceMarkName( - keyString, - withText - ? ( inParenthesis - ? OOBibBase.AUTHORYEAR_PAR - : OOBibBase.AUTHORYEAR_INTEXT ) - : OOBibBase.INVISIBLE_CIT - ); + int citationType = citationTypeFromOptions( withText, inParenthesis ); + String bName = getUniqueReferenceMarkName( keyString, citationType ); // If we should store metadata for page info, do that now: if (pageInfo != null) { @@ -488,35 +534,51 @@ public void insertEntry(List entries, setCustomProperty(bName, pageInfo); } - xViewCursor.getText().insertString(xViewCursor, " ", false); - if (style.isFormatCitations()) { - XPropertySet xCursorProps = unoQI(XPropertySet.class, xViewCursor); - String charStyle = style.getCitationCharacterFormat(); + // insert space + cursor + .getText() + .insertString(cursor, " ", false); + + if ( style.isFormatCitations() ) { + XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); + String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | - WrappedTargetException ex) { - // Setting the character format failed, so we throw an exception that - // will result in an error message for the user. Before that, - // delete the space we inserted: - xViewCursor.goLeft((short) 1, true); - xViewCursor.setString(""); - throw new UndefinedCharacterFormatException(charStyle); - } + } catch ( UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex + ) + { + // Setting the character format failed, so we throw an exception that + // will result in an error message for the user. Before that, + // delete the space we inserted: + cursor.goLeft((short) 1, true); + cursor.setString(""); + throw new UndefinedCharacterFormatException(charStyle); + } } - xViewCursor.goLeft((short) 1, false); + cursor.goLeft((short) 1, false); Map databaseMap = new HashMap<>(); for (BibEntry entry : entries) { databaseMap.put(entry, database); } - String citeText = style.isNumberEntries() ? "-" : style.getCitationMarker(entries, databaseMap, - inParenthesis, null, null); - insertReferenceMark(bName, citeText, xViewCursor, withText, style); + String citeText = + style.isNumberEntries() + ? "-" + : style.getCitationMarker(entries, + databaseMap, + inParenthesis, + null, + null + ); + + insertReferenceMark(bName, citeText, cursor, withText, style); - xViewCursor.collapseToEnd(); - xViewCursor.goRight((short) 1, false); + cursor.collapseToEnd(); + cursor.goRight((short) 1, false); - XTextRange position = xViewCursor.getEnd(); + XTextRange position = cursor.getEnd(); if (sync) { // To account for numbering and for uniqiefiers, we must refresh the cite markers: @@ -528,7 +590,7 @@ public void insertEntry(List entries, } // Go back to the relevant position: - xViewCursor.gotoRange(position, false); + cursor.gotoRange(position, false); } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference @@ -925,10 +987,11 @@ private List getSortedReferenceMarks(final XNameAccess nameAccess) return result; } - public XNameAccess getReferenceMarks() { - XReferenceMarksSupplier supplier = - unoQI(XReferenceMarksSupplier.class, xCurrentComponent); - return supplier.getReferenceMarks(); + public void updateSortedReferenceMarks() + throws WrappedTargetException, + NoSuchElementException + { + this.sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks()); } /* From d4f10f2ef187295d050d42fc9dc28e6f517d6dcf Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 14:39:29 +0100 Subject: [PATCH 0021/1068] drop expanded sortBibEntryList --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1804ffc14f6..d4c2f277ed7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -509,14 +509,6 @@ public void insertEntry(List entries, } sortBibEntryList( entries, style ); - // if (entries.size() > 1) { - // if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { - // entries.sort(yearAuthorTitleComparator); - // } else { - // entries.sort(entryComparator); - // } - // } - String keyString = String.join(",", From 3f179ce7000028ce80a8b8bbb6e1657a8a6cb081 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 15:03:39 +0100 Subject: [PATCH 0022/1068] format insertEntry --- .../org/jabref/gui/openoffice/OOBibBase.java | 95 +++++++++++-------- 1 file changed, 58 insertions(+), 37 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d4c2f277ed7..847882bc870 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -492,20 +492,27 @@ public void insertEntry(List entries, XTextViewCursor xViewCursor = this.xViewCursorSupplier .getViewCursor(); - // - // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Example:_Visible_Cursor_Position - // - // We create a model cursor at the current view cursor - // position with the following steps: we get the Text - // service from the TextViewCursor, the cursor is an - // XTextRange and has therefore a method getText() - // - XText xDocumentText = xViewCursor.getText(); - // the text creates a model cursor from the viewcursor - XTextCursor xModelCursor = - xDocumentText.createTextCursorByRange(xViewCursor.getStart()); - // use the xModelCursor - cursor = xModelCursor; + if ( true ){ + cursor = xViewCursor; + } else { + // + // An XTextCursor is sufficient for the rest. + // + // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/\ + // Example:_Visible_Cursor_Position + // + // We create a model cursor at the current view cursor + // position with the following steps: we get the Text + // service from the TextViewCursor, the cursor is an + // XTextRange and has therefore a method getText() + // + XText xDocumentText = xViewCursor.getText(); + // the text creates a model cursor from the viewcursor + XTextCursor xModelCursor = + xDocumentText.createTextCursorByRange(xViewCursor.getStart()); + // use the xModelCursor + cursor = xModelCursor; + } } sortBibEntryList( entries, style ); @@ -516,7 +523,7 @@ public void insertEntry(List entries, .map( entry -> entry.getCitationKey().orElse("") ) .collect( Collectors.toList() ) ); - // Insert bookmark: + // Generate unique bookmark-name int citationType = citationTypeFromOptions( withText, inParenthesis ); String bName = getUniqueReferenceMarkName( keyString, citationType ); @@ -531,6 +538,7 @@ public void insertEntry(List entries, .getText() .insertString(cursor, " ", false); + // format the space inserted if ( style.isFormatCitations() ) { XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); String charStyle = style.getCitationCharacterFormat(); @@ -542,47 +550,60 @@ public void insertEntry(List entries, | WrappedTargetException ex ) { - // Setting the character format failed, so we throw an exception that - // will result in an error message for the user. Before that, - // delete the space we inserted: + // Setting the character format failed, so we + // throw an exception that will result in an + // error message for the user. + // + // Before that, delete the space we inserted: cursor.goLeft((short) 1, true); cursor.setString(""); throw new UndefinedCharacterFormatException(charStyle); } } + + // go back to before the space cursor.goLeft((short) 1, false); - Map databaseMap = new HashMap<>(); - for (BibEntry entry : entries) { - databaseMap.put(entry, database); - } - String citeText = - style.isNumberEntries() - ? "-" - : style.getCitationMarker(entries, - databaseMap, - inParenthesis, - null, - null - ); - - insertReferenceMark(bName, citeText, cursor, withText, style); + // Insert bookmark and text + { + // Create a BibEntry to BibDatabase map (to make + // style.getCitationMarker happy?) + Map databaseMap = new HashMap<>(); + for (BibEntry entry : entries) { + databaseMap.put(entry, database); + } + String citeText = + style.isNumberEntries() + ? "-" + : style.getCitationMarker(entries, + databaseMap, + inParenthesis, + null, + null + ); + insertReferenceMark(bName, citeText, cursor, withText, style); + } + // + // Move to the right of the space and remember this + // position: we will come back here in the end. + // cursor.collapseToEnd(); cursor.goRight((short) 1, false); - XTextRange position = cursor.getEnd(); if (sync) { - // To account for numbering and for uniqiefiers, we must refresh the cite markers: + // To account for numbering and for uniqiefiers, we + // must refresh the cite markers: updateSortedReferenceMarks(); refreshCiteMarkers(allBases, style); // Insert it at the current position: rebuildBibTextSection(allBases, style); + + // Go back to the relevant position: + cursor.gotoRange(position, false); } - // Go back to the relevant position: - cursor.gotoRange(position, false); } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference From 3d534598534541b04030d942d2dd1391538aee8d Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 15:33:58 +0100 Subject: [PATCH 0023/1068] comments --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 847882bc870..a6ef721f268 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -461,6 +461,10 @@ private static int citationTypeFromOptions( boolean withText, boolean inParenthe * @throws CreationException * @throws BibEntryNotFoundException * @throws UndefinedParagraphFormatException + * + * TODO: https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html + * Group changes into a single Undo context. + * */ public void insertEntry(List entries, BibDatabase database, @@ -572,9 +576,10 @@ public void insertEntry(List entries, for (BibEntry entry : entries) { databaseMap.put(entry, database); } + // the text we insert? String citeText = style.isNumberEntries() - ? "-" + ? "-" // A dash only. Presumably : style.getCitationMarker(entries, databaseMap, inParenthesis, From 7b7cde7992f71b0f523f4c1cf4ed69a9d0b42ae5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 15:56:56 +0100 Subject: [PATCH 0024/1068] catch NoSuchElementException in clearBibTextSectionContent2 --- .../org/jabref/gui/openoffice/OOBibBase.java | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a6ef721f268..135341030ef 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1289,13 +1289,26 @@ private void clearBibTextSectionContent2() // Check if the section exists: XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, this.mxDoc); - if (supplier.getTextSections().hasByName(OOBibBase.BIB_SECTION_NAME)) { - XTextSection section = (XTextSection) ((Any) supplier.getTextSections().getByName(OOBibBase.BIB_SECTION_NAME)) - .getObject(); - // Clear it: - XTextCursor cursor = this.xtext.createTextCursorByRange(section.getAnchor()); - cursor.gotoRange(section.getAnchor(), false); - cursor.setString(""); + com.sun.star.container.XNameAccess ts = supplier.getTextSections(); + if (ts.hasByName(OOBibBase.BIB_SECTION_NAME)) { + try { + Any a = ((Any) ts.getByName(OOBibBase.BIB_SECTION_NAME)); + XTextSection section = (XTextSection) a.getObject(); + // Clear it: + XTextCursor cursor = this.xtext.createTextCursorByRange(section.getAnchor()); + cursor.gotoRange(section.getAnchor(), false); + cursor.setString(""); + } catch ( NoSuchElementException ex ) { + // NoSuchElementException: is thrown by child access + // methods of collections, if the addressed child does + // not exist. + // + // We got this exception from ts.getByName() despite the ts.hasByName() check + // just above. + // Try to create. + LOGGER.warn( "Could not get section '"+ OOBibBase.BIB_SECTION_NAME + "'", ex ); + createBibTextSection2(atEnd); + } } else { createBibTextSection2(atEnd); } From bdddbfeb6a9fdbd807d4e733689fb55433852330 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 16:09:50 +0100 Subject: [PATCH 0025/1068] OOBibBase.insertEntry: catch exception due to citing in "References" --- .../org/jabref/gui/openoffice/OOBibBase.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 135341030ef..74a9e83e820 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -605,8 +605,21 @@ public void insertEntry(List entries, // Insert it at the current position: rebuildBibTextSection(allBases, style); + /* + * TODO: inserting a reference in the "References" section + * provokes an "Unknown Source" exception here, because + * position was deleted by rebuildBibTextSection() + * + * at com.sun.proxy.$Proxy44.gotoRange(Unknown Source) + * at org.jabref@100.0.0/org.jabref.gui.openoffice.OOBibBase.insertEntry(OOBibBase.java:609) + * + */ // Go back to the relevant position: - cursor.gotoRange(position, false); + try { + cursor.gotoRange(position, false); + } catch ( com.sun.star.uno.RuntimeException ex ){ + LOGGER.warn("OOBibBase.insertEntry: Could not go back to end of in-text citation", ex); + } } } catch (DisposedException ex) { @@ -1298,6 +1311,7 @@ private void clearBibTextSectionContent2() XTextCursor cursor = this.xtext.createTextCursorByRange(section.getAnchor()); cursor.gotoRange(section.getAnchor(), false); cursor.setString(""); + return; } catch ( NoSuchElementException ex ) { // NoSuchElementException: is thrown by child access // methods of collections, if the addressed child does From 248e2801156d4cbe521d340f177031fdb0c4395c Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 16:13:37 +0100 Subject: [PATCH 0026/1068] break long line --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 74a9e83e820..25317c3d14a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -611,14 +611,16 @@ public void insertEntry(List entries, * position was deleted by rebuildBibTextSection() * * at com.sun.proxy.$Proxy44.gotoRange(Unknown Source) - * at org.jabref@100.0.0/org.jabref.gui.openoffice.OOBibBase.insertEntry(OOBibBase.java:609) + * at org.jabref@100.0.0/org.jabref.gui.openoffice + * .OOBibBase.insertEntry(OOBibBase.java:609) * */ // Go back to the relevant position: try { cursor.gotoRange(position, false); } catch ( com.sun.star.uno.RuntimeException ex ){ - LOGGER.warn("OOBibBase.insertEntry: Could not go back to end of in-text citation", ex); + LOGGER.warn("OOBibBase.insertEntry:" + +" Could not go back to end of in-text citation", ex); } } From 5fe1736b120463954b6d25d9e1cc01e153eb87d2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 18:27:05 +0100 Subject: [PATCH 0027/1068] getReferenceMarks moved --- .../org/jabref/gui/openoffice/OOBibBase.java | 60 +++++++++++-------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 25317c3d14a..d5c24e9bca3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -386,13 +386,6 @@ public Optional getCustomProperty(String property) return Optional.empty(); } - public XNameAccess getReferenceMarks() { - XReferenceMarksSupplier supplier = - unoQI(XReferenceMarksSupplier.class, - this.xCurrentComponent); - return supplier.getReferenceMarks(); - } - public void setCustomProperty(String property, String value) throws UnknownPropertyException, NotRemoveableException, @@ -415,6 +408,10 @@ public void setCustomProperty(String property, String value) } } + /* + * === insertEntry + */ + private void sortBibEntryList( List entries, OOBibStyle style ) { @@ -429,12 +426,42 @@ private void sortBibEntryList( List entries, } private static int citationTypeFromOptions( boolean withText, boolean inParenthesis ){ - if ( !withText ){ return OOBibBase.INVISIBLE_CIT ; } + if ( !withText ){ + return OOBibBase.INVISIBLE_CIT ; + } return ( inParenthesis ? OOBibBase.AUTHORYEAR_PAR : OOBibBase.AUTHORYEAR_INTEXT ); } + /* + * + */ + public XNameAccess getReferenceMarks() { + XReferenceMarksSupplier supplier = + unoQI(XReferenceMarksSupplier.class, + this.xCurrentComponent); + return supplier.getReferenceMarks(); + } + + /* + * The first occurrence of bibtexKey gets no serial number, the + * second gets 0, the third 1 ... + * + * Or the first unused in this series, after removals. + * + */ + private String getUniqueReferenceMarkName(String bibtexKey, int type) { + XNameAccess xNamedRefMarks = getReferenceMarks(); + int i = 0; + String name = BIB_CITATION + '_' + type + '_' + bibtexKey; + while (xNamedRefMarks.hasByName(name)) { + name = BIB_CITATION + i + '_' + type + '_' + bibtexKey; + i++; + } + return name; + } + /** * This method inserts a cite marker in the text (at the cursor) for the given * BibEntry, and may refresh the bibliography. @@ -1027,23 +1054,6 @@ public void updateSortedReferenceMarks() this.sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks()); } - /* - * The first occurrence of bibtexKey gets no serial number, the - * second gets 0, the third 1 ... - * - * Or the first unused in this series, after removals. - * - */ - private String getUniqueReferenceMarkName(String bibtexKey, int type) { - XNameAccess xNamedRefMarks = getReferenceMarks(); - int i = 0; - String name = BIB_CITATION + '_' + type + '_' + bibtexKey; - while (xNamedRefMarks.hasByName(name)) { - name = BIB_CITATION + i + '_' + type + '_' + bibtexKey; - i++; - } - return name; - } public void rebuildBibTextSection(List databases, OOBibStyle style) From 683a37beb0cad4ee4c2577f4af136486f6f8e252 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 19:04:35 +0100 Subject: [PATCH 0028/1068] keep details of getCitationEntries() in OOBibBase --- .../ManageCitationsDialogViewModel.java | 14 ++--- .../org/jabref/gui/openoffice/OOBibBase.java | 51 ++++++++++++++----- 2 files changed, 45 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 55d532caa62..ff827512931 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -35,13 +35,15 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogServ this.ooBase = ooBase; this.dialogService = dialogService; - XNameAccess nameAccess = ooBase.getReferenceMarks(); - List names = ooBase.getJabRefReferenceMarks(nameAccess); - for (String name : names) { + // XNameAccess nameAccess = ooBase.getReferenceMarks(); + // List names = ooBase.getJabRefReferenceMarks(nameAccess); + List cts = ooBase.getCitationEntries(); + //for (String name : names) { + for ( CitationEntry entry : cts ) { - CitationEntry entry = new CitationEntry(name, - ooBase.getCitationContext(nameAccess, name, 30, 30, true), - ooBase.getCustomProperty(name)); + //CitationEntry entry = new CitationEntry(name, + // ooBase.getCitationContext(nameAccess, name, 30, 30, true), + // ooBase.getCustomProperty(name)); CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d5c24e9bca3..5041c3cf1cc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -33,6 +33,8 @@ import org.jabref.logic.openoffice.OOUtil; import org.jabref.logic.openoffice.UndefinedBibtexEntry; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; +import org.jabref.logic.openoffice.CitationEntry; + import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; @@ -444,6 +446,40 @@ public XNameAccess getReferenceMarks() { return supplier.getReferenceMarks(); } + /* + * called from ManageCitationsDialogViewModel(...) + */ + public List getJabRefReferenceMarks(XNameAccess nameAccess) { + String[] names = nameAccess.getElementNames(); + // Remove all reference marks that don't look like JabRef citations: + List result = new ArrayList<>(); + if (names != null) { + for (String name : names) { + if (CITE_PATTERN.matcher(name).find()) { + result.add(name); + } + } + } + return result; + } + + public List getCitationEntries() + throws NoSuchElementException, + UnknownPropertyException, + WrappedTargetException + { + XNameAccess nameAccess = this.getReferenceMarks(); + List names = this.getJabRefReferenceMarks(nameAccess); + List citations = new ArrayList(names.size()); + for (String name : names) { + CitationEntry entry = new CitationEntry(name, + this.getCitationContext(nameAccess, name, 30, 30, true), + this.getCustomProperty(name)); + citations.add(entry); + } + return citations; + } + /* * The first occurrence of bibtexKey gets no serial number, the * second gets 0, the third 1 ... @@ -606,7 +642,7 @@ public void insertEntry(List entries, // the text we insert? String citeText = style.isNumberEntries() - ? "-" // A dash only. Presumably + ? "-" // A dash only. Presumably we expect a refresh later. : style.getCitationMarker(entries, databaseMap, inParenthesis, @@ -659,19 +695,6 @@ public void insertEntry(List entries, } } - public List getJabRefReferenceMarks(XNameAccess nameAccess) { - String[] names = nameAccess.getElementNames(); - // Remove all reference marks that don't look like JabRef citations: - List result = new ArrayList<>(); - if (names != null) { - for (String name : names) { - if (CITE_PATTERN.matcher(name).find()) { - result.add(name); - } - } - } - return result; - } /** * Refresh all cite markers in the document. From cc06a010f072678ee109b475112e7348d0d20966 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 19:07:03 +0100 Subject: [PATCH 0029/1068] getJabRefReferenceMarks renamed and made private --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5041c3cf1cc..0dad0c2edef 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -449,7 +449,7 @@ public XNameAccess getReferenceMarks() { /* * called from ManageCitationsDialogViewModel(...) */ - public List getJabRefReferenceMarks(XNameAccess nameAccess) { + private List getJabRefReferenceMarkNames(XNameAccess nameAccess) { String[] names = nameAccess.getElementNames(); // Remove all reference marks that don't look like JabRef citations: List result = new ArrayList<>(); @@ -469,7 +469,7 @@ public List getCitationEntries() WrappedTargetException { XNameAccess nameAccess = this.getReferenceMarks(); - List names = this.getJabRefReferenceMarks(nameAccess); + List names = this.getJabRefReferenceMarkNames(nameAccess); List citations = new ArrayList(names.size()); for (String name : names) { CitationEntry entry = new CitationEntry(name, From 33d68dfc309800d7f10b795dd84313f3c47be5b1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 19:07:53 +0100 Subject: [PATCH 0030/1068] comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0dad0c2edef..77b435e59c2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -447,7 +447,7 @@ public XNameAccess getReferenceMarks() { } /* - * called from ManageCitationsDialogViewModel(...) + * called from getCitationEntries(...) */ private List getJabRefReferenceMarkNames(XNameAccess nameAccess) { String[] names = nameAccess.getElementNames(); From 0b8d89718b8cd86340f0583cbf7198177eb637a2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 19:13:58 +0100 Subject: [PATCH 0031/1068] getReferenceMarks is private --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 77b435e59c2..ab94d7eb2ce 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -439,7 +439,7 @@ private static int citationTypeFromOptions( boolean withText, boolean inParenthe /* * */ - public XNameAccess getReferenceMarks() { + private XNameAccess getReferenceMarks() { XReferenceMarksSupplier supplier = unoQI(XReferenceMarksSupplier.class, this.xCurrentComponent); @@ -1034,9 +1034,12 @@ private List refreshCiteMarkersInternal(List databases, OOB } private List getSortedReferenceMarks(final XNameAccess nameAccess) - throws WrappedTargetException, NoSuchElementException { - XTextViewCursorSupplier cursorSupplier = unoQI(XTextViewCursorSupplier.class, - this.mxDoc.getCurrentController()); + throws WrappedTargetException, + NoSuchElementException + { + XTextViewCursorSupplier cursorSupplier = + unoQI(XTextViewCursorSupplier.class, + this.mxDoc.getCurrentController()); XTextViewCursor viewCursor = cursorSupplier.getViewCursor(); XTextRange initialPos = viewCursor.getStart(); From ccc8c4d1ce5074cf4cfb9fe7ff93cc8b18fa1249 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 19:19:43 +0100 Subject: [PATCH 0032/1068] cleanup getCitationEntries original --- .../gui/openoffice/ManageCitationsDialogViewModel.java | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index ff827512931..0402c7f9b7b 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -32,19 +32,11 @@ public class ManageCitationsDialogViewModel { private final DialogService dialogService; public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) throws NoSuchElementException, WrappedTargetException, UnknownPropertyException { - this.ooBase = ooBase; + this.ooBase = ooBase; this.dialogService = dialogService; - // XNameAccess nameAccess = ooBase.getReferenceMarks(); - // List names = ooBase.getJabRefReferenceMarks(nameAccess); List cts = ooBase.getCitationEntries(); - //for (String name : names) { for ( CitationEntry entry : cts ) { - - //CitationEntry entry = new CitationEntry(name, - // ooBase.getCitationContext(nameAccess, name, 30, 30, true), - // ooBase.getCustomProperty(name)); - CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); } From bf37bda427e4da928250b2503764541478e3fed3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 19:20:16 +0100 Subject: [PATCH 0033/1068] ws --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ab94d7eb2ce..169aace8d72 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -375,9 +375,11 @@ public Optional getCustomProperty(String property) WrappedTargetException { assert (this.propertySet != null); + XPropertySetInfo psi = this.propertySet .getPropertySetInfo(); + if (psi.hasPropertyByName(property)) { String v = this.propertySet From a245eeebd41b64756d15739720137d872b79ad2f Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 19:21:49 +0100 Subject: [PATCH 0034/1068] getCustomProperty is private --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 169aace8d72..9ec3804d502 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -370,7 +370,7 @@ public Optional getCurrentDocumentTitle() { } - public Optional getCustomProperty(String property) + private Optional getCustomProperty(String property) throws UnknownPropertyException, WrappedTargetException { From 3b1cdd1cc981299466220b9340c8157e375202da Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 20:05:52 +0100 Subject: [PATCH 0035/1068] applyCitationEntries() --- .../ManageCitationsDialogViewModel.java | 9 +-- .../org/jabref/gui/openoffice/OOBibBase.java | 64 ++++++++++++++++++- 2 files changed, 63 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 0402c7f9b7b..333edd757d4 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -43,14 +43,9 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogServ } public void storeSettings() { - List ciationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); + List citationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); try { - for (CitationEntry entry : ciationEntries) { - Optional pageInfo = entry.getPageInfo(); - if (pageInfo.isPresent()) { - ooBase.setCustomProperty(entry.getRefMarkName(), pageInfo.get()); - } - } + ooBase.applyCitationEntries( citationEntries ); } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException | IllegalArgumentException ex) { LOGGER.warn("Problem modifying citation", ex); diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9ec3804d502..603fb32003a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -465,6 +465,9 @@ private List getJabRefReferenceMarkNames(XNameAccess nameAccess) { return result; } + /** + * + */ public List getCitationEntries() throws NoSuchElementException, UnknownPropertyException, @@ -474,14 +477,69 @@ public List getCitationEntries() List names = this.getJabRefReferenceMarkNames(nameAccess); List citations = new ArrayList(names.size()); for (String name : names) { - CitationEntry entry = new CitationEntry(name, - this.getCitationContext(nameAccess, name, 30, 30, true), - this.getCustomProperty(name)); + CitationEntry entry = + new CitationEntry(name, + this.getCitationContext(nameAccess, name, 30, 30, true), + this.getCustomProperty(name) + ); citations.add(entry); } return citations; } + /** + * Apply editable parts of citationEntries to the document. + * + * - Currently the only editable part is pageInfo. + * + * Since the only call to applyCitationEntries() only changes + * pageInfo w.r.t those returned by getCitationEntries(), we can + * do with the following restrictions: + * + * - Missing pageInfo means no action. + * + * - Missing CitationEntry means no action (no attempt to + * remove citation from the text). + * + * - Reference to citation not present in the text evokes + * no error, and setCustomProperty() is called. + * + */ + public void applyCitationEntries( List citationEntries ) + throws UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException + { + // Leave exceptions to the caller. + // + // Note: not catching exceptions here means nothing is applied + // after the first problematic entry. We might catch and + // collect messages here. + // + // try { + for (CitationEntry entry : citationEntries) { + Optional pageInfo = entry.getPageInfo(); + if (pageInfo.isPresent()) { + this.setCustomProperty( entry.getRefMarkName(), pageInfo.get() ); + } else { + // TODO: if pageInfo is not present, or is empty: + // maybe we should remove it from the document. + } + } + // } catch (UnknownPropertyException + // | NotRemoveableException + // | PropertyExistException + // | IllegalTypeException + // | IllegalArgumentException ex) + // { + // LOGGER.warn("Problem modifying citation", ex); + // dialogService.showErrorDialogAndWait( + // Localization.lang("Problem modifying citation"), ex); + // } + } + /* * The first occurrence of bibtexKey gets no serial number, the * second gets 0, the third 1 ... From 026c0b5040228cfb51bc63beb2cfd30775ecd8b9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 20:08:49 +0100 Subject: [PATCH 0036/1068] setCustomProperty is private --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 603fb32003a..d41e7efc5dc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -390,7 +390,7 @@ private Optional getCustomProperty(String property) return Optional.empty(); } - public void setCustomProperty(String property, String value) + private void setCustomProperty(String property, String value) throws UnknownPropertyException, NotRemoveableException, PropertyExistException, From 718d01df28337936d7708969ccbe91977668c49b Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 20:33:36 +0100 Subject: [PATCH 0037/1068] parseRefMarkNameToUniqueCitationKeys --- .../org/jabref/gui/openoffice/OOBibBase.java | 169 ++++++++++-------- 1 file changed, 97 insertions(+), 72 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d41e7efc5dc..736dc5700c1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -137,7 +137,11 @@ class OOBibBase { private List sortedReferenceMarks; - // unoQI : short for UnoRuntime.queryInterface + /** unoQI : short for UnoRuntime.queryInterface + * + * Returns: a reference to the requested UNO interface type if + * available, otherwise null + */ private static T unoQI(Class zInterface, Object object) { @@ -755,6 +759,72 @@ public void insertEntry(List entries, } } + /** + * Extract the list of citation keys from a reference mark name. + * + * @param name The reference mark name. + * @return The list of citation keys encoded in the name. + * In case of duplicated citation keys, only the first occurrence. + * Otherwise their order is preserved. + */ + public List parseRefMarkNameToUniqueCitationKeys(String name) { + List keys = new ArrayList<>(); + Matcher citeMatcher = CITE_PATTERN.matcher(name); + if (citeMatcher.find()) { + String[] keystring = citeMatcher.group(2).split(","); + for (String aKeystring : keystring) { + if (!keys.contains(aKeystring)) { + keys.add(aKeystring); + } + } + } + return keys; + } + + private List findCitedKeys() + throws NoSuchElementException, + WrappedTargetException + { + XNameAccess xNamedMarks = getReferenceMarks(); + String[] names = xNamedMarks.getElementNames(); + + List keys = new ArrayList<>(); + for (String name1 : names) { + Object bookmark = xNamedMarks.getByName(name1); + assert (null != unoQI(XTextContent.class, bookmark)); + + List newKeys = parseRefMarkNameToUniqueCitationKeys(name1); + for (String key : newKeys) { + if (!keys.contains(key)) { + keys.add(key); + } + } + } + + return keys; + } + + private Map findCitedEntries(List databases, List keys, + Map linkSourceBase) { + Map entries = new LinkedHashMap<>(); + for (String key : keys) { + boolean found = false; + for (BibDatabase database : databases) { + Optional entry = database.getEntryByCitationKey(key); + if (entry.isPresent()) { + entries.put(entry.get(), database); + linkSourceBase.put(key, database); + found = true; + break; + } + } + + if (!found) { + entries.put(new UndefinedBibtexEntry(key), null); + } + } + return entries; + } /** * Refresh all cite markers in the document. @@ -772,10 +842,18 @@ public void insertEntry(List entries, * @throws PropertyVetoException * @throws UnknownPropertyException */ - public List refreshCiteMarkers(List databases, OOBibStyle style) - throws WrappedTargetException, IllegalArgumentException, NoSuchElementException, - UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, IOException, - CreationException, BibEntryNotFoundException { + public List refreshCiteMarkers(List databases, + OOBibStyle style) + throws WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException + { try { return refreshCiteMarkersInternal(databases, style); } catch (DisposedException ex) { @@ -786,11 +864,17 @@ public List refreshCiteMarkers(List databases, OOBibStyle s } } - private List refreshCiteMarkersInternal(List databases, OOBibStyle style) - throws WrappedTargetException, IllegalArgumentException, NoSuchElementException, - UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, - CreationException, BibEntryNotFoundException { - + private List refreshCiteMarkersInternal(List databases, + OOBibStyle style) + throws WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException + { List cited = findCitedKeys(); Map linkSourceBase = new HashMap<>(); Map entries = findCitedEntries(databases, cited, linkSourceBase); @@ -1178,71 +1262,12 @@ public void rebuildBibTextSection(List databases, populateBibTextSection(entries, style); } - private List findCitedKeys() throws NoSuchElementException, WrappedTargetException { - XNameAccess xNamedMarks = getReferenceMarks(); - String[] names = xNamedMarks.getElementNames(); - List keys = new ArrayList<>(); - for (String name1 : names) { - Object bookmark = xNamedMarks.getByName(name1); - unoQI(XTextContent.class, bookmark); - - List newKeys = parseRefMarkName(name1); - for (String key : newKeys) { - if (!keys.contains(key)) { - keys.add(key); - } - } - } - - return keys; - } - - private Map findCitedEntries(List databases, List keys, - Map linkSourceBase) { - Map entries = new LinkedHashMap<>(); - for (String key : keys) { - boolean found = false; - for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(key); - if (entry.isPresent()) { - entries.put(entry.get(), database); - linkSourceBase.put(key, database); - found = true; - break; - } - } - - if (!found) { - entries.put(new UndefinedBibtexEntry(key), null); - } - } - return entries; - } private Point findPosition(XTextViewCursor cursor, XTextRange range) { cursor.gotoRange(range, false); return cursor.getPosition(); } - /** - * Extract the list of citation keys from a reference mark name. - * - * @param name The reference mark name. - * @return The list of citation keys encoded in the name. - */ - public List parseRefMarkName(String name) { - List keys = new ArrayList<>(); - Matcher citeMatcher = CITE_PATTERN.matcher(name); - if (citeMatcher.find()) { - String[] keystring = citeMatcher.group(2).split(","); - for (String aKeystring : keystring) { - if (!keys.contains(aKeystring)) { - keys.add(aKeystring); - } - } - } - return keys; - } /** * Resolve the citation key from a citation reference marker name, and look up the index of the key in a list of keys. @@ -1619,8 +1644,8 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } } - List keys = parseRefMarkName(names.get(piv)); - keys.addAll(parseRefMarkName(names.get(piv + 1))); + List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); + keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(piv + 1))); removeReferenceMark(names.get(piv)); removeReferenceMark(names.get(piv + 1)); List entries = new ArrayList<>(); @@ -1688,7 +1713,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) } } - List keys = parseRefMarkName(names.get(piv)); + List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); if (keys.size() > 1) { removeReferenceMark(names.get(piv)); // From cf4f49f7470367fddb409896f99ee19774590756 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 20:45:23 +0100 Subject: [PATCH 0038/1068] parseRefMarkNameToUniqueCitationKeys is private --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 736dc5700c1..cf80cc06177 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -767,7 +767,7 @@ public void insertEntry(List entries, * In case of duplicated citation keys, only the first occurrence. * Otherwise their order is preserved. */ - public List parseRefMarkNameToUniqueCitationKeys(String name) { + private List parseRefMarkNameToUniqueCitationKeys(String name) { List keys = new ArrayList<>(); Matcher citeMatcher = CITE_PATTERN.matcher(name); if (citeMatcher.find()) { From c40ced5bd69c1d31be6f9f6d54996efd928e7bc5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 20:45:58 +0100 Subject: [PATCH 0039/1068] comment --- .../org/jabref/gui/openoffice/OOBibBase.java | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index cf80cc06177..5df41e85fe2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -766,6 +766,8 @@ public void insertEntry(List entries, * @return The list of citation keys encoded in the name. * In case of duplicated citation keys, only the first occurrence. * Otherwise their order is preserved. + * + * If name does not match CITE_PATTERN, an empty List is returned. */ private List parseRefMarkNameToUniqueCitationKeys(String name) { List keys = new ArrayList<>(); @@ -781,6 +783,14 @@ private List parseRefMarkNameToUniqueCitationKeys(String name) { return keys; } + /** + * Extract citation keys from names of referenceMarks in the document. + * + * Each citation key is listed only once, in the order of first appearance. + * + * doc.referenceMarks.names.map(parse).flatten.unique + * + */ private List findCitedKeys() throws NoSuchElementException, WrappedTargetException @@ -804,8 +814,23 @@ private List findCitedKeys() return keys; } - private Map findCitedEntries(List databases, List keys, - Map linkSourceBase) { + /** + * @return LinkedHashMap, from BibEntry to BibDatabase + * + * If a key is not found, BibEntry is new UndefinedBibtexEntry(key), BibDatabase is null. + * If key is found, then + * BibEntry is what we found, BibDatabase is the database we found it in. + * linkSourceBase.put(key, database); is called. + * + * So: + * - result has an entry for each key, in the same order + * - key in the entry is the same as the original key + * - on return linkSourceBase has an entry for the keys we did find + */ + private Map findCitedEntries(List databases, + List keys, + Map linkSourceBase) + { Map entries = new LinkedHashMap<>(); for (String key : keys) { boolean found = false; From b7909e54efac014da4985c718d27ab2ebefbc71e Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 23:12:11 +0100 Subject: [PATCH 0040/1068] implement parseRefMarkName --- .../org/jabref/gui/openoffice/OOBibBase.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5df41e85fe2..8c68829c9d3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -104,6 +104,10 @@ class OOBibBase { private static final Pattern CITE_PATTERN = Pattern.compile(BIB_CITATION + "\\d*_(\\d*)_(.*)"); + // Another pattern, to also recover the "i" part + private static final Pattern CITE_PATTERN2 = + Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + private static final String CHAR_STYLE_NAME = "CharStyleName"; /* Types of in-text citation. @@ -562,6 +566,27 @@ private String getUniqueReferenceMarkName(String bibtexKey, int type) { return name; } + private class ParsedRefMark { + public String i ; // "", "0", "1" ... + public int type ; + public List citedKeys; + ParsedRefMark( String i, int type, List citedKeys ){ + this.i=i; + this.type = type; + this.citedKeys = citedKeys; + } + } + private Optional parseRefMarkName( String name ){ + Matcher citeMatcher = CITE_PATTERN2.matcher(name); + if (!citeMatcher.find()) { + return Optional.empty(); + } + List keys = Arrays.asList( citeMatcher.group(3).split(",") ); + String i = citeMatcher.group(1); + int type = Integer.parseInt( citeMatcher.group(2) ); + return( Optional.of( new ParsedRefMark( i, type, keys ) ) ); + } + /** * This method inserts a cite marker in the text (at the cursor) for the given * BibEntry, and may refresh the bibliography. @@ -759,6 +784,7 @@ public void insertEntry(List entries, } } + /** * Extract the list of citation keys from a reference mark name. * From 01a14406f816b5850b599b75aa2350f01e1f8a4e Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 23:13:15 +0100 Subject: [PATCH 0041/1068] parseRefMarkNameToUniqueCitationKeys uses parseRefMarkName --- .../org/jabref/gui/openoffice/OOBibBase.java | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8c68829c9d3..c8c211210ae 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -796,17 +796,23 @@ public void insertEntry(List entries, * If name does not match CITE_PATTERN, an empty List is returned. */ private List parseRefMarkNameToUniqueCitationKeys(String name) { - List keys = new ArrayList<>(); - Matcher citeMatcher = CITE_PATTERN.matcher(name); - if (citeMatcher.find()) { - String[] keystring = citeMatcher.group(2).split(","); - for (String aKeystring : keystring) { - if (!keys.contains(aKeystring)) { - keys.add(aKeystring); - } - } - } - return keys; + /* + * List keys = new ArrayList<>(); + * Matcher citeMatcher = CITE_PATTERN.matcher(name); + * if (citeMatcher.find()) { + * String[] keystring = citeMatcher.group(2).split(","); + * for (String aKeystring : keystring) { + * if (!keys.contains(aKeystring)) { + * keys.add(aKeystring); + * } + * } + * } + */ + Optional< ParsedRefMark > op = parseRefMarkName( name ); + if ( op.isPresent() ){ + return op.get().citedKeys.stream().distinct().collect(Collectors.toList()); + } + return new ArrayList<>(); } /** From 78efa9a46ff9597610a5fd294df6af28a9b38247 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 23:13:51 +0100 Subject: [PATCH 0042/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c8c211210ae..37e7f2cdc0c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -933,7 +933,7 @@ private List refreshCiteMarkersInternal(List databases, BibEntryNotFoundException { List cited = findCitedKeys(); - Map linkSourceBase = new HashMap<>(); + Map linkSourceBase = new HashMap<>(); Map entries = findCitedEntries(databases, cited, linkSourceBase); XNameAccess xReferenceMarks = getReferenceMarks(); From a3b223d07b097e61d0d3d2833d26b525a139d75f Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 23:14:25 +0100 Subject: [PATCH 0043/1068] findCitedEntryIndex uses parseRefMarkName --- .../org/jabref/gui/openoffice/OOBibBase.java | 43 +++++++++++++------ 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 37e7f2cdc0c..f3fd6345e88 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1327,25 +1327,40 @@ private Point findPosition(XTextViewCursor cursor, XTextRange range) { /** - * Resolve the citation key from a citation reference marker name, and look up the index of the key in a list of keys. + * Resolve the citation key from a citation reference marker name, + * and look up the index of the key in a list of keys. * * @param citRefName The name of the ReferenceMark representing the citation. * @param keys A List of citation keys representing the entries in the bibliography. - * @return the indices of the cited keys, -1 if a key is not found. Returns null if the ref name could not be resolved as a citation. + * @return the (1-based) indices of the cited keys, -1 if a key is not found. + * Returns Collections.emptyList() if the ref name could not be resolved as a citation. */ private List findCitedEntryIndex(String citRefName, List keys) { - Matcher citeMatcher = CITE_PATTERN.matcher(citRefName); - if (citeMatcher.find()) { - List keyStrings = Arrays.asList(citeMatcher.group(2).split(",")); - List result = new ArrayList<>(keyStrings.size()); - for (String key : keyStrings) { - int ind = keys.indexOf(key); - result.add(ind == -1 ? -1 : 1 + ind); - } - return result; - } else { - return Collections.emptyList(); - } + /* + * Matcher citeMatcher = CITE_PATTERN.matcher(citRefName); + * if (citeMatcher.find()) { + * List keyStrings = Arrays.asList(citeMatcher.group(2).split(",")); + * List result = new ArrayList<>(keyStrings.size()); + * for (String key : keyStrings) { + * int ind = keys.indexOf(key); + * result.add(ind == -1 ? -1 : 1 + ind); + * } + * return result; + * } else { + * return Collections.emptyList(); + * } + */ + Optional< ParsedRefMark > op = parseRefMarkName( citRefName ); + if ( !op.isPresent() ){ + return Collections.emptyList(); + } + List keyStrings = op.get().citedKeys; + List result = new ArrayList<>(keyStrings.size()); + for (String key : keyStrings) { + int ind = keys.indexOf(key); + result.add(ind == -1 ? -1 : 1 + ind); + } + return result; } private Map getSortedEntriesFromSortedRefMarks(List names, From be6d8d493e9d99b109eb23b82eb0843947d084aa Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 23:24:18 +0100 Subject: [PATCH 0044/1068] getSortedEntriesFromSortedRefMarks uses parseRefMarkName --- .../org/jabref/gui/openoffice/OOBibBase.java | 47 ++++++++++--------- 1 file changed, 26 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f3fd6345e88..0e165d3e769 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1368,28 +1368,33 @@ private Map getSortedEntriesFromSortedRefMarks(List newList = new LinkedHashMap<>(); for (String name : names) { - Matcher citeMatcher = CITE_PATTERN.matcher(name); - if (citeMatcher.find()) { - String[] keys = citeMatcher.group(2).split(","); - for (String key : keys) { - BibDatabase database = linkSourceBase.get(key); - Optional origEntry = Optional.empty(); - if (database != null) { - origEntry = database.getEntryByCitationKey(key); - } - if (origEntry.isPresent()) { - if (!newList.containsKey(origEntry.get())) { - newList.put(origEntry.get(), database); - } - } else { - LOGGER.info("Citation key not found: '" + key + "'"); - LOGGER.info("Problem with reference mark: '" + name + "'"); - newList.put(new UndefinedBibtexEntry(key), null); - } - } - } + /* + * Matcher citeMatcher = CITE_PATTERN.matcher(name); + * if (citeMatcher.find()) { + * String[] keys = citeMatcher.group(2).split(","); + */ + Optional op = parseRefMarkName( name ); + if ( ! op.isPresent() ){ continue; } + List keys = op.get().citedKeys; + for (String key : keys) { + BibDatabase database = linkSourceBase.get(key); + Optional origEntry = Optional.empty(); + if (database != null) { + origEntry = database.getEntryByCitationKey(key); + } + if (origEntry.isPresent()) { + BibEntry oe = origEntry.get(); + if (!newList.containsKey(oe)) { + newList.put(oe, database); + } + } else { + LOGGER.info("Citation key not found: '" + key + "'"); + LOGGER.info("Problem with reference mark: '" + name + "'"); + newList.put(new UndefinedBibtexEntry(key), null); + } + } + /* } */ } - return newList; } From d4c729caf2813bb0827362a72701d1e64dea1f46 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 23:48:12 +0100 Subject: [PATCH 0045/1068] isJabRefReferenceMarkName, getJabRefReferenceMarkNames uses it --- .../org/jabref/gui/openoffice/OOBibBase.java | 32 +++++++++++++------ 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0e165d3e769..d442df4727b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -456,21 +456,35 @@ private XNameAccess getReferenceMarks() { return supplier.getReferenceMarks(); } + private static boolean isJabRefReferenceMarkName( String name ){ + return (CITE_PATTERN.matcher(name).find()); + } + /* * called from getCitationEntries(...) */ private List getJabRefReferenceMarkNames(XNameAccess nameAccess) { String[] names = nameAccess.getElementNames(); // Remove all reference marks that don't look like JabRef citations: - List result = new ArrayList<>(); - if (names != null) { - for (String name : names) { - if (CITE_PATTERN.matcher(name).find()) { - result.add(name); - } - } - } - return result; + /* + * List result = new ArrayList<>(); + * if (names != null) { + * for (String name : names) { + * if (CITE_PATTERN.matcher(name).find()) { + * result.add(name); + * } + * } + * } + * return result; + */ + if (names == null) { + return new ArrayList<>(); + } + return ( Arrays.asList( names ) + .stream() + .filter( OOBibBase::isJabRefReferenceMarkName ) + .collect(Collectors.toList()) + ); } /** From 67a16361356a751e20e6eb378f50f86238c5063f Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Feb 2021 23:59:39 +0100 Subject: [PATCH 0046/1068] filterIsJabRefReferenceMarkName --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d442df4727b..fcb9bef4271 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -459,6 +459,13 @@ private XNameAccess getReferenceMarks() { private static boolean isJabRefReferenceMarkName( String name ){ return (CITE_PATTERN.matcher(name).find()); } + private static List filterIsJabRefReferenceMarkName( List names ) { + return ( names + .stream() + .filter( OOBibBase::isJabRefReferenceMarkName ) + .collect(Collectors.toList()) + ); + } /* * called from getCitationEntries(...) From 054735ff177337c38b0541c1c68b51a90589892d Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 00:00:00 +0100 Subject: [PATCH 0047/1068] getJabRefReferenceMarkNames use filterIsJabRefReferenceMarkName --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index fcb9bef4271..8346134b9d4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -487,11 +487,7 @@ private List getJabRefReferenceMarkNames(XNameAccess nameAccess) { if (names == null) { return new ArrayList<>(); } - return ( Arrays.asList( names ) - .stream() - .filter( OOBibBase::isJabRefReferenceMarkName ) - .collect(Collectors.toList()) - ); + return filterIsJabRefReferenceMarkName( Arrays.asList( names ) ); } /** From 52832060124d0183f0daf2d7dd5830c38f6a4dd6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 00:22:08 +0100 Subject: [PATCH 0048/1068] CITE_PATTERN to parseRefMarkName --- .../org/jabref/gui/openoffice/OOBibBase.java | 55 +++++++++++-------- 1 file changed, 32 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8346134b9d4..d4faa7d7066 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -978,39 +978,48 @@ private List refreshCiteMarkersInternal(List databases, } // Remove all reference marks that don't look like JabRef citations: - List tmp = new ArrayList<>(); - for (String name : names) { - if (CITE_PATTERN.matcher(name).find()) { - tmp.add(name); - } - } - names = tmp; + /* + * List tmp = new ArrayList<>(); + * for (String name : names) { + * if (CITE_PATTERN.matcher(name).find()) { + * tmp.add(name); + * } + * } + * names = tmp; + */ + names = filterIsJabRefReferenceMarkName( names ); Map numbers = new HashMap<>(); int lastNum = 0; // First compute citation markers for all citations: - String[] citMarkers = new String[names.size()]; + String[] citMarkers = new String[names.size()]; String[][] normCitMarkers = new String[names.size()][]; - String[][] bibtexKeys = new String[names.size()][]; + String[][] bibtexKeys = new String[names.size()][]; - int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); int[] types = new int[names.size()]; for (int i = 0; i < names.size(); i++) { - Matcher citeMatcher = CITE_PATTERN.matcher(names.get(i)); - if (citeMatcher.find()) { - String typeStr = citeMatcher.group(1); - int type = Integer.parseInt(typeStr); + // Matcher citeMatcher = CITE_PATTERN.matcher(names.get(i)); + Optional op = parseRefMarkName( names.get(i) ); + // if (citeMatcher.find()) { + if ( op.isPresent() ) { + ParsedRefMark ov = op.get(); + // String typeStr = citeMatcher.group(1); + // int type = Integer.parseInt(typeStr); + int type = ov.type; types[i] = type; // Remember the type in case we need to uniquefy. - String[] keys = citeMatcher.group(2).split(","); + // String[] keys = citeMatcher.group(2).split(","); + String[] keys = ov.citedKeys.stream().toArray(String[]::new); bibtexKeys[i] = keys; + // BibEntry[] cEntries = new BibEntry[keys.length]; - for (int j = 0; j < cEntries.length; j++) { + for (int j = 0; j < keys.length; j++) { BibDatabase database = linkSourceBase.get(keys[j]); - Optional tmpEntry = Optional.empty(); - if (database != null) { - tmpEntry = database.getEntryByCitationKey(keys[j]); - } + Optional tmpEntry = ( (database == null) + ? Optional.empty() + : database.getEntryByCitationKey(keys[j]) + ); if (tmpEntry.isPresent()) { cEntries[j] = tmpEntry.get(); } else { @@ -1019,7 +1028,7 @@ private List refreshCiteMarkersInternal(List databases, throw new BibEntryNotFoundException(names.get(i), Localization .lang("Could not resolve BibTeX entry for citation marker '%0'.", names.get(i))); } - } + } // for j String[] normCitMarker = new String[keys.length]; String citationMarker; @@ -1099,8 +1108,8 @@ private List refreshCiteMarkersInternal(List databases, } citMarkers[i] = citationMarker; normCitMarkers[i] = normCitMarker; - } - } + } // if (citeMatcher.find()) + } // for i uniquefiers.clear(); if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { From 7d9772cec9f27a26d837cf12a60a1198874028a4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 00:36:39 +0100 Subject: [PATCH 0049/1068] linkSourceBaseCiteKeyToBibEbtry --- .../org/jabref/gui/openoffice/OOBibBase.java | 34 +++++++++++-------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d4faa7d7066..9c2e7f4ee72 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -938,6 +938,16 @@ public List refreshCiteMarkers(List databases, } } + private static Optional linkSourceBaseCiteKeyToBibEbtry( Map linkSourceBase, + String kj ) + { + BibDatabase database = linkSourceBase.get(kj); + Optional res = ( (database == null) + ? Optional.empty() + : database.getEntryByCitationKey(kj) + ); + return res; + } private List refreshCiteMarkersInternal(List databases, OOBibStyle style) throws WrappedTargetException, @@ -1000,33 +1010,29 @@ private List refreshCiteMarkersInternal(List databases, int[] types = new int[names.size()]; for (int i = 0; i < names.size(); i++) { - // Matcher citeMatcher = CITE_PATTERN.matcher(names.get(i)); - Optional op = parseRefMarkName( names.get(i) ); - // if (citeMatcher.find()) { + final String namei = names.get(i); + Optional op = parseRefMarkName( namei ); if ( op.isPresent() ) { ParsedRefMark ov = op.get(); - // String typeStr = citeMatcher.group(1); - // int type = Integer.parseInt(typeStr); int type = ov.type; types[i] = type; // Remember the type in case we need to uniquefy. - // String[] keys = citeMatcher.group(2).split(","); String[] keys = ov.citedKeys.stream().toArray(String[]::new); bibtexKeys[i] = keys; // BibEntry[] cEntries = new BibEntry[keys.length]; for (int j = 0; j < keys.length; j++) { - BibDatabase database = linkSourceBase.get(keys[j]); - Optional tmpEntry = ( (database == null) - ? Optional.empty() - : database.getEntryByCitationKey(keys[j]) - ); + String kj = keys[j]; + Optional tmpEntry = linkSourceBaseCiteKeyToBibEbtry( linkSourceBase, kj ); if (tmpEntry.isPresent()) { cEntries[j] = tmpEntry.get(); } else { - LOGGER.info("Citation key not found: '" + keys[j] + '\''); + LOGGER.info("Citation key not found: '" + kj + '\''); LOGGER.info("Problem with reference mark: '" + names.get(i) + '\''); - throw new BibEntryNotFoundException(names.get(i), Localization - .lang("Could not resolve BibTeX entry for citation marker '%0'.", names.get(i))); + String msg = Localization.lang("Could not resolve BibTeX entry" + +" for citation marker '%0'.", + names.get(i) + ); + throw new BibEntryNotFoundException(names.get(i), msg); } } // for j From 0dd93d3baf574f72b391fdbb3b88ce4441cf9dde Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 00:41:53 +0100 Subject: [PATCH 0050/1068] kj -> citeKey --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9c2e7f4ee72..9940350ea35 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -801,7 +801,7 @@ public void insertEntry(List entries, } } - + /** * Extract the list of citation keys from a reference mark name. * @@ -938,16 +938,17 @@ public List refreshCiteMarkers(List databases, } } - private static Optional linkSourceBaseCiteKeyToBibEbtry( Map linkSourceBase, - String kj ) + private static Optional linkSourceBaseCiteKeyToBibEbtry( Map linkSourceBase, + String citeKey ) { - BibDatabase database = linkSourceBase.get(kj); + BibDatabase database = linkSourceBase.get(citeKey); Optional res = ( (database == null) ? Optional.empty() - : database.getEntryByCitationKey(kj) + : database.getEntryByCitationKey(citeKey) ); return res; } + private List refreshCiteMarkersInternal(List databases, OOBibStyle style) throws WrappedTargetException, @@ -1020,9 +1021,11 @@ private List refreshCiteMarkersInternal(List databases, bibtexKeys[i] = keys; // BibEntry[] cEntries = new BibEntry[keys.length]; + // fill cEntries for (int j = 0; j < keys.length; j++) { String kj = keys[j]; - Optional tmpEntry = linkSourceBaseCiteKeyToBibEbtry( linkSourceBase, kj ); + Optional tmpEntry = + linkSourceBaseCiteKeyToBibEbtry( linkSourceBase, kj ); if (tmpEntry.isPresent()) { cEntries[j] = tmpEntry.get(); } else { From fdea1447c22db5c5edf88a3f7d152811ee18ac38 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 01:04:42 +0100 Subject: [PATCH 0051/1068] linkSourceBaseGetBibEntriesOfCiteKeys --- .../org/jabref/gui/openoffice/OOBibBase.java | 49 +++++++++++++++---- 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9940350ea35..bfe3816bdc2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -938,7 +938,7 @@ public List refreshCiteMarkers(List databases, } } - private static Optional linkSourceBaseCiteKeyToBibEbtry( Map linkSourceBase, + private static Optional linkSourceBaseCiteKeyToBibEntry( Map linkSourceBase, String citeKey ) { BibDatabase database = linkSourceBase.get(citeKey); @@ -949,6 +949,33 @@ private static Optional linkSourceBaseCiteKeyToBibEbtry( Map linkSourceBase, + String[] keys, // citeKeys + String namei // refMarkName + ) + throws BibEntryNotFoundException + { + BibEntry[] cEntries = new BibEntry[keys.length]; + // fill cEntries + for (int j = 0; j < keys.length; j++) { + String kj = keys[j]; + Optional tmpEntry = + linkSourceBaseCiteKeyToBibEntry( linkSourceBase, kj ); + if (tmpEntry.isPresent()) { + cEntries[j] = tmpEntry.get(); + } else { + LOGGER.info("Citation key not found: '" + kj + '\''); + LOGGER.info("Problem with reference mark: '" + namei + '\''); + String msg = Localization.lang("Could not resolve BibTeX entry" + +" for citation marker '%0'.", + namei + ); + throw new BibEntryNotFoundException(namei, msg); + } + } // for j + return cEntries; + } + private List refreshCiteMarkersInternal(List databases, OOBibStyle style) throws WrappedTargetException, @@ -962,7 +989,8 @@ private List refreshCiteMarkersInternal(List databases, { List cited = findCitedKeys(); Map linkSourceBase = new HashMap<>(); - Map entries = findCitedEntries(databases, cited, linkSourceBase); + Map entries = + findCitedEntries(databases, cited, linkSourceBase); XNameAccess xReferenceMarks = getReferenceMarks(); @@ -974,8 +1002,9 @@ private List refreshCiteMarkersInternal(List databases, // We need to sort the reference marks according to the sorting of the bibliographic // entries: SortedMap newMap = new TreeMap<>(entryComparator); - for (Map.Entry bibtexEntryBibtexDatabaseEntry : entries.entrySet()) { - newMap.put(bibtexEntryBibtexDatabaseEntry.getKey(), bibtexEntryBibtexDatabaseEntry.getValue()); + for (Map.Entry ee : entries.entrySet()) { + newMap.put(ee.getKey(), + ee.getValue()); } entries = newMap; // Rebuild the list of cited keys according to the sort order: @@ -1020,25 +1049,27 @@ private List refreshCiteMarkersInternal(List databases, String[] keys = ov.citedKeys.stream().toArray(String[]::new); bibtexKeys[i] = keys; // + /* BibEntry[] cEntries = new BibEntry[keys.length]; // fill cEntries for (int j = 0; j < keys.length; j++) { String kj = keys[j]; Optional tmpEntry = - linkSourceBaseCiteKeyToBibEbtry( linkSourceBase, kj ); + linkSourceBaseCiteKeyToBibEntry( linkSourceBase, kj ); if (tmpEntry.isPresent()) { cEntries[j] = tmpEntry.get(); } else { LOGGER.info("Citation key not found: '" + kj + '\''); - LOGGER.info("Problem with reference mark: '" + names.get(i) + '\''); + LOGGER.info("Problem with reference mark: '" + namei + '\''); String msg = Localization.lang("Could not resolve BibTeX entry" +" for citation marker '%0'.", - names.get(i) + namei ); - throw new BibEntryNotFoundException(names.get(i), msg); + throw new BibEntryNotFoundException(namei, msg); } } // for j - + */ + BibEntry[] cEntries = linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, keys, namei ); String[] normCitMarker = new String[keys.length]; String citationMarker; if (style.isCitationKeyCiteMarkers()) { From e75efdf3fe3f7e95d2890ec209641f58fbab4d36 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 10:02:56 +0100 Subject: [PATCH 0052/1068] fromat --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index bfe3816bdc2..588f30ca992 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -996,15 +996,15 @@ private List refreshCiteMarkersInternal(List databases, List names; if (style.isSortByPosition()) { - // We need to sort the reference marks according to their order of appearance: + // We need to sort the reference marks according to their + // order of appearance: names = sortedReferenceMarks; } else if (style.isNumberEntries()) { - // We need to sort the reference marks according to the sorting of the bibliographic - // entries: + // We need to sort the reference marks according to the + // sorting of the bibliographic entries: SortedMap newMap = new TreeMap<>(entryComparator); for (Map.Entry ee : entries.entrySet()) { - newMap.put(ee.getKey(), - ee.getValue()); + newMap.put(ee.getKey(), ee.getValue()); } entries = newMap; // Rebuild the list of cited keys according to the sort order: From 8809b45082479ff70fb42cc2a8a88a35e144cbb1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 10:23:43 +0100 Subject: [PATCH 0053/1068] cleanup --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 588f30ca992..59827fa59d5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1018,15 +1018,6 @@ private List refreshCiteMarkersInternal(List databases, } // Remove all reference marks that don't look like JabRef citations: - /* - * List tmp = new ArrayList<>(); - * for (String name : names) { - * if (CITE_PATTERN.matcher(name).find()) { - * tmp.add(name); - * } - * } - * names = tmp; - */ names = filterIsJabRefReferenceMarkName( names ); Map numbers = new HashMap<>(); From 02e7fd398b784a274d8750a2640ef8941c716994 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 10:23:57 +0100 Subject: [PATCH 0054/1068] run_useless_parts --- .../org/jabref/gui/openoffice/OOBibBase.java | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 59827fa59d5..c8cdabd3dc4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -152,6 +152,11 @@ private static T unoQI(Class zInterface, return UnoRuntime.queryInterface( zInterface, object ); } + /* + * Shall we keep calls I suspect to be useless? + */ + private final boolean run_useless_parts = true; + /* * Constructor */ @@ -175,7 +180,9 @@ private XDesktop simpleBootstrap(Path loPath) XDesktop result = unoQI(XDesktop.class, desktop); // TODO: useless call? - // unoQI(XComponentLoader.class, desktop); + if ( run_useless_parts ){ + unoQI(XComponentLoader.class, desktop); + } return result; } @@ -346,8 +353,9 @@ public void selectDocument() // TODO: what is the point of the next line? Does it have a side effect? - // - // unoQI(XDocumentIndexesSupplier.class, xCurrentComponent); + if ( run_useless_parts ){ + unoQI(XDocumentIndexesSupplier.class, xCurrentComponent); + } { XModel mo = unoQI(XModel.class, this.xCurrentComponent); @@ -1027,7 +1035,8 @@ private List refreshCiteMarkersInternal(List databases, String[][] normCitMarkers = new String[names.size()][]; String[][] bibtexKeys = new String[names.size()][]; - final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + final int minGroupingCount = + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); int[] types = new int[names.size()]; for (int i = 0; i < names.size(); i++) { From 1af3eb49fd24e593f8f0c0f5e189071a866783cf Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 10:26:17 +0100 Subject: [PATCH 0055/1068] cleanup --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c8cdabd3dc4..4a5742fcd1d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -821,18 +821,6 @@ public void insertEntry(List entries, * If name does not match CITE_PATTERN, an empty List is returned. */ private List parseRefMarkNameToUniqueCitationKeys(String name) { - /* - * List keys = new ArrayList<>(); - * Matcher citeMatcher = CITE_PATTERN.matcher(name); - * if (citeMatcher.find()) { - * String[] keystring = citeMatcher.group(2).split(","); - * for (String aKeystring : keystring) { - * if (!keys.contains(aKeystring)) { - * keys.add(aKeystring); - * } - * } - * } - */ Optional< ParsedRefMark > op = parseRefMarkName( name ); if ( op.isPresent() ){ return op.get().citedKeys.stream().distinct().collect(Collectors.toList()); From 700b33d50190f9e292c7aa272a300e224c518fba Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 10:40:39 +0100 Subject: [PATCH 0056/1068] format --- .../java/org/jabref/gui/openoffice/NoDocumentException.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java b/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java index 05d5f6d06ac..74bb643224c 100644 --- a/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java +++ b/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java @@ -1,8 +1,9 @@ package org.jabref.gui.openoffice; /** - * Exception used to indicate that the plugin attempted to set a character format that is - * not defined in the current OpenOffice document. + * Exception used to indicate that the plugin attempted to set a + * character format that is not defined in the current OpenOffice + * document. */ class NoDocumentException extends Exception { From 6bc4c89f70aae9a293fc2c4ff5931359fde3aea7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 12:12:47 +0100 Subject: [PATCH 0057/1068] doc correction --- .../org/jabref/gui/openoffice/NoDocumentException.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java b/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java index 74bb643224c..170cbed69c7 100644 --- a/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java +++ b/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java @@ -1,9 +1,10 @@ package org.jabref.gui.openoffice; /** - * Exception used to indicate that the plugin attempted to set a - * character format that is not defined in the current OpenOffice - * document. + * Exception used to indicate that + * + * OOBibBase.selectDocument : NoDocumentException("No Writer documents found"); + * OOBibBase.getReferenceMarks : NoDocumentException("getReferenceMarks failed"); */ class NoDocumentException extends Exception { From 0e9fe88641259e8167dc21497a0cc7936dfce485 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 12:13:28 +0100 Subject: [PATCH 0058/1068] getReferenceMarks throws NoDocumentException --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4a5742fcd1d..1abd3b3c129 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -457,11 +457,19 @@ private static int citationTypeFromOptions( boolean withText, boolean inParenthe /* * */ - private XNameAccess getReferenceMarks() { + private XNameAccess getReferenceMarks() + throws NoDocumentException + { XReferenceMarksSupplier supplier = unoQI(XReferenceMarksSupplier.class, this.xCurrentComponent); - return supplier.getReferenceMarks(); + try { + XNameAccess res = supplier.getReferenceMarks(); + return Optional.of(res); + } catch ( Exception ex ){ + LOGGER.warn( "getReferenceMarks caught: ", ex ); + throw NoDocumentException("getReferenceMarks failed"); + } } private static boolean isJabRefReferenceMarkName( String name ){ From 8d275562e84bf855310eb499eff865d34a1df9d8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 12:14:46 +0100 Subject: [PATCH 0059/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1abd3b3c129..85ebb1b8c1d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -445,7 +445,7 @@ private void sortBibEntryList( List entries, } } - private static int citationTypeFromOptions( boolean withText, boolean inParenthesis ){ + private static int citationTypeFromOptions( boolean withText, boolean inParenthesis ) { if ( !withText ){ return OOBibBase.INVISIBLE_CIT ; } From 207bd9d693cddaef6acc70006fde6a428c699935 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 12:14:58 +0100 Subject: [PATCH 0060/1068] checkDocumentConnection --- .../org/jabref/gui/openoffice/OOBibBase.java | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 85ebb1b8c1d..9813d0e0000 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -222,9 +222,6 @@ public OOBibBase(Path loPath, this.xDesktop = simpleBootstrap(loPath); } - public boolean isConnectedToDocument() { - return this.xCurrentComponent != null; - } /* * section: selectDocument() @@ -375,6 +372,44 @@ public void selectDocument() this.userProperties = supp.getDocumentProperties().getUserDefinedProperties(); } this.propertySet = unoQI(XPropertySet.class, this.userProperties); + + // TODO: maybe we should install an event handler for document + // close: addCloseListener + // + // https://www.openoffice.org/api/docs/common/ref/com/sun/star/util/XCloseBroadcaster.html#addCloseListener + } + + private void forgetDocument(){ + this.xCurrentComponent = null ; + this.mxDoc = null ; + this.xViewCursorSupplier = null ; + this.xtext = null ; + this.mxDocFactory = null ; + this.userProperties = null ; + this.propertySet = null ; + } + public boolean isConnectedToDocument() { + return this.xCurrentComponent != null; + } + + public boolean checkDocumentConnection(){ + boolean res = true; + // These are set by selectDocument: + if (null == this.xCurrentComponent ){ res = false; } + if (null == this.mxDoc ){ res = false; } + if (null == this.xViewCursorSupplier ){ res = false; } + if (null == this.xtext ){ res = false; } + if (null == this.mxDocFactory ){ res = false; } + if (null == this.userProperties ){ res = false; } + if (null == this.propertySet ){ res = false; } + // + if ( ! res ){ + forgetDocument(); + return false; + } + // Attempt to check document is really available + // TODO + return true; } /* From 38069560e517f471c98305e2680c5725450aba74 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 12:18:09 +0100 Subject: [PATCH 0061/1068] checkDocumentConnection tests with getReferenceMarks --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9813d0e0000..16c7caa7dcc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -409,6 +409,12 @@ public boolean checkDocumentConnection(){ } // Attempt to check document is really available // TODO + try { + getReferenceMarks(); + } catch (NoDocumentException ex ) { + forgetDocument(); + return false; + } return true; } From af54e4842894c5f57ba52b5f8c9bb63c86b1506c Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 12:19:48 +0100 Subject: [PATCH 0062/1068] doc --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 16c7caa7dcc..29742abc28b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -495,7 +495,9 @@ private static int citationTypeFromOptions( boolean withText, boolean inParenthe : OOBibBase.AUTHORYEAR_INTEXT ); } - /* + /** + * + * @throws NoDocumentException * */ private XNameAccess getReferenceMarks() From 892a997e382d59395fef3cb97d0a46c095614afc Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 13:53:07 +0100 Subject: [PATCH 0063/1068] NoDocumentException propagated --- .../openoffice/ConnectionLostException.java | 6 +- .../openoffice/ManageCitationsDialogView.java | 23 +++++-- .../ManageCitationsDialogViewModel.java | 8 ++- .../gui/openoffice/NoDocumentException.java | 11 ++- .../org/jabref/gui/openoffice/OOBibBase.java | 68 ++++++++++++++----- .../gui/openoffice/OpenOfficePanel.java | 48 ++++++++++--- src/main/resources/l10n/JabRef_en.properties | 2 + 7 files changed, 132 insertions(+), 34 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java b/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java index 36fc16e5e3f..9101ee4cd0a 100644 --- a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java +++ b/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java @@ -1,7 +1,11 @@ package org.jabref.gui.openoffice; /** - * This exception is used to indicate that connection to OpenOffice has been lost. + * This exception is used to indicate that connection to OpenOffice + * has been lost. + * + * Note: related, but different: NoDocumentException + * */ class ConnectionLostException extends RuntimeException { diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index a312a4ef375..33befd351f1 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -56,14 +56,29 @@ public ManageCitationsDialogView(OOBibBase ooBase) { } @FXML - private void initialize() throws NoSuchElementException, WrappedTargetException, UnknownPropertyException { + private void initialize() + throws NoSuchElementException, + WrappedTargetException, + UnknownPropertyException, + NoDocumentException + { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); - citation.setCellValueFactory(cellData -> cellData.getValue().citationProperty()); - new ValueTableCellFactory().withGraphic(this::getText).install(citation); + citation.setCellValueFactory(cellData -> + cellData.getValue() + .citationProperty() + ); - extraInfo.setCellValueFactory(cellData -> cellData.getValue().extraInformationProperty()); + new ValueTableCellFactory() + .withGraphic(this::getText) + .install(citation); + + extraInfo.setCellValueFactory(cellData + -> + cellData.getValue() + .extraInformationProperty() + ); extraInfo.setEditable(true); citationsTableView.setEditable(true); diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 333edd757d4..600eeef5d81 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -31,7 +31,13 @@ public class ManageCitationsDialogViewModel { private final OOBibBase ooBase; private final DialogService dialogService; - public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) throws NoSuchElementException, WrappedTargetException, UnknownPropertyException { + public ManageCitationsDialogViewModel(OOBibBase ooBase, + DialogService dialogService) + throws NoSuchElementException, + WrappedTargetException, + UnknownPropertyException, + NoDocumentException + { this.ooBase = ooBase; this.dialogService = dialogService; diff --git a/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java b/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java index 170cbed69c7..b952b2adab3 100644 --- a/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java +++ b/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java @@ -1,10 +1,19 @@ package org.jabref.gui.openoffice; /** - * Exception used to indicate that + * Exception used to indicate that we cannot manipulate the current + * document. * * OOBibBase.selectDocument : NoDocumentException("No Writer documents found"); * OOBibBase.getReferenceMarks : NoDocumentException("getReferenceMarks failed"); + * + * Note: similar to ConnectionLostException, but here connection to + * OpenOffice may be intact, e.g. if the document is closed, but + * OpenOffice is not. + * + * On the other hand: it is not clear what this distinction buys + * us, since we do not connect to multiple documents. + * */ class NoDocumentException extends Exception { diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 29742abc28b..6ac36971869 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -508,10 +508,10 @@ private XNameAccess getReferenceMarks() this.xCurrentComponent); try { XNameAccess res = supplier.getReferenceMarks(); - return Optional.of(res); + return res; } catch ( Exception ex ){ LOGGER.warn( "getReferenceMarks caught: ", ex ); - throw NoDocumentException("getReferenceMarks failed"); + throw new NoDocumentException("getReferenceMarks failed"); } } @@ -555,7 +555,8 @@ private List getJabRefReferenceMarkNames(XNameAccess nameAccess) { public List getCitationEntries() throws NoSuchElementException, UnknownPropertyException, - WrappedTargetException + WrappedTargetException, + NoDocumentException { XNameAccess nameAccess = this.getReferenceMarks(); List names = this.getJabRefReferenceMarkNames(nameAccess); @@ -631,7 +632,9 @@ public void applyCitationEntries( List citationEntries ) * Or the first unused in this series, after removals. * */ - private String getUniqueReferenceMarkName(String bibtexKey, int type) { + private String getUniqueReferenceMarkName(String bibtexKey, int type) + throws NoDocumentException + { XNameAccess xNamedRefMarks = getReferenceMarks(); int i = 0; String name = BIB_CITATION + '_' + type + '_' + bibtexKey; @@ -715,7 +718,8 @@ public void insertEntry(List entries, IOException, CreationException, BibEntryNotFoundException, - UndefinedParagraphFormatException + UndefinedParagraphFormatException, + NoDocumentException { try { XTextCursor cursor; @@ -889,7 +893,8 @@ private List parseRefMarkNameToUniqueCitationKeys(String name) { */ private List findCitedKeys() throws NoSuchElementException, - WrappedTargetException + WrappedTargetException, + NoDocumentException { XNameAccess xNamedMarks = getReferenceMarks(); String[] names = xNamedMarks.getElementNames(); @@ -973,7 +978,8 @@ public List refreshCiteMarkers(List databases, PropertyVetoException, IOException, CreationException, - BibEntryNotFoundException + BibEntryNotFoundException, + NoDocumentException { try { return refreshCiteMarkersInternal(databases, style); @@ -1032,7 +1038,8 @@ private List refreshCiteMarkersInternal(List databases, UnknownPropertyException, PropertyVetoException, CreationException, - BibEntryNotFoundException + BibEntryNotFoundException, + NoDocumentException { List cited = findCitedKeys(); Map linkSourceBase = new HashMap<>(); @@ -1381,7 +1388,8 @@ private List getSortedReferenceMarks(final XNameAccess nameAccess) public void updateSortedReferenceMarks() throws WrappedTargetException, - NoSuchElementException + NoSuchElementException, + NoDocumentException { this.sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks()); } @@ -1395,7 +1403,8 @@ public void rebuildBibTextSection(List databases, CreationException, PropertyVetoException, UnknownPropertyException, - UndefinedParagraphFormatException + UndefinedParagraphFormatException, + NoDocumentException { List cited = findCitedKeys(); Map linkSourceBase = new HashMap<>(); @@ -1729,7 +1738,11 @@ private void insertReferenceMark(String name, String citationText, XTextCursor p position.collapseToEnd(); } - private void removeReferenceMark(String name) throws NoSuchElementException, WrappedTargetException { + private void removeReferenceMark(String name) + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException + { XNameAccess xReferenceMarks = getReferenceMarks(); if (xReferenceMarks.hasByName(name)) { Object referenceMark = xReferenceMarks.getByName(name); @@ -1780,9 +1793,17 @@ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, } public void combineCiteMarkers(List databases, OOBibStyle style) - throws IOException, WrappedTargetException, NoSuchElementException, IllegalArgumentException, - UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException, - BibEntryNotFoundException { + throws IOException, + WrappedTargetException, + NoSuchElementException, + IllegalArgumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException + { XNameAccess nameAccess = getReferenceMarks(); // TODO: doesn't work for citations in footnotes/tables List names = getSortedReferenceMarks(nameAccess); @@ -1862,9 +1883,17 @@ public void combineCiteMarkers(List databases, OOBibStyle style) * Combined markers are split, with a space inserted between. */ public void unCombineCiteMarkers(List databases, OOBibStyle style) - throws IOException, WrappedTargetException, NoSuchElementException, IllegalArgumentException, - UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException, - BibEntryNotFoundException { + throws IOException, + WrappedTargetException, + NoSuchElementException, + IllegalArgumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException + { XNameAccess nameAccess = getReferenceMarks(); // TODO: doesn't work for citations in footnotes/tables List names = getSortedReferenceMarks(nameAccess); @@ -1923,7 +1952,10 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) } public BibDatabase generateDatabase(List databases) - throws NoSuchElementException, WrappedTargetException { + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException + { BibDatabase resultDatabase = new BibDatabase(); List cited = findCitedKeys(); List entriesToInsert = new ArrayList<>(); diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 635d9469a31..2441acaf549 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -196,15 +196,20 @@ private void initPanel() { style.ensureUpToDate(); } - ooBase.updateSortedReferenceMarks(); + ooBase.updateSortedReferenceMarks(); // NoDocumentException List databases = getBaseList(); List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style); ooBase.rebuildBibTextSection(databases, style); if (!unresolvedKeys.isEmpty()) { - dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), - Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - unresolvedKeys.get(0))); + dialogService + .showErrorDialogAndWait( + Localization.lang + ("Unable to synchronize bibliography"), + Localization.lang + ("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", + unresolvedKeys.get(0) ) + ); } } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); @@ -212,6 +217,8 @@ private void initPanel() { reportUndefinedParagraphFormat(ex); } catch (ConnectionLostException ex) { showConnectionLostErrorMessage(); + } catch (NoDocumentException ex) { + showNoDocumentErrorMessage(); } catch (IOException ex) { LOGGER.warn("Problem with style file", ex); dialogService.showErrorDialogAndWait(Localization.lang("No valid style file defined"), @@ -234,6 +241,8 @@ private void initPanel() { ooBase.combineCiteMarkers(getBaseList(), style); } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); + } catch (NoDocumentException ex) { + showNoDocumentErrorMessage(); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | BibEntryNotFoundException ex) { @@ -246,6 +255,8 @@ private void initPanel() { unmerge.setOnAction(e -> { try { ooBase.unCombineCiteMarkers(getBaseList(), style); + } catch (NoDocumentException ex) { + showNoDocumentErrorMessage(); } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | @@ -303,7 +314,7 @@ private void exportEntries() { style.ensureUpToDate(); } - ooBase.updateSortedReferenceMarks(); + ooBase.updateSortedReferenceMarks(); // NoDocumentException List databases = getBaseList(); List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style); @@ -317,6 +328,8 @@ private void exportEntries() { BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase); this.frame.addTab(databaseContext, true); + } catch (NoDocumentException ex ) { + showNoDocumentErrorMessage(); } catch (BibEntryNotFoundException ex) { LOGGER.debug("BibEntry not found", ex); dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), @@ -504,8 +517,15 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP if (style == null) { style = loader.getUsedStyle(); } - ooBase.insertEntry(entries, database, getBaseList(), style, inParenthesis, withText, pageInfo, - ooPrefs.getSyncWhenCiting()); + ooBase.insertEntry(entries, + database, + getBaseList(), + style, + inParenthesis, + withText, + pageInfo, + ooPrefs.getSyncWhenCiting() + ); } catch (FileNotFoundException ex) { dialogService.showErrorDialogAndWait( @@ -513,6 +533,8 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP Localization.lang("You must select either a valid style file, or use one of the default styles.")); LOGGER.warn("Problem with style file", ex); + } catch (NoDocumentException ex) { + showNoDocumentErrorMessage(); } catch (ConnectionLostException ex) { showConnectionLostErrorMessage(); } catch (UndefinedCharacterFormatException ex) { @@ -582,8 +604,16 @@ private boolean checkThatEntriesHaveKeys(List entries) { } private void showConnectionLostErrorMessage() { - dialogService.showErrorDialogAndWait(Localization.lang("Connection lost"), - Localization.lang("Connection to OpenOffice/LibreOffice has been lost. " + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); + dialogService.showErrorDialogAndWait + (Localization.lang("Connection lost"), + Localization.lang + ("Connection to OpenOffice/LibreOffice has been lost. " + + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); + } + + private void showNoDocumentErrorMessage() { + dialogService.showErrorDialogAndWait(Localization.lang("Connection to document lost"), + Localization.lang("Connection to OpenOffice/LibreOffice document has been lost. " + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); } private void reportUndefinedParagraphFormat(UndefinedParagraphFormatException ex) { diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 56f6d51106f..4b0423e4e60 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1039,6 +1039,7 @@ Combine\ pairs\ of\ citations\ that\ are\ separated\ by\ spaces\ only=Combine pa Autodetection\ failed=Autodetection failed Please\ wait...=Please wait... Connection\ lost=Connection lost +Connection\ to\ document\ lost=Connection to document lost The\ paragraph\ format\ is\ controlled\ by\ the\ property\ 'ReferenceParagraphFormat'\ or\ 'ReferenceHeaderParagraphFormat'\ in\ the\ style\ file.=The paragraph format is controlled by the property 'ReferenceParagraphFormat' or 'ReferenceHeaderParagraphFormat' in the style file. The\ character\ format\ is\ controlled\ by\ the\ citation\ property\ 'CitationCharacterFormat'\ in\ the\ style\ file.=The character format is controlled by the citation property 'CitationCharacterFormat' in the style file. Automatically\ sync\ bibliography\ when\ inserting\ citations=Automatically sync bibliography when inserting citations @@ -1137,6 +1138,7 @@ Toggle\ print\ status=Toggle print status Update\ keywords=Update keywords Write\ values\ of\ special\ fields\ as\ separate\ fields\ to\ BibTeX=Write values of special fields as separate fields to BibTeX Connection\ to\ OpenOffice/LibreOffice\ has\ been\ lost.\ Please\ make\ sure\ OpenOffice/LibreOffice\ is\ running,\ and\ try\ to\ reconnect.=Connection to OpenOffice/LibreOffice has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect. +Connection\ to\ OpenOffice/LibreOffice\ document\ has\ been\ lost.\ Please\ make\ sure\ OpenOffice/LibreOffice\ is\ running,\ and\ try\ to\ reconnect.=Connection to OpenOffice/LibreOffice document has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect. JabRef\ will\ send\ at\ least\ one\ request\ per\ entry\ to\ a\ publisher.=JabRef will send at least one request per entry to a publisher. Correct\ the\ entry,\ and\ reopen\ editor\ to\ display/edit\ source.=Correct the entry, and reopen editor to display/edit source. Could\ not\ connect\ to\ running\ OpenOffice/LibreOffice.=Could not connect to running OpenOffice/LibreOffice. From 5c27a37b09805e3adc21689a2a4cd6f1fdb5f667 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 14:49:46 +0100 Subject: [PATCH 0064/1068] getSortedCitedEntries --- .../org/jabref/gui/openoffice/OOBibBase.java | 173 ++++++++++++++---- 1 file changed, 139 insertions(+), 34 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6ac36971869..348124ed655 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -379,6 +379,9 @@ public void selectDocument() // https://www.openoffice.org/api/docs/common/ref/com/sun/star/util/XCloseBroadcaster.html#addCloseListener } + /* + * TODO: GUI should be notified + */ private void forgetDocument(){ this.xCurrentComponent = null ; this.mxDoc = null ; @@ -388,6 +391,7 @@ private void forgetDocument(){ this.userProperties = null ; this.propertySet = null ; } + public boolean isConnectedToDocument() { return this.xCurrentComponent != null; } @@ -532,17 +536,6 @@ private static List filterIsJabRefReferenceMarkName( List names private List getJabRefReferenceMarkNames(XNameAccess nameAccess) { String[] names = nameAccess.getElementNames(); // Remove all reference marks that don't look like JabRef citations: - /* - * List result = new ArrayList<>(); - * if (names != null) { - * for (String name : names) { - * if (CITE_PATTERN.matcher(name).find()) { - * result.add(name); - * } - * } - * } - * return result; - */ if (names == null) { return new ArrayList<>(); } @@ -625,7 +618,8 @@ public void applyCitationEntries( List citationEntries ) // } } - /* + /** + * * The first occurrence of bibtexKey gets no serial number, the * second gets 0, the third 1 ... * @@ -645,6 +639,10 @@ private String getUniqueReferenceMarkName(String bibtexKey, int type) return name; } + /** + * This is what we get back from parsing a refMarkName + * + */ private class ParsedRefMark { public String i ; // "", "0", "1" ... public int type ; @@ -655,6 +653,11 @@ private class ParsedRefMark { this.citedKeys = citedKeys; } } + + /** + * Parse a refMarkName. + * + */ private Optional parseRefMarkName( String name ){ Matcher citeMatcher = CITE_PATTERN2.matcher(name); if (!citeMatcher.find()) { @@ -918,35 +921,35 @@ private List findCitedKeys() /** * @return LinkedHashMap, from BibEntry to BibDatabase * - * If a key is not found, BibEntry is new UndefinedBibtexEntry(key), BibDatabase is null. - * If key is found, then + * If a citedKey is not found, BibEntry is new UndefinedBibtexEntry(citedKey), BibDatabase is null. + * If citedKey is found, then * BibEntry is what we found, BibDatabase is the database we found it in. - * linkSourceBase.put(key, database); is called. + * linkSourceBase.put(citedKey, database); is called. * * So: - * - result has an entry for each key, in the same order - * - key in the entry is the same as the original key - * - on return linkSourceBase has an entry for the keys we did find + * - result has an entry for each citedKey, in the same order + * - citedKey in the entry is the same as the original citedKey + * - on return linkSourceBase has an entry for the citedKey we did find */ private Map findCitedEntries(List databases, - List keys, + List citedKeys, Map linkSourceBase) { Map entries = new LinkedHashMap<>(); - for (String key : keys) { + for (String citedKey : citedKeys) { boolean found = false; for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(key); + Optional entry = database.getEntryByCitationKey(citedKey); if (entry.isPresent()) { entries.put(entry.get(), database); - linkSourceBase.put(key, database); + linkSourceBase.put(citedKey, database); found = true; break; } } if (!found) { - entries.put(new UndefinedBibtexEntry(key), null); + entries.put(new UndefinedBibtexEntry(citedKey), null); } } return entries; @@ -991,8 +994,9 @@ public List refreshCiteMarkers(List databases, } } - private static Optional linkSourceBaseCiteKeyToBibEntry( Map linkSourceBase, - String citeKey ) + private static Optional linkSourceBaseCiteKeyToBibEntry + ( Map linkSourceBase, + String citeKey ) { BibDatabase database = linkSourceBase.get(citeKey); Optional res = ( (database == null) @@ -1002,10 +1006,11 @@ private static Optional linkSourceBaseCiteKeyToBibEntry( Map linkSourceBase, - String[] keys, // citeKeys - String namei // refMarkName - ) + private static BibEntry[] linkSourceBaseGetBibEntriesOfCiteKeys + ( Map linkSourceBase, + String[] keys, // citeKeys + String namei // refMarkName + ) throws BibEntryNotFoundException { BibEntry[] cEntries = new BibEntry[keys.length]; @@ -1029,8 +1034,97 @@ private static BibEntry[] linkSourceBaseGetBibEntriesOfCiteKeys( Map refreshCiteMarkersInternal(List databases, - OOBibStyle style) + private class GetSortedCitedEntriesResult { + Map linkSourceBase; + List citedKeys; + Map entries; + List refMarkNames; + public GetSortedCitedEntriesResult + ( + Map linkSourceBase, + List citedKeys, + Map entries, + List refMarkNames ) + { + this.linkSourceBase = linkSourceBase; + this.citedKeys = citedKeys; + this.entries = entries; + this.refMarkNames = refMarkNames; + } + } + + /** + * + * @return GetSortedCitedEntriesResult where + * + * linkSourceBase maps the citedKeys to the database we found it in + * + * refMarkNames : sortedReferenceMarks, + * except for style.isNumberEntries(), + * where we keep the order from xReferenceMarks.getElementNames() + * + * entries : from findCitedEntries() + * for style.isNumberEntries() reordered by entryComparator + * + * citedKeys : citeKey for each ref we found in the document. + * order: from findCitedKeys(), + * except for style.isNumberEntries() where reordered as entries + */ + private GetSortedCitedEntriesResult getSortedCitedEntries + ( List databases, + OOBibStyle style, + XNameAccess xReferenceMarks + ) + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException + { + Map linkSourceBase = new HashMap<>(); + + List cited = findCitedKeys(); + Map entries = + findCitedEntries(databases, cited, linkSourceBase); + + List names; + if (style.isSortByPosition()) { + // We need to sort the reference marks according to their + // order of appearance: + names = sortedReferenceMarks; + } else if (style.isNumberEntries()) { + // + // We need to sort the reference marks according to the + // sorting of the bibliographic entries: + // + SortedMap newMap = new TreeMap<>(entryComparator); + for (Map.Entry ee : entries.entrySet()) { + newMap.put(ee.getKey(), ee.getValue()); + } + entries = newMap; + // Rebuild the list of cited keys according to the sort order: + cited.clear(); + for (BibEntry entry : entries.keySet()) { + cited.add(entry.getCitationKey().orElse(null)); + } + // + names = Arrays.asList(xReferenceMarks.getElementNames()); + } else { + names = sortedReferenceMarks; + } + + // Remove all reference marks that don't look like JabRef citations: + names = filterIsJabRefReferenceMarkName( names ); + + return new GetSortedCitedEntriesResult( linkSourceBase, + cited, + entries, + names + ); + } + + private List refreshCiteMarkersInternal + ( List databases, + OOBibStyle style + ) throws WrappedTargetException, IllegalArgumentException, NoSuchElementException, @@ -1041,13 +1135,22 @@ private List refreshCiteMarkersInternal(List databases, BibEntryNotFoundException, NoDocumentException { - List cited = findCitedKeys(); + XNameAccess xReferenceMarks = getReferenceMarks(); + + GetSortedCitedEntriesResult sce = + getSortedCitedEntries( databases, style, xReferenceMarks ); + Map linkSourceBase = sce.linkSourceBase; + List cited = sce.citedKeys; + Map entries = ece.entries; + List names = sce.refMarkNames; + //***** + /* Map linkSourceBase = new HashMap<>(); + + List cited = findCitedKeys(); Map entries = findCitedEntries(databases, cited, linkSourceBase); - XNameAccess xReferenceMarks = getReferenceMarks(); - List names; if (style.isSortByPosition()) { // We need to sort the reference marks according to their @@ -1073,6 +1176,8 @@ private List refreshCiteMarkersInternal(List databases, // Remove all reference marks that don't look like JabRef citations: names = filterIsJabRefReferenceMarkName( names ); + */ + //********** Map numbers = new HashMap<>(); int lastNum = 0; From 9267f256872a9b77b32bbad639b1d7733fe0e2f4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 14:51:56 +0100 Subject: [PATCH 0065/1068] typo corr --- .../org/jabref/gui/openoffice/OOBibBase.java | 36 +------------------ 1 file changed, 1 insertion(+), 35 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 348124ed655..891b42b692b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1141,43 +1141,9 @@ private class GetSortedCitedEntriesResult { getSortedCitedEntries( databases, style, xReferenceMarks ); Map linkSourceBase = sce.linkSourceBase; List cited = sce.citedKeys; - Map entries = ece.entries; + Map entries = sce.entries; List names = sce.refMarkNames; //***** - /* - Map linkSourceBase = new HashMap<>(); - - List cited = findCitedKeys(); - Map entries = - findCitedEntries(databases, cited, linkSourceBase); - - List names; - if (style.isSortByPosition()) { - // We need to sort the reference marks according to their - // order of appearance: - names = sortedReferenceMarks; - } else if (style.isNumberEntries()) { - // We need to sort the reference marks according to the - // sorting of the bibliographic entries: - SortedMap newMap = new TreeMap<>(entryComparator); - for (Map.Entry ee : entries.entrySet()) { - newMap.put(ee.getKey(), ee.getValue()); - } - entries = newMap; - // Rebuild the list of cited keys according to the sort order: - cited.clear(); - for (BibEntry entry : entries.keySet()) { - cited.add(entry.getCitationKey().orElse(null)); - } - names = Arrays.asList(xReferenceMarks.getElementNames()); - } else { - names = sortedReferenceMarks; - } - - // Remove all reference marks that don't look like JabRef citations: - names = filterIsJabRefReferenceMarkName( names ); - */ - //********** Map numbers = new HashMap<>(); int lastNum = 0; From 52bc7665ebdc82acca9202795de47a89293e4f4c Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 16:11:13 +0100 Subject: [PATCH 0066/1068] comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 891b42b692b..a793e2074f3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -110,7 +110,7 @@ class OOBibBase { private static final String CHAR_STYLE_NAME = "CharStyleName"; - /* Types of in-text citation. + /* Types of in-text citation. (itcType) * Their numeric values are used in reference mark names. */ private static final int AUTHORYEAR_PAR = 1; From 835c9edc773dfba59b586279bb054fc1120dec04 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 16:12:05 +0100 Subject: [PATCH 0067/1068] itcType --- .../org/jabref/gui/openoffice/OOBibBase.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a793e2074f3..2e96747b699 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -626,14 +626,14 @@ public void applyCitationEntries( List citationEntries ) * Or the first unused in this series, after removals. * */ - private String getUniqueReferenceMarkName(String bibtexKey, int type) + private String getUniqueReferenceMarkName(String bibtexKey, int itcType) throws NoDocumentException { XNameAccess xNamedRefMarks = getReferenceMarks(); int i = 0; - String name = BIB_CITATION + '_' + type + '_' + bibtexKey; + String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; while (xNamedRefMarks.hasByName(name)) { - name = BIB_CITATION + i + '_' + type + '_' + bibtexKey; + name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; i++; } return name; @@ -645,11 +645,11 @@ private String getUniqueReferenceMarkName(String bibtexKey, int type) */ private class ParsedRefMark { public String i ; // "", "0", "1" ... - public int type ; + public int itcType ; // in-text-citation type public List citedKeys; - ParsedRefMark( String i, int type, List citedKeys ){ + ParsedRefMark( String i, int itcType, List citedKeys ){ this.i=i; - this.type = type; + this.itcType = itcType; this.citedKeys = citedKeys; } } @@ -665,8 +665,8 @@ private Optional parseRefMarkName( String name ){ } List keys = Arrays.asList( citeMatcher.group(3).split(",") ); String i = citeMatcher.group(1); - int type = Integer.parseInt( citeMatcher.group(2) ); - return( Optional.of( new ParsedRefMark( i, type, keys ) ) ); + int itcType = Integer.parseInt( citeMatcher.group(2) ); + return( Optional.of( new ParsedRefMark( i, itcType, keys ) ) ); } /** From 77569b603b67c82953482133939fbac383e0a6de Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 16:12:30 +0100 Subject: [PATCH 0068/1068] comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2e96747b699..19524646795 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1062,6 +1062,7 @@ private class GetSortedCitedEntriesResult { * refMarkNames : sortedReferenceMarks, * except for style.isNumberEntries(), * where we keep the order from xReferenceMarks.getElementNames() + * In any case: we apply filterIsJabRefReferenceMarkName. * * entries : from findCitedEntries() * for style.isNumberEntries() reordered by entryComparator From 7dc973c9647971fe242b5255a8f831c2ca62f3fa Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 16:12:52 +0100 Subject: [PATCH 0069/1068] comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 19524646795..e9205dbf523 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1146,8 +1146,10 @@ private class GetSortedCitedEntriesResult { List names = sce.refMarkNames; //***** + // For numbered citation style. Map( citedKey, number ) Map numbers = new HashMap<>(); int lastNum = 0; + // First compute citation markers for all citations: String[] citMarkers = new String[names.size()]; String[][] normCitMarkers = new String[names.size()][]; From 9c13d1db72dff5c7d6073ae3dec15cf17e34e953 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 16:13:39 +0100 Subject: [PATCH 0070/1068] findCitedEntryIndex reformat --- .../org/jabref/gui/openoffice/OOBibBase.java | 30 +++++-------------- 1 file changed, 8 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e9205dbf523..701ea0204a6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1518,34 +1518,20 @@ private Point findPosition(XTextViewCursor cursor, XTextRange range) { * Resolve the citation key from a citation reference marker name, * and look up the index of the key in a list of keys. * - * @param citRefName The name of the ReferenceMark representing the citation. - * @param keys A List of citation keys representing the entries in the bibliography. + * @param refMarkName The name of the ReferenceMark representing the citation. + * @param orderedCiteKeys A List of citation keys representing the entries in the bibliography. * @return the (1-based) indices of the cited keys, -1 if a key is not found. * Returns Collections.emptyList() if the ref name could not be resolved as a citation. */ - private List findCitedEntryIndex(String citRefName, List keys) { - /* - * Matcher citeMatcher = CITE_PATTERN.matcher(citRefName); - * if (citeMatcher.find()) { - * List keyStrings = Arrays.asList(citeMatcher.group(2).split(",")); - * List result = new ArrayList<>(keyStrings.size()); - * for (String key : keyStrings) { - * int ind = keys.indexOf(key); - * result.add(ind == -1 ? -1 : 1 + ind); - * } - * return result; - * } else { - * return Collections.emptyList(); - * } - */ - Optional< ParsedRefMark > op = parseRefMarkName( citRefName ); + private List findCitedEntryIndex(String refMarkName, List orderedCiteKeys) { + Optional< ParsedRefMark > op = parseRefMarkName( refMarkName ); if ( !op.isPresent() ){ return Collections.emptyList(); } - List keyStrings = op.get().citedKeys; - List result = new ArrayList<>(keyStrings.size()); - for (String key : keyStrings) { - int ind = keys.indexOf(key); + List keysCitedHere = op.get().citedKeys; + List result = new ArrayList<>(keysCitedHere.size()); + for (String key : keysCitedHere) { + int ind = orderedCiteKeys.indexOf(key); result.add(ind == -1 ? -1 : 1 + ind); } return result; From 2b719dd00f8d7b46a633309cc12d53455e6afa90 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 16:15:11 +0100 Subject: [PATCH 0071/1068] working on refreshCiteMarkersInternal --- .../org/jabref/gui/openoffice/OOBibBase.java | 114 ++++++++++-------- 1 file changed, 65 insertions(+), 49 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 701ea0204a6..3663c7dd660 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1164,76 +1164,92 @@ private class GetSortedCitedEntriesResult { Optional op = parseRefMarkName( namei ); if ( op.isPresent() ) { ParsedRefMark ov = op.get(); - int type = ov.type; - types[i] = type; // Remember the type in case we need to uniquefy. + int type = ov.itcType; + types[i] = type; // Remember the itcType in case we need to uniquefy. String[] keys = ov.citedKeys.stream().toArray(String[]::new); bibtexKeys[i] = keys; // - /* - BibEntry[] cEntries = new BibEntry[keys.length]; - // fill cEntries - for (int j = 0; j < keys.length; j++) { - String kj = keys[j]; - Optional tmpEntry = - linkSourceBaseCiteKeyToBibEntry( linkSourceBase, kj ); - if (tmpEntry.isPresent()) { - cEntries[j] = tmpEntry.get(); - } else { - LOGGER.info("Citation key not found: '" + kj + '\''); - LOGGER.info("Problem with reference mark: '" + namei + '\''); - String msg = Localization.lang("Could not resolve BibTeX entry" - +" for citation marker '%0'.", - namei - ); - throw new BibEntryNotFoundException(namei, msg); - } - } // for j - */ - BibEntry[] cEntries = linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, keys, namei ); - String[] normCitMarker = new String[keys.length]; - String citationMarker; + BibEntry[] cEntries = + linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, keys, namei ); + assert (cEntries.length == keys.length) ; + // + // normCitMarker[ cEntries.length ] null if missing + String[] normCitMarker = new String[cEntries.length]; + String citationMarker; // normCitMarker.replace( null -> "" ).join(",") + // + // fill normCitMarker, set citationMarker if (style.isCitationKeyCiteMarkers()) { + // StringBuilder sb = new StringBuilder(); - normCitMarkers[i] = new String[keys.length]; - for (int j = 0; j < keys.length; j++) { - normCitMarkers[i][j] = cEntries[j].getCitationKey().orElse(null); - sb.append(cEntries[j].getCitationKey().orElse("")); + normCitMarkers[i] = new String[cEntries.length]; + for (int j = 0; j < cEntries.length; j++) { + Optional cejKey = cEntries[j].getCitationKey(); + normCitMarkers[i][j] = cejKey.orElse(null); + sb.append(cejKey.orElse("")); if (j < (keys.length - 1)) { sb.append(','); } } citationMarker = sb.toString(); + // } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { - // We have sorted the citation markers according to their order of appearance, - // so we simply count up for each marker referring to a new entry: - List num = new ArrayList<>(keys.length); - for (int j = 0; j < keys.length; j++) { - if (cEntries[j] instanceof UndefinedBibtexEntry) { - num.add(j, -1); + // We have sorted the citation markers + // according to their order of appearance, so + // we simply count up for each marker + // referring to a new entry: + // + // num: Numbers for namei parts. (-1) for none. + // Passed to style.getNumCitationMarker() + List num = new ArrayList<>(cEntries.length); + // + // + // fill num while adjusting lastNum and filling numbers + // + for (int j = 0; j < cEntries.length; j++) { + BibEntry cej = cEntries[j]; + String kj = keys[j]; + if (cej instanceof UndefinedBibtexEntry) { + num.add(j, -1); // gets no number } else { - num.add(j, lastNum + 1); - if (numbers.containsKey(keys[j])) { - num.set(j, numbers.get(keys[j])); + if (numbers.containsKey(kj)) { + // already seen + num.add(j, numbers.get(kj)); } else { - numbers.put(keys[j], num.get(j)); - lastNum = num.get(j); + // new + lastNum++; // 1-based + num.add( j, lastNum); + numbers.put(kj, lastNum); } } } - citationMarker = style.getNumCitationMarker(num, minGroupingCount, false); - for (int j = 0; j < keys.length; j++) { - normCitMarker[j] = style.getNumCitationMarker(Collections.singletonList(num.get(j)), - minGroupingCount, false); + // set citationMarker + citationMarker = + style.getNumCitationMarker(num, minGroupingCount, false); + // + // fill normCitMarker + for (int j = 0; j < cEntries.length; j++) { + List numj = Collections.singletonList(num.get(j)); + normCitMarker[j] = + style.getNumCitationMarker( numj, minGroupingCount, false ); } } else { - // We need to find the number of the cited entry in the bibliography, - // and use that number for the cite marker: - List num = findCitedEntryIndex(names.get(i), cited); + // + // (numbered_citations, order_from bibliography) + // + // We need to find the number of the cited + // entry in the bibliography, and use that + // number for the cite marker: + // + List num = findCitedEntryIndex( namei, cited ); if (num.isEmpty()) { - throw new BibEntryNotFoundException(names.get(i), Localization - .lang("Could not resolve BibTeX entry for citation marker '%0'.", names.get(i))); + throw new BibEntryNotFoundException + ( names.get(i) + , Localization.lang + ( "Could not resolve BibTeX entry for citation marker '%0'." + , names.get(i) ) + ); } else { citationMarker = style.getNumCitationMarker(num, minGroupingCount, false); } From 4cf90653d53bc8bd78dc73876225c9f003fcfcdd Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 16:50:13 +0100 Subject: [PATCH 0072/1068] sortBibEntryArray --- .../org/jabref/gui/openoffice/OOBibBase.java | 81 +++++++++++++------ 1 file changed, 56 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3663c7dd660..870f7d9066e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -489,6 +489,18 @@ private void sortBibEntryList( List entries, entries.sort(this.entryComparator); } } + private void sortBibEntryArray( BibEntry[] entries, + OOBibStyle style ) + { + if (entries.length >= 1) { + return; + } + if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { + Arrays.sort(entries, yearAuthorTitleComparator); + } else { + Arrays.sort(entries, entryComparator); + } + } private static int citationTypeFromOptions( boolean withText, boolean inParenthesis ) { if ( !withText ){ @@ -1159,6 +1171,14 @@ private class GetSortedCitedEntriesResult { style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); int[] types = new int[names.size()]; + // + // + // fill: + // types[i] = ov.itcType + // bibtexKeys[i] = ov.citedKeys.toArray() + // citMarkers[i] = what goes in the text + // normCitMarkers[i][j] = for unification + // for (int i = 0; i < names.size(); i++) { final String namei = names.get(i); Optional op = parseRefMarkName( namei ); @@ -1250,47 +1270,55 @@ private class GetSortedCitedEntriesResult { ( "Could not resolve BibTeX entry for citation marker '%0'." , names.get(i) ) ); - } else { - citationMarker = style.getNumCitationMarker(num, minGroupingCount, false); } - + // + citationMarker = + style.getNumCitationMarker(num, minGroupingCount, false); + // normCitMarker for (int j = 0; j < keys.length; j++) { - List list = new ArrayList<>(1); - list.add(num.get(j)); - normCitMarker[j] = style.getNumCitationMarker(list, minGroupingCount, false); + List numj = Collections.singletonList(num.get(j)); + normCitMarker[j] = style.getNumCitationMarker(numj, minGroupingCount, false); } } } else { + sortBibEntryArray( cEntries, style ); + // Update key list to match the new sorting: + for (int j = 0; j < cEntries.length; j++) { + bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); + } - if (cEntries.length > 1) { - if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { - Arrays.sort(cEntries, yearAuthorTitleComparator); - } else { - Arrays.sort(cEntries, entryComparator); - } - // Update key list to match the new sorting: - for (int j = 0; j < cEntries.length; j++) { - bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); - } - } - - citationMarker = style.getCitationMarker(Arrays.asList(cEntries), entries, - type == OOBibBase.AUTHORYEAR_PAR, null, null); + citationMarker = style.getCitationMarker( Arrays.asList(cEntries), + entries, + type == OOBibBase.AUTHORYEAR_PAR, + null, + null ); // We need "normalized" (in parenthesis) markers for uniqueness checking purposes: for (int j = 0; j < cEntries.length; j++) { - normCitMarker[j] = style.getCitationMarker(Collections.singletonList(cEntries[j]), entries, - true, null, new int[] {-1}); + List cej = Collections.singletonList(cEntries[j]); + normCitMarker[j] = + style.getCitationMarker( cej, + entries, + true, + null, + new int[] {-1} + ); } } - citMarkers[i] = citationMarker; + citMarkers[i] = citationMarker; normCitMarkers[i] = normCitMarker; } // if (citeMatcher.find()) } // for i + // + // uniqiefiers + // uniquefiers.clear(); if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { - // See if there are duplicate citations marks referring to different entries. If so, we need to - // use uniquefiers: + // Numbered citations do not need uniquefiers + // + // + // See if there are duplicate citations marks referring to + // different entries. If so, we need to use uniquefiers: Map> refKeys = new HashMap<>(); Map> refNums = new HashMap<>(); for (int i = 0; i < citMarkers.length; i++) { @@ -1436,6 +1464,9 @@ private class GetSortedCitedEntriesResult { return unresolvedKeys; } + /** + * + */ private List getSortedReferenceMarks(final XNameAccess nameAccess) throws WrappedTargetException, NoSuchElementException From 3d32399228db9bc44c4acc00b82dbca5ceb062e2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 17:03:59 +0100 Subject: [PATCH 0073/1068] fill normCitMarker[j], not normCitMarkers[i][j] --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 870f7d9066e..602181ff80d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1201,10 +1201,9 @@ private class GetSortedCitedEntriesResult { if (style.isCitationKeyCiteMarkers()) { // StringBuilder sb = new StringBuilder(); - normCitMarkers[i] = new String[cEntries.length]; for (int j = 0; j < cEntries.length; j++) { Optional cejKey = cEntries[j].getCitationKey(); - normCitMarkers[i][j] = cejKey.orElse(null); + normCitMarker[j] = cejKey.orElse(null); sb.append(cejKey.orElse("")); if (j < (keys.length - 1)) { sb.append(','); From c9ccf7067c4a9119c5f5612d5e7fa3eba40c7f4c Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 21:03:23 +0100 Subject: [PATCH 0074/1068] rcmCitationMarkerForIsCitationKeyCiteMarkers --- .../org/jabref/gui/openoffice/OOBibBase.java | 37 ++++++++++++++----- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 602181ff80d..0f4cd95df1e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1134,6 +1134,31 @@ private class GetSortedCitedEntriesResult { ); } + private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] cEntries, OOBibStyle style ){ + + assert( style.isCitationKeyCiteMarkers() ); + + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < cEntries.length; j++) { + if (j > 0) { sb.append(','); } + Optional cejKey = cEntries[j].getCitationKey(); + sb.append(cejKey.orElse("")); + } + String citationMarker = sb.toString(); + return citationMarker; + } + + private static String[] rcmNormCitMarkersForIsCitationKeyCiteMarkers( BibEntry[] cEntries, OOBibStyle style ){ + assert( style.isCitationKeyCiteMarkers() ); + + String[] normCitMarker = new String[cEntries.length]; + for (int j = 0; j < cEntries.length; j++) { + Optional cejKey = cEntries[j].getCitationKey(); + normCitMarker[j] = cejKey.orElse(null); + } + return normCitMarker; + } + private List refreshCiteMarkersInternal ( List databases, OOBibStyle style @@ -1200,16 +1225,8 @@ private class GetSortedCitedEntriesResult { // fill normCitMarker, set citationMarker if (style.isCitationKeyCiteMarkers()) { // - StringBuilder sb = new StringBuilder(); - for (int j = 0; j < cEntries.length; j++) { - Optional cejKey = cEntries[j].getCitationKey(); - normCitMarker[j] = cejKey.orElse(null); - sb.append(cejKey.orElse("")); - if (j < (keys.length - 1)) { - sb.append(','); - } - } - citationMarker = sb.toString(); + citationMarker = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); + normCitMarker = rcmNormCitMarkersForIsCitationKeyCiteMarkers( cEntries, style ); // } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { From 67f9e4d45ceb7aba0ade685638f13e8f365781b8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 21:55:16 +0100 Subject: [PATCH 0075/1068] rcmNumForIsNumberEntriesIsSortByPosition --- .../org/jabref/gui/openoffice/OOBibBase.java | 112 +++++++++++++----- 1 file changed, 83 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0f4cd95df1e..b62c0f4b422 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1159,6 +1159,85 @@ private static String[] rcmNormCitMarkersForIsCitationKeyCiteMarkers( BibEntry[] return normCitMarker; } + private class CitationNumberingState { + public Map numbers; + public int lastNum; + CitationNumberingState(){ + // For numbered citation style. Map( citedKey, number ) + Map numbers = new HashMap<>(); + int lastNum = 0; + } + } + + /** + * Number citations. + * + * @param cEntries BibEntries to number. Numbering follows this order. + * @param keys : assert( keys[j] == cEntries[j].getCitationKey() ) + * @param style + * @param cns IN:keys already seen mapped to their number, and + * lastNum the largest number already used. (0 for + * none) + * + * OUT: the same, updated according to the numbers + * allocated here. + * + * @return an int for each cEntry. (-1) for UndefinedBibtexEntry + */ + private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry[] cEntries, + String[] keys, + OOBibStyle style, + CitationNumberingState cns ) + { + assert (style.isNumberEntries()); + assert (style.isSortByPosition()); + assert (cEntries.length == keys.length ); + if ( true ){ + /* + * If this never prints (or throws), we can drop the "keys" parameter. + */ + for (int j = 0; j < cEntries.length; j++) { + BibEntry cej = cEntries[j]; + String kj = keys[j]; + if ( kj != cej.getCitationKey().get() ){ + System.out.println + ( "keys != cEntries in rcmNumForIsNumberEntriesIsSortByPosition" ); + } + } + } + // + // We have sorted the citation markers + // according to their order of appearance, so + // we simply count up for each marker + // referring to a new entry: + // + // num: Numbers for namei parts. (-1) for none. + // Passed to style.getNumCitationMarker() + List num = new ArrayList<>(cEntries.length); + // + // + // fill num while adjusting lastNum and filling numbers + // + for (int j = 0; j < cEntries.length; j++) { + BibEntry cej = cEntries[j]; + String kj = keys[j]; // cej.getCitationKey().get() + if (cej instanceof UndefinedBibtexEntry) { + num.add(j, -1); // gets no cns.number + } else { + if (cns.numbers.containsKey(kj)) { + // already seen + num.add(j, cns.numbers.get(kj)); + } else { + // new + cns.lastNum++; // 1-based + num.add( j, cns.lastNum); + cns.numbers.put(kj, cns.lastNum); + } + } + } + return num; + } + private List refreshCiteMarkersInternal ( List databases, OOBibStyle style @@ -1183,9 +1262,8 @@ private static String[] rcmNormCitMarkersForIsCitationKeyCiteMarkers( BibEntry[] List names = sce.refMarkNames; //***** - // For numbered citation style. Map( citedKey, number ) - Map numbers = new HashMap<>(); - int lastNum = 0; + // // For numbered citation style. Map( citedKey, number ) + CitationNumberingState cns = new CitationNumberingState(); // First compute citation markers for all citations: String[] citMarkers = new String[names.size()]; @@ -1230,35 +1308,11 @@ private static String[] rcmNormCitMarkersForIsCitationKeyCiteMarkers( BibEntry[] // } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { - // We have sorted the citation markers - // according to their order of appearance, so - // we simply count up for each marker - // referring to a new entry: - // // num: Numbers for namei parts. (-1) for none. // Passed to style.getNumCitationMarker() - List num = new ArrayList<>(cEntries.length); - // + List num = + rcmNumForIsNumberEntriesIsSortByPosition( cEntries, keys, style, cns ); // - // fill num while adjusting lastNum and filling numbers - // - for (int j = 0; j < cEntries.length; j++) { - BibEntry cej = cEntries[j]; - String kj = keys[j]; - if (cej instanceof UndefinedBibtexEntry) { - num.add(j, -1); // gets no number - } else { - if (numbers.containsKey(kj)) { - // already seen - num.add(j, numbers.get(kj)); - } else { - // new - lastNum++; // 1-based - num.add( j, lastNum); - numbers.put(kj, lastNum); - } - } - } // set citationMarker citationMarker = style.getNumCitationMarker(num, minGroupingCount, false); From 6efaf6e8832e3ab773589bf067836c40294801f5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 22:02:00 +0100 Subject: [PATCH 0076/1068] findCitedEntryIndex moved up --- .../org/jabref/gui/openoffice/OOBibBase.java | 45 ++++++++++--------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b62c0f4b422..4f0bce5dcd8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1238,6 +1238,29 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry return num; } + /** + * Resolve the citation key from a citation reference marker name, + * and look up the index of the key in a list of keys. + * + * @param refMarkName The name of the ReferenceMark representing the citation. + * @param orderedCiteKeys A List of citation keys representing the entries in the bibliography. + * @return the (1-based) indices of the cited keys, -1 if a key is not found. + * Returns Collections.emptyList() if the ref name could not be resolved as a citation. + */ + private List findCitedEntryIndex(String refMarkName, List orderedCiteKeys) { + Optional< ParsedRefMark > op = parseRefMarkName( refMarkName ); + if ( !op.isPresent() ){ + return Collections.emptyList(); + } + List keysCitedHere = op.get().citedKeys; + List result = new ArrayList<>(keysCitedHere.size()); + for (String key : keysCitedHere) { + int ind = orderedCiteKeys.indexOf(key); + result.add(ind == -1 ? -1 : 1 + ind); + } + return result; + } + private List refreshCiteMarkersInternal ( List databases, OOBibStyle style @@ -1631,28 +1654,6 @@ private Point findPosition(XTextViewCursor cursor, XTextRange range) { } - /** - * Resolve the citation key from a citation reference marker name, - * and look up the index of the key in a list of keys. - * - * @param refMarkName The name of the ReferenceMark representing the citation. - * @param orderedCiteKeys A List of citation keys representing the entries in the bibliography. - * @return the (1-based) indices of the cited keys, -1 if a key is not found. - * Returns Collections.emptyList() if the ref name could not be resolved as a citation. - */ - private List findCitedEntryIndex(String refMarkName, List orderedCiteKeys) { - Optional< ParsedRefMark > op = parseRefMarkName( refMarkName ); - if ( !op.isPresent() ){ - return Collections.emptyList(); - } - List keysCitedHere = op.get().citedKeys; - List result = new ArrayList<>(keysCitedHere.size()); - for (String key : keysCitedHere) { - int ind = orderedCiteKeys.indexOf(key); - result.add(ind == -1 ? -1 : 1 + ind); - } - return result; - } private Map getSortedEntriesFromSortedRefMarks(List names, Map linkSourceBase) { From f16253b4607e05ec7fb9754dae79b9f49f9834cd Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 22:09:39 +0100 Subject: [PATCH 0077/1068] parseRefMarkName is static --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4f0bce5dcd8..66db4b509d2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -655,13 +655,13 @@ private String getUniqueReferenceMarkName(String bibtexKey, int itcType) * This is what we get back from parsing a refMarkName * */ - private class ParsedRefMark { + private static class ParsedRefMark { public String i ; // "", "0", "1" ... public int itcType ; // in-text-citation type public List citedKeys; ParsedRefMark( String i, int itcType, List citedKeys ){ - this.i=i; - this.itcType = itcType; + this.i = i; + this.itcType = itcType; this.citedKeys = citedKeys; } } @@ -670,7 +670,7 @@ private class ParsedRefMark { * Parse a refMarkName. * */ - private Optional parseRefMarkName( String name ){ + private static Optional parseRefMarkName( String name ){ Matcher citeMatcher = CITE_PATTERN2.matcher(name); if (!citeMatcher.find()) { return Optional.empty(); @@ -678,7 +678,7 @@ private Optional parseRefMarkName( String name ){ List keys = Arrays.asList( citeMatcher.group(3).split(",") ); String i = citeMatcher.group(1); int itcType = Integer.parseInt( citeMatcher.group(2) ); - return( Optional.of( new ParsedRefMark( i, itcType, keys ) ) ); + return( Optional.of( new OOBibBase.ParsedRefMark( i, itcType, keys ) ) ); } /** From cc986733bfe99ad8bdf18f08e9e4496221d0ac15 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 22:11:18 +0100 Subject: [PATCH 0078/1068] name -> refMarkName --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 66db4b509d2..e77541b11de 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -670,8 +670,8 @@ private static class ParsedRefMark { * Parse a refMarkName. * */ - private static Optional parseRefMarkName( String name ){ - Matcher citeMatcher = CITE_PATTERN2.matcher(name); + private static Optional parseRefMarkName( String refMarkName ){ + Matcher citeMatcher = CITE_PATTERN2.matcher(refMarkName); if (!citeMatcher.find()) { return Optional.empty(); } From c5aeb49e67a70b37236a76a5f66e4c53f7cad507 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 22:41:37 +0100 Subject: [PATCH 0079/1068] findCitedEntryIndices, dedup case style.isSortByPosition --- .../org/jabref/gui/openoffice/OOBibBase.java | 81 +++++++------------ 1 file changed, 30 insertions(+), 51 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e77541b11de..ff3eaf7d6e5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1134,7 +1134,9 @@ private class GetSortedCitedEntriesResult { ); } - private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] cEntries, OOBibStyle style ){ + private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] cEntries, + OOBibStyle style ) + { assert( style.isCitationKeyCiteMarkers() ); @@ -1148,7 +1150,9 @@ private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] c return citationMarker; } - private static String[] rcmNormCitMarkersForIsCitationKeyCiteMarkers( BibEntry[] cEntries, OOBibStyle style ){ + private static String[] rcmNormCitMarkersForIsCitationKeyCiteMarkers( BibEntry[] cEntries, + OOBibStyle style ) + { assert( style.isCitationKeyCiteMarkers() ); String[] normCitMarker = new String[cEntries.length]; @@ -1194,6 +1198,8 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry assert (cEntries.length == keys.length ); if ( true ){ /* + * TODO: do we need a test case? + * * If this never prints (or throws), we can drop the "keys" parameter. */ for (int j = 0; j < cEntries.length; j++) { @@ -1242,18 +1248,15 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry * Resolve the citation key from a citation reference marker name, * and look up the index of the key in a list of keys. * - * @param refMarkName The name of the ReferenceMark representing the citation. - * @param orderedCiteKeys A List of citation keys representing the entries in the bibliography. + * @param keysCitedHere The citation keys needing indices. + * @param orderedCiteKeys A List of citation keys representing the entries in the bibliography. * @return the (1-based) indices of the cited keys, -1 if a key is not found. * Returns Collections.emptyList() if the ref name could not be resolved as a citation. */ - private List findCitedEntryIndex(String refMarkName, List orderedCiteKeys) { - Optional< ParsedRefMark > op = parseRefMarkName( refMarkName ); - if ( !op.isPresent() ){ - return Collections.emptyList(); - } - List keysCitedHere = op.get().citedKeys; - List result = new ArrayList<>(keysCitedHere.size()); + private List findCitedEntryIndices( List keysCitedHere, + List orderedCiteKeys) + { + List result = new ArrayList<>(keysCitedHere.size()); for (String key : keysCitedHere) { int ind = orderedCiteKeys.indexOf(key); result.add(ind == -1 ? -1 : 1 + ind); @@ -1261,6 +1264,7 @@ private List findCitedEntryIndex(String refMarkName, List order return result; } + private List refreshCiteMarkersInternal ( List databases, OOBibStyle style @@ -1330,49 +1334,24 @@ private List findCitedEntryIndex(String refMarkName, List order normCitMarker = rcmNormCitMarkersForIsCitationKeyCiteMarkers( cEntries, style ); // } else if (style.isNumberEntries()) { + List num ; if (style.isSortByPosition()) { - // num: Numbers for namei parts. (-1) for none. - // Passed to style.getNumCitationMarker() - List num = - rcmNumForIsNumberEntriesIsSortByPosition( cEntries, keys, style, cns ); - // - // set citationMarker - citationMarker = - style.getNumCitationMarker(num, minGroupingCount, false); - // - // fill normCitMarker - for (int j = 0; j < cEntries.length; j++) { - List numj = Collections.singletonList(num.get(j)); - normCitMarker[j] = - style.getNumCitationMarker( numj, minGroupingCount, false ); - } + num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, keys, style, cns ); } else { - // - // (numbered_citations, order_from bibliography) - // - // We need to find the number of the cited - // entry in the bibliography, and use that - // number for the cite marker: - // - List num = findCitedEntryIndex( namei, cited ); - - if (num.isEmpty()) { - throw new BibEntryNotFoundException - ( names.get(i) - , Localization.lang - ( "Could not resolve BibTeX entry for citation marker '%0'." - , names.get(i) ) - ); - } - // - citationMarker = - style.getNumCitationMarker(num, minGroupingCount, false); - // normCitMarker - for (int j = 0; j < keys.length; j++) { - List numj = Collections.singletonList(num.get(j)); - normCitMarker[j] = style.getNumCitationMarker(numj, minGroupingCount, false); - } + num = findCitedEntryIndices( Arrays.asList(keys) , cited ); } + // + // set citationMarker + citationMarker = + style.getNumCitationMarker(num, minGroupingCount, false); + // + // fill normCitMarker + for (int j = 0; j < cEntries.length; j++) { + List numj = Collections.singletonList(num.get(j)); + normCitMarker[j] = + style.getNumCitationMarker( numj, minGroupingCount, false ); + } + // } else { sortBibEntryArray( cEntries, style ); // Update key list to match the new sorting: From 8e801a824371ce288c1d1eb38c341efa2b7acd70 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 23:11:56 +0100 Subject: [PATCH 0080/1068] add parens --- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 63120d0776e..794b2fbb148 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -606,7 +606,7 @@ private String getAuthorYearParenthesisMarker(List entries, Map 0 ? unlimA : maxA; String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); @@ -659,7 +659,7 @@ private String getAuthorYearInTextMarker(List entries, Map 0 ? unlimA : maxA; if (i > 0) { From 43cd9a16b98f946d32d237e9809459c6b40605a7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 23:18:53 +0100 Subject: [PATCH 0081/1068] comments --- .../org/jabref/gui/openoffice/OOBibBase.java | 46 ++++++++++++------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ff3eaf7d6e5..f566c9ac950 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -830,8 +830,8 @@ public void insertEntry(List entries, : style.getCitationMarker(entries, databaseMap, inParenthesis, - null, - null + null, // uniquefiers + null // unlimAuthors ); insertReferenceMark(bName, citeText, cursor, withText, style); } @@ -1353,26 +1353,35 @@ private List findCitedEntryIndices( List keysCitedHere, } // } else { + assert( !style.isCitationKeyCiteMarkers() ); + assert( !style.isNumberEntries() ); + // sort itcBlock sortBibEntryArray( cEntries, style ); + // // Update key list to match the new sorting: for (int j = 0; j < cEntries.length; j++) { bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); } - - citationMarker = style.getCitationMarker( Arrays.asList(cEntries), - entries, - type == OOBibBase.AUTHORYEAR_PAR, - null, - null ); - // We need "normalized" (in parenthesis) markers for uniqueness checking purposes: + // + citationMarker = style.getCitationMarker( Arrays.asList(cEntries), // entries + entries, // database + type == OOBibBase.AUTHORYEAR_PAR, // inParenthesis + null, // uniquefiers + null // unlimAuthors + ); + // + // We need "normalized" (in parenthesis) markers + // for uniqueness checking purposes: + // + // Fill normCitMarker for (int j = 0; j < cEntries.length; j++) { List cej = Collections.singletonList(cEntries[j]); normCitMarker[j] = - style.getCitationMarker( cej, - entries, - true, - null, - new int[] {-1} + style.getCitationMarker( cej, // entries + entries, // database + true, // inParenthesis + null, // uniquefiers + new int[] {-1} // unlimAuthors ); } } @@ -1476,8 +1485,13 @@ private List findCitedEntryIndices( List keysCitedHere, } } if (needsChange) { - citMarkers[j] = style.getCitationMarker(Arrays.asList(cEntries), entries, - types[j] == OOBibBase.AUTHORYEAR_PAR, uniquif, firstLimAuthors); + citMarkers[j] = + style.getCitationMarker( Arrays.asList(cEntries), + entries, + types[j] == OOBibBase.AUTHORYEAR_PAR, + uniquif, + firstLimAuthors + ); } } } From fda9e63537d58a7a2dbeb779edb0c439443bd660 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 23:39:48 +0100 Subject: [PATCH 0082/1068] comments --- .../org/jabref/gui/openoffice/OOBibBase.java | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f566c9ac950..d3b4571de9f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1355,6 +1355,8 @@ private List findCitedEntryIndices( List keysCitedHere, } else { assert( !style.isCitationKeyCiteMarkers() ); assert( !style.isNumberEntries() ); + // Citations in (Au1, Au2 2000) form + // // sort itcBlock sortBibEntryArray( cEntries, style ); // @@ -1391,21 +1393,29 @@ private List findCitedEntryIndices( List keysCitedHere, } // for i // - // uniqiefiers + // uniqiefiers "a", "b" in (2000a, 2000b) // uniquefiers.clear(); if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { - // Numbered citations do not need uniquefiers - // + // Only for normal citations. Numbered citations and + // citeKeys are already unique. + // // // See if there are duplicate citations marks referring to // different entries. If so, we need to use uniquefiers: - Map> refKeys = new HashMap<>(); + // + // refKeys: normCitMarker to bibtexkeys sharing it + // refNums: normCitMarker to (indices of normCitMarkers) + // + // Two lists keyed to the same marker correspond, and are + // ordered as in normCitMarkers[i][j] + // + Map> refKeys = new HashMap<>(); Map> refNums = new HashMap<>(); for (int i = 0; i < citMarkers.length; i++) { String[] markers = normCitMarkers[i]; // compare normalized markers, since the actual markers can be different for (int j = 0; j < markers.length; j++) { - String marker = markers[j]; + String marker = markers[j]; String currentKey = bibtexKeys[i][j]; if (refKeys.containsKey(marker)) { // Ok, we have seen this exact marker before. @@ -1415,6 +1425,7 @@ private List findCitedEntryIndices( List keysCitedHere, refNums.get(marker).add(i); } } else { + // add as new entry List l = new ArrayList<>(1); l.add(currentKey); refKeys.put(marker, l); From 3c6d67e621785a3033e829e76c63365aeabddea0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Feb 2021 23:42:20 +0100 Subject: [PATCH 0083/1068] drop unused variable refNums --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d3b4571de9f..53e06782721 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1405,13 +1405,11 @@ private List findCitedEntryIndices( List keysCitedHere, // different entries. If so, we need to use uniquefiers: // // refKeys: normCitMarker to bibtexkeys sharing it - // refNums: normCitMarker to (indices of normCitMarkers) // - // Two lists keyed to the same marker correspond, and are - // ordered as in normCitMarkers[i][j] + // The entries in the lists are ordered as in + // normCitMarkers[i][j] // Map> refKeys = new HashMap<>(); - Map> refNums = new HashMap<>(); for (int i = 0; i < citMarkers.length; i++) { String[] markers = normCitMarkers[i]; // compare normalized markers, since the actual markers can be different for (int j = 0; j < markers.length; j++) { @@ -1422,16 +1420,12 @@ private List findCitedEntryIndices( List keysCitedHere, if (!refKeys.get(marker).contains(currentKey)) { // ... but not for this entry. refKeys.get(marker).add(currentKey); - refNums.get(marker).add(i); } } else { // add as new entry List l = new ArrayList<>(1); l.add(currentKey); refKeys.put(marker, l); - List l2 = new ArrayList<>(1); - l2.add(i); - refNums.put(marker, l2); } } } From c743bfa574e54ea6b473afb99383e548296f74cf Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 10:05:29 +0100 Subject: [PATCH 0084/1068] comments --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 53e06782721..acdf0ef987c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -136,7 +136,9 @@ class OOBibBase { private XPropertySet propertySet; private XPropertyContainer userProperties; - + /* + * uniquefiers : maps bibtexkeys to letters ("a", "b") + */ private final Map uniquefiers = new HashMap<>(); private List sortedReferenceMarks; @@ -1393,7 +1395,7 @@ private List findCitedEntryIndices( List keysCitedHere, } // for i // - // uniqiefiers "a", "b" in (2000a, 2000b) + // uniquefiers "a", "b" in (2000a, 2000b) // uniquefiers.clear(); if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { @@ -1411,7 +1413,9 @@ private List findCitedEntryIndices( List keysCitedHere, // Map> refKeys = new HashMap<>(); for (int i = 0; i < citMarkers.length; i++) { - String[] markers = normCitMarkers[i]; // compare normalized markers, since the actual markers can be different + // compare normalized markers, since the actual + // markers can be different + String[] markers = normCitMarkers[i]; for (int j = 0; j < markers.length; j++) { String marker = markers[j]; String currentKey = bibtexKeys[i][j]; @@ -1499,7 +1503,7 @@ private List findCitedEntryIndices( List keysCitedHere, ); } } - } + } // if normalStyle // Refresh all reference marks with the citation markers we computed: boolean hadBibSection = getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null; From e651262546cb60728f27952e816600dd11c49317 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 10:06:30 +0100 Subject: [PATCH 0085/1068] format --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index acdf0ef987c..09e765a3998 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1433,22 +1433,26 @@ private List findCitedEntryIndices( List keysCitedHere, } } } - // Go through the collected lists and see where we need to uniquefy: + // Go through the collected lists and see where we need to + // uniquefy: for (Map.Entry> stringListEntry : refKeys.entrySet()) { List keys = stringListEntry.getValue(); if (keys.size() > 1) { // This marker appears for more than one unique entry: int uniq = 'a'; for (String key : keys) { - // Update the map of uniquefiers for the benefit of both the following generation of new - // citation markers, and for the method that builds the bibliography: + // Update the map of uniquefiers for the + // benefit of both the following generation of + // new citation markers, and for the method + // that builds the bibliography: uniquefiers.put(key, String.valueOf((char) uniq)); uniq++; } } } - // Finally, go through all citation markers, and update those referring to entries in our current list: + // Finally, go through all citation markers, and update + // those referring to entries in our current list: int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); for (int j = 0; j < bibtexKeys.length; j++) { From 1639396873a959117383c027d26bbe40b943db6d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 17:20:21 +0100 Subject: [PATCH 0086/1068] untabify --- .../org/jabref/gui/openoffice/OOBibBase.java | 1538 ++++++++--------- 1 file changed, 769 insertions(+), 769 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 09e765a3998..77a9819f468 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -102,11 +102,11 @@ class OOBibBase { private static final String BIB_CITATION = "JR_cite"; private static final Pattern CITE_PATTERN = - Pattern.compile(BIB_CITATION + "\\d*_(\\d*)_(.*)"); + Pattern.compile(BIB_CITATION + "\\d*_(\\d*)_(.*)"); // Another pattern, to also recover the "i" part private static final Pattern CITE_PATTERN2 = - Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); private static final String CHAR_STYLE_NAME = "CharStyleName"; @@ -118,7 +118,7 @@ class OOBibBase { private static final int INVISIBLE_CIT = 3; private static final Logger LOGGER = - LoggerFactory.getLogger(OOBibBase.class); + LoggerFactory.getLogger(OOBibBase.class); /* variables */ private final DialogService dialogService; @@ -149,9 +149,9 @@ class OOBibBase { * available, otherwise null */ private static T unoQI(Class zInterface, - Object object) + Object object) { - return UnoRuntime.queryInterface( zInterface, object ); + return UnoRuntime.queryInterface( zInterface, object ); } /* @@ -164,8 +164,8 @@ private static T unoQI(Class zInterface, */ private XDesktop simpleBootstrap(Path loPath) - throws CreationException, - BootstrapException + throws CreationException, + BootstrapException { // Get the office component context: XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); @@ -181,45 +181,45 @@ private XDesktop simpleBootstrap(Path loPath) } XDesktop result = unoQI(XDesktop.class, desktop); - // TODO: useless call? - if ( run_useless_parts ){ - unoQI(XComponentLoader.class, desktop); - } + // TODO: useless call? + if ( run_useless_parts ){ + unoQI(XComponentLoader.class, desktop); + } return result; } public OOBibBase(Path loPath, - boolean atEnd, - DialogService dialogService - ) throws IllegalAccessException, - InvocationTargetException, - BootstrapException, - CreationException, - IOException, - ClassNotFoundException + boolean atEnd, + DialogService dialogService + ) throws IllegalAccessException, + InvocationTargetException, + BootstrapException, + CreationException, + IOException, + ClassNotFoundException { this.dialogService = dialogService; - { - FieldComparator a = new FieldComparator(StandardField.AUTHOR); - FieldComparator y = new FieldComparator(StandardField.YEAR); - FieldComparator t = new FieldComparator(StandardField.TITLE); - - { - List> ayt = new ArrayList<>(3); - ayt.add(a); - ayt.add(y); - ayt.add(t); - this.entryComparator= new FieldComparatorStack<>(ayt); - } - { - List> yat = new ArrayList<>(3); - yat.add(y); - yat.add(a); - yat.add(t); - this.yearAuthorTitleComparator = new FieldComparatorStack<>(yat); - } - } + { + FieldComparator a = new FieldComparator(StandardField.AUTHOR); + FieldComparator y = new FieldComparator(StandardField.YEAR); + FieldComparator t = new FieldComparator(StandardField.TITLE); + + { + List> ayt = new ArrayList<>(3); + ayt.add(a); + ayt.add(y); + ayt.add(t); + this.entryComparator= new FieldComparatorStack<>(ayt); + } + { + List> yat = new ArrayList<>(3); + yat.add(y); + yat.add(a); + yat.add(t); + this.yearAuthorTitleComparator = new FieldComparatorStack<>(yat); + } + } this.atEnd = atEnd; this.xDesktop = simpleBootstrap(loPath); } @@ -230,8 +230,8 @@ public OOBibBase(Path loPath, */ private static List getTextDocuments( XDesktop desktop ) - throws NoSuchElementException, - WrappedTargetException + throws NoSuchElementException, + WrappedTargetException { List result = new ArrayList<>(); @@ -256,59 +256,59 @@ private static Optional getDocumentTitle(XTextDocument doc) { return Optional.empty(); } - try { - XFrame frame = doc.getCurrentController().getFrame(); - Object frame_title_obj = OOUtil.getProperty( frame , "Title"); - String frame_title_str = String.valueOf(frame_title_obj); - return Optional.of(frame_title_str); - } catch (UnknownPropertyException | WrappedTargetException e) { - LOGGER.warn("Could not get document title", e); - return Optional.empty(); - } + try { + XFrame frame = doc.getCurrentController().getFrame(); + Object frame_title_obj = OOUtil.getProperty( frame , "Title"); + String frame_title_str = String.valueOf(frame_title_obj); + return Optional.of(frame_title_str); + } catch (UnknownPropertyException | WrappedTargetException e) { + LOGGER.warn("Could not get document title", e); + return Optional.empty(); + } } private static XTextDocument selectDocumentDialog(List list, - DialogService dialogService) + DialogService dialogService) { - class DocumentTitleViewModel { + class DocumentTitleViewModel { - private final XTextDocument xTextDocument; - private final String description; + private final XTextDocument xTextDocument; + private final String description; - public DocumentTitleViewModel(XTextDocument xTextDocument) { - this.xTextDocument = xTextDocument; - this.description = OOBibBase.getDocumentTitle(xTextDocument).orElse(""); - } + public DocumentTitleViewModel(XTextDocument xTextDocument) { + this.xTextDocument = xTextDocument; + this.description = OOBibBase.getDocumentTitle(xTextDocument).orElse(""); + } - public XTextDocument getXtextDocument() { - return xTextDocument; - } + public XTextDocument getXtextDocument() { + return xTextDocument; + } - @Override - public String toString() { - return description; - } - } + @Override + public String toString() { + return description; + } + } List viewModel = - list.stream() - .map( DocumentTitleViewModel::new ) - .collect(Collectors.toList()); + list.stream() + .map( DocumentTitleViewModel::new ) + .collect(Collectors.toList()); // This whole method is part of a background task when // auto-detecting instances, so we need to show dialog in FX // thread Optional selectedDocument = - dialogService - .showChoiceDialogAndWait( - Localization.lang("Select document"), - Localization.lang("Found documents:"), - Localization.lang("Use selected document"), - viewModel - ); + dialogService + .showChoiceDialogAndWait( + Localization.lang("Select document"), + Localization.lang("Found documents:"), + Localization.lang("Use selected document"), + viewModel + ); return - selectedDocument - .map( DocumentTitleViewModel::getXtextDocument ) - .orElse(null); + selectedDocument + .map( DocumentTitleViewModel::getXtextDocument ) + .orElse(null); } /** Choose a document to work with. @@ -324,43 +324,43 @@ public String toString() { * */ public void selectDocument() - throws NoDocumentException, - NoSuchElementException, - WrappedTargetException + throws NoDocumentException, + NoSuchElementException, + WrappedTargetException { - { - XTextDocument selected; - List textDocumentList = getTextDocuments(this.xDesktop); - if (textDocumentList.isEmpty()) { - throw new NoDocumentException("No Writer documents found"); - } else if (textDocumentList.size() == 1) { - // Get the only one - selected = textDocumentList.get(0); - } else { - // Bring up a dialog - selected = - OOBibBase.selectDocumentDialog(textDocumentList, - this.dialogService); - } - - if (selected == null) { - return; - } - this.xCurrentComponent = unoQI(XComponent.class, selected); - this.mxDoc = selected; - } - - - // TODO: what is the point of the next line? Does it have a side effect? - if ( run_useless_parts ){ - unoQI(XDocumentIndexesSupplier.class, xCurrentComponent); - } - - { - XModel mo = unoQI(XModel.class, this.xCurrentComponent); - XController co = mo.getCurrentController(); - this.xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); - } + { + XTextDocument selected; + List textDocumentList = getTextDocuments(this.xDesktop); + if (textDocumentList.isEmpty()) { + throw new NoDocumentException("No Writer documents found"); + } else if (textDocumentList.size() == 1) { + // Get the only one + selected = textDocumentList.get(0); + } else { + // Bring up a dialog + selected = + OOBibBase.selectDocumentDialog(textDocumentList, + this.dialogService); + } + + if (selected == null) { + return; + } + this.xCurrentComponent = unoQI(XComponent.class, selected); + this.mxDoc = selected; + } + + + // TODO: what is the point of the next line? Does it have a side effect? + if ( run_useless_parts ){ + unoQI(XDocumentIndexesSupplier.class, xCurrentComponent); + } + + { + XModel mo = unoQI(XModel.class, this.xCurrentComponent); + XController co = mo.getCurrentController(); + this.xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); + } // get a reference to the body text of the document this.xtext = this.mxDoc.getText(); @@ -368,30 +368,30 @@ public void selectDocument() // Access the text document's multi service factory: this.mxDocFactory = unoQI(XMultiServiceFactory.class, this.mxDoc); - { - XDocumentPropertiesSupplier supp = - unoQI(XDocumentPropertiesSupplier.class, this.mxDoc); - this.userProperties = supp.getDocumentProperties().getUserDefinedProperties(); - } + { + XDocumentPropertiesSupplier supp = + unoQI(XDocumentPropertiesSupplier.class, this.mxDoc); + this.userProperties = supp.getDocumentProperties().getUserDefinedProperties(); + } this.propertySet = unoQI(XPropertySet.class, this.userProperties); - // TODO: maybe we should install an event handler for document - // close: addCloseListener - // - // https://www.openoffice.org/api/docs/common/ref/com/sun/star/util/XCloseBroadcaster.html#addCloseListener + // TODO: maybe we should install an event handler for document + // close: addCloseListener + // + // https://www.openoffice.org/api/docs/common/ref/com/sun/star/util/XCloseBroadcaster.html#addCloseListener } /* * TODO: GUI should be notified */ private void forgetDocument(){ - this.xCurrentComponent = null ; - this.mxDoc = null ; - this.xViewCursorSupplier = null ; - this.xtext = null ; - this.mxDocFactory = null ; - this.userProperties = null ; - this.propertySet = null ; + this.xCurrentComponent = null ; + this.mxDoc = null ; + this.xViewCursorSupplier = null ; + this.xtext = null ; + this.mxDocFactory = null ; + this.userProperties = null ; + this.propertySet = null ; } public boolean isConnectedToDocument() { @@ -399,29 +399,29 @@ public boolean isConnectedToDocument() { } public boolean checkDocumentConnection(){ - boolean res = true; - // These are set by selectDocument: - if (null == this.xCurrentComponent ){ res = false; } - if (null == this.mxDoc ){ res = false; } - if (null == this.xViewCursorSupplier ){ res = false; } - if (null == this.xtext ){ res = false; } - if (null == this.mxDocFactory ){ res = false; } - if (null == this.userProperties ){ res = false; } - if (null == this.propertySet ){ res = false; } - // - if ( ! res ){ - forgetDocument(); - return false; - } - // Attempt to check document is really available - // TODO - try { - getReferenceMarks(); - } catch (NoDocumentException ex ) { - forgetDocument(); - return false; - } - return true; + boolean res = true; + // These are set by selectDocument: + if (null == this.xCurrentComponent ){ res = false; } + if (null == this.mxDoc ){ res = false; } + if (null == this.xViewCursorSupplier ){ res = false; } + if (null == this.xtext ){ res = false; } + if (null == this.mxDocFactory ){ res = false; } + if (null == this.userProperties ){ res = false; } + if (null == this.propertySet ){ res = false; } + // + if ( ! res ){ + forgetDocument(); + return false; + } + // Attempt to check document is really available + // TODO + try { + getReferenceMarks(); + } catch (NoDocumentException ex ) { + forgetDocument(); + return false; + } + return true; } /* @@ -434,44 +434,44 @@ public Optional getCurrentDocumentTitle() { private Optional getCustomProperty(String property) - throws UnknownPropertyException, - WrappedTargetException + throws UnknownPropertyException, + WrappedTargetException { - assert (this.propertySet != null); + assert (this.propertySet != null); - XPropertySetInfo psi = - this.propertySet - .getPropertySetInfo(); + XPropertySetInfo psi = + this.propertySet + .getPropertySetInfo(); if (psi.hasPropertyByName(property)) { - String v = - this.propertySet - .getPropertyValue(property) - .toString(); + String v = + this.propertySet + .getPropertyValue(property) + .toString(); return Optional.ofNullable(v); } return Optional.empty(); } private void setCustomProperty(String property, String value) - throws UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException + throws UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException { - XPropertySetInfo psi = - this.propertySet - .getPropertySetInfo(); + XPropertySetInfo psi = + this.propertySet + .getPropertySetInfo(); if (psi.hasPropertyByName(property)) { this.userProperties.removeProperty(property); } if (value != null) { this.userProperties - .addProperty(property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value) - ); + .addProperty(property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value) + ); } } @@ -480,37 +480,37 @@ private void setCustomProperty(String property, String value) */ private void sortBibEntryList( List entries, - OOBibStyle style ) + OOBibStyle style ) { - if (entries.size() <= 1){ - return; - } - if (style.getBooleanCitProperty( OOBibStyle.MULTI_CITE_CHRONOLOGICAL )) { - entries.sort(this.yearAuthorTitleComparator); - } else { - entries.sort(this.entryComparator); - } + if (entries.size() <= 1){ + return; + } + if (style.getBooleanCitProperty( OOBibStyle.MULTI_CITE_CHRONOLOGICAL )) { + entries.sort(this.yearAuthorTitleComparator); + } else { + entries.sort(this.entryComparator); + } } private void sortBibEntryArray( BibEntry[] entries, - OOBibStyle style ) + OOBibStyle style ) { - if (entries.length >= 1) { - return; - } - if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { - Arrays.sort(entries, yearAuthorTitleComparator); - } else { - Arrays.sort(entries, entryComparator); - } + if (entries.length >= 1) { + return; + } + if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { + Arrays.sort(entries, yearAuthorTitleComparator); + } else { + Arrays.sort(entries, entryComparator); + } } private static int citationTypeFromOptions( boolean withText, boolean inParenthesis ) { - if ( !withText ){ - return OOBibBase.INVISIBLE_CIT ; - } - return ( inParenthesis - ? OOBibBase.AUTHORYEAR_PAR - : OOBibBase.AUTHORYEAR_INTEXT ); + if ( !withText ){ + return OOBibBase.INVISIBLE_CIT ; + } + return ( inParenthesis + ? OOBibBase.AUTHORYEAR_PAR + : OOBibBase.AUTHORYEAR_INTEXT ); } /** @@ -519,29 +519,29 @@ private static int citationTypeFromOptions( boolean withText, boolean inParenthe * */ private XNameAccess getReferenceMarks() - throws NoDocumentException + throws NoDocumentException { XReferenceMarksSupplier supplier = - unoQI(XReferenceMarksSupplier.class, - this.xCurrentComponent); - try { - XNameAccess res = supplier.getReferenceMarks(); - return res; - } catch ( Exception ex ){ - LOGGER.warn( "getReferenceMarks caught: ", ex ); - throw new NoDocumentException("getReferenceMarks failed"); - } + unoQI(XReferenceMarksSupplier.class, + this.xCurrentComponent); + try { + XNameAccess res = supplier.getReferenceMarks(); + return res; + } catch ( Exception ex ){ + LOGGER.warn( "getReferenceMarks caught: ", ex ); + throw new NoDocumentException("getReferenceMarks failed"); + } } private static boolean isJabRefReferenceMarkName( String name ){ - return (CITE_PATTERN.matcher(name).find()); + return (CITE_PATTERN.matcher(name).find()); } private static List filterIsJabRefReferenceMarkName( List names ) { - return ( names - .stream() - .filter( OOBibBase::isJabRefReferenceMarkName ) - .collect(Collectors.toList()) - ); + return ( names + .stream() + .filter( OOBibBase::isJabRefReferenceMarkName ) + .collect(Collectors.toList()) + ); } /* @@ -550,33 +550,33 @@ private static List filterIsJabRefReferenceMarkName( List names private List getJabRefReferenceMarkNames(XNameAccess nameAccess) { String[] names = nameAccess.getElementNames(); // Remove all reference marks that don't look like JabRef citations: - if (names == null) { - return new ArrayList<>(); - } - return filterIsJabRefReferenceMarkName( Arrays.asList( names ) ); + if (names == null) { + return new ArrayList<>(); + } + return filterIsJabRefReferenceMarkName( Arrays.asList( names ) ); } /** * */ public List getCitationEntries() - throws NoSuchElementException, - UnknownPropertyException, - WrappedTargetException, - NoDocumentException + throws NoSuchElementException, + UnknownPropertyException, + WrappedTargetException, + NoDocumentException { XNameAccess nameAccess = this.getReferenceMarks(); List names = this.getJabRefReferenceMarkNames(nameAccess); - List citations = new ArrayList(names.size()); + List citations = new ArrayList(names.size()); for (String name : names) { CitationEntry entry = - new CitationEntry(name, - this.getCitationContext(nameAccess, name, 30, 30, true), - this.getCustomProperty(name) - ); + new CitationEntry(name, + this.getCitationContext(nameAccess, name, 30, 30, true), + this.getCustomProperty(name) + ); citations.add(entry); } - return citations; + return citations; } /** @@ -598,38 +598,38 @@ public List getCitationEntries() * */ public void applyCitationEntries( List citationEntries ) - throws UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException + throws UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException { - // Leave exceptions to the caller. - // - // Note: not catching exceptions here means nothing is applied - // after the first problematic entry. We might catch and - // collect messages here. - // - // try { - for (CitationEntry entry : citationEntries) { - Optional pageInfo = entry.getPageInfo(); - if (pageInfo.isPresent()) { - this.setCustomProperty( entry.getRefMarkName(), pageInfo.get() ); - } else { - // TODO: if pageInfo is not present, or is empty: - // maybe we should remove it from the document. - } - } - // } catch (UnknownPropertyException - // | NotRemoveableException - // | PropertyExistException - // | IllegalTypeException - // | IllegalArgumentException ex) - // { - // LOGGER.warn("Problem modifying citation", ex); - // dialogService.showErrorDialogAndWait( - // Localization.lang("Problem modifying citation"), ex); - // } + // Leave exceptions to the caller. + // + // Note: not catching exceptions here means nothing is applied + // after the first problematic entry. We might catch and + // collect messages here. + // + // try { + for (CitationEntry entry : citationEntries) { + Optional pageInfo = entry.getPageInfo(); + if (pageInfo.isPresent()) { + this.setCustomProperty( entry.getRefMarkName(), pageInfo.get() ); + } else { + // TODO: if pageInfo is not present, or is empty: + // maybe we should remove it from the document. + } + } + // } catch (UnknownPropertyException + // | NotRemoveableException + // | PropertyExistException + // | IllegalTypeException + // | IllegalArgumentException ex) + // { + // LOGGER.warn("Problem modifying citation", ex); + // dialogService.showErrorDialogAndWait( + // Localization.lang("Problem modifying citation"), ex); + // } } /** @@ -641,7 +641,7 @@ public void applyCitationEntries( List citationEntries ) * */ private String getUniqueReferenceMarkName(String bibtexKey, int itcType) - throws NoDocumentException + throws NoDocumentException { XNameAccess xNamedRefMarks = getReferenceMarks(); int i = 0; @@ -658,14 +658,14 @@ private String getUniqueReferenceMarkName(String bibtexKey, int itcType) * */ private static class ParsedRefMark { - public String i ; // "", "0", "1" ... - public int itcType ; // in-text-citation type - public List citedKeys; - ParsedRefMark( String i, int itcType, List citedKeys ){ - this.i = i; - this.itcType = itcType; - this.citedKeys = citedKeys; - } + public String i ; // "", "0", "1" ... + public int itcType ; // in-text-citation type + public List citedKeys; + ParsedRefMark( String i, int itcType, List citedKeys ){ + this.i = i; + this.itcType = itcType; + this.citedKeys = citedKeys; + } } /** @@ -675,12 +675,12 @@ private static class ParsedRefMark { private static Optional parseRefMarkName( String refMarkName ){ Matcher citeMatcher = CITE_PATTERN2.matcher(refMarkName); if (!citeMatcher.find()) { - return Optional.empty(); - } - List keys = Arrays.asList( citeMatcher.group(3).split(",") ); - String i = citeMatcher.group(1); - int itcType = Integer.parseInt( citeMatcher.group(2) ); - return( Optional.of( new OOBibBase.ParsedRefMark( i, itcType, keys ) ) ); + return Optional.empty(); + } + List keys = Arrays.asList( citeMatcher.group(3).split(",") ); + String i = citeMatcher.group(1); + int itcType = Integer.parseInt( citeMatcher.group(2) ); + return( Optional.of( new OOBibBase.ParsedRefMark( i, itcType, keys ) ) ); } /** @@ -715,69 +715,69 @@ private static Optional parseRefMarkName( String refMarkName ){ * */ public void insertEntry(List entries, - BibDatabase database, + BibDatabase database, List allBases, - OOBibStyle style, + OOBibStyle style, boolean inParenthesis, - boolean withText, - String pageInfo, - boolean sync - ) - throws IllegalArgumentException, - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - UndefinedCharacterFormatException, - WrappedTargetException, - NoSuchElementException, - PropertyVetoException, - IOException, - CreationException, - BibEntryNotFoundException, - UndefinedParagraphFormatException, - NoDocumentException + boolean withText, + String pageInfo, + boolean sync + ) + throws IllegalArgumentException, + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + UndefinedCharacterFormatException, + WrappedTargetException, + NoSuchElementException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException, + UndefinedParagraphFormatException, + NoDocumentException { try { - XTextCursor cursor; - { - // Get the cursor positioned by the user. - XTextViewCursor xViewCursor = - this.xViewCursorSupplier - .getViewCursor(); - if ( true ){ - cursor = xViewCursor; - } else { - // - // An XTextCursor is sufficient for the rest. - // - // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/\ - // Example:_Visible_Cursor_Position - // - // We create a model cursor at the current view cursor - // position with the following steps: we get the Text - // service from the TextViewCursor, the cursor is an - // XTextRange and has therefore a method getText() - // - XText xDocumentText = xViewCursor.getText(); - // the text creates a model cursor from the viewcursor - XTextCursor xModelCursor = - xDocumentText.createTextCursorByRange(xViewCursor.getStart()); - // use the xModelCursor - cursor = xModelCursor; - } - } - - sortBibEntryList( entries, style ); + XTextCursor cursor; + { + // Get the cursor positioned by the user. + XTextViewCursor xViewCursor = + this.xViewCursorSupplier + .getViewCursor(); + if ( true ){ + cursor = xViewCursor; + } else { + // + // An XTextCursor is sufficient for the rest. + // + // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/\ + // Example:_Visible_Cursor_Position + // + // We create a model cursor at the current view cursor + // position with the following steps: we get the Text + // service from the TextViewCursor, the cursor is an + // XTextRange and has therefore a method getText() + // + XText xDocumentText = xViewCursor.getText(); + // the text creates a model cursor from the viewcursor + XTextCursor xModelCursor = + xDocumentText.createTextCursorByRange(xViewCursor.getStart()); + // use the xModelCursor + cursor = xModelCursor; + } + } + + sortBibEntryList( entries, style ); String keyString = - String.join(",", - entries.stream() - .map( entry -> entry.getCitationKey().orElse("") ) - .collect( Collectors.toList() ) - ); - // Generate unique bookmark-name - int citationType = citationTypeFromOptions( withText, inParenthesis ); + String.join(",", + entries.stream() + .map( entry -> entry.getCitationKey().orElse("") ) + .collect( Collectors.toList() ) + ); + // Generate unique bookmark-name + int citationType = citationTypeFromOptions( withText, inParenthesis ); String bName = getUniqueReferenceMarkName( keyString, citationType ); // If we should store metadata for page info, do that now: @@ -786,61 +786,61 @@ public void insertEntry(List entries, setCustomProperty(bName, pageInfo); } - // insert space + // insert space cursor - .getText() - .insertString(cursor, " ", false); + .getText() + .insertString(cursor, " ", false); - // format the space inserted + // format the space inserted if ( style.isFormatCitations() ) { XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); } catch ( UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex - ) - { - // Setting the character format failed, so we - // throw an exception that will result in an - // error message for the user. - // - // Before that, delete the space we inserted: - cursor.goLeft((short) 1, true); - cursor.setString(""); - throw new UndefinedCharacterFormatException(charStyle); - } + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex + ) + { + // Setting the character format failed, so we + // throw an exception that will result in an + // error message for the user. + // + // Before that, delete the space we inserted: + cursor.goLeft((short) 1, true); + cursor.setString(""); + throw new UndefinedCharacterFormatException(charStyle); + } } - // go back to before the space + // go back to before the space cursor.goLeft((short) 1, false); // Insert bookmark and text - { - // Create a BibEntry to BibDatabase map (to make - // style.getCitationMarker happy?) - Map databaseMap = new HashMap<>(); - for (BibEntry entry : entries) { - databaseMap.put(entry, database); - } - // the text we insert? - String citeText = - style.isNumberEntries() - ? "-" // A dash only. Presumably we expect a refresh later. - : style.getCitationMarker(entries, - databaseMap, - inParenthesis, - null, // uniquefiers - null // unlimAuthors - ); - insertReferenceMark(bName, citeText, cursor, withText, style); - } - // - // Move to the right of the space and remember this - // position: we will come back here in the end. - // + { + // Create a BibEntry to BibDatabase map (to make + // style.getCitationMarker happy?) + Map databaseMap = new HashMap<>(); + for (BibEntry entry : entries) { + databaseMap.put(entry, database); + } + // the text we insert? + String citeText = + style.isNumberEntries() + ? "-" // A dash only. Presumably we expect a refresh later. + : style.getCitationMarker(entries, + databaseMap, + inParenthesis, + null, // uniquefiers + null // unlimAuthors + ); + insertReferenceMark(bName, citeText, cursor, withText, style); + } + // + // Move to the right of the space and remember this + // position: we will come back here in the end. + // cursor.collapseToEnd(); cursor.goRight((short) 1, false); XTextRange position = cursor.getEnd(); @@ -854,23 +854,23 @@ public void insertEntry(List entries, // Insert it at the current position: rebuildBibTextSection(allBases, style); - /* - * TODO: inserting a reference in the "References" section - * provokes an "Unknown Source" exception here, because - * position was deleted by rebuildBibTextSection() - * - * at com.sun.proxy.$Proxy44.gotoRange(Unknown Source) - * at org.jabref@100.0.0/org.jabref.gui.openoffice - * .OOBibBase.insertEntry(OOBibBase.java:609) - * - */ - // Go back to the relevant position: - try { - cursor.gotoRange(position, false); - } catch ( com.sun.star.uno.RuntimeException ex ){ - LOGGER.warn("OOBibBase.insertEntry:" - +" Could not go back to end of in-text citation", ex); - } + /* + * TODO: inserting a reference in the "References" section + * provokes an "Unknown Source" exception here, because + * position was deleted by rebuildBibTextSection() + * + * at com.sun.proxy.$Proxy44.gotoRange(Unknown Source) + * at org.jabref@100.0.0/org.jabref.gui.openoffice + * .OOBibBase.insertEntry(OOBibBase.java:609) + * + */ + // Go back to the relevant position: + try { + cursor.gotoRange(position, false); + } catch ( com.sun.star.uno.RuntimeException ex ){ + LOGGER.warn("OOBibBase.insertEntry:" + +" Could not go back to end of in-text citation", ex); + } } } catch (DisposedException ex) { @@ -893,10 +893,10 @@ public void insertEntry(List entries, * If name does not match CITE_PATTERN, an empty List is returned. */ private List parseRefMarkNameToUniqueCitationKeys(String name) { - Optional< ParsedRefMark > op = parseRefMarkName( name ); - if ( op.isPresent() ){ - return op.get().citedKeys.stream().distinct().collect(Collectors.toList()); - } + Optional< ParsedRefMark > op = parseRefMarkName( name ); + if ( op.isPresent() ){ + return op.get().citedKeys.stream().distinct().collect(Collectors.toList()); + } return new ArrayList<>(); } @@ -909,9 +909,9 @@ private List parseRefMarkNameToUniqueCitationKeys(String name) { * */ private List findCitedKeys() - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException { XNameAccess xNamedMarks = getReferenceMarks(); String[] names = xNamedMarks.getElementNames(); @@ -946,7 +946,7 @@ private List findCitedKeys() * - on return linkSourceBase has an entry for the citedKey we did find */ private Map findCitedEntries(List databases, - List citedKeys, + List citedKeys, Map linkSourceBase) { Map entries = new LinkedHashMap<>(); @@ -986,17 +986,17 @@ private Map findCitedEntries(List databases, * @throws UnknownPropertyException */ public List refreshCiteMarkers(List databases, - OOBibStyle style) - throws WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - IOException, - CreationException, - BibEntryNotFoundException, - NoDocumentException + OOBibStyle style) + throws WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { try { return refreshCiteMarkersInternal(databases, style); @@ -1009,62 +1009,62 @@ public List refreshCiteMarkers(List databases, } private static Optional linkSourceBaseCiteKeyToBibEntry - ( Map linkSourceBase, - String citeKey ) + ( Map linkSourceBase, + String citeKey ) { - BibDatabase database = linkSourceBase.get(citeKey); - Optional res = ( (database == null) - ? Optional.empty() - : database.getEntryByCitationKey(citeKey) - ); - return res; + BibDatabase database = linkSourceBase.get(citeKey); + Optional res = ( (database == null) + ? Optional.empty() + : database.getEntryByCitationKey(citeKey) + ); + return res; } private static BibEntry[] linkSourceBaseGetBibEntriesOfCiteKeys - ( Map linkSourceBase, - String[] keys, // citeKeys - String namei // refMarkName - ) - throws BibEntryNotFoundException + ( Map linkSourceBase, + String[] keys, // citeKeys + String namei // refMarkName + ) + throws BibEntryNotFoundException { - BibEntry[] cEntries = new BibEntry[keys.length]; - // fill cEntries - for (int j = 0; j < keys.length; j++) { - String kj = keys[j]; - Optional tmpEntry = - linkSourceBaseCiteKeyToBibEntry( linkSourceBase, kj ); - if (tmpEntry.isPresent()) { - cEntries[j] = tmpEntry.get(); - } else { - LOGGER.info("Citation key not found: '" + kj + '\''); - LOGGER.info("Problem with reference mark: '" + namei + '\''); - String msg = Localization.lang("Could not resolve BibTeX entry" - +" for citation marker '%0'.", - namei - ); - throw new BibEntryNotFoundException(namei, msg); - } - } // for j - return cEntries; + BibEntry[] cEntries = new BibEntry[keys.length]; + // fill cEntries + for (int j = 0; j < keys.length; j++) { + String kj = keys[j]; + Optional tmpEntry = + linkSourceBaseCiteKeyToBibEntry( linkSourceBase, kj ); + if (tmpEntry.isPresent()) { + cEntries[j] = tmpEntry.get(); + } else { + LOGGER.info("Citation key not found: '" + kj + '\''); + LOGGER.info("Problem with reference mark: '" + namei + '\''); + String msg = Localization.lang("Could not resolve BibTeX entry" + +" for citation marker '%0'.", + namei + ); + throw new BibEntryNotFoundException(namei, msg); + } + } // for j + return cEntries; } private class GetSortedCitedEntriesResult { - Map linkSourceBase; - List citedKeys; - Map entries; - List refMarkNames; - public GetSortedCitedEntriesResult - ( - Map linkSourceBase, - List citedKeys, - Map entries, - List refMarkNames ) - { - this.linkSourceBase = linkSourceBase; - this.citedKeys = citedKeys; - this.entries = entries; - this.refMarkNames = refMarkNames; - } + Map linkSourceBase; + List citedKeys; + Map entries; + List refMarkNames; + public GetSortedCitedEntriesResult + ( + Map linkSourceBase, + List citedKeys, + Map entries, + List refMarkNames ) + { + this.linkSourceBase = linkSourceBase; + this.citedKeys = citedKeys; + this.entries = entries; + this.refMarkNames = refMarkNames; + } } /** @@ -1086,19 +1086,19 @@ private class GetSortedCitedEntriesResult { * except for style.isNumberEntries() where reordered as entries */ private GetSortedCitedEntriesResult getSortedCitedEntries - ( List databases, - OOBibStyle style, - XNameAccess xReferenceMarks - ) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException + ( List databases, + OOBibStyle style, + XNameAccess xReferenceMarks + ) + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException { Map linkSourceBase = new HashMap<>(); List cited = findCitedKeys(); Map entries = - findCitedEntries(databases, cited, linkSourceBase); + findCitedEntries(databases, cited, linkSourceBase); List names; if (style.isSortByPosition()) { @@ -1106,10 +1106,10 @@ private class GetSortedCitedEntriesResult { // order of appearance: names = sortedReferenceMarks; } else if (style.isNumberEntries()) { - // + // // We need to sort the reference marks according to the // sorting of the bibliographic entries: - // + // SortedMap newMap = new TreeMap<>(entryComparator); for (Map.Entry ee : entries.entrySet()) { newMap.put(ee.getKey(), ee.getValue()); @@ -1120,59 +1120,59 @@ private class GetSortedCitedEntriesResult { for (BibEntry entry : entries.keySet()) { cited.add(entry.getCitationKey().orElse(null)); } - // + // names = Arrays.asList(xReferenceMarks.getElementNames()); } else { names = sortedReferenceMarks; } // Remove all reference marks that don't look like JabRef citations: - names = filterIsJabRefReferenceMarkName( names ); + names = filterIsJabRefReferenceMarkName( names ); - return new GetSortedCitedEntriesResult( linkSourceBase, - cited, - entries, - names - ); + return new GetSortedCitedEntriesResult( linkSourceBase, + cited, + entries, + names + ); } private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] cEntries, - OOBibStyle style ) + OOBibStyle style ) { - assert( style.isCitationKeyCiteMarkers() ); + assert( style.isCitationKeyCiteMarkers() ); - StringBuilder sb = new StringBuilder(); - for (int j = 0; j < cEntries.length; j++) { - if (j > 0) { sb.append(','); } - Optional cejKey = cEntries[j].getCitationKey(); - sb.append(cejKey.orElse("")); - } - String citationMarker = sb.toString(); - return citationMarker; + StringBuilder sb = new StringBuilder(); + for (int j = 0; j < cEntries.length; j++) { + if (j > 0) { sb.append(','); } + Optional cejKey = cEntries[j].getCitationKey(); + sb.append(cejKey.orElse("")); + } + String citationMarker = sb.toString(); + return citationMarker; } private static String[] rcmNormCitMarkersForIsCitationKeyCiteMarkers( BibEntry[] cEntries, - OOBibStyle style ) + OOBibStyle style ) { - assert( style.isCitationKeyCiteMarkers() ); - - String[] normCitMarker = new String[cEntries.length]; - for (int j = 0; j < cEntries.length; j++) { - Optional cejKey = cEntries[j].getCitationKey(); - normCitMarker[j] = cejKey.orElse(null); - } - return normCitMarker; + assert( style.isCitationKeyCiteMarkers() ); + + String[] normCitMarker = new String[cEntries.length]; + for (int j = 0; j < cEntries.length; j++) { + Optional cejKey = cEntries[j].getCitationKey(); + normCitMarker[j] = cejKey.orElse(null); + } + return normCitMarker; } private class CitationNumberingState { - public Map numbers; - public int lastNum; - CitationNumberingState(){ - // For numbered citation style. Map( citedKey, number ) - Map numbers = new HashMap<>(); - int lastNum = 0; - } + public Map numbers; + public int lastNum; + CitationNumberingState(){ + // For numbered citation style. Map( citedKey, number ) + Map numbers = new HashMap<>(); + int lastNum = 0; + } } /** @@ -1191,59 +1191,59 @@ private class CitationNumberingState { * @return an int for each cEntry. (-1) for UndefinedBibtexEntry */ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry[] cEntries, - String[] keys, - OOBibStyle style, - CitationNumberingState cns ) + String[] keys, + OOBibStyle style, + CitationNumberingState cns ) { - assert (style.isNumberEntries()); - assert (style.isSortByPosition()); - assert (cEntries.length == keys.length ); - if ( true ){ - /* - * TODO: do we need a test case? - * - * If this never prints (or throws), we can drop the "keys" parameter. - */ - for (int j = 0; j < cEntries.length; j++) { - BibEntry cej = cEntries[j]; - String kj = keys[j]; - if ( kj != cej.getCitationKey().get() ){ - System.out.println - ( "keys != cEntries in rcmNumForIsNumberEntriesIsSortByPosition" ); - } - } - } - // - // We have sorted the citation markers - // according to their order of appearance, so - // we simply count up for each marker - // referring to a new entry: - // - // num: Numbers for namei parts. (-1) for none. - // Passed to style.getNumCitationMarker() - List num = new ArrayList<>(cEntries.length); - // - // - // fill num while adjusting lastNum and filling numbers - // - for (int j = 0; j < cEntries.length; j++) { - BibEntry cej = cEntries[j]; - String kj = keys[j]; // cej.getCitationKey().get() - if (cej instanceof UndefinedBibtexEntry) { - num.add(j, -1); // gets no cns.number - } else { - if (cns.numbers.containsKey(kj)) { - // already seen - num.add(j, cns.numbers.get(kj)); - } else { - // new - cns.lastNum++; // 1-based - num.add( j, cns.lastNum); - cns.numbers.put(kj, cns.lastNum); - } - } - } - return num; + assert (style.isNumberEntries()); + assert (style.isSortByPosition()); + assert (cEntries.length == keys.length ); + if ( true ){ + /* + * TODO: do we need a test case? + * + * If this never prints (or throws), we can drop the "keys" parameter. + */ + for (int j = 0; j < cEntries.length; j++) { + BibEntry cej = cEntries[j]; + String kj = keys[j]; + if ( kj != cej.getCitationKey().get() ){ + System.out.println + ( "keys != cEntries in rcmNumForIsNumberEntriesIsSortByPosition" ); + } + } + } + // + // We have sorted the citation markers + // according to their order of appearance, so + // we simply count up for each marker + // referring to a new entry: + // + // num: Numbers for namei parts. (-1) for none. + // Passed to style.getNumCitationMarker() + List num = new ArrayList<>(cEntries.length); + // + // + // fill num while adjusting lastNum and filling numbers + // + for (int j = 0; j < cEntries.length; j++) { + BibEntry cej = cEntries[j]; + String kj = keys[j]; // cej.getCitationKey().get() + if (cej instanceof UndefinedBibtexEntry) { + num.add(j, -1); // gets no cns.number + } else { + if (cns.numbers.containsKey(kj)) { + // already seen + num.add(j, cns.numbers.get(kj)); + } else { + // new + cns.lastNum++; // 1-based + num.add( j, cns.lastNum); + cns.numbers.put(kj, cns.lastNum); + } + } + } + return num; } /** @@ -1256,43 +1256,43 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry * Returns Collections.emptyList() if the ref name could not be resolved as a citation. */ private List findCitedEntryIndices( List keysCitedHere, - List orderedCiteKeys) + List orderedCiteKeys) { - List result = new ArrayList<>(keysCitedHere.size()); - for (String key : keysCitedHere) { - int ind = orderedCiteKeys.indexOf(key); - result.add(ind == -1 ? -1 : 1 + ind); - } - return result; + List result = new ArrayList<>(keysCitedHere.size()); + for (String key : keysCitedHere) { + int ind = orderedCiteKeys.indexOf(key); + result.add(ind == -1 ? -1 : 1 + ind); + } + return result; } private List refreshCiteMarkersInternal - ( List databases, - OOBibStyle style - ) - throws WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException + ( List databases, + OOBibStyle style + ) + throws WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { XNameAccess xReferenceMarks = getReferenceMarks(); - GetSortedCitedEntriesResult sce = - getSortedCitedEntries( databases, style, xReferenceMarks ); - Map linkSourceBase = sce.linkSourceBase; - List cited = sce.citedKeys; - Map entries = sce.entries; - List names = sce.refMarkNames; - //***** + GetSortedCitedEntriesResult sce = + getSortedCitedEntries( databases, style, xReferenceMarks ); + Map linkSourceBase = sce.linkSourceBase; + List cited = sce.citedKeys; + Map entries = sce.entries; + List names = sce.refMarkNames; + //***** - // // For numbered citation style. Map( citedKey, number ) - CitationNumberingState cns = new CitationNumberingState(); + // // For numbered citation style. Map( citedKey, number ) + CitationNumberingState cns = new CitationNumberingState(); // First compute citation markers for all citations: String[] citMarkers = new String[names.size()]; @@ -1300,93 +1300,93 @@ private List findCitedEntryIndices( List keysCitedHere, String[][] bibtexKeys = new String[names.size()][]; final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); int[] types = new int[names.size()]; - // - // - // fill: - // types[i] = ov.itcType - // bibtexKeys[i] = ov.citedKeys.toArray() - // citMarkers[i] = what goes in the text - // normCitMarkers[i][j] = for unification - // + // + // + // fill: + // types[i] = ov.itcType + // bibtexKeys[i] = ov.citedKeys.toArray() + // citMarkers[i] = what goes in the text + // normCitMarkers[i][j] = for unification + // for (int i = 0; i < names.size(); i++) { - final String namei = names.get(i); - Optional op = parseRefMarkName( namei ); + final String namei = names.get(i); + Optional op = parseRefMarkName( namei ); if ( op.isPresent() ) { - ParsedRefMark ov = op.get(); - int type = ov.itcType; + ParsedRefMark ov = op.get(); + int type = ov.itcType; types[i] = type; // Remember the itcType in case we need to uniquefy. String[] keys = ov.citedKeys.stream().toArray(String[]::new); bibtexKeys[i] = keys; - // - BibEntry[] cEntries = - linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, keys, namei ); - assert (cEntries.length == keys.length) ; - // - // normCitMarker[ cEntries.length ] null if missing + // + BibEntry[] cEntries = + linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, keys, namei ); + assert (cEntries.length == keys.length) ; + // + // normCitMarker[ cEntries.length ] null if missing String[] normCitMarker = new String[cEntries.length]; String citationMarker; // normCitMarker.replace( null -> "" ).join(",") - // - // fill normCitMarker, set citationMarker + // + // fill normCitMarker, set citationMarker if (style.isCitationKeyCiteMarkers()) { - // - citationMarker = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); - normCitMarker = rcmNormCitMarkersForIsCitationKeyCiteMarkers( cEntries, style ); - // + // + citationMarker = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); + normCitMarker = rcmNormCitMarkersForIsCitationKeyCiteMarkers( cEntries, style ); + // } else if (style.isNumberEntries()) { - List num ; + List num ; if (style.isSortByPosition()) { num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, keys, style, cns ); } else { num = findCitedEntryIndices( Arrays.asList(keys) , cited ); } - // - // set citationMarker - citationMarker = - style.getNumCitationMarker(num, minGroupingCount, false); - // - // fill normCitMarker - for (int j = 0; j < cEntries.length; j++) { - List numj = Collections.singletonList(num.get(j)); - normCitMarker[j] = - style.getNumCitationMarker( numj, minGroupingCount, false ); - } - // + // + // set citationMarker + citationMarker = + style.getNumCitationMarker(num, minGroupingCount, false); + // + // fill normCitMarker + for (int j = 0; j < cEntries.length; j++) { + List numj = Collections.singletonList(num.get(j)); + normCitMarker[j] = + style.getNumCitationMarker( numj, minGroupingCount, false ); + } + // } else { - assert( !style.isCitationKeyCiteMarkers() ); - assert( !style.isNumberEntries() ); - // Citations in (Au1, Au2 2000) form - // - // sort itcBlock - sortBibEntryArray( cEntries, style ); - // - // Update key list to match the new sorting: - for (int j = 0; j < cEntries.length; j++) { - bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); - } - // + assert( !style.isCitationKeyCiteMarkers() ); + assert( !style.isNumberEntries() ); + // Citations in (Au1, Au2 2000) form + // + // sort itcBlock + sortBibEntryArray( cEntries, style ); + // + // Update key list to match the new sorting: + for (int j = 0; j < cEntries.length; j++) { + bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); + } + // citationMarker = style.getCitationMarker( Arrays.asList(cEntries), // entries - entries, // database - type == OOBibBase.AUTHORYEAR_PAR, // inParenthesis - null, // uniquefiers - null // unlimAuthors - ); - // + entries, // database + type == OOBibBase.AUTHORYEAR_PAR, // inParenthesis + null, // uniquefiers + null // unlimAuthors + ); + // // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: - // - // Fill normCitMarker + // + // Fill normCitMarker for (int j = 0; j < cEntries.length; j++) { - List cej = Collections.singletonList(cEntries[j]); + List cej = Collections.singletonList(cEntries[j]); normCitMarker[j] = - style.getCitationMarker( cej, // entries - entries, // database - true, // inParenthesis - null, // uniquefiers - new int[] {-1} // unlimAuthors - ); + style.getCitationMarker( cej, // entries + entries, // database + true, // inParenthesis + null, // uniquefiers + new int[] {-1} // unlimAuthors + ); } } citMarkers[i] = citationMarker; @@ -1394,27 +1394,27 @@ private List findCitedEntryIndices( List keysCitedHere, } // if (citeMatcher.find()) } // for i - // - // uniquefiers "a", "b" in (2000a, 2000b) - // + // + // uniquefiers "a", "b" in (2000a, 2000b) + // uniquefiers.clear(); if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { - // Only for normal citations. Numbered citations and - // citeKeys are already unique. - // - // + // Only for normal citations. Numbered citations and + // citeKeys are already unique. + // + // // See if there are duplicate citations marks referring to // different entries. If so, we need to use uniquefiers: - // - // refKeys: normCitMarker to bibtexkeys sharing it - // - // The entries in the lists are ordered as in - // normCitMarkers[i][j] - // + // + // refKeys: normCitMarker to bibtexkeys sharing it + // + // The entries in the lists are ordered as in + // normCitMarkers[i][j] + // Map> refKeys = new HashMap<>(); for (int i = 0; i < citMarkers.length; i++) { - // compare normalized markers, since the actual - // markers can be different + // compare normalized markers, since the actual + // markers can be different String[] markers = normCitMarkers[i]; for (int j = 0; j < markers.length; j++) { String marker = markers[j]; @@ -1426,7 +1426,7 @@ private List findCitedEntryIndices( List keysCitedHere, refKeys.get(marker).add(currentKey); } } else { - // add as new entry + // add as new entry List l = new ArrayList<>(1); l.add(currentKey); refKeys.put(marker, l); @@ -1499,12 +1499,12 @@ private List findCitedEntryIndices( List keysCitedHere, } if (needsChange) { citMarkers[j] = - style.getCitationMarker( Arrays.asList(cEntries), - entries, - types[j] == OOBibBase.AUTHORYEAR_PAR, - uniquif, - firstLimAuthors - ); + style.getCitationMarker( Arrays.asList(cEntries), + entries, + types[j] == OOBibBase.AUTHORYEAR_PAR, + uniquif, + firstLimAuthors + ); } } } // if normalStyle @@ -1518,10 +1518,10 @@ private List findCitedEntryIndices( List keysCitedHere, XTextContent bookmark = unoQI(XTextContent.class, referenceMark); XTextCursor cursor = - bookmark - .getAnchor() - .getText() - .createTextCursorByRange(bookmark.getAnchor()); + bookmark + .getAnchor() + .getText() + .createTextCursorByRange(bookmark.getAnchor()); if (mustTestCharFormat) { // If we are supposed to set character format for citations, must run a test before we @@ -1568,11 +1568,11 @@ private List findCitedEntryIndices( List keysCitedHere, */ private List getSortedReferenceMarks(final XNameAccess nameAccess) throws WrappedTargetException, - NoSuchElementException + NoSuchElementException { XTextViewCursorSupplier cursorSupplier = - unoQI(XTextViewCursorSupplier.class, - this.mxDoc.getCurrentController()); + unoQI(XTextViewCursorSupplier.class, + this.mxDoc.getCurrentController()); XTextViewCursor viewCursor = cursorSupplier.getViewCursor(); XTextRange initialPos = viewCursor.getStart(); @@ -1580,7 +1580,7 @@ private List getSortedReferenceMarks(final XNameAccess nameAccess) List positions = new ArrayList<>(names.size()); for (String name : names) { XTextContent textContent = - unoQI(XTextContent.class, nameAccess.getByName(name)); + unoQI(XTextContent.class, nameAccess.getByName(name)); XTextRange range = textContent.getAnchor(); // Check if we are inside a footnote: if (unoQI(XFootnote.class, range.getText()) != null) { @@ -1607,46 +1607,46 @@ private List getSortedReferenceMarks(final XNameAccess nameAccess) } public void updateSortedReferenceMarks() - throws WrappedTargetException, - NoSuchElementException, - NoDocumentException + throws WrappedTargetException, + NoSuchElementException, + NoDocumentException { this.sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks()); } public void rebuildBibTextSection(List databases, - OOBibStyle style) - throws NoSuchElementException, - WrappedTargetException, - IllegalArgumentException, - CreationException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - NoDocumentException + OOBibStyle style) + throws NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException, + NoDocumentException { List cited = findCitedKeys(); Map linkSourceBase = new HashMap<>(); Map entries = - // Although entries are redefined without use, this also - // updates linkSourceBase - findCitedEntries(databases, cited, linkSourceBase); + // Although entries are redefined without use, this also + // updates linkSourceBase + findCitedEntries(databases, cited, linkSourceBase); if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: - List names = sortedReferenceMarks; + List names = sortedReferenceMarks; entries = getSortedEntriesFromSortedRefMarks(names, linkSourceBase); } else { - // Find them again? Why? - Map entries2 = - findCitedEntries(databases, cited, linkSourceBase); + // Find them again? Why? + Map entries2 = + findCitedEntries(databases, cited, linkSourceBase); SortedMap newMap = new TreeMap<>(entryComparator); for (Map.Entry kv : entries2.entrySet()) { - newMap.put(kv.getKey(), - kv.getValue()); - } + newMap.put(kv.getKey(), + kv.getValue()); + } entries = newMap; } clearBibTextSectionContent2(); @@ -1666,32 +1666,32 @@ private Map getSortedEntriesFromSortedRefMarks(List newList = new LinkedHashMap<>(); for (String name : names) { - /* - * Matcher citeMatcher = CITE_PATTERN.matcher(name); - * if (citeMatcher.find()) { + /* + * Matcher citeMatcher = CITE_PATTERN.matcher(name); + * if (citeMatcher.find()) { * String[] keys = citeMatcher.group(2).split(","); - */ - Optional op = parseRefMarkName( name ); - if ( ! op.isPresent() ){ continue; } - List keys = op.get().citedKeys; - for (String key : keys) { - BibDatabase database = linkSourceBase.get(key); - Optional origEntry = Optional.empty(); - if (database != null) { - origEntry = database.getEntryByCitationKey(key); - } - if (origEntry.isPresent()) { - BibEntry oe = origEntry.get(); - if (!newList.containsKey(oe)) { - newList.put(oe, database); - } - } else { - LOGGER.info("Citation key not found: '" + key + "'"); - LOGGER.info("Problem with reference mark: '" + name + "'"); - newList.put(new UndefinedBibtexEntry(key), null); - } - } - /* } */ + */ + Optional op = parseRefMarkName( name ); + if ( ! op.isPresent() ){ continue; } + List keys = op.get().citedKeys; + for (String key : keys) { + BibDatabase database = linkSourceBase.get(key); + Optional origEntry = Optional.empty(); + if (database != null) { + origEntry = database.getEntryByCitationKey(key); + } + if (origEntry.isPresent()) { + BibEntry oe = origEntry.get(); + if (!newList.containsKey(oe)) { + newList.put(oe, database); + } + } else { + LOGGER.info("Citation key not found: '" + key + "'"); + LOGGER.info("Problem with reference mark: '" + name + "'"); + newList.put(new UndefinedBibtexEntry(key), null); + } + } + /* } */ } return newList; } @@ -1800,27 +1800,27 @@ private void clearBibTextSectionContent2() // Check if the section exists: XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, this.mxDoc); - com.sun.star.container.XNameAccess ts = supplier.getTextSections(); + com.sun.star.container.XNameAccess ts = supplier.getTextSections(); if (ts.hasByName(OOBibBase.BIB_SECTION_NAME)) { - try { - Any a = ((Any) ts.getByName(OOBibBase.BIB_SECTION_NAME)); - XTextSection section = (XTextSection) a.getObject(); - // Clear it: - XTextCursor cursor = this.xtext.createTextCursorByRange(section.getAnchor()); - cursor.gotoRange(section.getAnchor(), false); - cursor.setString(""); - return; - } catch ( NoSuchElementException ex ) { - // NoSuchElementException: is thrown by child access - // methods of collections, if the addressed child does - // not exist. - // - // We got this exception from ts.getByName() despite the ts.hasByName() check - // just above. - // Try to create. - LOGGER.warn( "Could not get section '"+ OOBibBase.BIB_SECTION_NAME + "'", ex ); - createBibTextSection2(atEnd); - } + try { + Any a = ((Any) ts.getByName(OOBibBase.BIB_SECTION_NAME)); + XTextSection section = (XTextSection) a.getObject(); + // Clear it: + XTextCursor cursor = this.xtext.createTextCursorByRange(section.getAnchor()); + cursor.gotoRange(section.getAnchor(), false); + cursor.setString(""); + return; + } catch ( NoSuchElementException ex ) { + // NoSuchElementException: is thrown by child access + // methods of collections, if the addressed child does + // not exist. + // + // We got this exception from ts.getByName() despite the ts.hasByName() check + // just above. + // Try to create. + LOGGER.warn( "Could not get section '"+ OOBibBase.BIB_SECTION_NAME + "'", ex ); + createBibTextSection2(atEnd); + } } else { createBibTextSection2(atEnd); } @@ -1923,9 +1923,9 @@ private void insertReferenceMark(String name, String citationText, XTextCursor p } private void removeReferenceMark(String name) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException { XNameAccess xReferenceMarks = getReferenceMarks(); if (xReferenceMarks.hasByName(name)) { @@ -1978,15 +1978,15 @@ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, public void combineCiteMarkers(List databases, OOBibStyle style) throws IOException, - WrappedTargetException, - NoSuchElementException, - IllegalArgumentException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException + WrappedTargetException, + NoSuchElementException, + IllegalArgumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { XNameAccess nameAccess = getReferenceMarks(); // TODO: doesn't work for citations in footnotes/tables @@ -2067,16 +2067,16 @@ public void combineCiteMarkers(List databases, OOBibStyle style) * Combined markers are split, with a space inserted between. */ public void unCombineCiteMarkers(List databases, OOBibStyle style) - throws IOException, - WrappedTargetException, - NoSuchElementException, - IllegalArgumentException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException + throws IOException, + WrappedTargetException, + NoSuchElementException, + IllegalArgumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { XNameAccess nameAccess = getReferenceMarks(); // TODO: doesn't work for citations in footnotes/tables @@ -2136,9 +2136,9 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) } public BibDatabase generateDatabase(List databases) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException { BibDatabase resultDatabase = new BibDatabase(); List cited = findCitedKeys(); From 053eac8e166386caa17ac03aafa4954b86284f01 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 17:26:25 +0100 Subject: [PATCH 0087/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 77a9819f468..0254ba241b1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1394,24 +1394,21 @@ private List findCitedEntryIndices( List keysCitedHere, } // if (citeMatcher.find()) } // for i - // - // uniquefiers "a", "b" in (2000a, 2000b) - // + + // uniquefiers: "a", "b" in (2000a, 2000b) uniquefiers.clear(); if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { // Only for normal citations. Numbered citations and // citeKeys are already unique. - // - // + // See if there are duplicate citations marks referring to // different entries. If so, we need to use uniquefiers: - // - // refKeys: normCitMarker to bibtexkeys sharing it - // - // The entries in the lists are ordered as in - // normCitMarkers[i][j] - // + + // refKeys: normCitMarker to list of bibtexkeys sharing it. + // The entries in the lists are ordered as in + // normCitMarkers[i][j] Map> refKeys = new HashMap<>(); + for (int i = 0; i < citMarkers.length; i++) { // compare normalized markers, since the actual // markers can be different @@ -1433,6 +1430,7 @@ private List findCitedEntryIndices( List keysCitedHere, } } } + // Go through the collected lists and see where we need to // uniquefy: for (Map.Entry> stringListEntry : refKeys.entrySet()) { From d140563097128b85debbe0f63ac030ba110b0d44 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 17:33:02 +0100 Subject: [PATCH 0088/1068] keys renamed to clashingKeys --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0254ba241b1..8af32dd7095 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1410,8 +1410,8 @@ private List findCitedEntryIndices( List keysCitedHere, Map> refKeys = new HashMap<>(); for (int i = 0; i < citMarkers.length; i++) { - // compare normalized markers, since the actual - // markers can be different + // Compare normalized markers, since the actual + // markers can be different. String[] markers = normCitMarkers[i]; for (int j = 0; j < markers.length; j++) { String marker = markers[j]; @@ -1434,11 +1434,11 @@ private List findCitedEntryIndices( List keysCitedHere, // Go through the collected lists and see where we need to // uniquefy: for (Map.Entry> stringListEntry : refKeys.entrySet()) { - List keys = stringListEntry.getValue(); - if (keys.size() > 1) { + List clashingKeys = stringListEntry.getValue(); + if (clashingKeys.size() > 1) { // This marker appears for more than one unique entry: int uniq = 'a'; - for (String key : keys) { + for (String key : clashingKeys) { // Update the map of uniquefiers for the // benefit of both the following generation of // new citation markers, and for the method @@ -1454,10 +1454,10 @@ private List findCitedEntryIndices( List keysCitedHere, int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); for (int j = 0; j < bibtexKeys.length; j++) { - boolean needsChange = false; - int[] firstLimAuthors = new int[bibtexKeys[j].length]; - String[] uniquif = new String[bibtexKeys[j].length]; - BibEntry[] cEntries = new BibEntry[bibtexKeys[j].length]; + boolean needsChange = false; + int[] firstLimAuthors = new int[bibtexKeys[j].length]; + String[] uniquif = new String[bibtexKeys[j].length]; + BibEntry[] cEntries = new BibEntry[bibtexKeys[j].length]; for (int k = 0; k < bibtexKeys[j].length; k++) { String currentKey = bibtexKeys[j][k]; firstLimAuthors[k] = -1; @@ -1504,7 +1504,7 @@ private List findCitedEntryIndices( List keysCitedHere, firstLimAuthors ); } - } + } // for j } // if normalStyle // Refresh all reference marks with the citation markers we computed: From 378033d0a83fb20d26aa64dfcad9efcea565b581 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 17:35:31 +0100 Subject: [PATCH 0089/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8af32dd7095..5bbe5cfc48a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1458,6 +1458,7 @@ private List findCitedEntryIndices( List keysCitedHere, int[] firstLimAuthors = new int[bibtexKeys[j].length]; String[] uniquif = new String[bibtexKeys[j].length]; BibEntry[] cEntries = new BibEntry[bibtexKeys[j].length]; + for (int k = 0; k < bibtexKeys[j].length; k++) { String currentKey = bibtexKeys[j][k]; firstLimAuthors[k] = -1; @@ -1495,6 +1496,7 @@ private List findCitedEntryIndices( List keysCitedHere, cEntries[k] = tmpEntry.get(); } } + if (needsChange) { citMarkers[j] = style.getCitationMarker( Arrays.asList(cEntries), From bf122e015776d9031b7fa9486579aad14bb25edc Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 17:39:13 +0100 Subject: [PATCH 0090/1068] reanedm j to i (first level of iteration) --- .../org/jabref/gui/openoffice/OOBibBase.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5bbe5cfc48a..e46fa0b8e6a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1453,14 +1453,14 @@ private List findCitedEntryIndices( List keysCitedHere, // those referring to entries in our current list: int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); - for (int j = 0; j < bibtexKeys.length; j++) { + for (int i = 0; i < bibtexKeys.length; i++) { boolean needsChange = false; - int[] firstLimAuthors = new int[bibtexKeys[j].length]; - String[] uniquif = new String[bibtexKeys[j].length]; - BibEntry[] cEntries = new BibEntry[bibtexKeys[j].length]; + int[] firstLimAuthors = new int[bibtexKeys[i].length]; + String[] uniquif = new String[bibtexKeys[i].length]; + BibEntry[] cEntries = new BibEntry[bibtexKeys[i].length]; - for (int k = 0; k < bibtexKeys[j].length; k++) { - String currentKey = bibtexKeys[j][k]; + for (int k = 0; k < bibtexKeys[i].length; k++) { + String currentKey = bibtexKeys[i][k]; firstLimAuthors[k] = -1; if (maxAuthorsFirst > 0) { if (!seenBefore.contains(currentKey)) { @@ -1498,15 +1498,15 @@ private List findCitedEntryIndices( List keysCitedHere, } if (needsChange) { - citMarkers[j] = + citMarkers[i] = style.getCitationMarker( Arrays.asList(cEntries), entries, - types[j] == OOBibBase.AUTHORYEAR_PAR, + types[i] == OOBibBase.AUTHORYEAR_PAR, uniquif, firstLimAuthors ); } - } // for j + } // for i } // if normalStyle // Refresh all reference marks with the citation markers we computed: From 8ac2a219cec05911a3a55b50ed20c8b257369b1b Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 17:41:15 +0100 Subject: [PATCH 0091/1068] rename k to j (2nd level of iteration) --- .../org/jabref/gui/openoffice/OOBibBase.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e46fa0b8e6a..27913eb82d6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1459,19 +1459,19 @@ private List findCitedEntryIndices( List keysCitedHere, String[] uniquif = new String[bibtexKeys[i].length]; BibEntry[] cEntries = new BibEntry[bibtexKeys[i].length]; - for (int k = 0; k < bibtexKeys[i].length; k++) { - String currentKey = bibtexKeys[i][k]; - firstLimAuthors[k] = -1; + for (int j = 0; j < bibtexKeys[i].length; j++) { + String currentKey = bibtexKeys[i][j]; + firstLimAuthors[j] = -1; if (maxAuthorsFirst > 0) { if (!seenBefore.contains(currentKey)) { - firstLimAuthors[k] = maxAuthorsFirst; + firstLimAuthors[j] = maxAuthorsFirst; } seenBefore.add(currentKey); } String uniq = uniquefiers.get(currentKey); Optional tmpEntry = Optional.empty(); if (uniq == null) { - if (firstLimAuthors[k] > 0) { + if (firstLimAuthors[j] > 0) { needsChange = true; BibDatabase database = linkSourceBase.get(currentKey); if (database != null) { @@ -1483,17 +1483,17 @@ private List findCitedEntryIndices( List keysCitedHere, tmpEntry = database.getEntryByCitationKey(currentKey); } } - uniquif[k] = ""; + uniquif[j] = ""; } else { needsChange = true; BibDatabase database = linkSourceBase.get(currentKey); if (database != null) { tmpEntry = database.getEntryByCitationKey(currentKey); } - uniquif[k] = uniq; + uniquif[j] = uniq; } if (tmpEntry.isPresent()) { - cEntries[k] = tmpEntry.get(); + cEntries[j] = tmpEntry.get(); } } From cd5260423c92325ff2df565cea185dcb56d71c22 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 17:52:15 +0100 Subject: [PATCH 0092/1068] nRefMarks gives uniform name of the same length --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 27913eb82d6..5873a0e1018 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1295,14 +1295,15 @@ private List findCitedEntryIndices( List keysCitedHere, CitationNumberingState cns = new CitationNumberingState(); // First compute citation markers for all citations: - String[] citMarkers = new String[names.size()]; - String[][] normCitMarkers = new String[names.size()][]; - String[][] bibtexKeys = new String[names.size()][]; + final int nRefMarks = names.size(); + String[] citMarkers = new String[nRefMarks]; + String[][] normCitMarkers = new String[nRefMarks][]; + String[][] bibtexKeys = new String[nRefMarks][]; final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - int[] types = new int[names.size()]; + int[] types = new int[nRefMarks]; // // // fill: @@ -1409,7 +1410,7 @@ private List findCitedEntryIndices( List keysCitedHere, // normCitMarkers[i][j] Map> refKeys = new HashMap<>(); - for (int i = 0; i < citMarkers.length; i++) { + for (int i = 0; i < nRefMarks; i++) { // Compare normalized markers, since the actual // markers can be different. String[] markers = normCitMarkers[i]; @@ -1453,7 +1454,7 @@ private List findCitedEntryIndices( List keysCitedHere, // those referring to entries in our current list: int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); - for (int i = 0; i < bibtexKeys.length; i++) { + for (int i = 0; i < nRefMarks; i++) { boolean needsChange = false; int[] firstLimAuthors = new int[bibtexKeys[i].length]; String[] uniquif = new String[bibtexKeys[i].length]; @@ -1513,7 +1514,7 @@ private List findCitedEntryIndices( List keysCitedHere, boolean hadBibSection = getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null; // Check if we are supposed to set a character format for citations: boolean mustTestCharFormat = style.isFormatCitations(); - for (int i = 0; i < names.size(); i++) { + for (int i = 0; i < nRefMarks; i++) { Object referenceMark = xReferenceMarks.getByName(names.get(i)); XTextContent bookmark = unoQI(XTextContent.class, referenceMark); From 3ee8f57361eb6a6ac73d293954b3f88bf4770d2d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 17:58:41 +0100 Subject: [PATCH 0093/1068] nCitedEntries --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5873a0e1018..2dc3693b4c1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1455,12 +1455,13 @@ private List findCitedEntryIndices( List keysCitedHere, int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); for (int i = 0; i < nRefMarks; i++) { + final int nCitedEntries = bibtexKeys[i].length; boolean needsChange = false; - int[] firstLimAuthors = new int[bibtexKeys[i].length]; - String[] uniquif = new String[bibtexKeys[i].length]; - BibEntry[] cEntries = new BibEntry[bibtexKeys[i].length]; + int[] firstLimAuthors = new int[nCitedEntries]; + String[] uniquif = new String[nCitedEntries]; + BibEntry[] cEntries = new BibEntry[nCitedEntries]; - for (int j = 0; j < bibtexKeys[i].length; j++) { + for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; firstLimAuthors[j] = -1; if (maxAuthorsFirst > 0) { From 86af03e9d75a27175c1bfd8683c5322ef82b3bcc Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:00:56 +0100 Subject: [PATCH 0094/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2dc3693b4c1..e8a873798e3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1455,11 +1455,11 @@ private List findCitedEntryIndices( List keysCitedHere, int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); for (int i = 0; i < nRefMarks; i++) { - final int nCitedEntries = bibtexKeys[i].length; - boolean needsChange = false; - int[] firstLimAuthors = new int[nCitedEntries]; - String[] uniquif = new String[nCitedEntries]; - BibEntry[] cEntries = new BibEntry[nCitedEntries]; + final int nCitedEntries = bibtexKeys[i].length; + boolean needsChange = false; + int[] firstLimAuthors = new int[nCitedEntries]; + String[] uniquif = new String[nCitedEntries]; + BibEntry[] cEntries = new BibEntry[nCitedEntries]; for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; From 12b07c7f6e24784fe71814481276c3d091638709 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:08:09 +0100 Subject: [PATCH 0095/1068] maxAuthorsFirst is finale here --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e8a873798e3..3f72ae96fbf 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1452,7 +1452,7 @@ private List findCitedEntryIndices( List keysCitedHere, // Finally, go through all citation markers, and update // those referring to entries in our current list: - int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); + final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); for (int i = 0; i < nRefMarks; i++) { final int nCitedEntries = bibtexKeys[i].length; From c50ab6536d3ab3e2f36a60fc331cad3a0859b317 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:21:34 +0100 Subject: [PATCH 0096/1068] comment on firstLimAuthors --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3f72ae96fbf..5f59a0f6b41 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1463,6 +1463,15 @@ private List findCitedEntryIndices( List keysCitedHere, for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; + + // firstLimAuthors will be (-1) except at the first + // refMark it appears at, where a positive maxAuthorsFirst + // may override. This is why: + // https://discourse.jabref.org/t/number-of-authors-in-citations-style-libreoffice/747/3 + // "Some citation styles require to list the full + // names of the first 4 authors for the first + // time. Later it is sufficient to have only maybe + // (Author A and Author B 2019 et al.)" firstLimAuthors[j] = -1; if (maxAuthorsFirst > 0) { if (!seenBefore.contains(currentKey)) { @@ -1470,6 +1479,7 @@ private List findCitedEntryIndices( List keysCitedHere, } seenBefore.add(currentKey); } + String uniq = uniquefiers.get(currentKey); Optional tmpEntry = Optional.empty(); if (uniq == null) { @@ -1505,7 +1515,7 @@ private List findCitedEntryIndices( List keysCitedHere, entries, types[i] == OOBibBase.AUTHORYEAR_PAR, uniquif, - firstLimAuthors + firstLimAuthors // unlimAuthors ); } } // for i From c86ba556744546945d356a3825a2eb74f8656eab Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:26:43 +0100 Subject: [PATCH 0097/1068] drop comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5f59a0f6b41..a6ab9b757a6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1515,7 +1515,7 @@ private List findCitedEntryIndices( List keysCitedHere, entries, types[i] == OOBibBase.AUTHORYEAR_PAR, uniquif, - firstLimAuthors // unlimAuthors + firstLimAuthors ); } } // for i From dc1789719f863f6c0305216e066db71fba04edfa Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:31:19 +0100 Subject: [PATCH 0098/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a6ab9b757a6..cc1e1cced8f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1482,6 +1482,7 @@ private List findCitedEntryIndices( List keysCitedHere, String uniq = uniquefiers.get(currentKey); Optional tmpEntry = Optional.empty(); + if (uniq == null) { if (firstLimAuthors[j] > 0) { needsChange = true; @@ -1504,10 +1505,12 @@ private List findCitedEntryIndices( List keysCitedHere, } uniquif[j] = uniq; } + if (tmpEntry.isPresent()) { cEntries[j] = tmpEntry.get(); } - } + + } // for j if (needsChange) { citMarkers[i] = From 9cff02fd39de4390fcb79a1a7b51d708b50ed218 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:34:25 +0100 Subject: [PATCH 0099/1068] extracted block executed in every case --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index cc1e1cced8f..649ff07ac32 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1486,24 +1486,19 @@ private List findCitedEntryIndices( List keysCitedHere, if (uniq == null) { if (firstLimAuthors[j] > 0) { needsChange = true; - BibDatabase database = linkSourceBase.get(currentKey); - if (database != null) { - tmpEntry = database.getEntryByCitationKey(currentKey); - } } else { - BibDatabase database = linkSourceBase.get(currentKey); - if (database != null) { - tmpEntry = database.getEntryByCitationKey(currentKey); - } } uniquif[j] = ""; } else { needsChange = true; + uniquif[j] = uniq; + } + + { BibDatabase database = linkSourceBase.get(currentKey); if (database != null) { tmpEntry = database.getEntryByCitationKey(currentKey); } - uniquif[j] = uniq; } if (tmpEntry.isPresent()) { From 49cf8e2f35f66e2a3befc4a778ad9c0547088d3c Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:35:56 +0100 Subject: [PATCH 0100/1068] drop empty branch --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 649ff07ac32..43fb7085fd0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1486,7 +1486,6 @@ private List findCitedEntryIndices( List keysCitedHere, if (uniq == null) { if (firstLimAuthors[j] > 0) { needsChange = true; - } else { } uniquif[j] = ""; } else { From e9b7af91c1954a2879cbb186872c6e45626301c8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:38:04 +0100 Subject: [PATCH 0101/1068] extract firstLimAuthors case --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 43fb7085fd0..ce2c6ac1106 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1483,10 +1483,11 @@ private List findCitedEntryIndices( List keysCitedHere, String uniq = uniquefiers.get(currentKey); Optional tmpEntry = Optional.empty(); + if (uniq == null && (firstLimAuthors[j] > 0) ) { + needsChange = true; + } + if (uniq == null) { - if (firstLimAuthors[j] > 0) { - needsChange = true; - } uniquif[j] = ""; } else { needsChange = true; From 5878c4e42d5e81c3e40f6648a194de8e36a15783 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:39:21 +0100 Subject: [PATCH 0102/1068] drop useless condition --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ce2c6ac1106..57c60c9d9ea 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1483,7 +1483,7 @@ private List findCitedEntryIndices( List keysCitedHere, String uniq = uniquefiers.get(currentKey); Optional tmpEntry = Optional.empty(); - if (uniq == null && (firstLimAuthors[j] > 0) ) { + if (firstLimAuthors[j] > 0) { needsChange = true; } From 2d00a1cf7a8282532c699dd79ffda239d7e7b256 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:42:31 +0100 Subject: [PATCH 0103/1068] move uniq and tmpEntry closer to first use --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 57c60c9d9ea..63e739716ca 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1481,19 +1481,18 @@ private List findCitedEntryIndices( List keysCitedHere, } String uniq = uniquefiers.get(currentKey); - Optional tmpEntry = Optional.empty(); - - if (firstLimAuthors[j] > 0) { - needsChange = true; - } - if (uniq == null) { uniquif[j] = ""; } else { - needsChange = true; uniquif[j] = uniq; + needsChange = true; + } + + if (firstLimAuthors[j] > 0) { + needsChange = true; } + Optional tmpEntry = Optional.empty(); { BibDatabase database = linkSourceBase.get(currentKey); if (database != null) { From 3d0308eadfd4fd1c4e18bb46cde900d1f9e2bd0e Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:43:15 +0100 Subject: [PATCH 0104/1068] restrict scope of uniq --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 63e739716ca..e500ba25e71 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1480,12 +1480,14 @@ private List findCitedEntryIndices( List keysCitedHere, seenBefore.add(currentKey); } - String uniq = uniquefiers.get(currentKey); - if (uniq == null) { - uniquif[j] = ""; - } else { - uniquif[j] = uniq; - needsChange = true; + { + String uniq = uniquefiers.get(currentKey); + if (uniq == null) { + uniquif[j] = ""; + } else { + uniquif[j] = uniq; + needsChange = true; + } } if (firstLimAuthors[j] > 0) { From df316c12e8c2832f9195f87578067299eb946594 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:45:58 +0100 Subject: [PATCH 0105/1068] tmpEntry scope --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e500ba25e71..45fc7462993 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1494,17 +1494,17 @@ private List findCitedEntryIndices( List keysCitedHere, needsChange = true; } - Optional tmpEntry = Optional.empty(); { BibDatabase database = linkSourceBase.get(currentKey); + Optional tmpEntry = Optional.empty(); if (database != null) { tmpEntry = database.getEntryByCitationKey(currentKey); } + if (tmpEntry.isPresent()) { + cEntries[j] = tmpEntry.get(); + } } - if (tmpEntry.isPresent()) { - cEntries[j] = tmpEntry.get(); - } } // for j From 257152a982b138f513057c270c1dac4aa983bf53 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:50:16 +0100 Subject: [PATCH 0106/1068] if database is null, then tmpEntry is not present. Move it in. --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 45fc7462993..ea8041feb07 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1499,9 +1499,9 @@ private List findCitedEntryIndices( List keysCitedHere, Optional tmpEntry = Optional.empty(); if (database != null) { tmpEntry = database.getEntryByCitationKey(currentKey); - } - if (tmpEntry.isPresent()) { - cEntries[j] = tmpEntry.get(); + if (tmpEntry.isPresent()) { + cEntries[j] = tmpEntry.get(); + } } } From ba2e0b887b4c8499d5ec2f0c4431aaa01ec3ae9d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:51:46 +0100 Subject: [PATCH 0107/1068] tmpEntry scope --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ea8041feb07..49dae3b4e32 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1496,9 +1496,8 @@ private List findCitedEntryIndices( List keysCitedHere, { BibDatabase database = linkSourceBase.get(currentKey); - Optional tmpEntry = Optional.empty(); if (database != null) { - tmpEntry = database.getEntryByCitationKey(currentKey); + Optional tmpEntry = database.getEntryByCitationKey(currentKey); if (tmpEntry.isPresent()) { cEntries[j] = tmpEntry.get(); } From 1f16aea101bde6dbc409243aca2d094eddc9afa6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 18:53:01 +0100 Subject: [PATCH 0108/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 49dae3b4e32..3b721054885 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1504,7 +1504,6 @@ private List findCitedEntryIndices( List keysCitedHere, } } - } // for j if (needsChange) { From 3a986692ad03c7d9bec2fa8a343701bc85fdb31b Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 19:01:14 +0100 Subject: [PATCH 0109/1068] parens --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3b721054885..f53cda24449 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1519,7 +1519,7 @@ private List findCitedEntryIndices( List keysCitedHere, } // if normalStyle // Refresh all reference marks with the citation markers we computed: - boolean hadBibSection = getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null; + boolean hadBibSection = (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); // Check if we are supposed to set a character format for citations: boolean mustTestCharFormat = style.isFormatCitations(); for (int i = 0; i < nRefMarks; i++) { From 0ea3d277c96bde151e7e3055dffd8b8c70297648 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 20:55:29 +0100 Subject: [PATCH 0110/1068] comments --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f53cda24449..f88f33f5cae 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1398,6 +1398,13 @@ private List findCitedEntryIndices( List keysCitedHere, // uniquefiers: "a", "b" in (2000a, 2000b) uniquefiers.clear(); + + // The following block + // changes: citMarkers[i], uniquefiers + // uses: nRefMarks, normCitMarkers, bibtexKeys, + // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) + // linkSourceBase, entries, types + // if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { // Only for normal citations. Numbered citations and // citeKeys are already unique. From 4dde06fc36c18933593fdd384761904f45146609 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 20:56:42 +0100 Subject: [PATCH 0111/1068] comments --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f88f33f5cae..ab1d4d64e72 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1526,9 +1526,14 @@ private List findCitedEntryIndices( List keysCitedHere, } // if normalStyle // Refresh all reference marks with the citation markers we computed: + // changes: + // uses: style, names, xReferenceMarks, this.xtext, citMarkers, types + boolean hadBibSection = (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); + // Check if we are supposed to set a character format for citations: boolean mustTestCharFormat = style.isFormatCitations(); + for (int i = 0; i < nRefMarks; i++) { Object referenceMark = xReferenceMarks.getByName(names.get(i)); XTextContent bookmark = unoQI(XTextContent.class, referenceMark); @@ -1567,6 +1572,7 @@ private List findCitedEntryIndices( List keysCitedHere, } } + // uses: entries List unresolvedKeys = new ArrayList<>(); for (BibEntry entry : entries.keySet()) { if (entry instanceof UndefinedBibtexEntry) { From 013b631d80dd771c9aad16e44d506ce440c2e44c Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 20:57:12 +0100 Subject: [PATCH 0112/1068] format --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ab1d4d64e72..42acc2fa40e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1554,15 +1554,23 @@ private List findCitedEntryIndices( List keysCitedHere, String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | - WrappedTargetException ex) { + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { throw new UndefinedCharacterFormatException(charStyle); } } this.xtext.removeTextContent(bookmark); - insertReferenceMark(names.get(i), citMarkers[i], cursor, types[i] != OOBibBase.INVISIBLE_CIT, style); + insertReferenceMark(names.get(i), + citMarkers[i], + cursor, + types[i] != OOBibBase.INVISIBLE_CIT, + style + ); + if (hadBibSection && (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { // We have overwritten the marker for the start of the reference list. // We need to add it again. From 66e08aa4cec842302db6c6f2a6bea4a0627c47c7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 20:57:54 +0100 Subject: [PATCH 0113/1068] hadBibSection is final --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 42acc2fa40e..b13073f708f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1529,7 +1529,7 @@ private List findCitedEntryIndices( List keysCitedHere, // changes: // uses: style, names, xReferenceMarks, this.xtext, citMarkers, types - boolean hadBibSection = (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); + final boolean hadBibSection = (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); // Check if we are supposed to set a character format for citations: boolean mustTestCharFormat = style.isFormatCitations(); From 07c6f5026f111947e96c040218939d7884b3a36a Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 20:59:29 +0100 Subject: [PATCH 0114/1068] hadBibSection scope --- .../org/jabref/gui/openoffice/OOBibBase.java | 91 ++++++++++--------- 1 file changed, 46 insertions(+), 45 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b13073f708f..39cff3e4424 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1528,55 +1528,56 @@ private List findCitedEntryIndices( List keysCitedHere, // Refresh all reference marks with the citation markers we computed: // changes: // uses: style, names, xReferenceMarks, this.xtext, citMarkers, types + { + final boolean hadBibSection = (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); - final boolean hadBibSection = (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); - - // Check if we are supposed to set a character format for citations: - boolean mustTestCharFormat = style.isFormatCitations(); + // Check if we are supposed to set a character format for citations: + boolean mustTestCharFormat = style.isFormatCitations(); - for (int i = 0; i < nRefMarks; i++) { - Object referenceMark = xReferenceMarks.getByName(names.get(i)); - XTextContent bookmark = unoQI(XTextContent.class, referenceMark); - - XTextCursor cursor = - bookmark - .getAnchor() - .getText() - .createTextCursorByRange(bookmark.getAnchor()); - - if (mustTestCharFormat) { - // If we are supposed to set character format for citations, must run a test before we - // delete old citation markers. Otherwise, if the specified character format doesn't - // exist, we end up deleting the markers before the process crashes due to a the missing - // format, with catastrophic consequences for the user. - mustTestCharFormat = false; // need to do this only once - XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); - String charStyle = style.getCitationCharacterFormat(); - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - throw new UndefinedCharacterFormatException(charStyle); + for (int i = 0; i < nRefMarks; i++) { + Object referenceMark = xReferenceMarks.getByName(names.get(i)); + XTextContent bookmark = unoQI(XTextContent.class, referenceMark); + + XTextCursor cursor = + bookmark + .getAnchor() + .getText() + .createTextCursorByRange(bookmark.getAnchor()); + + if (mustTestCharFormat) { + // If we are supposed to set character format for citations, must run a test before we + // delete old citation markers. Otherwise, if the specified character format doesn't + // exist, we end up deleting the markers before the process crashes due to a the missing + // format, with catastrophic consequences for the user. + mustTestCharFormat = false; // need to do this only once + XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); + String charStyle = style.getCitationCharacterFormat(); + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + throw new UndefinedCharacterFormatException(charStyle); + } } - } - this.xtext.removeTextContent(bookmark); - - insertReferenceMark(names.get(i), - citMarkers[i], - cursor, - types[i] != OOBibBase.INVISIBLE_CIT, - style - ); - - if (hadBibSection && (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { - // We have overwritten the marker for the start of the reference list. - // We need to add it again. - cursor.collapseToEnd(); - OOUtil.insertParagraphBreak(this.xtext, cursor); - insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); + this.xtext.removeTextContent(bookmark); + + insertReferenceMark(names.get(i), + citMarkers[i], + cursor, + types[i] != OOBibBase.INVISIBLE_CIT, + style + ); + + if (hadBibSection && (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { + // We have overwritten the marker for the start of the reference list. + // We need to add it again. + cursor.collapseToEnd(); + OOUtil.insertParagraphBreak(this.xtext, cursor); + insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); + } } } From 1d12339b4994953b54b4488f081e3378029c4551 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 21:41:21 +0100 Subject: [PATCH 0115/1068] extract to separate method rcmApplyNewCitationMarkers --- .../org/jabref/gui/openoffice/OOBibBase.java | 138 +++++++++++------- 1 file changed, 84 insertions(+), 54 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 39cff3e4424..8f018827553 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1266,6 +1266,89 @@ private List findCitedEntryIndices( List keysCitedHere, return result; } + /** + * Visit each reference mark in names, + * remove its text content, + * call insertReferenceMark. + * + * After each insertReferenceMark call check if we lost the + * OOBibBase.BIB_SECTION_NAME bookmark and recrate it if we did. + * + * @param names Reference mark names + * @param citMarkers Corresponding text for each reference mark, + * that replaces the old text. + * @param types itcType codes for each reference mark. + * @param style + */ + private void rcmApplyNewCitationMarkers( List names, + String[] citMarkers, + int[] types, + OOBibStyle style ) + throws NoDocumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + CreationException, + WrappedTargetException, + PropertyVetoException + { + final int nRefMarks = names.size(); + assert( citMarkers.length == nRefMarks ); + assert( types.length == nRefMarks ); + + XNameAccess xReferenceMarks = getReferenceMarks(); + final boolean hadBibSection = (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); + + // If we are supposed to set character format for citations, + // must run a test before we delete old citation + // markers. Otherwise, if the specified character format + // doesn't exist, we end up deleting the markers before the + // process crashes due to a the missing format, with + // catastrophic consequences for the user. + boolean mustTestCharFormat = style.isFormatCitations(); + + for (int i = 0; i < nRefMarks; i++) { + Object referenceMark = xReferenceMarks.getByName(names.get(i)); + XTextContent bookmark = unoQI(XTextContent.class, referenceMark); + + XTextCursor cursor = + bookmark + .getAnchor() + .getText() + .createTextCursorByRange(bookmark.getAnchor()); + + if (mustTestCharFormat) { + mustTestCharFormat = false; // need to do this only once + XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); + String charStyle = style.getCitationCharacterFormat(); + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + throw new UndefinedCharacterFormatException(charStyle); + } + } + + this.xtext.removeTextContent(bookmark); + + insertReferenceMark(names.get(i), + citMarkers[i], + cursor, + types[i] != OOBibBase.INVISIBLE_CIT, + style + ); + + if (hadBibSection && (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { + // We have overwritten the marker for the start of the reference list. + // We need to add it again. + cursor.collapseToEnd(); + OOUtil.insertParagraphBreak(this.xtext, cursor); + insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); + } + } + } private List refreshCiteMarkersInternal ( List databases, @@ -1526,60 +1609,7 @@ private List findCitedEntryIndices( List keysCitedHere, } // if normalStyle // Refresh all reference marks with the citation markers we computed: - // changes: - // uses: style, names, xReferenceMarks, this.xtext, citMarkers, types - { - final boolean hadBibSection = (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); - - // Check if we are supposed to set a character format for citations: - boolean mustTestCharFormat = style.isFormatCitations(); - - for (int i = 0; i < nRefMarks; i++) { - Object referenceMark = xReferenceMarks.getByName(names.get(i)); - XTextContent bookmark = unoQI(XTextContent.class, referenceMark); - - XTextCursor cursor = - bookmark - .getAnchor() - .getText() - .createTextCursorByRange(bookmark.getAnchor()); - - if (mustTestCharFormat) { - // If we are supposed to set character format for citations, must run a test before we - // delete old citation markers. Otherwise, if the specified character format doesn't - // exist, we end up deleting the markers before the process crashes due to a the missing - // format, with catastrophic consequences for the user. - mustTestCharFormat = false; // need to do this only once - XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); - String charStyle = style.getCitationCharacterFormat(); - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - throw new UndefinedCharacterFormatException(charStyle); - } - } - - this.xtext.removeTextContent(bookmark); - - insertReferenceMark(names.get(i), - citMarkers[i], - cursor, - types[i] != OOBibBase.INVISIBLE_CIT, - style - ); - - if (hadBibSection && (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { - // We have overwritten the marker for the start of the reference list. - // We need to add it again. - cursor.collapseToEnd(); - OOUtil.insertParagraphBreak(this.xtext, cursor); - insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); - } - } - } + rcmApplyNewCitationMarkers( names, citMarkers, types, style ); // uses: entries List unresolvedKeys = new ArrayList<>(); From b35767feba66a36d0cbf25b0041d7946cc4595b8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 21:50:12 +0100 Subject: [PATCH 0116/1068] skip this itertaion if !op.isPresent() --- .../org/jabref/gui/openoffice/OOBibBase.java | 150 +++++++++--------- 1 file changed, 76 insertions(+), 74 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8f018827553..5fe52d33211 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1398,84 +1398,85 @@ private void rcmApplyNewCitationMarkers( List names, for (int i = 0; i < names.size(); i++) { final String namei = names.get(i); Optional op = parseRefMarkName( namei ); - if ( op.isPresent() ) { - ParsedRefMark ov = op.get(); - int type = ov.itcType; - types[i] = type; // Remember the itcType in case we need to uniquefy. - String[] keys = ov.citedKeys.stream().toArray(String[]::new); - bibtexKeys[i] = keys; - // - BibEntry[] cEntries = - linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, keys, namei ); - assert (cEntries.length == keys.length) ; + if ( !op.isPresent() ) { + continue; + } + ParsedRefMark ov = op.get(); + int type = ov.itcType; + types[i] = type; // Remember the itcType in case we need to uniquefy. + String[] keys = ov.citedKeys.stream().toArray(String[]::new); + bibtexKeys[i] = keys; + // + BibEntry[] cEntries = + linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, keys, namei ); + assert (cEntries.length == keys.length) ; + // + // normCitMarker[ cEntries.length ] null if missing + String[] normCitMarker = new String[cEntries.length]; + String citationMarker; // normCitMarker.replace( null -> "" ).join(",") + // + // fill normCitMarker, set citationMarker + if (style.isCitationKeyCiteMarkers()) { // - // normCitMarker[ cEntries.length ] null if missing - String[] normCitMarker = new String[cEntries.length]; - String citationMarker; // normCitMarker.replace( null -> "" ).join(",") + citationMarker = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); + normCitMarker = rcmNormCitMarkersForIsCitationKeyCiteMarkers( cEntries, style ); // - // fill normCitMarker, set citationMarker - if (style.isCitationKeyCiteMarkers()) { - // - citationMarker = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); - normCitMarker = rcmNormCitMarkersForIsCitationKeyCiteMarkers( cEntries, style ); - // - } else if (style.isNumberEntries()) { - List num ; - if (style.isSortByPosition()) { - num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, keys, style, cns ); - } else { - num = findCitedEntryIndices( Arrays.asList(keys) , cited ); - } - // - // set citationMarker - citationMarker = - style.getNumCitationMarker(num, minGroupingCount, false); - // - // fill normCitMarker - for (int j = 0; j < cEntries.length; j++) { - List numj = Collections.singletonList(num.get(j)); - normCitMarker[j] = - style.getNumCitationMarker( numj, minGroupingCount, false ); - } - // + } else if (style.isNumberEntries()) { + List num ; + if (style.isSortByPosition()) { + num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, keys, style, cns ); } else { - assert( !style.isCitationKeyCiteMarkers() ); - assert( !style.isNumberEntries() ); - // Citations in (Au1, Au2 2000) form - // - // sort itcBlock - sortBibEntryArray( cEntries, style ); - // - // Update key list to match the new sorting: - for (int j = 0; j < cEntries.length; j++) { - bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); - } - // - citationMarker = style.getCitationMarker( Arrays.asList(cEntries), // entries - entries, // database - type == OOBibBase.AUTHORYEAR_PAR, // inParenthesis - null, // uniquefiers - null // unlimAuthors - ); - // - // We need "normalized" (in parenthesis) markers - // for uniqueness checking purposes: - // - // Fill normCitMarker - for (int j = 0; j < cEntries.length; j++) { - List cej = Collections.singletonList(cEntries[j]); - normCitMarker[j] = - style.getCitationMarker( cej, // entries - entries, // database - true, // inParenthesis - null, // uniquefiers - new int[] {-1} // unlimAuthors - ); - } + num = findCitedEntryIndices( Arrays.asList(keys) , cited ); } - citMarkers[i] = citationMarker; - normCitMarkers[i] = normCitMarker; - } // if (citeMatcher.find()) + // + // set citationMarker + citationMarker = + style.getNumCitationMarker(num, minGroupingCount, false); + // + // fill normCitMarker + for (int j = 0; j < cEntries.length; j++) { + List numj = Collections.singletonList(num.get(j)); + normCitMarker[j] = + style.getNumCitationMarker( numj, minGroupingCount, false ); + } + // + } else { + assert( !style.isCitationKeyCiteMarkers() ); + assert( !style.isNumberEntries() ); + // Citations in (Au1, Au2 2000) form + // + // sort itcBlock + sortBibEntryArray( cEntries, style ); + // + // Update key list to match the new sorting: + for (int j = 0; j < cEntries.length; j++) { + bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); + } + // + citationMarker = style.getCitationMarker( Arrays.asList(cEntries), // entries + entries, // database + type == OOBibBase.AUTHORYEAR_PAR, // inParenthesis + null, // uniquefiers + null // unlimAuthors + ); + // + // We need "normalized" (in parenthesis) markers + // for uniqueness checking purposes: + // + // Fill normCitMarker + for (int j = 0; j < cEntries.length; j++) { + List cej = Collections.singletonList(cEntries[j]); + normCitMarker[j] = + style.getCitationMarker( cej, // entries + entries, // database + true, // inParenthesis + null, // uniquefiers + new int[] {-1} // unlimAuthors + ); + } + } + citMarkers[i] = citationMarker; + normCitMarkers[i] = normCitMarker; } // for i @@ -1611,6 +1612,7 @@ private void rcmApplyNewCitationMarkers( List names, // Refresh all reference marks with the citation markers we computed: rcmApplyNewCitationMarkers( names, citMarkers, types, style ); + // Collect and return uunresolved citation keys. // uses: entries List unresolvedKeys = new ArrayList<>(); for (BibEntry entry : entries.keySet()) { From 873d2733b4d963e25876120286dacd4572f6df46 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 22:09:38 +0100 Subject: [PATCH 0117/1068] split the large loop into two smaller ones --- .../org/jabref/gui/openoffice/OOBibBase.java | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5fe52d33211..3140f29a1dc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1387,14 +1387,10 @@ private void rcmApplyNewCitationMarkers( List names, style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); int[] types = new int[nRefMarks]; - // - // + // fill: // types[i] = ov.itcType // bibtexKeys[i] = ov.citedKeys.toArray() - // citMarkers[i] = what goes in the text - // normCitMarkers[i][j] = for unification - // for (int i = 0; i < names.size(); i++) { final String namei = names.get(i); Optional op = parseRefMarkName( namei ); @@ -1402,14 +1398,20 @@ private void rcmApplyNewCitationMarkers( List names, continue; } ParsedRefMark ov = op.get(); - int type = ov.itcType; - types[i] = type; // Remember the itcType in case we need to uniquefy. - String[] keys = ov.citedKeys.stream().toArray(String[]::new); - bibtexKeys[i] = keys; + types[i] = ov.itcType; // Remember the itcType in case we need to uniquefy. + bibtexKeys[i] = ov.citedKeys.stream().toArray(String[]::new); // + } + + // fill: + // citMarkers[i] = what goes in the text + // normCitMarkers[i][j] = for unification + for (int i = 0; i < names.size(); i++) { + final String namei = names.get(i); + BibEntry[] cEntries = - linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, keys, namei ); - assert (cEntries.length == keys.length) ; + linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); + assert (cEntries.length == bibtexKeys[i].length) ; // // normCitMarker[ cEntries.length ] null if missing String[] normCitMarker = new String[cEntries.length]; @@ -1424,9 +1426,9 @@ private void rcmApplyNewCitationMarkers( List names, } else if (style.isNumberEntries()) { List num ; if (style.isSortByPosition()) { - num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, keys, style, cns ); + num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, bibtexKeys[i], style, cns ); } else { - num = findCitedEntryIndices( Arrays.asList(keys) , cited ); + num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , cited ); } // // set citationMarker @@ -1455,7 +1457,7 @@ private void rcmApplyNewCitationMarkers( List names, // citationMarker = style.getCitationMarker( Arrays.asList(cEntries), // entries entries, // database - type == OOBibBase.AUTHORYEAR_PAR, // inParenthesis + types[i] == OOBibBase.AUTHORYEAR_PAR, // inParenthesis null, // uniquefiers null // unlimAuthors ); From 2f8d1c17a59ed523a5bee2fd080d8f354f88cc54 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 22:12:44 +0100 Subject: [PATCH 0118/1068] use nRefMarks in first loop --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3140f29a1dc..a0d4d7d1cb3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1391,7 +1391,7 @@ private void rcmApplyNewCitationMarkers( List names, // fill: // types[i] = ov.itcType // bibtexKeys[i] = ov.citedKeys.toArray() - for (int i = 0; i < names.size(); i++) { + for (int i = 0; i < nRefMarks; i++) { final String namei = names.get(i); Optional op = parseRefMarkName( namei ); if ( !op.isPresent() ) { From 7704893fb151e1c34486b224a5fe54afb62b6595 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 22:18:07 +0100 Subject: [PATCH 0119/1068] move variable towards their use sites --- .../org/jabref/gui/openoffice/OOBibBase.java | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a0d4d7d1cb3..00e116b1744 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1368,25 +1368,13 @@ private void rcmApplyNewCitationMarkers( List names, GetSortedCitedEntriesResult sce = getSortedCitedEntries( databases, style, xReferenceMarks ); - Map linkSourceBase = sce.linkSourceBase; - List cited = sce.citedKeys; - Map entries = sce.entries; List names = sce.refMarkNames; //***** - // // For numbered citation style. Map( citedKey, number ) - CitationNumberingState cns = new CitationNumberingState(); - - // First compute citation markers for all citations: + // Compute citation markers for all citations: final int nRefMarks = names.size(); - String[] citMarkers = new String[nRefMarks]; - String[][] normCitMarkers = new String[nRefMarks][]; - String[][] bibtexKeys = new String[nRefMarks][]; - - final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - - int[] types = new int[nRefMarks]; + int[] types = new int[nRefMarks]; + String[][] bibtexKeys = new String[nRefMarks][]; // fill: // types[i] = ov.itcType @@ -1403,6 +1391,18 @@ private void rcmApplyNewCitationMarkers( List names, // } + Map entries = sce.entries; + List cited = sce.citedKeys; + Map linkSourceBase = sce.linkSourceBase; + + // // For numbered citation style. Map( citedKey, number ) + CitationNumberingState cns = new CitationNumberingState(); + + final int minGroupingCount = + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + + String[] citMarkers = new String[nRefMarks]; + String[][] normCitMarkers = new String[nRefMarks][]; // fill: // citMarkers[i] = what goes in the text // normCitMarkers[i][j] = for unification From 56ecce4565fe3bf76f964ea4f43f17551df0bece Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Feb 2021 22:23:26 +0100 Subject: [PATCH 0120/1068] The 3 ifelse cases will get teair own loops --- .../org/jabref/gui/openoffice/OOBibBase.java | 342 +++++++++--------- 1 file changed, 167 insertions(+), 175 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 00e116b1744..c9ae0f9f0cd 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1152,19 +1152,6 @@ private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] c return citationMarker; } - private static String[] rcmNormCitMarkersForIsCitationKeyCiteMarkers( BibEntry[] cEntries, - OOBibStyle style ) - { - assert( style.isCitationKeyCiteMarkers() ); - - String[] normCitMarker = new String[cEntries.length]; - for (int j = 0; j < cEntries.length; j++) { - Optional cejKey = cEntries[j].getCitationKey(); - normCitMarker[j] = cejKey.orElse(null); - } - return normCitMarker; - } - private class CitationNumberingState { public Map numbers; public int lastNum; @@ -1402,70 +1389,78 @@ private void rcmApplyNewCitationMarkers( List names, style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); String[] citMarkers = new String[nRefMarks]; - String[][] normCitMarkers = new String[nRefMarks][]; // fill: // citMarkers[i] = what goes in the text - // normCitMarkers[i][j] = for unification - for (int i = 0; i < names.size(); i++) { - final String namei = names.get(i); - BibEntry[] cEntries = - linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); - assert (cEntries.length == bibtexKeys[i].length) ; - // - // normCitMarker[ cEntries.length ] null if missing - String[] normCitMarker = new String[cEntries.length]; - String citationMarker; // normCitMarker.replace( null -> "" ).join(",") - // - // fill normCitMarker, set citationMarker - if (style.isCitationKeyCiteMarkers()) { - // - citationMarker = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); - normCitMarker = rcmNormCitMarkersForIsCitationKeyCiteMarkers( cEntries, style ); - // - } else if (style.isNumberEntries()) { + + // fill citMarkers + if (style.isCitationKeyCiteMarkers()) { + + for (int i = 0; i < names.size(); i++) { + final String namei = names.get(i); + + BibEntry[] cEntries = + linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); + assert (cEntries.length == bibtexKeys[i].length) ; + citMarkers[i] = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); + } + uniquefiers.clear(); + + } else if (style.isNumberEntries()) { + + for (int i = 0; i < names.size(); i++) { + final String namei = names.get(i); + + BibEntry[] cEntries = + linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); + assert (cEntries.length == bibtexKeys[i].length) ; + List num ; if (style.isSortByPosition()) { num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, bibtexKeys[i], style, cns ); } else { num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , cited ); } - // - // set citationMarker - citationMarker = - style.getNumCitationMarker(num, minGroupingCount, false); - // - // fill normCitMarker - for (int j = 0; j < cEntries.length; j++) { - List numj = Collections.singletonList(num.get(j)); - normCitMarker[j] = - style.getNumCitationMarker( numj, minGroupingCount, false ); - } - // - } else { - assert( !style.isCitationKeyCiteMarkers() ); - assert( !style.isNumberEntries() ); - // Citations in (Au1, Au2 2000) form - // + citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); + } + uniquefiers.clear(); + + } else { + + assert( !style.isCitationKeyCiteMarkers() ); + assert( !style.isNumberEntries() ); + // Citations in (Au1, Au2 2000) form + + // normCitMarkers[i][j] = for unification + String[][] normCitMarkers = new String[nRefMarks][]; + + for (int i = 0; i < names.size(); i++) { + final String namei = names.get(i); + + BibEntry[] cEntries = + linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); + assert (cEntries.length == bibtexKeys[i].length) ; + // sort itcBlock sortBibEntryArray( cEntries, style ); - // + // Update key list to match the new sorting: for (int j = 0; j < cEntries.length; j++) { bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); } - // - citationMarker = style.getCitationMarker( Arrays.asList(cEntries), // entries - entries, // database - types[i] == OOBibBase.AUTHORYEAR_PAR, // inParenthesis - null, // uniquefiers - null // unlimAuthors - ); - // + + citMarkers[i] = style.getCitationMarker( Arrays.asList(cEntries), // entries + entries, // database + types[i] == OOBibBase.AUTHORYEAR_PAR, + null, // uniquefiers + null // unlimAuthors + ); + // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: // - // Fill normCitMarker + // normCitMarker[ cEntries.length ] null if missing + String[] normCitMarker = new String[cEntries.length]; for (int j = 0; j < cEntries.length; j++) { List cej = Collections.singletonList(cEntries[j]); normCitMarker[j] = @@ -1476,140 +1471,137 @@ private void rcmApplyNewCitationMarkers( List names, new int[] {-1} // unlimAuthors ); } + normCitMarkers[i] = normCitMarker; } - citMarkers[i] = citationMarker; - normCitMarkers[i] = normCitMarker; - } // for i + uniquefiers.clear(); - - // uniquefiers: "a", "b" in (2000a, 2000b) - uniquefiers.clear(); - - // The following block - // changes: citMarkers[i], uniquefiers - // uses: nRefMarks, normCitMarkers, bibtexKeys, - // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) - // linkSourceBase, entries, types - // - if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { - // Only for normal citations. Numbered citations and - // citeKeys are already unique. - - // See if there are duplicate citations marks referring to - // different entries. If so, we need to use uniquefiers: - - // refKeys: normCitMarker to list of bibtexkeys sharing it. - // The entries in the lists are ordered as in - // normCitMarkers[i][j] - Map> refKeys = new HashMap<>(); - - for (int i = 0; i < nRefMarks; i++) { - // Compare normalized markers, since the actual - // markers can be different. - String[] markers = normCitMarkers[i]; - for (int j = 0; j < markers.length; j++) { - String marker = markers[j]; - String currentKey = bibtexKeys[i][j]; - if (refKeys.containsKey(marker)) { - // Ok, we have seen this exact marker before. - if (!refKeys.get(marker).contains(currentKey)) { - // ... but not for this entry. - refKeys.get(marker).add(currentKey); + // The following block + // changes: citMarkers[i], uniquefiers + // uses: nRefMarks, normCitMarkers, bibtexKeys, + // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) + // linkSourceBase, entries, types + // + if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { + // Only for normal citations. Numbered citations and + // citeKeys are already unique. + + // See if there are duplicate citations marks referring to + // different entries. If so, we need to use uniquefiers: + + // refKeys: normCitMarker to list of bibtexkeys sharing it. + // The entries in the lists are ordered as in + // normCitMarkers[i][j] + Map> refKeys = new HashMap<>(); + + for (int i = 0; i < nRefMarks; i++) { + // Compare normalized markers, since the actual + // markers can be different. + String[] markers = normCitMarkers[i]; + for (int j = 0; j < markers.length; j++) { + String marker = markers[j]; + String currentKey = bibtexKeys[i][j]; + if (refKeys.containsKey(marker)) { + // Ok, we have seen this exact marker before. + if (!refKeys.get(marker).contains(currentKey)) { + // ... but not for this entry. + refKeys.get(marker).add(currentKey); + } + } else { + // add as new entry + List l = new ArrayList<>(1); + l.add(currentKey); + refKeys.put(marker, l); } - } else { - // add as new entry - List l = new ArrayList<>(1); - l.add(currentKey); - refKeys.put(marker, l); } } - } - // Go through the collected lists and see where we need to - // uniquefy: - for (Map.Entry> stringListEntry : refKeys.entrySet()) { - List clashingKeys = stringListEntry.getValue(); - if (clashingKeys.size() > 1) { - // This marker appears for more than one unique entry: - int uniq = 'a'; - for (String key : clashingKeys) { - // Update the map of uniquefiers for the - // benefit of both the following generation of - // new citation markers, and for the method - // that builds the bibliography: - uniquefiers.put(key, String.valueOf((char) uniq)); - uniq++; + // Go through the collected lists and see where we need to + // uniquefy: + for (Map.Entry> stringListEntry : refKeys.entrySet()) { + List clashingKeys = stringListEntry.getValue(); + if (clashingKeys.size() > 1) { + // This marker appears for more than one unique entry: + int uniq = 'a'; + for (String key : clashingKeys) { + // Update the map of uniquefiers for the + // benefit of both the following generation of + // new citation markers, and for the method + // that builds the bibliography: + uniquefiers.put(key, String.valueOf((char) uniq)); + uniq++; + } } } - } - // Finally, go through all citation markers, and update - // those referring to entries in our current list: - final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); - Set seenBefore = new HashSet<>(); - for (int i = 0; i < nRefMarks; i++) { - final int nCitedEntries = bibtexKeys[i].length; - boolean needsChange = false; - int[] firstLimAuthors = new int[nCitedEntries]; - String[] uniquif = new String[nCitedEntries]; - BibEntry[] cEntries = new BibEntry[nCitedEntries]; - - for (int j = 0; j < nCitedEntries; j++) { - String currentKey = bibtexKeys[i][j]; - - // firstLimAuthors will be (-1) except at the first - // refMark it appears at, where a positive maxAuthorsFirst - // may override. This is why: - // https://discourse.jabref.org/t/number-of-authors-in-citations-style-libreoffice/747/3 - // "Some citation styles require to list the full - // names of the first 4 authors for the first - // time. Later it is sufficient to have only maybe - // (Author A and Author B 2019 et al.)" - firstLimAuthors[j] = -1; - if (maxAuthorsFirst > 0) { - if (!seenBefore.contains(currentKey)) { - firstLimAuthors[j] = maxAuthorsFirst; + // Finally, go through all citation markers, and update + // those referring to entries in our current list: + final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); + Set seenBefore = new HashSet<>(); + for (int i = 0; i < nRefMarks; i++) { + final int nCitedEntries = bibtexKeys[i].length; + boolean needsChange = false; + int[] firstLimAuthors = new int[nCitedEntries]; + String[] uniquif = new String[nCitedEntries]; + BibEntry[] cEntries = new BibEntry[nCitedEntries]; + + for (int j = 0; j < nCitedEntries; j++) { + String currentKey = bibtexKeys[i][j]; + + // firstLimAuthors will be (-1) except at the first + // refMark it appears at, where a positive maxAuthorsFirst + // may override. This is why: + // https://discourse.jabref.org/t/number-of-authors-in-citations-style-libreoffice/747/3 + // "Some citation styles require to list the full + // names of the first 4 authors for the first + // time. Later it is sufficient to have only maybe + // (Author A and Author B 2019 et al.)" + firstLimAuthors[j] = -1; + if (maxAuthorsFirst > 0) { + if (!seenBefore.contains(currentKey)) { + firstLimAuthors[j] = maxAuthorsFirst; + } + seenBefore.add(currentKey); } - seenBefore.add(currentKey); - } - { - String uniq = uniquefiers.get(currentKey); - if (uniq == null) { - uniquif[j] = ""; - } else { - uniquif[j] = uniq; - needsChange = true; + { + String uniq = uniquefiers.get(currentKey); + if (uniq == null) { + uniquif[j] = ""; + } else { + uniquif[j] = uniq; + needsChange = true; + } } - } - if (firstLimAuthors[j] > 0) { - needsChange = true; - } + if (firstLimAuthors[j] > 0) { + needsChange = true; + } - { - BibDatabase database = linkSourceBase.get(currentKey); - if (database != null) { - Optional tmpEntry = database.getEntryByCitationKey(currentKey); - if (tmpEntry.isPresent()) { - cEntries[j] = tmpEntry.get(); + { + BibDatabase database = linkSourceBase.get(currentKey); + if (database != null) { + Optional tmpEntry = database.getEntryByCitationKey(currentKey); + if (tmpEntry.isPresent()) { + cEntries[j] = tmpEntry.get(); + } } } - } - } // for j + } // for j + + if (needsChange) { + citMarkers[i] = + style.getCitationMarker( Arrays.asList(cEntries), + entries, + types[i] == OOBibBase.AUTHORYEAR_PAR, + uniquif, + firstLimAuthors + ); + } + } // for i + } // if normalStyle + } - if (needsChange) { - citMarkers[i] = - style.getCitationMarker( Arrays.asList(cEntries), - entries, - types[i] == OOBibBase.AUTHORYEAR_PAR, - uniquif, - firstLimAuthors - ); - } - } // for i - } // if normalStyle // Refresh all reference marks with the citation markers we computed: rcmApplyNewCitationMarkers( names, citMarkers, types, style ); From fa0cb88220fe912fc50b2015a9442aad1f0e7121 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 09:35:35 +0100 Subject: [PATCH 0121/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c9ae0f9f0cd..50d64dbb119 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1337,10 +1337,8 @@ private void rcmApplyNewCitationMarkers( List names, } } - private List refreshCiteMarkersInternal - ( List databases, - OOBibStyle style - ) + private List refreshCiteMarkersInternal( List databases, + OOBibStyle style ) throws WrappedTargetException, IllegalArgumentException, NoSuchElementException, From 99070a987996b29bbbac1ff4ee9e6d1dc3c3a6a0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 09:56:11 +0100 Subject: [PATCH 0122/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 50d64dbb119..f8e6bf35f76 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1085,11 +1085,9 @@ private class GetSortedCitedEntriesResult { * order: from findCitedKeys(), * except for style.isNumberEntries() where reordered as entries */ - private GetSortedCitedEntriesResult getSortedCitedEntries - ( List databases, - OOBibStyle style, - XNameAccess xReferenceMarks - ) + private GetSortedCitedEntriesResult getSortedCitedEntries( List databases, + OOBibStyle style, + XNameAccess xReferenceMarks ) throws NoSuchElementException, WrappedTargetException, NoDocumentException @@ -1354,7 +1352,6 @@ private List refreshCiteMarkersInternal( List databases, GetSortedCitedEntriesResult sce = getSortedCitedEntries( databases, style, xReferenceMarks ); List names = sce.refMarkNames; - //***** // Compute citation markers for all citations: final int nRefMarks = names.size(); From 79f10327490acf6c50b0a86d73a107ca2f664c58 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 10:24:06 +0100 Subject: [PATCH 0123/1068] xtext -> xText --- .../org/jabref/gui/openoffice/OOBibBase.java | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f8e6bf35f76..6dc80ff59ae 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -130,7 +130,7 @@ class OOBibBase { /* document-related */ private XMultiServiceFactory mxDocFactory; private XTextDocument mxDoc; - private XText xtext; + private XText xText; private XTextViewCursorSupplier xViewCursorSupplier; private XComponent xCurrentComponent; private XPropertySet propertySet; @@ -317,7 +317,7 @@ public String toString() { * - this.xCurrentComponent * - this.mxDoc * - this.xViewCursorSupplier - * - this.xtext + * - this.xText * - this.mxDocFactory * - this.userProperties * - this.propertySet @@ -363,7 +363,7 @@ public void selectDocument() } // get a reference to the body text of the document - this.xtext = this.mxDoc.getText(); + this.xText = this.mxDoc.getText(); // Access the text document's multi service factory: this.mxDocFactory = unoQI(XMultiServiceFactory.class, this.mxDoc); @@ -388,7 +388,7 @@ private void forgetDocument(){ this.xCurrentComponent = null ; this.mxDoc = null ; this.xViewCursorSupplier = null ; - this.xtext = null ; + this.xText = null ; this.mxDocFactory = null ; this.userProperties = null ; this.propertySet = null ; @@ -404,7 +404,7 @@ public boolean checkDocumentConnection(){ if (null == this.xCurrentComponent ){ res = false; } if (null == this.mxDoc ){ res = false; } if (null == this.xViewCursorSupplier ){ res = false; } - if (null == this.xtext ){ res = false; } + if (null == this.xText ){ res = false; } if (null == this.mxDocFactory ){ res = false; } if (null == this.userProperties ){ res = false; } if (null == this.propertySet ){ res = false; } @@ -1316,7 +1316,7 @@ private void rcmApplyNewCitationMarkers( List names, } } - this.xtext.removeTextContent(bookmark); + this.xText.removeTextContent(bookmark); insertReferenceMark(names.get(i), citMarkers[i], @@ -1329,7 +1329,7 @@ private void rcmApplyNewCitationMarkers( List names, // We have overwritten the marker for the start of the reference list. // We need to add it again. cursor.collapseToEnd(); - OOUtil.insertParagraphBreak(this.xtext, cursor); + OOUtil.insertParagraphBreak(this.xText, cursor); insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); } } @@ -1811,15 +1811,15 @@ private void insertFullReferenceAtCursor(XTextCursor cursor, Map entries, OOBibSty XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, this.mxDoc); XTextSection section = (XTextSection) ((Any) supplier.getTextSections().getByName(OOBibBase.BIB_SECTION_NAME)) .getObject(); - XTextCursor cursor = this.xtext.createTextCursorByRange(section.getAnchor()); - OOUtil.insertTextAtCurrentLocation(this.xtext, cursor, (String) style.getProperty(OOBibStyle.TITLE), + XTextCursor cursor = this.xText.createTextCursorByRange(section.getAnchor()); + OOUtil.insertTextAtCurrentLocation(this.xText, cursor, (String) style.getProperty(OOBibStyle.TITLE), (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT)); insertFullReferenceAtCursor(cursor, entries, style, (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT)); @@ -1907,7 +1907,7 @@ private XTextContent insertBookMark(String name, XTextCursor position) XTextContent xTextContent = unoQI(XTextContent.class, bookmark); // insert bookmark at the end of the document // instead of mxDocText.getEnd you could use a text cursor's XTextRange interface or any XTextRange - this.xtext.insertTextContent(position, xTextContent, true); + this.xText.insertTextContent(position, xTextContent, true); position.collapseToEnd(); return xTextContent; } @@ -1983,7 +1983,7 @@ private void removeReferenceMark(String name) if (xReferenceMarks.hasByName(name)) { Object referenceMark = xReferenceMarks.getByName(name); XTextContent bookmark = unoQI(XTextContent.class, referenceMark); - this.xtext.removeTextContent(bookmark); + this.xText.removeTextContent(bookmark); } } @@ -2044,7 +2044,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // TODO: doesn't work for citations in footnotes/tables List names = getSortedReferenceMarks(nameAccess); - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, this.xtext); + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, this.xText); int piv = 0; boolean madeModifications = false; @@ -2134,7 +2134,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) // TODO: doesn't work for citations in footnotes/tables List names = getSortedReferenceMarks(nameAccess); - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, this.xtext); + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, this.xText); int piv = 0; boolean madeModifications = false; From 84c4a385efd7eddd20bf9495930a63dd5121beba Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 11:17:11 +0100 Subject: [PATCH 0124/1068] start to move connection stuff to documentConnection --- .../org/jabref/gui/openoffice/OOBibBase.java | 221 ++++++++++-------- 1 file changed, 127 insertions(+), 94 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6dc80ff59ae..85a72b0c130 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -127,15 +127,100 @@ class OOBibBase { private final Comparator entryComparator; private final Comparator yearAuthorTitleComparator; - /* document-related */ - private XMultiServiceFactory mxDocFactory; - private XTextDocument mxDoc; - private XText xText; - private XTextViewCursorSupplier xViewCursorSupplier; - private XComponent xCurrentComponent; - private XPropertySet propertySet; - private XPropertyContainer userProperties; + /* document-connection related */ + private class DocumentConnection { + public XMultiServiceFactory mxDocFactory; + public XTextDocument mxDoc; + public XText xText; + public XTextViewCursorSupplier xViewCursorSupplier; + public XComponent xCurrentComponent; + public XPropertySet propertySet; + public XPropertyContainer userProperties; + DocumentConnection(XMultiServiceFactory mxDocFactory, + XTextDocument mxDoc, + XText xText, + XTextViewCursorSupplier xViewCursorSupplier, + XComponent xCurrentComponent, + XPropertySet propertySet, + XPropertyContainer userProperties + ) { + this.mxDocFactory = mxDocFactory ; + this.mxDoc = mxDoc ; + this.xText = xText ; + this.xViewCursorSupplier = xViewCursorSupplier ; + this.xCurrentComponent = xCurrentComponent ; + this.propertySet = propertySet ; + this.userProperties = userProperties ; + } + + public Optional getDocumentTitle() { + return OOBibBase.getDocumentTitle( this.mxDoc ); + } + + private Optional getCustomProperty(String property) + throws UnknownPropertyException, + WrappedTargetException + { + assert (this.propertySet != null); + + XPropertySetInfo psi = + this.propertySet + .getPropertySetInfo(); + if (psi.hasPropertyByName(property)) { + String v = + this.propertySet + .getPropertyValue(property) + .toString(); + return Optional.ofNullable(v); + } + return Optional.empty(); + } + + private void setCustomProperty(String property, String value) + throws UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException + { + XPropertySetInfo psi = + this.propertySet + .getPropertySetInfo(); + if (psi.hasPropertyByName(property)) { + this.userProperties.removeProperty(property); + } + if (value != null) { + this.userProperties + .addProperty(property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value) + ); + } + } + + /** + * + * @throws NoDocumentException + * + */ + private XNameAccess getReferenceMarks() + throws NoDocumentException + { + XReferenceMarksSupplier supplier = + unoQI(XReferenceMarksSupplier.class, + this.xCurrentComponent); + try { + XNameAccess res = supplier.getReferenceMarks(); + return res; + } catch ( Exception ex ){ + LOGGER.warn( "getReferenceMarks caught: ", ex ); + throw new NoDocumentException("getReferenceMarks failed"); + } + } + } + + private DocumentConnection documentConnection; /* * uniquefiers : maps bibtexkeys to letters ("a", "b") */ @@ -328,6 +413,7 @@ public void selectDocument() NoSuchElementException, WrappedTargetException { + XTextDocument mxDoc; { XTextDocument selected; List textDocumentList = getTextDocuments(this.xDesktop); @@ -346,34 +432,47 @@ public void selectDocument() if (selected == null) { return; } - this.xCurrentComponent = unoQI(XComponent.class, selected); - this.mxDoc = selected; + mxDoc = selected; } + XComponent component = unoQI(XComponent.class, mxDoc); // TODO: what is the point of the next line? Does it have a side effect? if ( run_useless_parts ){ - unoQI(XDocumentIndexesSupplier.class, xCurrentComponent); + unoQI(XDocumentIndexesSupplier.class, component); } + XTextViewCursorSupplier viewCursorSupplier; { - XModel mo = unoQI(XModel.class, this.xCurrentComponent); + XModel mo = unoQI(XModel.class, component); XController co = mo.getCurrentController(); - this.xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); + viewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); } // get a reference to the body text of the document - this.xText = this.mxDoc.getText(); + XText text = mxDoc.getText(); // Access the text document's multi service factory: - this.mxDocFactory = unoQI(XMultiServiceFactory.class, this.mxDoc); + XMultiServiceFactory mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); + XPropertyContainer userProperties; { XDocumentPropertiesSupplier supp = - unoQI(XDocumentPropertiesSupplier.class, this.mxDoc); - this.userProperties = supp.getDocumentProperties().getUserDefinedProperties(); + unoQI(XDocumentPropertiesSupplier.class, mxDoc); + userProperties = supp.getDocumentProperties().getUserDefinedProperties(); } - this.propertySet = unoQI(XPropertySet.class, this.userProperties); + + XPropertySet propertySet = unoQI(XPropertySet.class, userProperties); + + this.documentConnection = new DocumentConnection( + mxDocFactory, + mxDoc, + text, + viewCursorSupplier, + component, + propertySet, + userProperties + ); // TODO: maybe we should install an event handler for document // close: addCloseListener @@ -385,29 +484,23 @@ public void selectDocument() * TODO: GUI should be notified */ private void forgetDocument(){ - this.xCurrentComponent = null ; - this.mxDoc = null ; - this.xViewCursorSupplier = null ; - this.xText = null ; - this.mxDocFactory = null ; - this.userProperties = null ; - this.propertySet = null ; + this.documentConnection = null ; } public boolean isConnectedToDocument() { - return this.xCurrentComponent != null; + return this.documentConnection != null; } public boolean checkDocumentConnection(){ boolean res = true; // These are set by selectDocument: - if (null == this.xCurrentComponent ){ res = false; } - if (null == this.mxDoc ){ res = false; } - if (null == this.xViewCursorSupplier ){ res = false; } - if (null == this.xText ){ res = false; } - if (null == this.mxDocFactory ){ res = false; } - if (null == this.userProperties ){ res = false; } - if (null == this.propertySet ){ res = false; } + if (null == this.documentConnection.xCurrentComponent ){ res = false; } + if (null == this.documentConnection.mxDoc ){ res = false; } + if (null == this.documentConnection.xViewCursorSupplier ){ res = false; } + if (null == this.documentConnection.xText ){ res = false; } + if (null == this.documentConnection.mxDocFactory ){ res = false; } + if (null == this.documentConnection.userProperties ){ res = false; } + if (null == this.documentConnection.propertySet ){ res = false; } // if ( ! res ){ forgetDocument(); @@ -429,51 +522,10 @@ public boolean checkDocumentConnection(){ */ public Optional getCurrentDocumentTitle() { - return OOBibBase.getDocumentTitle( this.mxDoc ); + return this.documentConnection.getDocumentTitle(); } - private Optional getCustomProperty(String property) - throws UnknownPropertyException, - WrappedTargetException - { - assert (this.propertySet != null); - - XPropertySetInfo psi = - this.propertySet - .getPropertySetInfo(); - - if (psi.hasPropertyByName(property)) { - String v = - this.propertySet - .getPropertyValue(property) - .toString(); - return Optional.ofNullable(v); - } - return Optional.empty(); - } - - private void setCustomProperty(String property, String value) - throws UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException - { - XPropertySetInfo psi = - this.propertySet - .getPropertySetInfo(); - if (psi.hasPropertyByName(property)) { - this.userProperties.removeProperty(property); - } - if (value != null) { - this.userProperties - .addProperty(property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value) - ); - } - } /* * === insertEntry @@ -513,25 +565,6 @@ private static int citationTypeFromOptions( boolean withText, boolean inParenthe : OOBibBase.AUTHORYEAR_INTEXT ); } - /** - * - * @throws NoDocumentException - * - */ - private XNameAccess getReferenceMarks() - throws NoDocumentException - { - XReferenceMarksSupplier supplier = - unoQI(XReferenceMarksSupplier.class, - this.xCurrentComponent); - try { - XNameAccess res = supplier.getReferenceMarks(); - return res; - } catch ( Exception ex ){ - LOGGER.warn( "getReferenceMarks caught: ", ex ); - throw new NoDocumentException("getReferenceMarks failed"); - } - } private static boolean isJabRefReferenceMarkName( String name ){ return (CITE_PATTERN.matcher(name).find()); From 347aaf28501931aa215c1091d9fe28d1779ef9c3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 11:40:14 +0100 Subject: [PATCH 0125/1068] getJabRefReferenceMarkNames uses documentConnection --- .../org/jabref/gui/openoffice/OOBibBase.java | 86 ++++++++++++------- 1 file changed, 53 insertions(+), 33 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 85a72b0c130..28caf72074d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -218,9 +218,42 @@ private XNameAccess getReferenceMarks() throw new NoDocumentException("getReferenceMarks failed"); } } - } - private DocumentConnection documentConnection; + public boolean checkDocumentConnection(){ + boolean res = true; + // These are set by selectDocument: + if (null == this.xCurrentComponent ){ res = false; } + if (null == this.mxDoc ){ res = false; } + if (null == this.xViewCursorSupplier ){ res = false; } + if (null == this.xText ){ res = false; } + if (null == this.mxDocFactory ){ res = false; } + if (null == this.userProperties ){ res = false; } + if (null == this.propertySet ){ res = false; } + // + if ( ! res ){ + return false; + } + // Attempt to check document is really available + // TODO + try { + getReferenceMarks(); + } catch (NoDocumentException ex ) { + return false; + } + return true; + } + + List getReferenceMarknames(){ + XNameAccess nameAccess = getReferenceMarks(); + String[] names = nameAccess.getElementNames(); + if (names == null) { + return new ArrayList<>(); + } + return Arrays.asList( names ); + } + } // end DocumentConnection + + private DocumentConnection xDocumentConnection; /* * uniquefiers : maps bibtexkeys to letters ("a", "b") */ @@ -464,7 +497,7 @@ public void selectDocument() XPropertySet propertySet = unoQI(XPropertySet.class, userProperties); - this.documentConnection = new DocumentConnection( + this.xDocumentConnection = new DocumentConnection( mxDocFactory, mxDoc, text, @@ -484,37 +517,19 @@ public void selectDocument() * TODO: GUI should be notified */ private void forgetDocument(){ - this.documentConnection = null ; + this.xDocumentConnection = null ; } public boolean isConnectedToDocument() { - return this.documentConnection != null; + return this.xDocumentConnection != null; } public boolean checkDocumentConnection(){ - boolean res = true; - // These are set by selectDocument: - if (null == this.documentConnection.xCurrentComponent ){ res = false; } - if (null == this.documentConnection.mxDoc ){ res = false; } - if (null == this.documentConnection.xViewCursorSupplier ){ res = false; } - if (null == this.documentConnection.xText ){ res = false; } - if (null == this.documentConnection.mxDocFactory ){ res = false; } - if (null == this.documentConnection.userProperties ){ res = false; } - if (null == this.documentConnection.propertySet ){ res = false; } - // + boolean res = this.xDocumentConnection.checkDocumentConnection(); if ( ! res ){ forgetDocument(); - return false; } - // Attempt to check document is really available - // TODO - try { - getReferenceMarks(); - } catch (NoDocumentException ex ) { - forgetDocument(); - return false; - } - return true; + return res; } /* @@ -522,7 +537,7 @@ public boolean checkDocumentConnection(){ */ public Optional getCurrentDocumentTitle() { - return this.documentConnection.getDocumentTitle(); + return this.xDocumentConnection.getDocumentTitle(); } @@ -580,13 +595,8 @@ private static List filterIsJabRefReferenceMarkName( List names /* * called from getCitationEntries(...) */ - private List getJabRefReferenceMarkNames(XNameAccess nameAccess) { - String[] names = nameAccess.getElementNames(); - // Remove all reference marks that don't look like JabRef citations: - if (names == null) { - return new ArrayList<>(); - } - return filterIsJabRefReferenceMarkName( Arrays.asList( names ) ); + private List getJabRefReferenceMarkNames(DocumentConnection documentConnection) { + return filterIsJabRefReferenceMarkName( documentConnection.getReferenceMarknames() ); } /** @@ -597,9 +607,19 @@ public List getCitationEntries() UnknownPropertyException, WrappedTargetException, NoDocumentException + { + return this.getCitationEntriesImpl( this.xDocumentConnection ); + } + + private List getCitationEntriesImpl( DocumentConnection documentConnection ) + throws NoSuchElementException, + UnknownPropertyException, + WrappedTargetException, + NoDocumentException { XNameAccess nameAccess = this.getReferenceMarks(); List names = this.getJabRefReferenceMarkNames(nameAccess); + List citations = new ArrayList(names.size()); for (String name : names) { CitationEntry entry = From 21250679bb4d8eeb3d3cda0d2c5c44e4d6952e0b Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 11:49:42 +0100 Subject: [PATCH 0126/1068] getCitationEntriesImpl --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 28caf72074d..2bb8a7fbb59 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -617,9 +617,9 @@ private List getCitationEntriesImpl( DocumentConnection documentC WrappedTargetException, NoDocumentException { - XNameAccess nameAccess = this.getReferenceMarks(); - List names = this.getJabRefReferenceMarkNames(nameAccess); + List names = this.getJabRefReferenceMarkNames(documentConnection); + XNameAccess nameAccess = this.getReferenceMarks(); List citations = new ArrayList(names.size()); for (String name : names) { CitationEntry entry = From e6837b60e3b709a965c0a56ddd8b6a847a42cf80 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:07:28 +0100 Subject: [PATCH 0127/1068] getCitationContext in DocumentConnection --- .../org/jabref/gui/openoffice/OOBibBase.java | 109 +++++++++++------- 1 file changed, 65 insertions(+), 44 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2bb8a7fbb59..23d0cf2f4c4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -251,6 +251,69 @@ List getReferenceMarknames(){ } return Arrays.asList( names ); } + + public String getCitationContext(String refMarkName, + int charBefore, + int charAfter, + boolean htmlMarkup) + throws NoSuchElementException, + WrappedTargetException + { + XNameAccess nameAccess = getReferenceMarks(); + Object referenceMark = nameAccess.getByName(refMarkName); + XTextContent bookmark = unoQI(XTextContent.class, referenceMark); + + XTextCursor cursor = + bookmark.getAnchor() // the text range to which the content is attached. + .getText() + .createTextCursorByRange(bookmark.getAnchor()); + + String citPart = cursor.getString(); + + // extend cursor range left + int flex = 8; + for (int i = 0; i < charBefore; i++) { + try { + cursor.goLeft((short) 1, true); + // If we are close to charBefore and see a space, + // then cut here. Might avoid cutting a word in half. + if ((i >= (charBefore - flex)) + && Character.isWhitespace(cursor.getString().charAt(0))) { + break; + } + } catch (IndexOutOfBoundsException ex) { + LOGGER.warn("Problem going left", ex); + } + } + + int lengthWithBefore = cursor.getString().length(); + int addedBefore = lengthWithBefore - citPart.length(); + + cursor.collapseToStart(); + for (int i = 0; i < (charAfter + lengthWithBefore); i++) { + try { + cursor.goRight((short) 1, true); + if (i >= ((charAfter + lengthWithBefore) - flex)) { + String strNow = cursor.getString(); + if (Character.isWhitespace(strNow.charAt(strNow.length() - 1))) { + break; + } + } + } catch (IndexOutOfBoundsException ex) { + LOGGER.warn("Problem going right", ex); + } + } + + String result = cursor.getString(); + if (htmlMarkup) { + result = + result.substring(0, addedBefore) + + "" + citPart + "" + + result.substring(lengthWithBefore); + } + return result.trim(); + } + } // end DocumentConnection private DocumentConnection xDocumentConnection; @@ -624,8 +687,8 @@ private List getCitationEntriesImpl( DocumentConnection documentC for (String name : names) { CitationEntry entry = new CitationEntry(name, - this.getCitationContext(nameAccess, name, 30, 30, true), - this.getCustomProperty(name) + documentConnection.getCitationContext(name, 30, 30, true), + documentConnection.getCustomProperty(name) ); citations.add(entry); } @@ -1801,48 +1864,6 @@ private Map getSortedEntriesFromSortedRefMarks(List= (charBefore - flex)) && Character.isWhitespace(cursor.getString().charAt(0))) { - break; - } - } catch (IndexOutOfBoundsException ex) { - LOGGER.warn("Problem going left", ex); - } - } - int length = cursor.getString().length(); - int added = length - citPart.length(); - cursor.collapseToStart(); - for (int i = 0; i < (charAfter + length); i++) { - try { - cursor.goRight((short) 1, true); - if (i >= ((charAfter + length) - flex)) { - String strNow = cursor.getString(); - if (Character.isWhitespace(strNow.charAt(strNow.length() - 1))) { - break; - } - } - } catch (IndexOutOfBoundsException ex) { - LOGGER.warn("Problem going right", ex); - } - } - - String result = cursor.getString(); - if (htmlMarkup) { - result = result.substring(0, added) + "" + citPart + "" + result.substring(length); - } - return result.trim(); - } private void insertFullReferenceAtCursor(XTextCursor cursor, Map entries, OOBibStyle style, String parFormat) From ab9848e27e05c8fe0d5a507db706556048c7a8e0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:16:30 +0100 Subject: [PATCH 0128/1068] getUniqueReferenceMarkName uses documentConnection --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 23d0cf2f4c4..94adff99a2b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -682,7 +682,6 @@ private List getCitationEntriesImpl( DocumentConnection documentC { List names = this.getJabRefReferenceMarkNames(documentConnection); - XNameAccess nameAccess = this.getReferenceMarks(); List citations = new ArrayList(names.size()); for (String name : names) { CitationEntry entry = @@ -730,7 +729,7 @@ public void applyCitationEntries( List citationEntries ) for (CitationEntry entry : citationEntries) { Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { - this.setCustomProperty( entry.getRefMarkName(), pageInfo.get() ); + this.xDocumentConnection.setCustomProperty( entry.getRefMarkName(), pageInfo.get() ); } else { // TODO: if pageInfo is not present, or is empty: // maybe we should remove it from the document. @@ -756,10 +755,12 @@ public void applyCitationEntries( List citationEntries ) * Or the first unused in this series, after removals. * */ - private String getUniqueReferenceMarkName(String bibtexKey, int itcType) + private String getUniqueReferenceMarkName(DocumentConnection documentConnection, + String bibtexKey, + int itcType) throws NoDocumentException { - XNameAccess xNamedRefMarks = getReferenceMarks(); + XNameAccess xNamedRefMarks = xDocumentConnection.getReferenceMarks(); int i = 0; String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; while (xNamedRefMarks.hasByName(name)) { @@ -894,7 +895,7 @@ public void insertEntry(List entries, ); // Generate unique bookmark-name int citationType = citationTypeFromOptions( withText, inParenthesis ); - String bName = getUniqueReferenceMarkName( keyString, citationType ); + String bName = getUniqueReferenceMarkName( this.xDocumentConnection, keyString, citationType ); // If we should store metadata for page info, do that now: if (pageInfo != null) { @@ -2175,7 +2176,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) String keyString = String.join(",", entries.stream().map(entry -> entry.getCitationKey().orElse("")) .collect(Collectors.toList())); // Insert bookmark: - String bName = getUniqueReferenceMarkName(keyString, OOBibBase.AUTHORYEAR_PAR); + String bName = getUniqueReferenceMarkName(this.xDocumentConnection, keyString, OOBibBase.AUTHORYEAR_PAR); insertReferenceMark(bName, "tmp", mxDocCursor, true, style); names.set(piv + 1, bName); madeModifications = true; @@ -2242,7 +2243,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) int last = keys.size() - 1; int i = 0; for (String key : keys) { - String bName = getUniqueReferenceMarkName(key, OOBibBase.AUTHORYEAR_PAR); + String bName = getUniqueReferenceMarkName(this.xDocumentConnection,key, OOBibBase.AUTHORYEAR_PAR); insertReferenceMark(bName, "tmp", mxDocCursor, true, style); mxDocCursor.collapseToEnd(); if (i != last) { From 603ac4aeb1104f476304a5555928ffaa6d191295 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:43:39 +0100 Subject: [PATCH 0129/1068] indent --- .../org/jabref/gui/openoffice/OOBibBase.java | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 94adff99a2b..f6a973caa07 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -157,32 +157,32 @@ public Optional getDocumentTitle() { return OOBibBase.getDocumentTitle( this.mxDoc ); } - private Optional getCustomProperty(String property) - throws UnknownPropertyException, - WrappedTargetException - { - assert (this.propertySet != null); - - XPropertySetInfo psi = - this.propertySet - .getPropertySetInfo(); + private Optional getCustomProperty(String property) + throws UnknownPropertyException, + WrappedTargetException + { + assert (this.propertySet != null); - if (psi.hasPropertyByName(property)) { - String v = + XPropertySetInfo psi = this.propertySet - .getPropertyValue(property) - .toString(); - return Optional.ofNullable(v); + .getPropertySetInfo(); + + if (psi.hasPropertyByName(property)) { + String v = + this.propertySet + .getPropertyValue(property) + .toString(); + return Optional.ofNullable(v); + } + return Optional.empty(); } - return Optional.empty(); - } - private void setCustomProperty(String property, String value) - throws UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException + private void setCustomProperty(String property, String value) + throws UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException { XPropertySetInfo psi = this.propertySet From e374f9921420e6dccad53c4faa71f095c6ee0e7d Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:43:56 +0100 Subject: [PATCH 0130/1068] getViewCursor --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f6a973caa07..c50c4b52a77 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -314,6 +314,12 @@ public String getCitationContext(String refMarkName, return result.trim(); } + // Get the cursor positioned by the user. + public XTextViewCursor getViewCursor(){ + return this.xViewCursorSupplier.getViewCursor(); + } + + } // end DocumentConnection private DocumentConnection xDocumentConnection; From de33c33bb6b4cf559c94a6a83b62d370383808ce Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:44:26 +0100 Subject: [PATCH 0131/1068] use getViewCursor --- .../org/jabref/gui/openoffice/OOBibBase.java | 31 ++----------------- 1 file changed, 3 insertions(+), 28 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c50c4b52a77..aa30004470d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -861,35 +861,10 @@ public void insertEntry(List entries, UndefinedParagraphFormatException, NoDocumentException { + try { - XTextCursor cursor; - { - // Get the cursor positioned by the user. - XTextViewCursor xViewCursor = - this.xViewCursorSupplier - .getViewCursor(); - if ( true ){ - cursor = xViewCursor; - } else { - // - // An XTextCursor is sufficient for the rest. - // - // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/\ - // Example:_Visible_Cursor_Position - // - // We create a model cursor at the current view cursor - // position with the following steps: we get the Text - // service from the TextViewCursor, the cursor is an - // XTextRange and has therefore a method getText() - // - XText xDocumentText = xViewCursor.getText(); - // the text creates a model cursor from the viewcursor - XTextCursor xModelCursor = - xDocumentText.createTextCursorByRange(xViewCursor.getStart()); - // use the xModelCursor - cursor = xModelCursor; - } - } + // Get the cursor positioned by the user. + XTextCursor cursor = this.xDocumentConnection.getViewCursor(); sortBibEntryList( entries, style ); From dfa6021338000e902165a1be72f8a42ca78ba7ee Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:45:08 +0100 Subject: [PATCH 0132/1068] findCitedKeys --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index aa30004470d..2ded3de6ca2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1006,20 +1006,26 @@ private List parseRefMarkNameToUniqueCitationKeys(String name) { * doc.referenceMarks.names.map(parse).flatten.unique * */ - private List findCitedKeys() + private List findCitedKeys( DocumentConnection documentConnection ) throws NoSuchElementException, WrappedTargetException, NoDocumentException { - XNameAccess xNamedMarks = getReferenceMarks(); - String[] names = xNamedMarks.getElementNames(); + + List names = getJabRefReferenceMarkNames( documentConnection ); + + { + XNameAccess xNamedMarks = getReferenceMarks(); + for (String name1 : names) { + // assert it supports XTextContent + Object bookmark = xNamedMarks.getByName(name1); + assert (null != unoQI(XTextContent.class, bookmark)); + } + } List keys = new ArrayList<>(); for (String name1 : names) { - Object bookmark = xNamedMarks.getByName(name1); - assert (null != unoQI(XTextContent.class, bookmark)); - - List newKeys = parseRefMarkNameToUniqueCitationKeys(name1); + List newKeys = parseRefMarkNameToUniqueCitationKeys( name1 ); for (String key : newKeys) { if (!keys.contains(key)) { keys.add(key); From 202cb765f05b0ec2104f3b030e5b7f97773d0624 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:45:52 +0100 Subject: [PATCH 0133/1068] use xDocumentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2ded3de6ca2..f053674a4d1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -876,12 +876,14 @@ public void insertEntry(List entries, ); // Generate unique bookmark-name int citationType = citationTypeFromOptions( withText, inParenthesis ); - String bName = getUniqueReferenceMarkName( this.xDocumentConnection, keyString, citationType ); + String bName = getUniqueReferenceMarkName( this.xDocumentConnection, + keyString, + citationType ); // If we should store metadata for page info, do that now: if (pageInfo != null) { LOGGER.info("Storing page info: " + pageInfo); - setCustomProperty(bName, pageInfo); + this.xDocumentConnection.setCustomProperty(bName, pageInfo); } // insert space From ff4e81d197481b01063177ab93e138e0cf9719d4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:47:41 +0100 Subject: [PATCH 0134/1068] getSortedCitedEntries needs DocumentConnection --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f053674a4d1..b0c5b0e9ac5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1017,7 +1017,7 @@ private List findCitedKeys( DocumentConnection documentConnection ) List names = getJabRefReferenceMarkNames( documentConnection ); { - XNameAccess xNamedMarks = getReferenceMarks(); + XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); for (String name1 : names) { // assert it supports XTextContent Object bookmark = xNamedMarks.getByName(name1); @@ -1191,16 +1191,17 @@ private class GetSortedCitedEntriesResult { * order: from findCitedKeys(), * except for style.isNumberEntries() where reordered as entries */ - private GetSortedCitedEntriesResult getSortedCitedEntries( List databases, - OOBibStyle style, - XNameAccess xReferenceMarks ) + private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection documentConnection, + List databases, + OOBibStyle style, + XNameAccess xReferenceMarks ) throws NoSuchElementException, WrappedTargetException, NoDocumentException { Map linkSourceBase = new HashMap<>(); - List cited = findCitedKeys(); + List cited = findCitedKeys( documentConnection ); Map entries = findCitedEntries(databases, cited, linkSourceBase); From 7b73f9547c5f6d10e121b602677bb3f66e815e85 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:52:15 +0100 Subject: [PATCH 0135/1068] format --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b0c5b0e9ac5..5701ca14ac4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1977,10 +1977,17 @@ private XTextContent insertBookMark(String name, XTextCursor position) return xTextContent; } - private void insertReferenceMark(String name, String citationText, XTextCursor position, boolean withText, + private void insertReferenceMark(String name, + String citationText, + XTextCursor position, + boolean withText, OOBibStyle style) - throws UnknownPropertyException, WrappedTargetException, - PropertyVetoException, IllegalArgumentException, UndefinedCharacterFormatException, CreationException { + throws UnknownPropertyException, + WrappedTargetException, + PropertyVetoException, + IllegalArgumentException, + UndefinedCharacterFormatException, + CreationException { // Check if there is "page info" stored for this citation. If so, insert it into // the citation text before inserting the citation: From 1975b9cbff618018cf1055092c34de5a7ce47e28 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:53:19 +0100 Subject: [PATCH 0136/1068] rcmApplyNewCitationMarkers --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5701ca14ac4..225a822de8f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1372,10 +1372,11 @@ private List findCitedEntryIndices( List keysCitedHere, * @param types itcType codes for each reference mark. * @param style */ - private void rcmApplyNewCitationMarkers( List names, - String[] citMarkers, - int[] types, - OOBibStyle style ) + private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, + List names, + String[] citMarkers, + int[] types, + OOBibStyle style ) throws NoDocumentException, NoSuchElementException, UndefinedCharacterFormatException, @@ -1388,7 +1389,7 @@ private void rcmApplyNewCitationMarkers( List names, assert( citMarkers.length == nRefMarks ); assert( types.length == nRefMarks ); - XNameAccess xReferenceMarks = getReferenceMarks(); + XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); final boolean hadBibSection = (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); // If we are supposed to set character format for citations, @@ -1423,7 +1424,7 @@ private void rcmApplyNewCitationMarkers( List names, } } - this.xText.removeTextContent(bookmark); + documentConnection.xText.removeTextContent(bookmark); insertReferenceMark(names.get(i), citMarkers[i], From a5900624e728ea1feaff59af5f8ed726597024ad Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:54:28 +0100 Subject: [PATCH 0137/1068] use documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 225a822de8f..b930c071b5b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1437,7 +1437,7 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, // We have overwritten the marker for the start of the reference list. // We need to add it again. cursor.collapseToEnd(); - OOUtil.insertParagraphBreak(this.xText, cursor); + OOUtil.insertParagraphBreak(documentConnection.xText, cursor); insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); } } From 0e3e084b3f43d90ec8d55a71a644d6b54d2ce9aa Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:57:08 +0100 Subject: [PATCH 0138/1068] refreshCiteMarkersInternal use documentConnection --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b930c071b5b..fb99cba4a26 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1443,8 +1443,9 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, } } - private List refreshCiteMarkersInternal( List databases, - OOBibStyle style ) + private List refreshCiteMarkersInternal(DocumentConnection documentConnection, + List databases, + OOBibStyle style ) throws WrappedTargetException, IllegalArgumentException, NoSuchElementException, @@ -1455,10 +1456,10 @@ private List refreshCiteMarkersInternal( List databases, BibEntryNotFoundException, NoDocumentException { - XNameAccess xReferenceMarks = getReferenceMarks(); + XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); GetSortedCitedEntriesResult sce = - getSortedCitedEntries( databases, style, xReferenceMarks ); + getSortedCitedEntries(documentConnection, databases, style, xReferenceMarks ); List names = sce.refMarkNames; // Compute citation markers for all citations: @@ -1707,9 +1708,9 @@ private List refreshCiteMarkersInternal( List databases, // Refresh all reference marks with the citation markers we computed: - rcmApplyNewCitationMarkers( names, citMarkers, types, style ); + rcmApplyNewCitationMarkers(documentConnection, names, citMarkers, types, style ); - // Collect and return uunresolved citation keys. + // Collect and return unresolved citation keys. // uses: entries List unresolvedKeys = new ArrayList<>(); for (BibEntry entry : entries.keySet()) { From 812f93bc5387e39cd20665e842f379b2ab02827b Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 12:58:05 +0100 Subject: [PATCH 0139/1068] refreshCiteMarker uses xDocumentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index fb99cba4a26..54cb99e6e5d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1105,7 +1105,7 @@ public List refreshCiteMarkers(List databases, NoDocumentException { try { - return refreshCiteMarkersInternal(databases, style); + return refreshCiteMarkersInternal(this.xDocumentConnection, databases, style); } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference From 8aaf42f8a292edfe6b29b921a88af161bd1d6fb6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 13:31:20 +0100 Subject: [PATCH 0140/1068] getSortedReferenceMarks reorg --- .../org/jabref/gui/openoffice/OOBibBase.java | 63 +++++++++++-------- 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 54cb99e6e5d..8ce255a3b7c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1724,45 +1724,63 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne return unresolvedKeys; } + + /** * */ - private List getSortedReferenceMarks(final XNameAccess nameAccess) + private List getSortedReferenceMarks(DocumentConnection documentConnection) throws WrappedTargetException, NoSuchElementException { - XTextViewCursorSupplier cursorSupplier = - unoQI(XTextViewCursorSupplier.class, - this.mxDoc.getCurrentController()); + // Position as in a document on the screen. + // Probably to get the correct order with + // referenceMarks in footnotes + Point findPosition(XTextViewCursor cursor, XTextRange range) { + cursor.gotoRange(range, false); + return cursor.getPosition(); + // the cursor's coordinates relative to the top left position + // of the first page of the document. + } - XTextViewCursor viewCursor = cursorSupplier.getViewCursor(); - XTextRange initialPos = viewCursor.getStart(); - List names = Arrays.asList(nameAccess.getElementNames()); + List names = getJabRefReferenceMarkNames(documentConnection); + + + // find coordinates List positions = new ArrayList<>(names.size()); - for (String name : names) { - XTextContent textContent = - unoQI(XTextContent.class, nameAccess.getByName(name)); - XTextRange range = textContent.getAnchor(); - // Check if we are inside a footnote: - if (unoQI(XFootnote.class, range.getText()) != null) { - // Find the linking footnote marker: - XFootnote footer = unoQI(XFootnote.class, range.getText()); - // The footnote's anchor gives the correct position in the text: - range = footer.getAnchor(); + { + XTextViewCursor viewCursor = documentConnection.getViewCursor(); + // initialPos: to be restored before return + XTextRange initialPos = viewCursor.getStart(); + for (String name : names) { + XTextContent textContent = + unoQI(XTextContent.class, nameAccess.getByName(name)); + XTextRange range = textContent.getAnchor(); + + // Adjust range if we are inside a footnote: + if (unoQI(XFootnote.class, range.getText()) != null) { + // Find the linking footnote marker: + XFootnote footer = unoQI(XFootnote.class, range.getText()); + // The footnote's anchor gives the correct position in the text: + range = footer.getAnchor(); + } + positions.add(findPosition(viewCursor, range)); } - - positions.add(findPosition(viewCursor, range)); + // restore cursor position + viewCursor.gotoRange(initialPos, false); } + + // order by position Set set = new TreeSet<>(); for (int i = 0; i < positions.size(); i++) { set.add(new ComparableMark(names.get(i), positions.get(i))); } + // collect referenceMarkNames in order List result = new ArrayList<>(set.size()); for (ComparableMark mark : set) { result.add(mark.getName()); } - viewCursor.gotoRange(initialPos, false); return result; } @@ -1815,11 +1833,6 @@ public void rebuildBibTextSection(List databases, } - private Point findPosition(XTextViewCursor cursor, XTextRange range) { - cursor.gotoRange(range, false); - return cursor.getPosition(); - } - private Map getSortedEntriesFromSortedRefMarks(List names, From a57b0952188debd4a2ed79ecb9da32a9735128c4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 13:33:22 +0100 Subject: [PATCH 0141/1068] rename to getJabRefReferenceMarkNamesSortedByPosition --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8ce255a3b7c..916ba343c88 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1729,7 +1729,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne /** * */ - private List getSortedReferenceMarks(DocumentConnection documentConnection) + private List getJabRefReferenceMarkNamesSortedByPosition(DocumentConnection documentConnection) throws WrappedTargetException, NoSuchElementException { @@ -1790,7 +1790,7 @@ public void updateSortedReferenceMarks() NoSuchElementException, NoDocumentException { - this.sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks()); + this.sortedReferenceMarks = getJabRefReferenceMarkNamesSortedByPosition(getReferenceMarks()); } @@ -2129,7 +2129,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) { XNameAccess nameAccess = getReferenceMarks(); // TODO: doesn't work for citations in footnotes/tables - List names = getSortedReferenceMarks(nameAccess); + List names = getJabRefReferenceMarkNamesSortedByPosition(nameAccess); final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, this.xText); @@ -2219,7 +2219,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) { XNameAccess nameAccess = getReferenceMarks(); // TODO: doesn't work for citations in footnotes/tables - List names = getSortedReferenceMarks(nameAccess); + List names = getJabRefReferenceMarkNamesSortedByPosition(nameAccess); final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, this.xText); From 2fda999fecec1cefff56e73e25cd3086f27b04f8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 13:37:56 +0100 Subject: [PATCH 0142/1068] findPositionOfTextRange --- .../org/jabref/gui/openoffice/OOBibBase.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 916ba343c88..1c3f3bed484 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1726,6 +1726,16 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne + // Position as in a document on the screen. + // Probably to get the correct order with + // referenceMarks in footnotes + private static Point findPositionOfTextRange(XTextViewCursor cursor, XTextRange range) { + cursor.gotoRange(range, false); + return cursor.getPosition(); + // the cursor's coordinates relative to the top left position + // of the first page of the document. + } + /** * */ @@ -1733,15 +1743,6 @@ private List getJabRefReferenceMarkNamesSortedByPosition(DocumentConnect throws WrappedTargetException, NoSuchElementException { - // Position as in a document on the screen. - // Probably to get the correct order with - // referenceMarks in footnotes - Point findPosition(XTextViewCursor cursor, XTextRange range) { - cursor.gotoRange(range, false); - return cursor.getPosition(); - // the cursor's coordinates relative to the top left position - // of the first page of the document. - } List names = getJabRefReferenceMarkNames(documentConnection); @@ -1764,7 +1765,7 @@ Point findPosition(XTextViewCursor cursor, XTextRange range) { // The footnote's anchor gives the correct position in the text: range = footer.getAnchor(); } - positions.add(findPosition(viewCursor, range)); + positions.add(findPositionOfTextRange(viewCursor, range)); } // restore cursor position viewCursor.gotoRange(initialPos, false); From 5767e92cd47a09d36b6d6787c2c8fef8bcaeaa28 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 13:41:21 +0100 Subject: [PATCH 0143/1068] add back nameAccess --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1c3f3bed484..97a3e480382 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1750,10 +1750,12 @@ private List getJabRefReferenceMarkNamesSortedByPosition(DocumentConnect // find coordinates List positions = new ArrayList<>(names.size()); { + XNameAccess nameAccess = documentConnection.getReferenceMarks(); XTextViewCursor viewCursor = documentConnection.getViewCursor(); // initialPos: to be restored before return XTextRange initialPos = viewCursor.getStart(); for (String name : names) { + XTextContent textContent = unoQI(XTextContent.class, nameAccess.getByName(name)); XTextRange range = textContent.getAnchor(); From 1d956c936d32d73c53b55b93909672bf854c093e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 13:42:05 +0100 Subject: [PATCH 0144/1068] updateSortedReferenceMarks use xDocumentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 97a3e480382..ea509ac389b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1793,7 +1793,7 @@ public void updateSortedReferenceMarks() NoSuchElementException, NoDocumentException { - this.sortedReferenceMarks = getJabRefReferenceMarkNamesSortedByPosition(getReferenceMarks()); + this.sortedReferenceMarks = getJabRefReferenceMarkNamesSortedByPosition(this.xDocumentConnection); } From 1c4d7577e5e1a9fd3929f0fbea9751e159c7956c Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 13:54:50 +0100 Subject: [PATCH 0145/1068] public updateDocument for GUI --- .../org/jabref/gui/openoffice/OOBibBase.java | 23 +++++++++++++++++++ .../gui/openoffice/OpenOfficePanel.java | 6 ++--- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ea509ac389b..241316d1cf9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1796,6 +1796,28 @@ public void updateSortedReferenceMarks() this.sortedReferenceMarks = getJabRefReferenceMarkNamesSortedByPosition(this.xDocumentConnection); } + /** + * GUI action + * + * @return unresolvedKeys + */ + public List updateDocument(List databases, + OOBibStyle style) + throws NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException, + NoDocumentException + { + updateSortedReferenceMarks(); // NoDocumentException + List unresolvedKeys = refreshCiteMarkers(databases, style); + rebuildBibTextSection(databases, style); + return unresolvedKeys; + } + public void rebuildBibTextSection(List databases, OOBibStyle style) @@ -2314,6 +2336,7 @@ public BibDatabase generateDatabase(List databases) return resultDatabase; } + private static class ComparableMark implements Comparable { private final String name; diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 2441acaf549..4c935e9b2ab 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -196,11 +196,9 @@ private void initPanel() { style.ensureUpToDate(); } - ooBase.updateSortedReferenceMarks(); // NoDocumentException - List databases = getBaseList(); - List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style); - ooBase.rebuildBibTextSection(databases, style); + List unresolvedKeys = ooBase.updateDocument(databases, style); + if (!unresolvedKeys.isEmpty()) { dialogService .showErrorDialogAndWait( From d31a698fbf48ebf48269d3c7da51c8eb803a7ce6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 13:59:59 +0100 Subject: [PATCH 0146/1068] updateDocument -> updateDocumentActionHelper --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 241316d1cf9..079a42b4317 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1801,8 +1801,8 @@ public void updateSortedReferenceMarks() * * @return unresolvedKeys */ - public List updateDocument(List databases, - OOBibStyle style) + public List updateDocumentActionHelper(List databases, + OOBibStyle style) throws NoSuchElementException, WrappedTargetException, IllegalArgumentException, diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 4c935e9b2ab..4d35579f3a6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -197,7 +197,7 @@ private void initPanel() { } List databases = getBaseList(); - List unresolvedKeys = ooBase.updateDocument(databases, style); + List unresolvedKeys = ooBase.updateDocumentActionHelper(databases, style); if (!unresolvedKeys.isEmpty()) { dialogService From 4dd54cfc57e51216381941e97a055a2c70d4d87e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:03:34 +0100 Subject: [PATCH 0147/1068] more exceptions in updateDocumentActionHelper --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 079a42b4317..cf5bb9a049e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1810,7 +1810,9 @@ public List updateDocumentActionHelper(List databases, PropertyVetoException, UnknownPropertyException, UndefinedParagraphFormatException, - NoDocumentException + NoDocumentException, + UndefinedCharacterFormatException, + BibEntryNotFoundException { updateSortedReferenceMarks(); // NoDocumentException List unresolvedKeys = refreshCiteMarkers(databases, style); From 3e90a96af12ba2792db97a9cad505d3317d85708 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:05:16 +0100 Subject: [PATCH 0148/1068] rebuildBibTextSection uses xDocumentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index cf5bb9a049e..7007a3fe904 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1832,7 +1832,7 @@ public void rebuildBibTextSection(List databases, UndefinedParagraphFormatException, NoDocumentException { - List cited = findCitedKeys(); + List cited = findCitedKeys(this.xDocumentConnection); Map linkSourceBase = new HashMap<>(); Map entries = // Although entries are redefined without use, this also From dd4b735aa37f91938612f939a6247a69124a1b5c Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:09:17 +0100 Subject: [PATCH 0149/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 32 +++++++++++++++---- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7007a3fe904..f0abb5633eb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1898,10 +1898,16 @@ private Map getSortedEntriesFromSortedRefMarks(List entries, OOBibStyle style, + private void insertFullReferenceAtCursor(XTextCursor cursor, + Map entries, + OOBibStyle style, String parFormat) - throws UndefinedParagraphFormatException, IllegalArgumentException, - UnknownPropertyException, PropertyVetoException, WrappedTargetException { + throws UndefinedParagraphFormatException, + IllegalArgumentException, + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException + { Map correctEntries; // If we don't have numbered entries, we need to sort the entries before adding them: if (style.isSortByPosition()) { @@ -1921,13 +1927,25 @@ private void insertFullReferenceAtCursor(XTextCursor cursor, Map Date: Tue, 23 Feb 2021 14:11:33 +0100 Subject: [PATCH 0150/1068] insertFullReferenceAtCursor uses documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f0abb5633eb..44487451af6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1898,7 +1898,8 @@ private Map getSortedEntriesFromSortedRefMarks(List entries, OOBibStyle style, String parFormat) @@ -1924,11 +1925,11 @@ private void insertFullReferenceAtCursor(XTextCursor cursor, if (entry.getKey() instanceof UndefinedBibtexEntry) { continue; } - OOUtil.insertParagraphBreak(this.xText, cursor); + OOUtil.insertParagraphBreak(documentConnection.xText, cursor); if (style.isNumberEntries()) { int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); OOUtil.insertTextAtCurrentLocation - (this.xText, + (documentConnection.xText, cursor, style.getNumCitationMarker(Collections.singletonList(number++), minGroupingCount, true), @@ -1938,7 +1939,7 @@ private void insertFullReferenceAtCursor(XTextCursor cursor, Layout layout = style.getReferenceFormat(entry.getKey().getType()); layout.setPostFormatter(POSTFORMATTER); OOUtil.insertFullReferenceAtCurrentLocation - (this.xText, + (documentConnection.xText, cursor, layout, parFormat, From 7e9b065e8466d80fe0bf5f746c62369baa47265f Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:12:11 +0100 Subject: [PATCH 0151/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 44487451af6..9a00e626634 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1951,7 +1951,9 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, } private void createBibTextSection2(boolean end) - throws IllegalArgumentException, CreationException { + throws IllegalArgumentException, + CreationException + { XTextCursor mxDocCursor = this.xText.createTextCursor(); if (end) { From eddcc3b862069af55a54253484085d38c87357f5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:17:00 +0100 Subject: [PATCH 0152/1068] createBibTextSection2 use documentConnection --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9a00e626634..9f040562810 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1950,21 +1950,24 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, } } - private void createBibTextSection2(boolean end) + private void createBibTextSection2(DocumentConnection documentConnection, + boolean end) throws IllegalArgumentException, CreationException { - XTextCursor mxDocCursor = this.xText.createTextCursor(); + XTextCursor mxDocCursor = documentConnection.xText.createTextCursor(); if (end) { mxDocCursor.gotoEnd(false); } - OOUtil.insertParagraphBreak(this.xText, mxDocCursor); + OOUtil.insertParagraphBreak(documentConnection.xText, mxDocCursor); // Create a new TextSection from the document factory and access it's XNamed interface XNamed xChildNamed; try { xChildNamed = unoQI(XNamed.class, - this.mxDocFactory.createInstance("com.sun.star.text.TextSection")); + (documentConnection.mxDocFactory + .createInstance("com.sun.star.text.TextSection")) + ); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -1972,7 +1975,7 @@ private void createBibTextSection2(boolean end) xChildNamed.setName(OOBibBase.BIB_SECTION_NAME); // Access the Child_Section's XTextContent interface and insert it into the document XTextContent xChildSection = unoQI(XTextContent.class, xChildNamed); - this.xText.insertTextContent(mxDocCursor, xChildSection, false); + documentConnection.xText.insertTextContent(mxDocCursor, xChildSection, false); } private void clearBibTextSectionContent2() From f88d14f536ed9b254d38ae13eb5d85684da558f1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:20:01 +0100 Subject: [PATCH 0153/1068] format --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9f040562810..e0fb7a16ec2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1979,17 +1979,25 @@ private void createBibTextSection2(DocumentConnection documentConnection, } private void clearBibTextSectionContent2() - throws NoSuchElementException, WrappedTargetException, IllegalArgumentException, CreationException { + throws NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException + { // Check if the section exists: - XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, this.mxDoc); + XTextSectionsSupplier supplier = + unoQI(XTextSectionsSupplier.class, this.mxDoc); + com.sun.star.container.XNameAccess ts = supplier.getTextSections(); + if (ts.hasByName(OOBibBase.BIB_SECTION_NAME)) { try { Any a = ((Any) ts.getByName(OOBibBase.BIB_SECTION_NAME)); XTextSection section = (XTextSection) a.getObject(); // Clear it: - XTextCursor cursor = this.xText.createTextCursorByRange(section.getAnchor()); + XTextCursor cursor = + this.xText.createTextCursorByRange(section.getAnchor()); cursor.gotoRange(section.getAnchor(), false); cursor.setString(""); return; From 7e1795e3d6d01682bd4d9346d8252f5b6cc7d933 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:21:07 +0100 Subject: [PATCH 0154/1068] clearBibTextSectionContent2(DocumentConnection documentConnection) --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e0fb7a16ec2..7c23b53c31b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1978,7 +1978,7 @@ private void createBibTextSection2(DocumentConnection documentConnection, documentConnection.xText.insertTextContent(mxDocCursor, xChildSection, false); } - private void clearBibTextSectionContent2() + private void clearBibTextSectionContent2(DocumentConnection documentConnection) throws NoSuchElementException, WrappedTargetException, IllegalArgumentException, @@ -1987,7 +1987,7 @@ private void clearBibTextSectionContent2() // Check if the section exists: XTextSectionsSupplier supplier = - unoQI(XTextSectionsSupplier.class, this.mxDoc); + unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); com.sun.star.container.XNameAccess ts = supplier.getTextSections(); @@ -1997,7 +1997,7 @@ private void clearBibTextSectionContent2() XTextSection section = (XTextSection) a.getObject(); // Clear it: XTextCursor cursor = - this.xText.createTextCursorByRange(section.getAnchor()); + documentConnection.xText.createTextCursorByRange(section.getAnchor()); cursor.gotoRange(section.getAnchor(), false); cursor.setString(""); return; From 50cab50969f6fe8eaef8c7073f6cdba075025dc3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:22:40 +0100 Subject: [PATCH 0155/1068] as missinf documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7c23b53c31b..26536b09be1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1855,7 +1855,7 @@ public void rebuildBibTextSection(List databases, } entries = newMap; } - clearBibTextSectionContent2(); + clearBibTextSectionContent2(this.xDocumentConnection); populateBibTextSection(entries, style); } @@ -2010,10 +2010,10 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) // just above. // Try to create. LOGGER.warn( "Could not get section '"+ OOBibBase.BIB_SECTION_NAME + "'", ex ); - createBibTextSection2(atEnd); + createBibTextSection2(documentConnection, atEnd); } } else { - createBibTextSection2(atEnd); + createBibTextSection2(documentConnection, atEnd); } } From b0c0a06b29f7a15b18e06e4193ddf96514695300 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:26:42 +0100 Subject: [PATCH 0156/1068] format populateBibTextSection --- .../org/jabref/gui/openoffice/OOBibBase.java | 48 ++++++++++++++----- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 26536b09be1..95988e87c66 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2017,17 +2017,43 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) } } - private void populateBibTextSection(Map entries, OOBibStyle style) - throws NoSuchElementException, WrappedTargetException, PropertyVetoException, - UnknownPropertyException, UndefinedParagraphFormatException, IllegalArgumentException, CreationException { - XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, this.mxDoc); - XTextSection section = (XTextSection) ((Any) supplier.getTextSections().getByName(OOBibBase.BIB_SECTION_NAME)) - .getObject(); - XTextCursor cursor = this.xText.createTextCursorByRange(section.getAnchor()); - OOUtil.insertTextAtCurrentLocation(this.xText, cursor, (String) style.getProperty(OOBibStyle.TITLE), - (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT)); - insertFullReferenceAtCursor(cursor, entries, style, - (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT)); + private void populateBibTextSection(Map entries, + OOBibStyle style) + throws NoSuchElementException, + WrappedTargetException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException, + IllegalArgumentException, + CreationException + { + XTextSectionsSupplier supplier = + unoQI(XTextSectionsSupplier.class, + this.mxDoc); + + XTextSection section = + (XTextSection) ((Any) supplier + .getTextSections() + .getByName(OOBibBase.BIB_SECTION_NAME)) + .getObject(); + + XTextCursor cursor = + this.xText + .createTextCursorByRange(section.getAnchor()); + + OOUtil.insertTextAtCurrentLocation + (this.xText, + cursor, + (String) style.getProperty(OOBibStyle.TITLE), + (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT) + ); + + insertFullReferenceAtCursor + (cursor, + entries, + style, + (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT) + ); insertBookMark(OOBibBase.BIB_SECTION_END_NAME, cursor); } From a6ea04dee14e8a3b7d5ff14510b2ac6a142fbcca Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:28:59 +0100 Subject: [PATCH 0157/1068] populateBibTextSection use documentConnection --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 95988e87c66..f2715977c2f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2017,7 +2017,8 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) } } - private void populateBibTextSection(Map entries, + private void populateBibTextSection(DocumentConnection documentConnection, + Map entries, OOBibStyle style) throws NoSuchElementException, WrappedTargetException, @@ -2029,20 +2030,23 @@ private void populateBibTextSection(Map entries, { XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, - this.mxDoc); + documentConnection.mxDoc); XTextSection section = - (XTextSection) ((Any) supplier - .getTextSections() - .getByName(OOBibBase.BIB_SECTION_NAME)) - .getObject(); + ( (XTextSection) + ((Any) supplier + .getTextSections() + .getByName(OOBibBase.BIB_SECTION_NAME) + ) + .getObject() + ); XTextCursor cursor = - this.xText + documentConnection.xText .createTextCursorByRange(section.getAnchor()); OOUtil.insertTextAtCurrentLocation - (this.xText, + (documentConnection.xText, cursor, (String) style.getProperty(OOBibStyle.TITLE), (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT) From 1b913efd04878477c3f13cd5566c540a9d4ed10e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:31:03 +0100 Subject: [PATCH 0158/1068] rebuildBibTextSection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f2715977c2f..61d5d9aff43 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1832,7 +1832,8 @@ public void rebuildBibTextSection(List databases, UndefinedParagraphFormatException, NoDocumentException { - List cited = findCitedKeys(this.xDocumentConnection); + DocumentConnection documentConnection = this.xDocumentConnection; + List cited = findCitedKeys(documentConnection); Map linkSourceBase = new HashMap<>(); Map entries = // Although entries are redefined without use, this also @@ -1855,8 +1856,8 @@ public void rebuildBibTextSection(List databases, } entries = newMap; } - clearBibTextSectionContent2(this.xDocumentConnection); - populateBibTextSection(entries, style); + clearBibTextSectionContent2(documentConnection); + populateBibTextSection(documentConnection, entries, style); } From 49b9f74c15c91572a67c823d033e7e6f257e03e3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:33:23 +0100 Subject: [PATCH 0159/1068] insert documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 61d5d9aff43..889cf27d210 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2054,7 +2054,8 @@ private void populateBibTextSection(DocumentConnection documentConnection, ); insertFullReferenceAtCursor - (cursor, + (documentConnection, + cursor, entries, style, (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT) From c086bfd1bc95fb309990ca98cb8a52cffa37e4bb Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:34:29 +0100 Subject: [PATCH 0160/1068] format --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 889cf27d210..43a4aaa86de 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2063,11 +2063,15 @@ private void populateBibTextSection(DocumentConnection documentConnection, insertBookMark(OOBibBase.BIB_SECTION_END_NAME, cursor); } - private XTextContent insertBookMark(String name, XTextCursor position) - throws IllegalArgumentException, CreationException { + private XTextContent insertBookMark(String name, + XTextCursor position) + throws IllegalArgumentException, + CreationException + { Object bookmark; try { - bookmark = this.mxDocFactory.createInstance("com.sun.star.text.Bookmark"); + bookmark = ( this.mxDocFactory + .createInstance("com.sun.star.text.Bookmark") ); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -2077,7 +2081,8 @@ private XTextContent insertBookMark(String name, XTextCursor position) // get XTextContent interface XTextContent xTextContent = unoQI(XTextContent.class, bookmark); // insert bookmark at the end of the document - // instead of mxDocText.getEnd you could use a text cursor's XTextRange interface or any XTextRange + // instead of mxDocText.getEnd you could use + // a text cursor's XTextRange interface or any XTextRange this.xText.insertTextContent(position, xTextContent, true); position.collapseToEnd(); return xTextContent; From cbf47c846e1446feba2d898ff5621e4c052aef0d Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:38:33 +0100 Subject: [PATCH 0161/1068] insertBookMark use documentConnection --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 43a4aaa86de..7c19f914ac3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2063,27 +2063,29 @@ private void populateBibTextSection(DocumentConnection documentConnection, insertBookMark(OOBibBase.BIB_SECTION_END_NAME, cursor); } - private XTextContent insertBookMark(String name, + private XTextContent insertBookMark(DocumentConnection documentConnection, + String name, XTextCursor position) throws IllegalArgumentException, CreationException { Object bookmark; try { - bookmark = ( this.mxDocFactory + bookmark = ( documentConnection.mxDocFactory .createInstance("com.sun.star.text.Bookmark") ); } catch (Exception e) { throw new CreationException(e.getMessage()); } + // name the bookmark XNamed xNamed = unoQI(XNamed.class, bookmark); xNamed.setName(name); + // get XTextContent interface XTextContent xTextContent = unoQI(XTextContent.class, bookmark); - // insert bookmark at the end of the document - // instead of mxDocText.getEnd you could use - // a text cursor's XTextRange interface or any XTextRange - this.xText.insertTextContent(position, xTextContent, true); + + // insert bookmark at position + documentConnection.xText.insertTextContent(position, xTextContent, true); position.collapseToEnd(); return xTextContent; } From 5527f2a1368d67052b486454a6e0b90395121dd4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:40:16 +0100 Subject: [PATCH 0162/1068] insrt documentConnection arg --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7c19f914ac3..f90d89ed7aa 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1438,7 +1438,7 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, // We need to add it again. cursor.collapseToEnd(); OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); + insertBookMark(documentConnection, OOBibBase.BIB_SECTION_NAME, cursor); } } } @@ -2060,7 +2060,7 @@ private void populateBibTextSection(DocumentConnection documentConnection, style, (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT) ); - insertBookMark(OOBibBase.BIB_SECTION_END_NAME, cursor); + insertBookMark(documentConnection, OOBibBase.BIB_SECTION_END_NAME, cursor); } private XTextContent insertBookMark(DocumentConnection documentConnection, From 5050c5e8cbb9ea4218523e4561e13a9067b5e084 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:42:24 +0100 Subject: [PATCH 0163/1068] insertReferenceMark use documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f90d89ed7aa..f9840ceb6d6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2090,7 +2090,8 @@ private XTextContent insertBookMark(DocumentConnection documentConnection, return xTextContent; } - private void insertReferenceMark(String name, + private void insertReferenceMark(DocumentConnection documentConnection, + String name, String citationText, XTextCursor position, boolean withText, @@ -2104,7 +2105,7 @@ private void insertReferenceMark(String name, // Check if there is "page info" stored for this citation. If so, insert it into // the citation text before inserting the citation: - Optional pageInfo = getCustomProperty(name); + Optional pageInfo = documentConnection.getCustomProperty(name); String citText; if ((pageInfo.isPresent()) && !pageInfo.get().isEmpty()) { citText = style.insertPageInfo(citationText, pageInfo.get()); @@ -2114,7 +2115,7 @@ private void insertReferenceMark(String name, Object bookmark; try { - bookmark = this.mxDocFactory.createInstance("com.sun.star.text.ReferenceMark"); + bookmark = documentConnection.mxDocFactory.createInstance("com.sun.star.text.ReferenceMark"); } catch (Exception e) { throw new CreationException(e.getMessage()); } From 94a4df7d19e8ae1db76fec77e6cf1c25fe61fe8f Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:44:53 +0100 Subject: [PATCH 0164/1068] insert documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f9840ceb6d6..f902e1504e4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -861,10 +861,11 @@ public void insertEntry(List entries, UndefinedParagraphFormatException, NoDocumentException { + DocumentConnection documentConnection = this.xDocumentConnection; try { // Get the cursor positioned by the user. - XTextCursor cursor = this.xDocumentConnection.getViewCursor(); + XTextCursor cursor = documentConnection.getViewCursor(); sortBibEntryList( entries, style ); @@ -876,7 +877,7 @@ public void insertEntry(List entries, ); // Generate unique bookmark-name int citationType = citationTypeFromOptions( withText, inParenthesis ); - String bName = getUniqueReferenceMarkName( this.xDocumentConnection, + String bName = getUniqueReferenceMarkName( documentConnection, keyString, citationType ); @@ -1426,7 +1427,8 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, documentConnection.xText.removeTextContent(bookmark); - insertReferenceMark(names.get(i), + insertReferenceMark(documentConnection, + names.get(i), citMarkers[i], cursor, types[i] != OOBibBase.INVISIBLE_CIT, From 822e9eb08d5b550826d717c83ba6c4971d398bba Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:45:59 +0100 Subject: [PATCH 0165/1068] insert documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f902e1504e4..0e3f98a0367 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -936,7 +936,7 @@ public void insertEntry(List entries, null, // uniquefiers null // unlimAuthors ); - insertReferenceMark(bName, citeText, cursor, withText, style); + insertReferenceMark(documentConnection, bName, citeText, cursor, withText, style); } // // Move to the right of the space and remember this From 4b4fd11625323af17d9124044c8ae8644d1f3db4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:47:07 +0100 Subject: [PATCH 0166/1068] removeReferenceMark use documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0e3f98a0367..8de07e974c0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2162,12 +2162,12 @@ private void insertReferenceMark(DocumentConnection documentConnection, position.collapseToEnd(); } - private void removeReferenceMark(String name) + private void removeReferenceMark(DocumentConnection documentConnection, String name) throws NoSuchElementException, WrappedTargetException, NoDocumentException { - XNameAccess xReferenceMarks = getReferenceMarks(); + XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); if (xReferenceMarks.hasByName(name)) { Object referenceMark = xReferenceMarks.getByName(name); XTextContent bookmark = unoQI(XTextContent.class, referenceMark); From 02efafedbc03093deff589aae62e902eb2d06ff8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:48:00 +0100 Subject: [PATCH 0167/1068] insert documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8de07e974c0..973b612cfca 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2171,7 +2171,7 @@ private void removeReferenceMark(DocumentConnection documentConnection, String n if (xReferenceMarks.hasByName(name)) { Object referenceMark = xReferenceMarks.getByName(name); XTextContent bookmark = unoQI(XTextContent.class, referenceMark); - this.xText.removeTextContent(bookmark); + documentConnection.xText.removeTextContent(bookmark); } } From a01f536af2ff17d323d8e815e7a2c971a33c6904 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:49:46 +0100 Subject: [PATCH 0168/1068] format --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 973b612cfca..272cf562ee0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2183,7 +2183,10 @@ private void removeReferenceMark(DocumentConnection documentConnection, String n * @throws WrappedTargetException * @throws NoSuchElementException */ - private XTextRange getBookmarkRange(String name) throws NoSuchElementException, WrappedTargetException { + private XTextRange getBookmarkRange(String name) + throws NoSuchElementException, + WrappedTargetException + { XNameAccess xNamedBookmarks = getBookmarks(); // retrieve bookmark by name @@ -2196,9 +2199,12 @@ private XTextRange getBookmarkRange(String name) throws NoSuchElementException, } private XNameAccess getBookmarks() { - // query XBookmarksSupplier from document model and get bookmarks collection - XBookmarksSupplier xBookmarksSupplier = unoQI(XBookmarksSupplier.class, xCurrentComponent); - XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks(); + // query XBookmarksSupplier from document model + // and get bookmarks collection + XBookmarksSupplier xBookmarksSupplier = + unoQI(XBookmarksSupplier.class, xCurrentComponent); + XNameAccess xNamedBookmarks = + xBookmarksSupplier.getBookmarks(); return xNamedBookmarks; } From 35e7d170b7960fd97b9768452343468ca64b2a9b Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:51:08 +0100 Subject: [PATCH 0169/1068] getBookmarks use documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 272cf562ee0..49091474326 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2198,11 +2198,13 @@ private XTextRange getBookmarkRange(String name) return xFoundBookmark.getAnchor(); } - private XNameAccess getBookmarks() { + private XNameAccess getBookmarks(DocumentConnection documentConnection) { // query XBookmarksSupplier from document model // and get bookmarks collection XBookmarksSupplier xBookmarksSupplier = - unoQI(XBookmarksSupplier.class, xCurrentComponent); + unoQI(XBookmarksSupplier.class, + documentConnection.xCurrentComponent + ); XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks(); return xNamedBookmarks; From b498c2c8655979d60fc6ba1cdaedbec8e4c1e12d Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:52:13 +0100 Subject: [PATCH 0170/1068] getBookmarkRange use documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 49091474326..9423dac931f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2183,11 +2183,12 @@ private void removeReferenceMark(DocumentConnection documentConnection, String n * @throws WrappedTargetException * @throws NoSuchElementException */ - private XTextRange getBookmarkRange(String name) + private XTextRange getBookmarkRange(DocumentConnection documentConnection, + String name) throws NoSuchElementException, WrappedTargetException { - XNameAccess xNamedBookmarks = getBookmarks(); + XNameAccess xNamedBookmarks = getBookmarks(documentConnection); // retrieve bookmark by name if (!xNamedBookmarks.hasByName(name)) { From b502b913cd54745cdf4ef4ce38c34cbdb6f7d19f Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:54:04 +0100 Subject: [PATCH 0171/1068] insert documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9423dac931f..8c1615534b8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1391,7 +1391,8 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, assert( types.length == nRefMarks ); XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); - final boolean hadBibSection = (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); + final boolean hadBibSection = + (getBookmarkRange(documentConnection, OOBibBase.BIB_SECTION_NAME) != null); // If we are supposed to set character format for citations, // must run a test before we delete old citation @@ -1435,7 +1436,8 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, style ); - if (hadBibSection && (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { + if (hadBibSection && (getBookmarkRange(documentConnection, + OOBibBase.BIB_SECTION_NAME) == null)) { // We have overwritten the marker for the start of the reference list. // We need to add it again. cursor.collapseToEnd(); From c99e7699cc257213768756b4c65d371ab28012ce Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 14:58:52 +0100 Subject: [PATCH 0172/1068] combineCiteMarkers uses xDocumentConnection --- .../org/jabref/gui/openoffice/OOBibBase.java | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8c1615534b8..d207229b4b9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2227,6 +2227,9 @@ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, } } + /** + * GUI action + */ public void combineCiteMarkers(List databases, OOBibStyle style) throws IOException, WrappedTargetException, @@ -2239,11 +2242,15 @@ public void combineCiteMarkers(List databases, OOBibStyle style) BibEntryNotFoundException, NoDocumentException { - XNameAccess nameAccess = getReferenceMarks(); + DocumentConnection documentConnection = this.xDocumentConnection; + + XNameAccess nameAccess = documentConnection.getReferenceMarks(); // TODO: doesn't work for citations in footnotes/tables - List names = getJabRefReferenceMarkNamesSortedByPosition(nameAccess); + List names = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection, nameAccess); - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, this.xText); + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + documentConnection.xText); int piv = 0; boolean madeModifications = false; @@ -2284,8 +2291,8 @@ public void combineCiteMarkers(List databases, OOBibStyle style) List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(piv + 1))); - removeReferenceMark(names.get(piv)); - removeReferenceMark(names.get(piv + 1)); + removeReferenceMark(documentConnection, names.get(piv)); + removeReferenceMark(documentConnection, names.get(piv + 1)); List entries = new ArrayList<>(); for (String key : keys) { for (BibDatabase database : databases) { @@ -2300,8 +2307,11 @@ public void combineCiteMarkers(List databases, OOBibStyle style) String keyString = String.join(",", entries.stream().map(entry -> entry.getCitationKey().orElse("")) .collect(Collectors.toList())); // Insert bookmark: - String bName = getUniqueReferenceMarkName(this.xDocumentConnection, keyString, OOBibBase.AUTHORYEAR_PAR); - insertReferenceMark(bName, "tmp", mxDocCursor, true, style); + String bName = getUniqueReferenceMarkName(documentConnection, + keyString, + OOBibBase.AUTHORYEAR_PAR + ); + insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); names.set(piv + 1, bName); madeModifications = true; } From 3fc9825825af371b5b8dafee1eda520c5b988749 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:01:27 +0100 Subject: [PATCH 0173/1068] getJabRefReferenceMarkNamesSortedByPosition does not need nameAccess param --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d207229b4b9..3e5be7ac8b0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2244,16 +2244,16 @@ public void combineCiteMarkers(List databases, OOBibStyle style) { DocumentConnection documentConnection = this.xDocumentConnection; - XNameAccess nameAccess = documentConnection.getReferenceMarks(); // TODO: doesn't work for citations in footnotes/tables List names = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection, nameAccess); + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, documentConnection.xText); int piv = 0; boolean madeModifications = false; + XNameAccess nameAccess = documentConnection.getReferenceMarks(); while (piv < (names.size() - 1)) { XTextRange range1 = unoQI(XTextContent.class, nameAccess.getByName(names.get(piv))) .getAnchor().getEnd(); From a65279861736af393d4e01ab70d06cdaa218fffd Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:05:38 +0100 Subject: [PATCH 0174/1068] unCombineCiteMarkers use xDocumentConnection --- .../org/jabref/gui/openoffice/OOBibBase.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3e5be7ac8b0..d45d543d210 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2324,6 +2324,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } /** + * GUI action. * Do the opposite of combineCiteMarkers. * Combined markers are split, with a space inserted between. */ @@ -2339,14 +2340,17 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) BibEntryNotFoundException, NoDocumentException { - XNameAccess nameAccess = getReferenceMarks(); + DocumentConnection documentConnection = this.xDocumentConnection; + // TODO: doesn't work for citations in footnotes/tables - List names = getJabRefReferenceMarkNamesSortedByPosition(nameAccess); + List names = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, this.xText); + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + documentConnection.xText); int piv = 0; boolean madeModifications = false; + XNameAccess nameAccess = documentConnection.getReferenceMarks(); while (piv < (names.size())) { XTextRange range1 = unoQI(XTextContent.class, nameAccess.getByName(names.get(piv))) .getAnchor(); @@ -2371,14 +2375,17 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); if (keys.size() > 1) { - removeReferenceMark(names.get(piv)); + removeReferenceMark(documentConnection, names.get(piv)); // // Insert bookmark for each key int last = keys.size() - 1; int i = 0; for (String key : keys) { - String bName = getUniqueReferenceMarkName(this.xDocumentConnection,key, OOBibBase.AUTHORYEAR_PAR); - insertReferenceMark(bName, "tmp", mxDocCursor, true, style); + String bName = getUniqueReferenceMarkName(documentConnection, + key, + OOBibBase.AUTHORYEAR_PAR + ); + insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); mxDocCursor.collapseToEnd(); if (i != last) { mxDocCursor.setString(" "); From b8a6aef69434acaeec00bc125af020776c090cff Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 16 Apr 2021 23:14:15 +0200 Subject: [PATCH 0175/1068] insert arg documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d45d543d210..12ece019ed3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2403,13 +2403,17 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) } } + /** + * Used from GUI. + */ public BibDatabase generateDatabase(List databases) throws NoSuchElementException, WrappedTargetException, NoDocumentException { + DocumentConnection documentConnection = this.xDocumentConnection; BibDatabase resultDatabase = new BibDatabase(); - List cited = findCitedKeys(); + List cited = findCitedKeys(documentConnection); List entriesToInsert = new ArrayList<>(); // For each cited key From 85ebdeb9ab690d0c6d77645e112161fa9cb07324 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 16 Apr 2021 23:15:09 +0200 Subject: [PATCH 0176/1068] unCombineCiteMarkers rename piv to pivot --- .../org/jabref/gui/openoffice/OOBibBase.java | 58 +++++++------------ 1 file changed, 21 insertions(+), 37 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 12ece019ed3..ab146f47e69 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2324,44 +2324,31 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } /** - * GUI action. * Do the opposite of combineCiteMarkers. * Combined markers are split, with a space inserted between. */ public void unCombineCiteMarkers(List databases, OOBibStyle style) - throws IOException, - WrappedTargetException, - NoSuchElementException, - IllegalArgumentException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException - { - DocumentConnection documentConnection = this.xDocumentConnection; + throws IOException, WrappedTargetException, NoSuchElementException, IllegalArgumentException, + UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException, + BibEntryNotFoundException { + XNameAccess nameAccess = getReferenceMarks(); + List names = getSortedReferenceMarks(nameAccess); - // TODO: doesn't work for citations in footnotes/tables - List names = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + final XTextRangeCompare compare = UnoRuntime.queryInterface(XTextRangeCompare.class, text); - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - documentConnection.xText); - - int piv = 0; + int pivot = 0; boolean madeModifications = false; - XNameAccess nameAccess = documentConnection.getReferenceMarks(); - while (piv < (names.size())) { - XTextRange range1 = unoQI(XTextContent.class, nameAccess.getByName(names.get(piv))) + while (pivot < (names.size())) { + XTextRange range1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(pivot))) .getAnchor(); - XTextCursor mxDocCursor = range1.getText().createTextCursorByRange(range1); - // + XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); + // If we are supposed to set character format for citations, test this before // making any changes. This way we can throw an exception before any reference // marks are removed, preventing damage to the user's document: if (style.isFormatCitations()) { - XPropertySet xCursorProps = unoQI(XPropertySet.class, mxDocCursor); + XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, textCursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); @@ -2373,29 +2360,26 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) } } - List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); + List keys = parseRefMarkName(names.get(pivot)); if (keys.size() > 1) { - removeReferenceMark(documentConnection, names.get(piv)); - // + removeReferenceMark(names.get(pivot)); + // Insert bookmark for each key int last = keys.size() - 1; int i = 0; for (String key : keys) { - String bName = getUniqueReferenceMarkName(documentConnection, - key, - OOBibBase.AUTHORYEAR_PAR - ); - insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); - mxDocCursor.collapseToEnd(); + String newName = getUniqueReferenceMarkName(key, OOBibBase.AUTHORYEAR_PAR); + insertReferenceMark(newName, "tmp", textCursor, true, style); + textCursor.collapseToEnd(); if (i != last) { - mxDocCursor.setString(" "); - mxDocCursor.collapseToEnd(); + textCursor.setString(" "); + textCursor.collapseToEnd(); } i++; } madeModifications = true; } - piv++; + pivot++; } if (madeModifications) { updateSortedReferenceMarks(); From 2b98253065963f3e67d1bb752d3b8afb2a856326 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:10:33 +0100 Subject: [PATCH 0177/1068] add throws NoDocumentException --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ab146f47e69..070ef396357 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -243,7 +243,9 @@ public boolean checkDocumentConnection(){ return true; } - List getReferenceMarknames(){ + List getReferenceMarknames() + throws NoDocumentException + { XNameAccess nameAccess = getReferenceMarks(); String[] names = nameAccess.getElementNames(); if (names == null) { @@ -257,7 +259,8 @@ public String getCitationContext(String refMarkName, int charAfter, boolean htmlMarkup) throws NoSuchElementException, - WrappedTargetException + WrappedTargetException, + NoDocumentException { XNameAccess nameAccess = getReferenceMarks(); Object referenceMark = nameAccess.getByName(refMarkName); @@ -1745,7 +1748,8 @@ private static Point findPositionOfTextRange(XTextViewCursor cursor, XTextRange */ private List getJabRefReferenceMarkNamesSortedByPosition(DocumentConnection documentConnection) throws WrappedTargetException, - NoSuchElementException + NoSuchElementException, + NoDocumentException { List names = getJabRefReferenceMarkNames(documentConnection); From 6129fcb3e81bd044a9bdb926fe3c6e1d472bb8e3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:12:02 +0100 Subject: [PATCH 0178/1068] NoDocumentException --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 070ef396357..f5c23a610d3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -667,7 +667,9 @@ private static List filterIsJabRefReferenceMarkName( List names /* * called from getCitationEntries(...) */ - private List getJabRefReferenceMarkNames(DocumentConnection documentConnection) { + private List getJabRefReferenceMarkNames(DocumentConnection documentConnection) + throws NoDocumentException + { return filterIsJabRefReferenceMarkName( documentConnection.getReferenceMarknames() ); } From b909713f5916d83932efe96f6ea3be485dbb00fc Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:16:58 +0100 Subject: [PATCH 0179/1068] add IOException --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f5c23a610d3..ce8a7760d39 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1822,9 +1822,10 @@ public List updateDocumentActionHelper(List databases, UndefinedParagraphFormatException, NoDocumentException, UndefinedCharacterFormatException, - BibEntryNotFoundException + BibEntryNotFoundException, + IOException { - updateSortedReferenceMarks(); // NoDocumentException + updateSortedReferenceMarks(); List unresolvedKeys = refreshCiteMarkers(databases, style); rebuildBibTextSection(databases, style); return unresolvedKeys; From 15564134314ed1d13c53aa6723f0e3af8bb90cf8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:24:35 +0100 Subject: [PATCH 0180/1068] prep for xDocumentConnection checks --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ce8a7760d39..dfe740a5164 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -597,12 +597,22 @@ public boolean isConnectedToDocument() { } public boolean checkDocumentConnection(){ + if (this.xDocumentConnection == null){ + return false; + } boolean res = this.xDocumentConnection.checkDocumentConnection(); if ( ! res ){ forgetDocument(); } return res; } + public void checkDocumentConnectionThrow() + throw NoDocumentException + { + if ( ! checkDocumentConnection() ){ + throw new NoDocumentException("Not connected to document"); + } + } /* * Getters useful after selectDocument() From f54d4dd96631454c2c500c83f6981793994a5a0d Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 16 Apr 2021 23:18:40 +0200 Subject: [PATCH 0181/1068] public methods check documentConnection on entry --- .../org/jabref/gui/openoffice/OOBibBase.java | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index dfe740a5164..7b0bf5606d4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -606,12 +606,14 @@ public boolean checkDocumentConnection(){ } return res; } - public void checkDocumentConnectionThrow() + + private DocumentConnection getDocumentConnectionOrThrow() throw NoDocumentException { if ( ! checkDocumentConnection() ){ throw new NoDocumentException("Not connected to document"); } + return this.xDocumentConnection; } /* @@ -619,7 +621,7 @@ public void checkDocumentConnectionThrow() */ public Optional getCurrentDocumentTitle() { - return this.xDocumentConnection.getDocumentTitle(); + return this.getDocumentConnectionOrThrow().getDocumentTitle(); } @@ -692,7 +694,7 @@ public List getCitationEntries() WrappedTargetException, NoDocumentException { - return this.getCitationEntriesImpl( this.xDocumentConnection ); + return this.getCitationEntriesImpl( this.getDocumentConnectionOrThrow() ); } private List getCitationEntriesImpl( DocumentConnection documentConnection ) @@ -740,6 +742,7 @@ public void applyCitationEntries( List citationEntries ) IllegalTypeException, IllegalArgumentException { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); // Leave exceptions to the caller. // // Note: not catching exceptions here means nothing is applied @@ -750,7 +753,7 @@ public void applyCitationEntries( List citationEntries ) for (CitationEntry entry : citationEntries) { Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { - this.xDocumentConnection.setCustomProperty( entry.getRefMarkName(), pageInfo.get() ); + documentConnection.setCustomProperty( entry.getRefMarkName(), pageInfo.get() ); } else { // TODO: if pageInfo is not present, or is empty: // maybe we should remove it from the document. @@ -876,7 +879,7 @@ public void insertEntry(List entries, UndefinedParagraphFormatException, NoDocumentException { - DocumentConnection documentConnection = this.xDocumentConnection; + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { // Get the cursor positioned by the user. @@ -899,7 +902,7 @@ public void insertEntry(List entries, // If we should store metadata for page info, do that now: if (pageInfo != null) { LOGGER.info("Storing page info: " + pageInfo); - this.xDocumentConnection.setCustomProperty(bName, pageInfo); + documentConnection.setCustomProperty(bName, pageInfo); } // insert space @@ -1120,8 +1123,9 @@ public List refreshCiteMarkers(List databases, BibEntryNotFoundException, NoDocumentException { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { - return refreshCiteMarkersInternal(this.xDocumentConnection, databases, style); + return refreshCiteMarkersInternal(documentConnection, databases, style); } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference @@ -1813,7 +1817,9 @@ public void updateSortedReferenceMarks() NoSuchElementException, NoDocumentException { - this.sortedReferenceMarks = getJabRefReferenceMarkNamesSortedByPosition(this.xDocumentConnection); + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + this.sortedReferenceMarks = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); } /** @@ -1853,7 +1859,8 @@ public void rebuildBibTextSection(List databases, UndefinedParagraphFormatException, NoDocumentException { - DocumentConnection documentConnection = this.xDocumentConnection; + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + List cited = findCitedKeys(documentConnection); Map linkSourceBase = new HashMap<>(); Map entries = @@ -2412,7 +2419,8 @@ public BibDatabase generateDatabase(List databases) WrappedTargetException, NoDocumentException { - DocumentConnection documentConnection = this.xDocumentConnection; + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + BibDatabase resultDatabase = new BibDatabase(); List cited = findCitedKeys(documentConnection); List entriesToInsert = new ArrayList<>(); From 7c62678f1832cf1a0d6584f3c3bdfcd0b58b0351 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:39:38 +0100 Subject: [PATCH 0182/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7b0bf5606d4..b38a1c0dc73 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1367,8 +1367,8 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry * @return the (1-based) indices of the cited keys, -1 if a key is not found. * Returns Collections.emptyList() if the ref name could not be resolved as a citation. */ - private List findCitedEntryIndices( List keysCitedHere, - List orderedCiteKeys) + private List findCitedEntryIndices(List keysCitedHere, + List orderedCiteKeys) { List result = new ArrayList<>(keysCitedHere.size()); for (String key : keysCitedHere) { From 3e3da019e544f681e9c62c7f99036f2e1d07ff7e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:41:19 +0100 Subject: [PATCH 0183/1068] rename names to referenceMarkNames --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b38a1c0dc73..c700c21e9d2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1379,21 +1379,21 @@ private List findCitedEntryIndices(List keysCitedHere, } /** - * Visit each reference mark in names, + * Visit each reference mark in referenceMarkNames, * remove its text content, * call insertReferenceMark. * * After each insertReferenceMark call check if we lost the * OOBibBase.BIB_SECTION_NAME bookmark and recrate it if we did. * - * @param names Reference mark names + * @param referenceMarkNames Reference mark names * @param citMarkers Corresponding text for each reference mark, * that replaces the old text. * @param types itcType codes for each reference mark. * @param style */ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, - List names, + List referenceMarkNames, String[] citMarkers, int[] types, OOBibStyle style ) @@ -1405,7 +1405,7 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, WrappedTargetException, PropertyVetoException { - final int nRefMarks = names.size(); + final int nRefMarks = referenceMarkNames.size(); assert( citMarkers.length == nRefMarks ); assert( types.length == nRefMarks ); @@ -1422,7 +1422,7 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, boolean mustTestCharFormat = style.isFormatCitations(); for (int i = 0; i < nRefMarks; i++) { - Object referenceMark = xReferenceMarks.getByName(names.get(i)); + Object referenceMark = xReferenceMarks.getByName(referenceMarkNames.get(i)); XTextContent bookmark = unoQI(XTextContent.class, referenceMark); XTextCursor cursor = @@ -1448,7 +1448,7 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, documentConnection.xText.removeTextContent(bookmark); insertReferenceMark(documentConnection, - names.get(i), + referenceMarkNames.get(i), citMarkers[i], cursor, types[i] != OOBibBase.INVISIBLE_CIT, From 8ff3f47f85d75aa4a8916f30d688ac83b5d000cc Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:43:14 +0100 Subject: [PATCH 0184/1068] names to referenceMarkNames --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c700c21e9d2..6ddfa74b7da 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1483,10 +1483,10 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne GetSortedCitedEntriesResult sce = getSortedCitedEntries(documentConnection, databases, style, xReferenceMarks ); - List names = sce.refMarkNames; + List referenceMarkNames = sce.refMarkNames; // Compute citation markers for all citations: - final int nRefMarks = names.size(); + final int nRefMarks = referenceMarkNames.size(); int[] types = new int[nRefMarks]; String[][] bibtexKeys = new String[nRefMarks][]; @@ -1494,7 +1494,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // types[i] = ov.itcType // bibtexKeys[i] = ov.citedKeys.toArray() for (int i = 0; i < nRefMarks; i++) { - final String namei = names.get(i); + final String namei = referenceMarkNames.get(i); Optional op = parseRefMarkName( namei ); if ( !op.isPresent() ) { continue; @@ -1523,8 +1523,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // fill citMarkers if (style.isCitationKeyCiteMarkers()) { - for (int i = 0; i < names.size(); i++) { - final String namei = names.get(i); + for (int i = 0; i < referenceMarkNames.size(); i++) { + final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); @@ -1535,8 +1535,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne } else if (style.isNumberEntries()) { - for (int i = 0; i < names.size(); i++) { - final String namei = names.get(i); + for (int i = 0; i < referenceMarkNames.size(); i++) { + final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); @@ -1561,8 +1561,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // normCitMarkers[i][j] = for unification String[][] normCitMarkers = new String[nRefMarks][]; - for (int i = 0; i < names.size(); i++) { - final String namei = names.get(i); + for (int i = 0; i < referenceMarkNames.size(); i++) { + final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); @@ -1731,7 +1731,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // Refresh all reference marks with the citation markers we computed: - rcmApplyNewCitationMarkers(documentConnection, names, citMarkers, types, style ); + rcmApplyNewCitationMarkers(documentConnection, referenceMarkNames, citMarkers, types, style ); // Collect and return unresolved citation keys. // uses: entries From 8008da89ce4e4243e2d3dd454047cad97554ead4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:45:49 +0100 Subject: [PATCH 0185/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6ddfa74b7da..40336a3b500 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -321,7 +321,6 @@ public String getCitationContext(String refMarkName, public XTextViewCursor getViewCursor(){ return this.xViewCursorSupplier.getViewCursor(); } - } // end DocumentConnection From d90c8019ee7790e9bd98bded5bd057ce73566ce0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:46:53 +0100 Subject: [PATCH 0186/1068] rename uniquefiers xUniquefiers --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 40336a3b500..c768826c638 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -326,9 +326,9 @@ public XTextViewCursor getViewCursor(){ private DocumentConnection xDocumentConnection; /* - * uniquefiers : maps bibtexkeys to letters ("a", "b") + * xUniquefiers : maps bibtexkeys to letters ("a", "b") */ - private final Map uniquefiers = new HashMap<>(); + private final Map xUniquefiers = new HashMap<>(); private List sortedReferenceMarks; From d5642875b63a3f9b7acd3b89aed7e4fffc46a4ff Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:48:06 +0100 Subject: [PATCH 0187/1068] typp throw -> throws --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c768826c638..7367e9c1086 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -607,7 +607,7 @@ public boolean checkDocumentConnection(){ } private DocumentConnection getDocumentConnectionOrThrow() - throw NoDocumentException + throws NoDocumentException { if ( ! checkDocumentConnection() ){ throw new NoDocumentException("Not connected to document"); From e1292b24687aa2a1a516141d8ab1d66abe57b89d Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 15:53:58 +0100 Subject: [PATCH 0188/1068] propagating uses of uniquefiers --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7367e9c1086..a3c44549955 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1124,7 +1124,10 @@ public List refreshCiteMarkers(List databases, { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { - return refreshCiteMarkersInternal(documentConnection, databases, style); + return refreshCiteMarkersInternal(documentConnection, + databases, + style, + this.xUniquefiers); } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference @@ -1467,7 +1470,9 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, private List refreshCiteMarkersInternal(DocumentConnection documentConnection, List databases, - OOBibStyle style ) + OOBibStyle style, + final Map uniquefiers + ) throws WrappedTargetException, IllegalArgumentException, NoSuchElementException, @@ -1884,7 +1889,7 @@ public void rebuildBibTextSection(List databases, entries = newMap; } clearBibTextSectionContent2(documentConnection); - populateBibTextSection(documentConnection, entries, style); + populateBibTextSection(documentConnection, entries, style, this.xUniquefiers); } @@ -1930,7 +1935,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, XTextCursor cursor, Map entries, OOBibStyle style, - String parFormat) + String parFormat, + final Map uniquefiers) throws UndefinedParagraphFormatException, IllegalArgumentException, UnknownPropertyException, @@ -2047,7 +2053,8 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) private void populateBibTextSection(DocumentConnection documentConnection, Map entries, - OOBibStyle style) + OOBibStyle style, + final Map uniquefiers) throws NoSuchElementException, WrappedTargetException, PropertyVetoException, @@ -2085,7 +2092,8 @@ private void populateBibTextSection(DocumentConnection documentConnection, cursor, entries, style, - (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT) + (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT), + uniquefiers ); insertBookMark(documentConnection, OOBibBase.BIB_SECTION_END_NAME, cursor); } From 3487f9b8c980e25b06359f5401ca16f2a3122cc2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 16:00:14 +0100 Subject: [PATCH 0189/1068] getCurrentDocumentTitle does not throw --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a3c44549955..ca75b9ddeba 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -620,7 +620,11 @@ private DocumentConnection getDocumentConnectionOrThrow() */ public Optional getCurrentDocumentTitle() { - return this.getDocumentConnectionOrThrow().getDocumentTitle(); + if ( ! checkDocumentConnection() ){ + return Optional.empty(); + } else { + return this.xDocumentConnection.getDocumentTitle(); + } } From af69b3474e7f6cfb4bca81a417ca7276c3c17a26 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 16:01:27 +0100 Subject: [PATCH 0190/1068] add NoDocumentException --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ca75b9ddeba..04b9599b39d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -743,7 +743,8 @@ public void applyCitationEntries( List citationEntries ) NotRemoveableException, PropertyExistException, IllegalTypeException, - IllegalArgumentException + IllegalArgumentException, + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); // Leave exceptions to the caller. From a7c51846e95b8bd6b9450c51e9dafde5d3c86d72 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 16:04:53 +0100 Subject: [PATCH 0191/1068] format --- .../ManageCitationsDialogViewModel.java | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 600eeef5d81..3a5dc07a6a3 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -49,14 +49,24 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, } public void storeSettings() { - List citationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); + + List citationEntries = + citations.stream() + .map(CitationEntryViewModel::toCitationEntry) + .collect(Collectors.toList()); + try { ooBase.applyCitationEntries( citationEntries ); - } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException | - IllegalArgumentException ex) { - LOGGER.warn("Problem modifying citation", ex); - dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex); - } + } catch (UnknownPropertyException + | NotRemoveableException + | PropertyExistException + | IllegalTypeException + | IllegalArgumentException ex + ) + { + LOGGER.warn("Problem modifying citation", ex); + dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex); + } } public ListProperty citationsProperty() { From 550ef8c4eb638ed0dea4c52a1aa823791172fa6e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 16:05:32 +0100 Subject: [PATCH 0192/1068] storeSettings catches NoDocumentException --- .../jabref/gui/openoffice/ManageCitationsDialogViewModel.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 3a5dc07a6a3..7d810d8a032 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -61,7 +61,8 @@ public void storeSettings() { | NotRemoveableException | PropertyExistException | IllegalTypeException - | IllegalArgumentException ex + | IllegalArgumentException + | NoDocumentException ex ) { LOGGER.warn("Problem modifying citation", ex); From 44808167548f39df9a5ecf248c34044830b24470 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 16:19:05 +0100 Subject: [PATCH 0193/1068] namei -> referenceMarkName --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 04b9599b39d..a209b4817ba 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1156,7 +1156,7 @@ public List refreshCiteMarkers(List databases, private static BibEntry[] linkSourceBaseGetBibEntriesOfCiteKeys ( Map linkSourceBase, String[] keys, // citeKeys - String namei // refMarkName + String referenceMarkName // for reporting ) throws BibEntryNotFoundException { @@ -1170,12 +1170,12 @@ public List refreshCiteMarkers(List databases, cEntries[j] = tmpEntry.get(); } else { LOGGER.info("Citation key not found: '" + kj + '\''); - LOGGER.info("Problem with reference mark: '" + namei + '\''); + LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); String msg = Localization.lang("Could not resolve BibTeX entry" +" for citation marker '%0'.", - namei + referenceMarkName ); - throw new BibEntryNotFoundException(namei, msg); + throw new BibEntryNotFoundException(referenceMarkName, msg); } } // for j return cEntries; From 0707616d93f67fa5180ecadcdbd6d4816fce4dc4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 16:31:34 +0100 Subject: [PATCH 0194/1068] drop comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a209b4817ba..c29ecf6b989 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1905,11 +1905,6 @@ private Map getSortedEntriesFromSortedRefMarks(List newList = new LinkedHashMap<>(); for (String name : names) { - /* - * Matcher citeMatcher = CITE_PATTERN.matcher(name); - * if (citeMatcher.find()) { - * String[] keys = citeMatcher.group(2).split(","); - */ Optional op = parseRefMarkName( name ); if ( ! op.isPresent() ){ continue; } List keys = op.get().citedKeys; From 7620404e25de4da6958479c52af9afc077fa65af Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 17:27:44 +0100 Subject: [PATCH 0195/1068] comment --- .../org/jabref/gui/openoffice/OOBibBase.java | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c29ecf6b989..446512c7766 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1061,8 +1061,10 @@ private List findCitedKeys( DocumentConnection documentConnection ) return keys; } + /** * @return LinkedHashMap, from BibEntry to BibDatabase + * Side effect: add found citedKeys to linkSourceBase * * If a citedKey is not found, BibEntry is new UndefinedBibtexEntry(citedKey), BibDatabase is null. * If citedKey is found, then @@ -1076,7 +1078,8 @@ private List findCitedKeys( DocumentConnection documentConnection ) */ private Map findCitedEntries(List databases, List citedKeys, - Map linkSourceBase) + Map linkSourceBase + ) { Map entries = new LinkedHashMap<>(); for (String citedKey : citedKeys) { @@ -1226,18 +1229,17 @@ private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection doc WrappedTargetException, NoDocumentException { - Map linkSourceBase = new HashMap<>(); + // keys cited in the text List cited = findCitedKeys( documentConnection ); - Map entries = - findCitedEntries(databases, cited, linkSourceBase); + + Map linkSourceBase = new HashMap<>(); + + Map entries = findCitedEntries(databases, cited, linkSourceBase); + List names; - if (style.isSortByPosition()) { - // We need to sort the reference marks according to their - // order of appearance: - names = sortedReferenceMarks; - } else if (style.isNumberEntries()) { + if (style.isNumberEntries() && ! style.isSortByPosition()) { // // We need to sort the reference marks according to the // sorting of the bibliographic entries: @@ -1255,6 +1257,8 @@ private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection doc // names = Arrays.asList(xReferenceMarks.getElementNames()); } else { + // We need to sort the reference marks according to their + // order of appearance: names = sortedReferenceMarks; } @@ -1492,6 +1496,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne GetSortedCitedEntriesResult sce = getSortedCitedEntries(documentConnection, databases, style, xReferenceMarks ); + + List referenceMarkNames = sce.refMarkNames; // Compute citation markers for all citations: From d83995c1d4e37e9dcd2c965413ecdb4ba2214c88 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 17:37:45 +0100 Subject: [PATCH 0196/1068] jabRefReferenceMarkNamesSortedByPosition --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 446512c7766..074c11fddf4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -330,7 +330,7 @@ public XTextViewCursor getViewCursor(){ */ private final Map xUniquefiers = new HashMap<>(); - private List sortedReferenceMarks; + private List jabRefReferenceMarkNamesSortedByPosition; /** unoQI : short for UnoRuntime.queryInterface * @@ -1209,7 +1209,7 @@ private class GetSortedCitedEntriesResult { * * linkSourceBase maps the citedKeys to the database we found it in * - * refMarkNames : sortedReferenceMarks, + * refMarkNames : jabRefReferenceMarkNamesSortedByPosition, * except for style.isNumberEntries(), * where we keep the order from xReferenceMarks.getElementNames() * In any case: we apply filterIsJabRefReferenceMarkName. @@ -1249,6 +1249,7 @@ private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection doc newMap.put(ee.getKey(), ee.getValue()); } entries = newMap; + // Rebuild the list of cited keys according to the sort order: cited.clear(); for (BibEntry entry : entries.keySet()) { @@ -1259,7 +1260,7 @@ private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection doc } else { // We need to sort the reference marks according to their // order of appearance: - names = sortedReferenceMarks; + names = jabRefReferenceMarkNamesSortedByPosition; } // Remove all reference marks that don't look like JabRef citations: @@ -1833,7 +1834,7 @@ public void updateSortedReferenceMarks() NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - this.sortedReferenceMarks = + this.jabRefReferenceMarkNamesSortedByPosition = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); } @@ -1885,7 +1886,7 @@ public void rebuildBibTextSection(List databases, if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: - List names = sortedReferenceMarks; + List names = jabRefReferenceMarkNamesSortedByPosition; entries = getSortedEntriesFromSortedRefMarks(names, linkSourceBase); } else { // Find them again? Why? From 3984536efb2469e9a87fb772e648c14106a985b4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 17:45:39 +0100 Subject: [PATCH 0197/1068] eliminate var names --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 074c11fddf4..795b6340af4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1886,8 +1886,10 @@ public void rebuildBibTextSection(List databases, if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: - List names = jabRefReferenceMarkNamesSortedByPosition; - entries = getSortedEntriesFromSortedRefMarks(names, linkSourceBase); + entries = getSortedEntriesFromSortedRefMarks( + jabRefReferenceMarkNamesSortedByPosition, + linkSourceBase + ); } else { // Find them again? Why? Map entries2 = From 6829a3f18cd5dbf91290b14c0a925751b21f9b95 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 17:47:52 +0100 Subject: [PATCH 0198/1068] rename arg --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 795b6340af4..add249089f0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1908,12 +1908,14 @@ public void rebuildBibTextSection(List databases, - - private Map getSortedEntriesFromSortedRefMarks(List names, + /** + * @param referenceMarkNames + */ + private Map getSortedEntriesFromSortedRefMarks(List referenceMarkNames, Map linkSourceBase) { Map newList = new LinkedHashMap<>(); - for (String name : names) { + for (String name : referenceMarkNames) { Optional op = parseRefMarkName( name ); if ( ! op.isPresent() ){ continue; } List keys = op.get().citedKeys; From 21fde38882a55eee97dd9cf4534af99a122d0925 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 17:59:03 +0100 Subject: [PATCH 0199/1068] origEntry is not present if we did not look it up --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index add249089f0..f399429e531 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1909,26 +1909,34 @@ public void rebuildBibTextSection(List databases, /** - * @param referenceMarkNames + * @param referenceMarkNames + * @param linkSourceBase Helps to find the entries + * + * @return LinkedHashMap from BibEntry to BibDatabase with + * iteration order as first appearance in referenceMarkNames. */ private Map getSortedEntriesFromSortedRefMarks(List referenceMarkNames, Map linkSourceBase) { + // LinkedHashMap: iteration order is insertion-order, not + // affected if a key is re-inserted. Map newList = new LinkedHashMap<>(); + for (String name : referenceMarkNames) { Optional op = parseRefMarkName( name ); if ( ! op.isPresent() ){ continue; } + List keys = op.get().citedKeys; for (String key : keys) { BibDatabase database = linkSourceBase.get(key); Optional origEntry = Optional.empty(); if (database != null) { origEntry = database.getEntryByCitationKey(key); - } - if (origEntry.isPresent()) { - BibEntry oe = origEntry.get(); - if (!newList.containsKey(oe)) { - newList.put(oe, database); + if (origEntry.isPresent()) { + BibEntry oe = origEntry.get(); + if (!newList.containsKey(oe)) { + newList.put(oe, database); + } } } else { LOGGER.info("Citation key not found: '" + key + "'"); From 4edd97a3348038486f1f258380d0677d9c08812a Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 18:02:21 +0100 Subject: [PATCH 0200/1068] scope --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f399429e531..8c05258df8e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1929,9 +1929,8 @@ private Map getSortedEntriesFromSortedRefMarks(List keys = op.get().citedKeys; for (String key : keys) { BibDatabase database = linkSourceBase.get(key); - Optional origEntry = Optional.empty(); if (database != null) { - origEntry = database.getEntryByCitationKey(key); + Optional origEntry = database.getEntryByCitationKey(key); if (origEntry.isPresent()) { BibEntry oe = origEntry.get(); if (!newList.containsKey(oe)) { From bff1cf29cf6dac698b718dcb9c595d8b935b3a4e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 18:13:19 +0100 Subject: [PATCH 0201/1068] citeKeyToBibEntry for findCitedEntries --- .../org/jabref/gui/openoffice/OOBibBase.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8c05258df8e..ba04bd75649 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1075,10 +1075,13 @@ private List findCitedKeys( DocumentConnection documentConnection ) * - result has an entry for each citedKey, in the same order * - citedKey in the entry is the same as the original citedKey * - on return linkSourceBase has an entry for the citedKey we did find + * + * - Also fill citeKeyToBibEntry */ private Map findCitedEntries(List databases, List citedKeys, - Map linkSourceBase + Map linkSourceBase, + Map citeKeyToBibEntry ) { Map entries = new LinkedHashMap<>(); @@ -1089,13 +1092,16 @@ private Map findCitedEntries(List databases, if (entry.isPresent()) { entries.put(entry.get(), database); linkSourceBase.put(citedKey, database); + citeKeyToBibEntry.put( citedKey, entry.get() ); found = true; break; } } if (!found) { - entries.put(new UndefinedBibtexEntry(citedKey), null); + BibEntry x = new UndefinedBibtexEntry(citedKey); + entries.put(x, null); + citeKeyToBibEntry.put( citedKey, x ); } } return entries; @@ -1234,8 +1240,8 @@ private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection doc List cited = findCitedKeys( documentConnection ); Map linkSourceBase = new HashMap<>(); - - Map entries = findCitedEntries(databases, cited, linkSourceBase); + Map citeKeyToBibEntry = new HashMap<>(); + Map entries = findCitedEntries(databases, cited, linkSourceBase, citeKeyToBibEntry); List names; @@ -1879,10 +1885,11 @@ public void rebuildBibTextSection(List databases, List cited = findCitedKeys(documentConnection); Map linkSourceBase = new HashMap<>(); + Map citeKeyToBibEntry = new HashMap<>(); Map entries = // Although entries are redefined without use, this also // updates linkSourceBase - findCitedEntries(databases, cited, linkSourceBase); + findCitedEntries(databases, cited, linkSourceBase, citeKeyToBibEntry); if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: @@ -1893,7 +1900,7 @@ public void rebuildBibTextSection(List databases, } else { // Find them again? Why? Map entries2 = - findCitedEntries(databases, cited, linkSourceBase); + findCitedEntries(databases, cited, linkSourceBase, citeKeyToBibEntry); SortedMap newMap = new TreeMap<>(entryComparator); for (Map.Entry kv : entries2.entrySet()) { From 2104c7873467047d810b4612e8247650b7d53626 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 18:38:31 +0100 Subject: [PATCH 0202/1068] comment --- .../org/jabref/gui/openoffice/OOBibBase.java | 57 ++++++++++++++----- 1 file changed, 42 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ba04bd75649..ade95e59e66 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1040,9 +1040,9 @@ private List findCitedKeys( DocumentConnection documentConnection ) List names = getJabRefReferenceMarkNames( documentConnection ); { + // assert each name provides an XTextContent XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); for (String name1 : names) { - // assert it supports XTextContent Object bookmark = xNamedMarks.getByName(name1); assert (null != unoQI(XTextContent.class, bookmark)); } @@ -1102,6 +1102,8 @@ private Map findCitedEntries(List databases, BibEntry x = new UndefinedBibtexEntry(citedKey); entries.put(x, null); citeKeyToBibEntry.put( citedKey, x ); + LOGGER.info("Citation key not found: '" + citedKey + "'"); + // LOGGER.info("Problem with reference mark: '" + name + "'"); } } return entries; @@ -1895,7 +1897,8 @@ public void rebuildBibTextSection(List databases, // We need to sort the entries according to their order of appearance: entries = getSortedEntriesFromSortedRefMarks( jabRefReferenceMarkNamesSortedByPosition, - linkSourceBase + linkSourceBase, + citeKeyToBibEntry ); } else { // Find them again? Why? @@ -1923,7 +1926,10 @@ public void rebuildBibTextSection(List databases, * iteration order as first appearance in referenceMarkNames. */ private Map getSortedEntriesFromSortedRefMarks(List referenceMarkNames, - Map linkSourceBase) { + Map linkSourceBase, + Map citeKeyToBibEntry + ) + { // LinkedHashMap: iteration order is insertion-order, not // affected if a key is re-inserted. @@ -1934,20 +1940,40 @@ private Map getSortedEntriesFromSortedRefMarks(List keys = op.get().citedKeys; - for (String key : keys) { + /* + if ( false ){ + for (String key : keys) { BibDatabase database = linkSourceBase.get(key); - if (database != null) { - Optional origEntry = database.getEntryByCitationKey(key); - if (origEntry.isPresent()) { - BibEntry oe = origEntry.get(); - if (!newList.containsKey(oe)) { - newList.put(oe, database); + if (database != null) { + Optional origEntry = database.getEntryByCitationKey(key); + if (origEntry.isPresent()) { + BibEntry oe = origEntry.get(); + if (!newList.containsKey(oe)) { + newList.put(oe, database); + } } + } else { + LOGGER.info("Citation key not found: '" + key + "'"); + LOGGER.info("Problem with reference mark: '" + name + "'"); + newList.put(new UndefinedBibtexEntry(key), null); + } + } + } else + */ + { + // no need to look in the database again + for (String key : keys) { + BibDatabase database = linkSourceBase.get(key); + BibEntry origEntry = citeKeyToBibEntry.get(key); + if (origEntry != null) { + if (!newList.containsKey(origEntry)) { + newList.put(origEntry, database); + } + } else { + LOGGER.info("Citation key not found: '" + key + "'"); + LOGGER.info("Problem with reference mark: '" + name + "'"); + newList.put(new UndefinedBibtexEntry(key), null); } - } else { - LOGGER.info("Citation key not found: '" + key + "'"); - LOGGER.info("Problem with reference mark: '" + name + "'"); - newList.put(new UndefinedBibtexEntry(key), null); } } /* } */ @@ -2480,12 +2506,13 @@ public BibDatabase generateDatabase(List databases) break; } } + // key not found. } resultDatabase.insertEntries(entriesToInsert); return resultDatabase; } - + private static class ComparableMark implements Comparable { private final String name; From 3f9045713e3fe4c4ab5353aeaf8f621e6a1b9615 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 18:40:12 +0100 Subject: [PATCH 0203/1068] Revert "comment" This reverts commit 0cf0a9f85f98572902fb1a9fac62c4c03e27c9b0. --- .../org/jabref/gui/openoffice/OOBibBase.java | 57 +++++-------------- 1 file changed, 15 insertions(+), 42 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ade95e59e66..ba04bd75649 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1040,9 +1040,9 @@ private List findCitedKeys( DocumentConnection documentConnection ) List names = getJabRefReferenceMarkNames( documentConnection ); { - // assert each name provides an XTextContent XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); for (String name1 : names) { + // assert it supports XTextContent Object bookmark = xNamedMarks.getByName(name1); assert (null != unoQI(XTextContent.class, bookmark)); } @@ -1102,8 +1102,6 @@ private Map findCitedEntries(List databases, BibEntry x = new UndefinedBibtexEntry(citedKey); entries.put(x, null); citeKeyToBibEntry.put( citedKey, x ); - LOGGER.info("Citation key not found: '" + citedKey + "'"); - // LOGGER.info("Problem with reference mark: '" + name + "'"); } } return entries; @@ -1897,8 +1895,7 @@ public void rebuildBibTextSection(List databases, // We need to sort the entries according to their order of appearance: entries = getSortedEntriesFromSortedRefMarks( jabRefReferenceMarkNamesSortedByPosition, - linkSourceBase, - citeKeyToBibEntry + linkSourceBase ); } else { // Find them again? Why? @@ -1926,10 +1923,7 @@ public void rebuildBibTextSection(List databases, * iteration order as first appearance in referenceMarkNames. */ private Map getSortedEntriesFromSortedRefMarks(List referenceMarkNames, - Map linkSourceBase, - Map citeKeyToBibEntry - ) - { + Map linkSourceBase) { // LinkedHashMap: iteration order is insertion-order, not // affected if a key is re-inserted. @@ -1940,40 +1934,20 @@ private Map getSortedEntriesFromSortedRefMarks(List keys = op.get().citedKeys; - /* - if ( false ){ - for (String key : keys) { + for (String key : keys) { BibDatabase database = linkSourceBase.get(key); - if (database != null) { - Optional origEntry = database.getEntryByCitationKey(key); - if (origEntry.isPresent()) { - BibEntry oe = origEntry.get(); - if (!newList.containsKey(oe)) { - newList.put(oe, database); - } - } - } else { - LOGGER.info("Citation key not found: '" + key + "'"); - LOGGER.info("Problem with reference mark: '" + name + "'"); - newList.put(new UndefinedBibtexEntry(key), null); - } - } - } else - */ - { - // no need to look in the database again - for (String key : keys) { - BibDatabase database = linkSourceBase.get(key); - BibEntry origEntry = citeKeyToBibEntry.get(key); - if (origEntry != null) { - if (!newList.containsKey(origEntry)) { - newList.put(origEntry, database); + if (database != null) { + Optional origEntry = database.getEntryByCitationKey(key); + if (origEntry.isPresent()) { + BibEntry oe = origEntry.get(); + if (!newList.containsKey(oe)) { + newList.put(oe, database); } - } else { - LOGGER.info("Citation key not found: '" + key + "'"); - LOGGER.info("Problem with reference mark: '" + name + "'"); - newList.put(new UndefinedBibtexEntry(key), null); } + } else { + LOGGER.info("Citation key not found: '" + key + "'"); + LOGGER.info("Problem with reference mark: '" + name + "'"); + newList.put(new UndefinedBibtexEntry(key), null); } } /* } */ @@ -2506,13 +2480,12 @@ public BibDatabase generateDatabase(List databases) break; } } - // key not found. } resultDatabase.insertEntries(entriesToInsert); return resultDatabase; } - + private static class ComparableMark implements Comparable { private final String name; From 2a7b231686e924bec4ffe98bff72a414f6cc15fc Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 18:43:24 +0100 Subject: [PATCH 0204/1068] comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ba04bd75649..ef0d17acf88 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1040,9 +1040,9 @@ private List findCitedKeys( DocumentConnection documentConnection ) List names = getJabRefReferenceMarkNames( documentConnection ); { + // assert it supports XTextContent XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); for (String name1 : names) { - // assert it supports XTextContent Object bookmark = xNamedMarks.getByName(name1); assert (null != unoQI(XTextContent.class, bookmark)); } From 5401f3ea5039212eb6c17b2b1df8a7a1a6dd4880 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 18:48:41 +0100 Subject: [PATCH 0205/1068] citeKeyToBibEntry --- .../org/jabref/gui/openoffice/OOBibBase.java | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ef0d17acf88..c515b291f26 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1895,7 +1895,8 @@ public void rebuildBibTextSection(List databases, // We need to sort the entries according to their order of appearance: entries = getSortedEntriesFromSortedRefMarks( jabRefReferenceMarkNamesSortedByPosition, - linkSourceBase + linkSourceBase, + citeKeyToBibEntry ); } else { // Find them again? Why? @@ -1923,7 +1924,8 @@ public void rebuildBibTextSection(List databases, * iteration order as first appearance in referenceMarkNames. */ private Map getSortedEntriesFromSortedRefMarks(List referenceMarkNames, - Map linkSourceBase) { + Map linkSourceBase, + Map citeKeyToBibEntry) { // LinkedHashMap: iteration order is insertion-order, not // affected if a key is re-inserted. @@ -1934,6 +1936,7 @@ private Map getSortedEntriesFromSortedRefMarks(List keys = op.get().citedKeys; + /* for (String key : keys) { BibDatabase database = linkSourceBase.get(key); if (database != null) { @@ -1950,7 +1953,21 @@ private Map getSortedEntriesFromSortedRefMarks(List Date: Tue, 23 Feb 2021 18:50:08 +0100 Subject: [PATCH 0206/1068] drop old impl --- .../org/jabref/gui/openoffice/OOBibBase.java | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c515b291f26..cbeb86a09c8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1936,24 +1936,6 @@ private Map getSortedEntriesFromSortedRefMarks(List keys = op.get().citedKeys; - /* - for (String key : keys) { - BibDatabase database = linkSourceBase.get(key); - if (database != null) { - Optional origEntry = database.getEntryByCitationKey(key); - if (origEntry.isPresent()) { - BibEntry oe = origEntry.get(); - if (!newList.containsKey(oe)) { - newList.put(oe, database); - } - } - } else { - LOGGER.info("Citation key not found: '" + key + "'"); - LOGGER.info("Problem with reference mark: '" + name + "'"); - newList.put(new UndefinedBibtexEntry(key), null); - } - } - */ // no need to look in the database again for (String key : keys) { BibDatabase database = linkSourceBase.get(key); From cd271cae8de4f898378907e21c0cf2853624bbcb Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 18:54:12 +0100 Subject: [PATCH 0207/1068] drop duplicate findCitedEntries --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index cbeb86a09c8..2ab341b8af9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1899,12 +1899,12 @@ public void rebuildBibTextSection(List databases, citeKeyToBibEntry ); } else { - // Find them again? Why? - Map entries2 = - findCitedEntries(databases, cited, linkSourceBase, citeKeyToBibEntry); + // // Find them again? Why? + // Map entries2 = + // findCitedEntries(databases, cited, linkSourceBase, citeKeyToBibEntry); SortedMap newMap = new TreeMap<>(entryComparator); - for (Map.Entry kv : entries2.entrySet()) { + for (Map.Entry kv : entries.entrySet()) { newMap.put(kv.getKey(), kv.getValue()); } From 792a5bcefbf6663c81b159598f4e0de1efe1a4ad Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 18:59:27 +0100 Subject: [PATCH 0208/1068] use entries to get database --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2ab341b8af9..8a1c0aa14f1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1895,8 +1895,9 @@ public void rebuildBibTextSection(List databases, // We need to sort the entries according to their order of appearance: entries = getSortedEntriesFromSortedRefMarks( jabRefReferenceMarkNamesSortedByPosition, - linkSourceBase, - citeKeyToBibEntry + //linkSourceBase, + citeKeyToBibEntry, + entries ); } else { // // Find them again? Why? @@ -1924,8 +1925,11 @@ public void rebuildBibTextSection(List databases, * iteration order as first appearance in referenceMarkNames. */ private Map getSortedEntriesFromSortedRefMarks(List referenceMarkNames, - Map linkSourceBase, - Map citeKeyToBibEntry) { + // Map linkSourceBase, + Map citeKeyToBibEntry, + Map entries + ) + { // LinkedHashMap: iteration order is insertion-order, not // affected if a key is re-inserted. @@ -1938,10 +1942,11 @@ private Map getSortedEntriesFromSortedRefMarks(List keys = op.get().citedKeys; // no need to look in the database again for (String key : keys) { - BibDatabase database = linkSourceBase.get(key); + // BibDatabase database = linkSourceBase.get(key); BibEntry origEntry = citeKeyToBibEntry.get(key); if (origEntry != null) { if (!newList.containsKey(origEntry)) { + BibDatabase database = entries.get( origEntry ); newList.put(origEntry, database); } } else { From ad4a2684e7ceb3edbb2792812741c58d5989510a Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 19:01:18 +0100 Subject: [PATCH 0209/1068] drop comments --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8a1c0aa14f1..64ad9094335 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1895,15 +1895,10 @@ public void rebuildBibTextSection(List databases, // We need to sort the entries according to their order of appearance: entries = getSortedEntriesFromSortedRefMarks( jabRefReferenceMarkNamesSortedByPosition, - //linkSourceBase, citeKeyToBibEntry, entries ); } else { - // // Find them again? Why? - // Map entries2 = - // findCitedEntries(databases, cited, linkSourceBase, citeKeyToBibEntry); - SortedMap newMap = new TreeMap<>(entryComparator); for (Map.Entry kv : entries.entrySet()) { newMap.put(kv.getKey(), @@ -1925,7 +1920,6 @@ public void rebuildBibTextSection(List databases, * iteration order as first appearance in referenceMarkNames. */ private Map getSortedEntriesFromSortedRefMarks(List referenceMarkNames, - // Map linkSourceBase, Map citeKeyToBibEntry, Map entries ) From 3456732013c3613f1733dbb5b25a9fbaddb5ca9b Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 19:03:34 +0100 Subject: [PATCH 0210/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 64ad9094335..43e573cbbeb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1919,10 +1919,11 @@ public void rebuildBibTextSection(List databases, * @return LinkedHashMap from BibEntry to BibDatabase with * iteration order as first appearance in referenceMarkNames. */ - private Map getSortedEntriesFromSortedRefMarks(List referenceMarkNames, - Map citeKeyToBibEntry, - Map entries - ) + private Map + getSortedEntriesFromSortedRefMarks(List referenceMarkNames, + Map citeKeyToBibEntry, + Map entries + ) { // LinkedHashMap: iteration order is insertion-order, not From 4e1037aa1fa7a77ce88bb16f80ed49e075409885 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 19:18:52 +0100 Subject: [PATCH 0211/1068] rename to sortEntriesByRefMarkNames --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 43e573cbbeb..aabc476c54e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1893,7 +1893,7 @@ public void rebuildBibTextSection(List databases, if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: - entries = getSortedEntriesFromSortedRefMarks( + entries = sortEntriesByRefMarkNames( jabRefReferenceMarkNamesSortedByPosition, citeKeyToBibEntry, entries @@ -1920,10 +1920,10 @@ public void rebuildBibTextSection(List databases, * iteration order as first appearance in referenceMarkNames. */ private Map - getSortedEntriesFromSortedRefMarks(List referenceMarkNames, - Map citeKeyToBibEntry, - Map entries - ) + sortEntriesByRefMarkNames(List referenceMarkNames, + Map citeKeyToBibEntry, + Map entries + ) { // LinkedHashMap: iteration order is insertion-order, not From 3054b115ca83074ecea2c08eb3fb46620b0fe19e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 19:25:55 +0100 Subject: [PATCH 0212/1068] sortEntriesByComparator --- .../org/jabref/gui/openoffice/OOBibBase.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index aabc476c54e..15d30d22d60 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1250,11 +1250,7 @@ private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection doc // We need to sort the reference marks according to the // sorting of the bibliographic entries: // - SortedMap newMap = new TreeMap<>(entryComparator); - for (Map.Entry ee : entries.entrySet()) { - newMap.put(ee.getKey(), ee.getValue()); - } - entries = newMap; + entries = sortEntriesByComparator( entries, entryComparator ); // Rebuild the list of cited keys according to the sort order: cited.clear(); @@ -1899,18 +1895,22 @@ public void rebuildBibTextSection(List databases, entries ); } else { - SortedMap newMap = new TreeMap<>(entryComparator); - for (Map.Entry kv : entries.entrySet()) { - newMap.put(kv.getKey(), - kv.getValue()); - } - entries = newMap; + entries = sortEntriesByComparator( entries, entryComparator ); } clearBibTextSectionContent2(documentConnection); populateBibTextSection(documentConnection, entries, style, this.xUniquefiers); } - + SortedMap sortEntriesByComparator( Map entries, + Comparator entryComparator ) + { + SortedMap newMap = new TreeMap<>(entryComparator); + for (Map.Entry kv : entries.entrySet()) { + newMap.put(kv.getKey(), + kv.getValue()); + } + return newMap; + } /** * @param referenceMarkNames From 384964f7c6999b8ce9c8aa2dea477d3ec7fa5f60 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 19:56:18 +0100 Subject: [PATCH 0213/1068] GetSortedCitedEntriesResult includes citeKeyToBibEntry --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 15d30d22d60..8c7bd08c9ca 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1195,17 +1195,20 @@ private class GetSortedCitedEntriesResult { List citedKeys; Map entries; List refMarkNames; + Map citeKeyToBibEntry; public GetSortedCitedEntriesResult ( Map linkSourceBase, List citedKeys, Map entries, - List refMarkNames ) + List refMarkNames, + Map citeKeyToBibEntry) { this.linkSourceBase = linkSourceBase; this.citedKeys = citedKeys; this.entries = entries; this.refMarkNames = refMarkNames; + this.citeKeyToBibEntry = citeKeyToBibEntry; } } @@ -1238,18 +1241,14 @@ private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection doc // keys cited in the text List cited = findCitedKeys( documentConnection ); - Map linkSourceBase = new HashMap<>(); - Map citeKeyToBibEntry = new HashMap<>(); - Map entries = findCitedEntries(databases, cited, linkSourceBase, citeKeyToBibEntry); + Map citeKeyToBibEntry = new HashMap<>(); + Map entries = + findCitedEntries(databases, cited, linkSourceBase, citeKeyToBibEntry); List names; if (style.isNumberEntries() && ! style.isSortByPosition()) { - // - // We need to sort the reference marks according to the - // sorting of the bibliographic entries: - // entries = sortEntriesByComparator( entries, entryComparator ); // Rebuild the list of cited keys according to the sort order: From 5a5f6455b45196d17d3c51f32a7a57c640f6e17f Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 19:57:16 +0100 Subject: [PATCH 0214/1068] GetSortedCitedEntriesResult includes citeKeyToBibEntry --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8c7bd08c9ca..bb444faa180 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1270,7 +1270,8 @@ private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection doc return new GetSortedCitedEntriesResult( linkSourceBase, cited, entries, - names + names, + citeKeyToBibEntry ); } From 13688294ad3364db3f2994edbb6fbfbc90f3d13e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 19:57:40 +0100 Subject: [PATCH 0215/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index bb444faa180..13b33c5dd88 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1879,9 +1879,9 @@ public void rebuildBibTextSection(List databases, { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - List cited = findCitedKeys(documentConnection); - Map linkSourceBase = new HashMap<>(); - Map citeKeyToBibEntry = new HashMap<>(); + List cited = findCitedKeys(documentConnection); + Map linkSourceBase = new HashMap<>(); + Map citeKeyToBibEntry = new HashMap<>(); Map entries = // Although entries are redefined without use, this also // updates linkSourceBase From 5949abc0a5766780dbbca763a2dcc9fc357c3b98 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 19:58:01 +0100 Subject: [PATCH 0216/1068] fromat --- .../org/jabref/gui/openoffice/OOBibBase.java | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 13b33c5dd88..8303e270f1e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2111,14 +2111,17 @@ private void populateBibTextSection(DocumentConnection documentConnection, (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT) ); - insertFullReferenceAtCursor - (documentConnection, - cursor, - entries, - style, - (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT), - uniquefiers - ); + { + String refParaFormat = + (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); + insertFullReferenceAtCursor(documentConnection, + cursor, + entries, + style, + refParaFormat, + uniquefiers + ); + } insertBookMark(documentConnection, OOBibBase.BIB_SECTION_END_NAME, cursor); } From 83cc80d585e061f1300f532a5e9f1537b1e199ff Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 19:58:11 +0100 Subject: [PATCH 0217/1068] user sortEntriesByComparator --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8303e270f1e..33dd11ceb99 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1974,9 +1974,10 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, correctEntries = entries; } else { // Sort map - Map newMap = new TreeMap<>(entryComparator); - newMap.putAll(entries); - correctEntries = newMap; + //Map newMap = new TreeMap<>(entryComparator); + //newMap.putAll(entries); + //correctEntries = newMap; + correctEntries = sortEntriesByComparator( entries, entryComparator ); } int number = 1; for (Map.Entry entry : correctEntries.entrySet()) { From 90531ea1161c37fdd11e143ef96a9edc2fb9182a Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:00:24 +0100 Subject: [PATCH 0218/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 33dd11ceb99..2ac08fe9f3b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2273,7 +2273,11 @@ private XNameAccess getBookmarks(DocumentConnection documentConnection) { } private void italicizeOrBold(XTextCursor position, boolean italicize, int start, int end) - throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException { + throws UnknownPropertyException, + PropertyVetoException, + IllegalArgumentException, + WrappedTargetException + { XTextRange range = position.getStart(); XTextCursor cursor = position.getText().createTextCursorByRange(range); cursor.goRight((short) start, false); @@ -2488,7 +2492,7 @@ public BibDatabase generateDatabase(List databases) return resultDatabase; } - + private static class ComparableMark implements Comparable { private final String name; From f83addadf461efa65e5d8e5a497506715c05409e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:10:49 +0100 Subject: [PATCH 0219/1068] insertFullReferenceAtCursor does not sort entries --- .../org/jabref/gui/openoffice/OOBibBase.java | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2ac08fe9f3b..2aef41334f3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1955,6 +1955,9 @@ SortedMap sortEntriesByComparator( Map entries, @@ -1967,20 +1970,9 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, PropertyVetoException, WrappedTargetException { - Map correctEntries; - // If we don't have numbered entries, we need to sort the entries before adding them: - if (style.isSortByPosition()) { - // Use the received map directly - correctEntries = entries; - } else { - // Sort map - //Map newMap = new TreeMap<>(entryComparator); - //newMap.putAll(entries); - //correctEntries = newMap; - correctEntries = sortEntriesByComparator( entries, entryComparator ); - } + int number = 1; - for (Map.Entry entry : correctEntries.entrySet()) { + for (Map.Entry entry : entries.entrySet()) { if (entry.getKey() instanceof UndefinedBibtexEntry) { continue; } @@ -2076,6 +2068,9 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) } } + /** + * Only called from: rebuildBibTextSection + */ private void populateBibTextSection(DocumentConnection documentConnection, Map entries, OOBibStyle style, From 427cc85ca7b3d33066932223160f3bc66a7723bd Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:16:18 +0100 Subject: [PATCH 0220/1068] minGroupingCount does not need style here --- .../org/jabref/gui/openoffice/OOBibBase.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2aef41334f3..b235ff6209a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1973,17 +1973,27 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, int number = 1; for (Map.Entry entry : entries.entrySet()) { + + // skip unresolved entries if (entry.getKey() instanceof UndefinedBibtexEntry) { continue; } + OOUtil.insertParagraphBreak(documentConnection.xText, cursor); + if (style.isNumberEntries()) { - int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + // NOte: minGroupingCount is pointless here, we are + // formatting a single entry. + // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + int minGroupingCount = 2; + String marker = style.getNumCitationMarker(Collections.singletonList(number++), + minGroupingCount, + true); + OOUtil.insertTextAtCurrentLocation (documentConnection.xText, cursor, - style.getNumCitationMarker(Collections.singletonList(number++), - minGroupingCount, true), + marker, Collections.emptyList() ); } From 9937ea7e78c9c9d10b1de1198435b8f398524475 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:19:18 +0100 Subject: [PATCH 0221/1068] formatting --- .../org/jabref/gui/openoffice/OOBibBase.java | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b235ff6209a..f5a608a9cf3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1780,10 +1780,11 @@ private static Point findPositionOfTextRange(XTextViewCursor cursor, XTextRange /** * */ - private List getJabRefReferenceMarkNamesSortedByPosition(DocumentConnection documentConnection) - throws WrappedTargetException, - NoSuchElementException, - NoDocumentException + private List + getJabRefReferenceMarkNamesSortedByPosition(DocumentConnection documentConnection) + throws WrappedTargetException, + NoSuchElementException, + NoDocumentException { List names = getJabRefReferenceMarkNames(documentConnection); @@ -1981,6 +1982,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, OOUtil.insertParagraphBreak(documentConnection.xText, cursor); + // insert marker if (style.isNumberEntries()) { // NOte: minGroupingCount is pointless here, we are // formatting a single entry. @@ -1990,13 +1992,14 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, minGroupingCount, true); - OOUtil.insertTextAtCurrentLocation - (documentConnection.xText, - cursor, - marker, - Collections.emptyList() - ); + OOUtil.insertTextAtCurrentLocation(documentConnection.xText, + cursor, + marker, + Collections.emptyList() + ); } + + // insert the actual details. Layout layout = style.getReferenceFormat(entry.getKey().getType()); layout.setPostFormatter(POSTFORMATTER); OOUtil.insertFullReferenceAtCurrentLocation From 238789c5639487b4049d51f40f00fb6d729c0e40 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:28:10 +0100 Subject: [PATCH 0222/1068] format, drop comment --- .../org/jabref/gui/openoffice/OOBibBase.java | 67 ++++++++++++------- 1 file changed, 42 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f5a608a9cf3..4319474b75f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -427,8 +427,6 @@ private static List getTextDocuments( XDesktop desktop ) XEnumerationAccess enumAccess = desktop.getComponents(); XEnumeration compEnum = enumAccess.createEnumeration(); - // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies - while (compEnum.hasMoreElements()) { Object next = compEnum.nextElement(); XComponent comp = unoQI(XComponent.class , next); @@ -581,7 +579,8 @@ public void selectDocument() // TODO: maybe we should install an event handler for document // close: addCloseListener // - // https://www.openoffice.org/api/docs/common/ref/com/sun/star/util/XCloseBroadcaster.html#addCloseListener + // https://www.openoffice.org/api/docs/common/ref/com/sun/star/ + // util/XCloseBroadcaster.html#addCloseListener } /* @@ -1695,7 +1694,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // firstLimAuthors will be (-1) except at the first // refMark it appears at, where a positive maxAuthorsFirst // may override. This is why: - // https://discourse.jabref.org/t/number-of-authors-in-citations-style-libreoffice/747/3 + // https://discourse.jabref.org/t/ + // number-of-authors-in-citations-style-libreoffice/747/3 // "Some citation styles require to list the full // names of the first 4 authors for the first // time. Later it is sufficient to have only maybe @@ -2395,31 +2395,45 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } /** + * GUI action. * Do the opposite of combineCiteMarkers. * Combined markers are split, with a space inserted between. */ public void unCombineCiteMarkers(List databases, OOBibStyle style) - throws IOException, WrappedTargetException, NoSuchElementException, IllegalArgumentException, - UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException, - BibEntryNotFoundException { - XNameAccess nameAccess = getReferenceMarks(); - List names = getSortedReferenceMarks(nameAccess); + throws IOException, + WrappedTargetException, + NoSuchElementException, + IllegalArgumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException + { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + + // TODO: doesn't work for citations in footnotes/tables + List names = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - final XTextRangeCompare compare = UnoRuntime.queryInterface(XTextRangeCompare.class, text); + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + documentConnection.xText); - int pivot = 0; + int piv = 0; boolean madeModifications = false; - while (pivot < (names.size())) { - XTextRange range1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(pivot))) + XNameAccess nameAccess = documentConnection.getReferenceMarks(); + while (piv < (names.size())) { + XTextRange range1 = unoQI(XTextContent.class, nameAccess.getByName(names.get(piv))) .getAnchor(); - XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); - + XTextCursor mxDocCursor = range1.getText().createTextCursorByRange(range1); + // // If we are supposed to set character format for citations, test this before // making any changes. This way we can throw an exception before any reference // marks are removed, preventing damage to the user's document: if (style.isFormatCitations()) { - XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, textCursor); + XPropertySet xCursorProps = unoQI(XPropertySet.class, mxDocCursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); @@ -2431,26 +2445,29 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) } } - List keys = parseRefMarkName(names.get(pivot)); + List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); if (keys.size() > 1) { - removeReferenceMark(names.get(pivot)); - + removeReferenceMark(documentConnection, names.get(piv)); + // // Insert bookmark for each key int last = keys.size() - 1; int i = 0; for (String key : keys) { - String newName = getUniqueReferenceMarkName(key, OOBibBase.AUTHORYEAR_PAR); - insertReferenceMark(newName, "tmp", textCursor, true, style); - textCursor.collapseToEnd(); + String bName = getUniqueReferenceMarkName(documentConnection, + key, + OOBibBase.AUTHORYEAR_PAR + ); + insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); + mxDocCursor.collapseToEnd(); if (i != last) { - textCursor.setString(" "); - textCursor.collapseToEnd(); + mxDocCursor.setString(" "); + mxDocCursor.collapseToEnd(); } i++; } madeModifications = true; } - pivot++; + piv++; } if (madeModifications) { updateSortedReferenceMarks(); From b7b13ba3009b55a0b57f4b7da4f89e80c40dfc63 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:30:34 +0100 Subject: [PATCH 0223/1068] typo? wring directionof comparison --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4319474b75f..30ddd2cd936 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -647,7 +647,7 @@ private void sortBibEntryList( List entries, private void sortBibEntryArray( BibEntry[] entries, OOBibStyle style ) { - if (entries.length >= 1) { + if (entries.length <= 1) { return; } if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { From 3910ca914df2588e6c1439d439ba9968be3e2a21 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:34:45 +0100 Subject: [PATCH 0224/1068] rename --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 30ddd2cd936..ab6b367a3ea 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -632,8 +632,8 @@ public Optional getCurrentDocumentTitle() { * === insertEntry */ - private void sortBibEntryList( List entries, - OOBibStyle style ) + private void sortBibEntryListForMulticite( List entries, + OOBibStyle style ) { if (entries.size() <= 1){ return; @@ -644,8 +644,8 @@ private void sortBibEntryList( List entries, entries.sort(this.entryComparator); } } - private void sortBibEntryArray( BibEntry[] entries, - OOBibStyle style ) + private void sortBibEntryArrayForMulticite( BibEntry[] entries, + OOBibStyle style ) { if (entries.length <= 1) { return; @@ -888,7 +888,7 @@ public void insertEntry(List entries, // Get the cursor positioned by the user. XTextCursor cursor = documentConnection.getViewCursor(); - sortBibEntryList( entries, style ); + sortBibEntryListForMulticite( entries, style ); String keyString = String.join(",", @@ -1586,7 +1586,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne assert (cEntries.length == bibtexKeys[i].length) ; // sort itcBlock - sortBibEntryArray( cEntries, style ); + sortBibEntryArrayForMulticite( cEntries, style ); // Update key list to match the new sorting: for (int j = 0; j < cEntries.length; j++) { From fcb82362594cc1d5b1b1ecb173ddc131ff691651 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:41:11 +0100 Subject: [PATCH 0225/1068] format --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ab6b367a3ea..a264789abb4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1161,19 +1161,21 @@ public List refreshCiteMarkers(List databases, return res; } - private static BibEntry[] linkSourceBaseGetBibEntriesOfCiteKeys - ( Map linkSourceBase, - String[] keys, // citeKeys - String referenceMarkName // for reporting - ) + private static BibEntry[] + linkSourceBaseGetBibEntriesOfCiteKeys( Map linkSourceBase, + String[] keys, // citeKeys + String referenceMarkName // for reporting + ) throws BibEntryNotFoundException { BibEntry[] cEntries = new BibEntry[keys.length]; + // fill cEntries for (int j = 0; j < keys.length; j++) { String kj = keys[j]; Optional tmpEntry = linkSourceBaseCiteKeyToBibEntry( linkSourceBase, kj ); + if (tmpEntry.isPresent()) { cEntries[j] = tmpEntry.get(); } else { @@ -1185,6 +1187,7 @@ public List refreshCiteMarkers(List databases, ); throw new BibEntryNotFoundException(referenceMarkName, msg); } + } // for j return cEntries; } @@ -1525,6 +1528,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne Map entries = sce.entries; List cited = sce.citedKeys; Map linkSourceBase = sce.linkSourceBase; + Map citeKeyToBibEntry = sce.citeKeyToBibEntry; // // For numbered citation style. Map( citedKey, number ) CitationNumberingState cns = new CitationNumberingState(); From 976a0f0cd6ca4f5e81dabec754227089dca5a68b Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:46:43 +0100 Subject: [PATCH 0226/1068] linkSourceBaseGetBibEntriesOfCiteKeys now uses citeKeyToBibEntry --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a264789abb4..784d2c9c796 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1162,8 +1162,8 @@ public List refreshCiteMarkers(List databases, } private static BibEntry[] - linkSourceBaseGetBibEntriesOfCiteKeys( Map linkSourceBase, - String[] keys, // citeKeys + linkSourceBaseGetBibEntriesOfCiteKeys( String[] keys, // citeKeys + Map citeKeyToBibEntry, String referenceMarkName // for reporting ) throws BibEntryNotFoundException @@ -1173,12 +1173,8 @@ public List refreshCiteMarkers(List databases, // fill cEntries for (int j = 0; j < keys.length; j++) { String kj = keys[j]; - Optional tmpEntry = - linkSourceBaseCiteKeyToBibEntry( linkSourceBase, kj ); - - if (tmpEntry.isPresent()) { - cEntries[j] = tmpEntry.get(); - } else { + BibEntry tmpEntry = citeKeyToBibEntry.get( kj ); + if ( tmpEntry == null ){ LOGGER.info("Citation key not found: '" + kj + '\''); LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); String msg = Localization.lang("Could not resolve BibTeX entry" @@ -1186,6 +1182,8 @@ public List refreshCiteMarkers(List databases, referenceMarkName ); throw new BibEntryNotFoundException(referenceMarkName, msg); + } else { + cEntries[j] = tmpEntry; } } // for j @@ -1548,7 +1546,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); + linkSourceBaseGetBibEntriesOfCiteKeys( bibtexKeys[i], citeKeyToBibEntry, namei ); assert (cEntries.length == bibtexKeys[i].length) ; citMarkers[i] = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); } @@ -1560,7 +1558,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); + linkSourceBaseGetBibEntriesOfCiteKeys( bibtexKeys[i], citeKeyToBibEntry, namei ); assert (cEntries.length == bibtexKeys[i].length) ; List num ; @@ -1586,7 +1584,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - linkSourceBaseGetBibEntriesOfCiteKeys( linkSourceBase, bibtexKeys[i], namei ); + linkSourceBaseGetBibEntriesOfCiteKeys( bibtexKeys[i], citeKeyToBibEntry, namei ); assert (cEntries.length == bibtexKeys[i].length) ; // sort itcBlock From 3532221c6c02b3ce20942f94d97755776d36d690 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:48:04 +0100 Subject: [PATCH 0227/1068] linkSourceBaseCiteKeyToBibEntry is not used, drop --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 784d2c9c796..9d766247115 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1149,18 +1149,6 @@ public List refreshCiteMarkers(List databases, } } - private static Optional linkSourceBaseCiteKeyToBibEntry - ( Map linkSourceBase, - String citeKey ) - { - BibDatabase database = linkSourceBase.get(citeKey); - Optional res = ( (database == null) - ? Optional.empty() - : database.getEntryByCitationKey(citeKey) - ); - return res; - } - private static BibEntry[] linkSourceBaseGetBibEntriesOfCiteKeys( String[] keys, // citeKeys Map citeKeyToBibEntry, From 6cf8f183bc42d96d016a4c92605c6b027adb5f5a Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 20:49:34 +0100 Subject: [PATCH 0228/1068] rename linkSourceBaseGetBibEntriesOfCiteKeys to mapCiteKeysToBibEntryArray --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9d766247115..8fc6b4160fa 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1150,7 +1150,7 @@ public List refreshCiteMarkers(List databases, } private static BibEntry[] - linkSourceBaseGetBibEntriesOfCiteKeys( String[] keys, // citeKeys + mapCiteKeysToBibEntryArray( String[] keys, // citeKeys Map citeKeyToBibEntry, String referenceMarkName // for reporting ) @@ -1534,7 +1534,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - linkSourceBaseGetBibEntriesOfCiteKeys( bibtexKeys[i], citeKeyToBibEntry, namei ); + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); assert (cEntries.length == bibtexKeys[i].length) ; citMarkers[i] = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); } @@ -1546,7 +1546,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - linkSourceBaseGetBibEntriesOfCiteKeys( bibtexKeys[i], citeKeyToBibEntry, namei ); + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); assert (cEntries.length == bibtexKeys[i].length) ; List num ; @@ -1572,7 +1572,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - linkSourceBaseGetBibEntriesOfCiteKeys( bibtexKeys[i], citeKeyToBibEntry, namei ); + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); assert (cEntries.length == bibtexKeys[i].length) ; // sort itcBlock From 104ab4722649402939fefd3fd7761352adee1fa7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 21:04:16 +0100 Subject: [PATCH 0229/1068] mapCiteKeysToBibEntryArray has arg undefinedToNull --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8fc6b4160fa..1db57dbef4c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1151,9 +1151,10 @@ public List refreshCiteMarkers(List databases, private static BibEntry[] mapCiteKeysToBibEntryArray( String[] keys, // citeKeys - Map citeKeyToBibEntry, - String referenceMarkName // for reporting - ) + Map citeKeyToBibEntry, + String referenceMarkName, // for reporting + boolean undefinedToNull // for undefined entries insert NULL + ) throws BibEntryNotFoundException { BibEntry[] cEntries = new BibEntry[keys.length]; @@ -1171,6 +1172,9 @@ public List refreshCiteMarkers(List databases, ); throw new BibEntryNotFoundException(referenceMarkName, msg); } else { + if ( undefinedToNull && tmpEntry instanceof UndefinedBibtexEntry ){ + tmpEntry = null; + } cEntries[j] = tmpEntry; } From a18ef9be8d5b8d423bbaf8507fb70310ea819829 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 21:04:47 +0100 Subject: [PATCH 0230/1068] use mapCiteKeysToBibEntryArray instead of linkSourceBase --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1db57dbef4c..7310edd5fd8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1676,11 +1676,13 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); for (int i = 0; i < nRefMarks; i++) { + final String namei = referenceMarkNames.get(i); final int nCitedEntries = bibtexKeys[i].length; boolean needsChange = false; int[] firstLimAuthors = new int[nCitedEntries]; String[] uniquif = new String[nCitedEntries]; - BibEntry[] cEntries = new BibEntry[nCitedEntries]; + // BibEntry[] cEntries = new BibEntry[nCitedEntries]; + BibEntry[] cEntries = mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; @@ -1716,15 +1718,6 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne needsChange = true; } - { - BibDatabase database = linkSourceBase.get(currentKey); - if (database != null) { - Optional tmpEntry = database.getEntryByCitationKey(currentKey); - if (tmpEntry.isPresent()) { - cEntries[j] = tmpEntry.get(); - } - } - } } // for j From 236e60fbd44d16dda830a43290f8b00a10a6e61b Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 21:07:22 +0100 Subject: [PATCH 0231/1068] insert undefinedToNull arg --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7310edd5fd8..e1edb854a48 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1538,7 +1538,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); assert (cEntries.length == bibtexKeys[i].length) ; citMarkers[i] = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); } @@ -1550,7 +1550,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); assert (cEntries.length == bibtexKeys[i].length) ; List num ; @@ -1576,7 +1576,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); assert (cEntries.length == bibtexKeys[i].length) ; // sort itcBlock @@ -1681,8 +1681,10 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne boolean needsChange = false; int[] firstLimAuthors = new int[nCitedEntries]; String[] uniquif = new String[nCitedEntries]; - // BibEntry[] cEntries = new BibEntry[nCitedEntries]; - BibEntry[] cEntries = mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); + BibEntry[] cEntries = mapCiteKeysToBibEntryArray( bibtexKeys[i], + citeKeyToBibEntry, + namei, + true); for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; From 27a2ea2f70a5368f12a2622622d7e410cb228980 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 21:11:38 +0100 Subject: [PATCH 0232/1068] comment update --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e1edb854a48..1f69630f740 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1063,19 +1063,16 @@ private List findCitedKeys( DocumentConnection documentConnection ) /** * @return LinkedHashMap, from BibEntry to BibDatabase - * Side effect: add found citedKeys to linkSourceBase + * Side effect: add citedKeys to citeKeyToBibEntry, using UndefinedBibtexEntry if not found. * * If a citedKey is not found, BibEntry is new UndefinedBibtexEntry(citedKey), BibDatabase is null. * If citedKey is found, then * BibEntry is what we found, BibDatabase is the database we found it in. - * linkSourceBase.put(citedKey, database); is called. * * So: - * - result has an entry for each citedKey, in the same order + * - result has an entry for each citedKey, in the same order as in citedKeys * - citedKey in the entry is the same as the original citedKey - * - on return linkSourceBase has an entry for the citedKey we did find * - * - Also fill citeKeyToBibEntry */ private Map findCitedEntries(List databases, List citedKeys, From 4cb40370fc0eabbf9655615f2919e1e1bcb9a22d Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 21:14:36 +0100 Subject: [PATCH 0233/1068] linkSourceBase removed --- .../org/jabref/gui/openoffice/OOBibBase.java | 23 +++++-------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1f69630f740..f236deb44c6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1076,7 +1076,6 @@ private List findCitedKeys( DocumentConnection documentConnection ) */ private Map findCitedEntries(List databases, List citedKeys, - Map linkSourceBase, Map citeKeyToBibEntry ) { @@ -1087,7 +1086,6 @@ private Map findCitedEntries(List databases, Optional entry = database.getEntryByCitationKey(citedKey); if (entry.isPresent()) { entries.put(entry.get(), database); - linkSourceBase.put(citedKey, database); citeKeyToBibEntry.put( citedKey, entry.get() ); found = true; break; @@ -1180,20 +1178,17 @@ public List refreshCiteMarkers(List databases, } private class GetSortedCitedEntriesResult { - Map linkSourceBase; List citedKeys; Map entries; List refMarkNames; Map citeKeyToBibEntry; public GetSortedCitedEntriesResult ( - Map linkSourceBase, List citedKeys, Map entries, List refMarkNames, Map citeKeyToBibEntry) { - this.linkSourceBase = linkSourceBase; this.citedKeys = citedKeys; this.entries = entries; this.refMarkNames = refMarkNames; @@ -1205,7 +1200,6 @@ private class GetSortedCitedEntriesResult { * * @return GetSortedCitedEntriesResult where * - * linkSourceBase maps the citedKeys to the database we found it in * * refMarkNames : jabRefReferenceMarkNamesSortedByPosition, * except for style.isNumberEntries(), @@ -1230,10 +1224,9 @@ private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection doc // keys cited in the text List cited = findCitedKeys( documentConnection ); - Map linkSourceBase = new HashMap<>(); Map citeKeyToBibEntry = new HashMap<>(); Map entries = - findCitedEntries(databases, cited, linkSourceBase, citeKeyToBibEntry); + findCitedEntries(databases, cited, citeKeyToBibEntry); List names; @@ -1256,8 +1249,7 @@ private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection doc // Remove all reference marks that don't look like JabRef citations: names = filterIsJabRefReferenceMarkName( names ); - return new GetSortedCitedEntriesResult( linkSourceBase, - cited, + return new GetSortedCitedEntriesResult( cited, entries, names, citeKeyToBibEntry @@ -1514,7 +1506,6 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne Map entries = sce.entries; List cited = sce.citedKeys; - Map linkSourceBase = sce.linkSourceBase; Map citeKeyToBibEntry = sce.citeKeyToBibEntry; // // For numbered citation style. Map( citedKey, number ) @@ -1614,7 +1605,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // changes: citMarkers[i], uniquefiers // uses: nRefMarks, normCitMarkers, bibtexKeys, // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) - // linkSourceBase, entries, types + // citeKeyToBibEntry, entries, types // if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { // Only for normal citations. Numbered citations and @@ -1867,12 +1858,11 @@ public void rebuildBibTextSection(List databases, DocumentConnection documentConnection = getDocumentConnectionOrThrow(); List cited = findCitedKeys(documentConnection); - Map linkSourceBase = new HashMap<>(); Map citeKeyToBibEntry = new HashMap<>(); Map entries = // Although entries are redefined without use, this also - // updates linkSourceBase - findCitedEntries(databases, cited, linkSourceBase, citeKeyToBibEntry); + // updates citeKeyToBibEntry + findCitedEntries(databases, cited, citeKeyToBibEntry); if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: @@ -1901,7 +1891,7 @@ SortedMap sortEntriesByComparator( Map sortEntriesByComparator( Map keys = op.get().citedKeys; // no need to look in the database again for (String key : keys) { - // BibDatabase database = linkSourceBase.get(key); BibEntry origEntry = citeKeyToBibEntry.get(key); if (origEntry != null) { if (!newList.containsKey(origEntry)) { From 35d71428a39a4d4dfd7053305c3997d387f1f895 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 22:05:56 +0100 Subject: [PATCH 0234/1068] getSortedCitedEntries body moved back --- .../org/jabref/gui/openoffice/OOBibBase.java | 136 +++++++++++------- 1 file changed, 87 insertions(+), 49 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f236deb44c6..c893a506b14 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1213,49 +1213,51 @@ private class GetSortedCitedEntriesResult { * order: from findCitedKeys(), * except for style.isNumberEntries() where reordered as entries */ - private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection documentConnection, - List databases, - OOBibStyle style, - XNameAccess xReferenceMarks ) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException - { - - // keys cited in the text - List cited = findCitedKeys( documentConnection ); - Map citeKeyToBibEntry = new HashMap<>(); - Map entries = - findCitedEntries(databases, cited, citeKeyToBibEntry); - - - List names; - if (style.isNumberEntries() && ! style.isSortByPosition()) { - entries = sortEntriesByComparator( entries, entryComparator ); - - // Rebuild the list of cited keys according to the sort order: - cited.clear(); - for (BibEntry entry : entries.keySet()) { - cited.add(entry.getCitationKey().orElse(null)); - } - // - names = Arrays.asList(xReferenceMarks.getElementNames()); - } else { - // We need to sort the reference marks according to their - // order of appearance: - names = jabRefReferenceMarkNamesSortedByPosition; - } - - // Remove all reference marks that don't look like JabRef citations: - names = filterIsJabRefReferenceMarkName( names ); - - return new GetSortedCitedEntriesResult( cited, - entries, - names, - citeKeyToBibEntry - ); - } - + /* +* private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection documentConnection, +* List databases, +* OOBibStyle style, +* XNameAccess xReferenceMarks ) +* throws NoSuchElementException, +* WrappedTargetException, +* NoDocumentException +* { +* +* // keys cited in the text +* List cited = findCitedKeys( documentConnection ); +* Map citeKeyToBibEntry = new HashMap<>(); +* Map entries = +* findCitedEntries(databases, cited, citeKeyToBibEntry); +* +* +* List names; +* if (style.isNumberEntries() && ! style.isSortByPosition()) { +* entries = sortEntriesByComparator( entries, entryComparator ); +* +* // Rebuild the list of cited keys according to the sort order: +* cited.clear(); +* for (BibEntry entry : entries.keySet()) { +* cited.add(entry.getCitationKey().orElse(null)); +* } +* // +* names = Arrays.asList(xReferenceMarks.getElementNames()); +* } else { +* // We need to sort the reference marks according to their +* // order of appearance: +* names = jabRefReferenceMarkNamesSortedByPosition; +* } +* +* // Remove all reference marks that don't look like JabRef citations: +* names = filterIsJabRefReferenceMarkName( names ); +* +* return new GetSortedCitedEntriesResult( cited, +* entries, +* names, +* citeKeyToBibEntry +* ); +* } + */ + private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] cEntries, OOBibStyle style ) { @@ -1478,11 +1480,46 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne { XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); - GetSortedCitedEntriesResult sce = - getSortedCitedEntries(documentConnection, databases, style, xReferenceMarks ); + List referenceMarkNames; + if ( style.isSortByPosition() || (!style.isNumberEntries()) ){ + // We sort the reference marks according to their + // order of appearance: + referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; + } else { + // isNumberEntries && !isSortByPosition + referenceMarkNames = Arrays.asList(xReferenceMarks.getElementNames()); + // Remove all reference marks that don't look like JabRef citations: + referenceMarkNames = filterIsJabRefReferenceMarkName( referenceMarkNames ); + } + + ///*********************** + // keys cited in the text + + List cited = findCitedKeys( documentConnection ); + Map citeKeyToBibEntry = new HashMap<>(); + Map entries = + findCitedEntries(databases, cited, citeKeyToBibEntry); + // entries are now in same order as cited + + if ( style.isSortByPosition() || (!style.isNumberEntries()) ){ + } else { + // (style.isNumberEntries() && ! style.isSortByPosition()) + + // sort entries to order in bibliography + entries = sortEntriesByComparator( entries, entryComparator ); + + // adjust order of cited to match + cited.clear(); + for (BibEntry entry : entries.keySet()) { + cited.add(entry.getCitationKey().orElse(null)); + } + // + } + + + //********************** - List referenceMarkNames = sce.refMarkNames; // Compute citation markers for all citations: final int nRefMarks = referenceMarkNames.size(); @@ -1504,9 +1541,9 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // } - Map entries = sce.entries; - List cited = sce.citedKeys; - Map citeKeyToBibEntry = sce.citeKeyToBibEntry; + // Map entries = sce.entries; + //List cited = sce.citedKeys; + //Map citeKeyToBibEntry = sce.citeKeyToBibEntry; // // For numbered citation style. Map( citedKey, number ) CitationNumberingState cns = new CitationNumberingState(); @@ -1528,6 +1565,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne BibEntry[] cEntries = mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); assert (cEntries.length == bibtexKeys[i].length) ; + citMarkers[i] = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); } uniquefiers.clear(); From 28df88c549477ae8ea773c3f8745ed4fc7f6e052 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 22:10:05 +0100 Subject: [PATCH 0235/1068] cns scop --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c893a506b14..6a2d1ed6ba5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1545,8 +1545,6 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne //List cited = sce.citedKeys; //Map citeKeyToBibEntry = sce.citeKeyToBibEntry; - // // For numbered citation style. Map( citedKey, number ) - CitationNumberingState cns = new CitationNumberingState(); final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); @@ -1572,6 +1570,9 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne } else if (style.isNumberEntries()) { + // // For numbered citation style. Map( citedKey, number ) + CitationNumberingState cns = new CitationNumberingState(); + for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); From d3f5f04d685a4faa7e411f404941487ef1d198d9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 22:11:07 +0100 Subject: [PATCH 0236/1068] minGroupingCount scope --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6a2d1ed6ba5..e188b1f9328 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1546,8 +1546,6 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne //Map citeKeyToBibEntry = sce.citeKeyToBibEntry; - final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); String[] citMarkers = new String[nRefMarks]; // fill: @@ -1573,6 +1571,9 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // // For numbered citation style. Map( citedKey, number ) CitationNumberingState cns = new CitationNumberingState(); + final int minGroupingCount = + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); From 96b7dd155950a1fbdfddce2493d56c414dd2fa2c Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 22:13:41 +0100 Subject: [PATCH 0237/1068] xReferenceMarks scope --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e188b1f9328..2eb917a72d3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1478,15 +1478,15 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne BibEntryNotFoundException, NoDocumentException { - XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); - List referenceMarkNames; + List referencenceMarkNames; if ( style.isSortByPosition() || (!style.isNumberEntries()) ){ // We sort the reference marks according to their // order of appearance: referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; } else { + XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); // isNumberEntries && !isSortByPosition referenceMarkNames = Arrays.asList(xReferenceMarks.getElementNames()); // Remove all reference marks that don't look like JabRef citations: From 7373dacd89444eb21004b952583d6b62faed486d Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 22:15:23 +0100 Subject: [PATCH 0238/1068] drop comments --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2eb917a72d3..066b7cc05cf 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1541,11 +1541,6 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // } - // Map entries = sce.entries; - //List cited = sce.citedKeys; - //Map citeKeyToBibEntry = sce.citeKeyToBibEntry; - - String[] citMarkers = new String[nRefMarks]; // fill: From 496bb2cb3004477abffcdbfc3469e9e97b106c3b Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 22:48:24 +0100 Subject: [PATCH 0239/1068] extract parseRefMarkNamesToArrays --- .../org/jabref/gui/openoffice/OOBibBase.java | 66 +++++++++++-------- 1 file changed, 39 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 066b7cc05cf..64b98af727b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1463,6 +1463,23 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, } } + private static parseRefMarkNamesToArrays( List referenceMarkNames, int[] types, String[][] bibtexKeys ) { + final int nRefMarks = referenceMarkNames.size(); + assert( types.length == nRefMarks ); + assert( bibtexKeys.length == nRefMarks ); + for (int i = 0; i < nRefMarks; i++) { + final String namei = referenceMarkNames.get(i); + Optional op = parseRefMarkName( namei ); + if ( !op.isPresent() ) { + assert( false ); + continue; + } + ParsedRefMark ov = op.get(); + types[i] = ov.itcType; // Remember the itcType in case we need to uniquefy. + bibtexKeys[i] = ov.citedKeys.stream().toArray(String[]::new); + } + } + private List refreshCiteMarkersInternal(DocumentConnection documentConnection, List databases, OOBibStyle style, @@ -1479,19 +1496,24 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne NoDocumentException { - List referencenceMarkNames; + // Normally we sort the reference marks according to their + // order of appearance: + List referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; - if ( style.isSortByPosition() || (!style.isNumberEntries()) ){ - // We sort the reference marks according to their - // order of appearance: - referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; - } else { - XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); - // isNumberEntries && !isSortByPosition - referenceMarkNames = Arrays.asList(xReferenceMarks.getElementNames()); - // Remove all reference marks that don't look like JabRef citations: - referenceMarkNames = filterIsJabRefReferenceMarkName( referenceMarkNames ); - } + + // An exception: numbered entries that are NOT sorted by position + // I think in this case we do not care, since numbering comes from + // order in cited + // + // if ( false ){ + // if (style.isNumberEntries() && ! style.isSortByPosition()) { + // XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); + // // isNumberEntries && !isSortByPosition + // referenceMarkNames = Arrays.asList(xReferenceMarks.getElementNames()); + // // Remove all reference marks that don't look like JabRef citations: + // referenceMarkNames = filterIsJabRefReferenceMarkName( referenceMarkNames ); + // } + // } ///*********************** // keys cited in the text @@ -1502,9 +1524,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne findCitedEntries(databases, cited, citeKeyToBibEntry); // entries are now in same order as cited - if ( style.isSortByPosition() || (!style.isNumberEntries()) ){ - } else { - // (style.isNumberEntries() && ! style.isSortByPosition()) + if (style.isNumberEntries() && ! style.isSortByPosition()) { // sort entries to order in bibliography entries = sortEntriesByComparator( entries, entryComparator ); @@ -1526,21 +1546,11 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne int[] types = new int[nRefMarks]; String[][] bibtexKeys = new String[nRefMarks][]; + // fill: // types[i] = ov.itcType // bibtexKeys[i] = ov.citedKeys.toArray() - for (int i = 0; i < nRefMarks; i++) { - final String namei = referenceMarkNames.get(i); - Optional op = parseRefMarkName( namei ); - if ( !op.isPresent() ) { - continue; - } - ParsedRefMark ov = op.get(); - types[i] = ov.itcType; // Remember the itcType in case we need to uniquefy. - bibtexKeys[i] = ov.citedKeys.stream().toArray(String[]::new); - // - } - + parseRefMarkNamesToArrays( referenceMarkNames, types, bibtexKeys ); String[] citMarkers = new String[nRefMarks]; // fill: @@ -1580,6 +1590,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne if (style.isSortByPosition()) { num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, bibtexKeys[i], style, cns ); } else { + // An exception: numbered entries that are NOT sorted by position + // exceptional_refmarkorder, entries and cited are sorted num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , cited ); } citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); From ef085acc971cab8f30b7c4c5478d89e4f405baf5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 22:49:18 +0100 Subject: [PATCH 0240/1068] return type added --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 64b98af727b..f1ac49fddde 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1463,7 +1463,7 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, } } - private static parseRefMarkNamesToArrays( List referenceMarkNames, int[] types, String[][] bibtexKeys ) { + private static void parseRefMarkNamesToArrays( List referenceMarkNames, int[] types, String[][] bibtexKeys ) { final int nRefMarks = referenceMarkNames.size(); assert( types.length == nRefMarks ); assert( bibtexKeys.length == nRefMarks ); From 7660c6252416e29a86c0ebf1f243da5c373fc391 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 22:55:12 +0100 Subject: [PATCH 0241/1068] extract unresolvedKeysFromEntries --- .../org/jabref/gui/openoffice/OOBibBase.java | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f1ac49fddde..f319695b1b1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1480,6 +1480,21 @@ private static void parseRefMarkNamesToArrays( List referenceMarkNames, } } + private static List unresolvedKeysFromEntries( Map entries ){ + // Collect and return unresolved citation keys. + // uses: entries + List unresolvedKeys = new ArrayList<>(); + for (BibEntry entry : entries.keySet()) { + if (entry instanceof UndefinedBibtexEntry) { + String key = ((UndefinedBibtexEntry) entry).getKey(); + if (!unresolvedKeys.contains(key)) { + unresolvedKeys.add(key); + } + } + } + return unresolvedKeys; + } + private List refreshCiteMarkersInternal(DocumentConnection documentConnection, List databases, OOBibStyle style, @@ -1775,18 +1790,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // Refresh all reference marks with the citation markers we computed: rcmApplyNewCitationMarkers(documentConnection, referenceMarkNames, citMarkers, types, style ); - // Collect and return unresolved citation keys. - // uses: entries - List unresolvedKeys = new ArrayList<>(); - for (BibEntry entry : entries.keySet()) { - if (entry instanceof UndefinedBibtexEntry) { - String key = ((UndefinedBibtexEntry) entry).getKey(); - if (!unresolvedKeys.contains(key)) { - unresolvedKeys.add(key); - } - } - } - return unresolvedKeys; + return unresolvedKeysFromEntries( entries ); } From 12a5ee450343fb02cde205a84a6adebe08e742c0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:10:34 +0100 Subject: [PATCH 0242/1068] extract rcmCitationMarkersForIsCitationKeyCiteMarkers --- .../org/jabref/gui/openoffice/OOBibBase.java | 71 +++++++++++-------- 1 file changed, 40 insertions(+), 31 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f319695b1b1..1f7494f8a00 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1274,6 +1274,28 @@ private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] c return citationMarker; } + private static String[] + rcmCitationMarkersForIsCitationKeyCiteMarkers( List referenceMarkNames, + String[][] bibtexKeys, + Map citeKeyToBibEntry, + OOBibStyle style ) + { + assert( style.isCitationKeyCiteMarkers() ); + final int nRefMarks = referenceMarkNames.size(); + assert( nRefMarks == bibtexKeys.length ); + String[] citMarkers = new String[nRefMarks]; + for (int i = 0; i < referenceMarkNames.size(); i++) { + final String namei = referenceMarkNames.get(i); + + BibEntry[] cEntries = + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); + assert (cEntries.length == bibtexKeys[i].length) ; + + citMarkers[i] = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); + } + return citMarkers; + } + private class CitationNumberingState { public Map numbers; public int lastNum; @@ -1514,8 +1536,17 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // Normally we sort the reference marks according to their // order of appearance: List referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; - - + // + // Compute citation markers for all citations: + final int nRefMarks = referenceMarkNames.size(); + int[] types = new int[nRefMarks]; + String[][] bibtexKeys = new String[nRefMarks][]; + // + // fill: + // types[i] = ov.itcType + // bibtexKeys[i] = ov.citedKeys.toArray() + parseRefMarkNamesToArrays( referenceMarkNames, types, bibtexKeys ); + // // An exception: numbered entries that are NOT sorted by position // I think in this case we do not care, since numbering comes from // order in cited @@ -1529,21 +1560,21 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // referenceMarkNames = filterIsJabRefReferenceMarkName( referenceMarkNames ); // } // } + // - ///*********************** - // keys cited in the text + // keys cited in the text List cited = findCitedKeys( documentConnection ); Map citeKeyToBibEntry = new HashMap<>(); Map entries = findCitedEntries(databases, cited, citeKeyToBibEntry); // entries are now in same order as cited - + // if (style.isNumberEntries() && ! style.isSortByPosition()) { - + // // sort entries to order in bibliography entries = sortEntriesByComparator( entries, entryComparator ); - + // // adjust order of cited to match cited.clear(); for (BibEntry entry : entries.keySet()) { @@ -1551,22 +1582,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne } // } - - - //********************** - - - // Compute citation markers for all citations: - final int nRefMarks = referenceMarkNames.size(); - int[] types = new int[nRefMarks]; - String[][] bibtexKeys = new String[nRefMarks][]; - - - // fill: - // types[i] = ov.itcType - // bibtexKeys[i] = ov.citedKeys.toArray() - parseRefMarkNamesToArrays( referenceMarkNames, types, bibtexKeys ); - + // String[] citMarkers = new String[nRefMarks]; // fill: // citMarkers[i] = what goes in the text @@ -1575,15 +1591,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // fill citMarkers if (style.isCitationKeyCiteMarkers()) { - for (int i = 0; i < referenceMarkNames.size(); i++) { - final String namei = referenceMarkNames.get(i); - - BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); - assert (cEntries.length == bibtexKeys[i].length) ; + citMarkers = rcmCitationMarkersForIsCitationKeyCiteMarkers( referenceMarkNames, bibtexKeys, citeKeyToBibEntry, style ); - citMarkers[i] = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); - } uniquefiers.clear(); } else if (style.isNumberEntries()) { From ed0aabe2d4f7e7eb41f2e24fd79721806c3f72cf Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:12:10 +0100 Subject: [PATCH 0243/1068] compiles --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1f7494f8a00..e5a9e21903e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1279,6 +1279,7 @@ private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] c String[][] bibtexKeys, Map citeKeyToBibEntry, OOBibStyle style ) + throws BibEntryNotFoundException { assert( style.isCitationKeyCiteMarkers() ); final int nRefMarks = referenceMarkNames.size(); From 77537726dacb73ea8043a8c9d5fa884c60b699dc Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:17:32 +0100 Subject: [PATCH 0244/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e5a9e21903e..fc7c9ac7507 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1567,8 +1567,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // keys cited in the text List cited = findCitedKeys( documentConnection ); Map citeKeyToBibEntry = new HashMap<>(); - Map entries = - findCitedEntries(databases, cited, citeKeyToBibEntry); + Map entries = findCitedEntries(databases, cited, citeKeyToBibEntry); // entries are now in same order as cited // if (style.isNumberEntries() && ! style.isSortByPosition()) { From a9cc54aa7cb97050929f6ec8ddd47f45b5b01abe Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:17:47 +0100 Subject: [PATCH 0245/1068] no init citMarkers --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index fc7c9ac7507..23f05ebdafa 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1583,18 +1583,15 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // } // - String[] citMarkers = new String[nRefMarks]; + String[] citMarkers; // = new String[nRefMarks]; // fill: // citMarkers[i] = what goes in the text // fill citMarkers if (style.isCitationKeyCiteMarkers()) { - citMarkers = rcmCitationMarkersForIsCitationKeyCiteMarkers( referenceMarkNames, bibtexKeys, citeKeyToBibEntry, style ); - - uniquefiers.clear(); - + uniquefiers.clear(); } else if (style.isNumberEntries()) { // // For numbered citation style. Map( citedKey, number ) From 586bfe5fd4c2ea8ba47274d752009bcc8d3409ef Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:18:06 +0100 Subject: [PATCH 0246/1068] citMarkers[i] in both branches --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 23f05ebdafa..e9e0f3fdec6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1610,13 +1610,14 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne List num ; if (style.isSortByPosition()) { num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, bibtexKeys[i], style, cns ); + citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } else { // An exception: numbered entries that are NOT sorted by position // exceptional_refmarkorder, entries and cited are sorted num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , cited ); + citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } - citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); - } + } // for uniquefiers.clear(); } else { From 42fe07e0a3a909145e1b8d7ac144d5d926354a52 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:19:23 +0100 Subject: [PATCH 0247/1068] scope num by branch --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e9e0f3fdec6..1e89d13630c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1607,13 +1607,14 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); assert (cEntries.length == bibtexKeys[i].length) ; - List num ; if (style.isSortByPosition()) { + List num ; num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, bibtexKeys[i], style, cns ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } else { // An exception: numbered entries that are NOT sorted by position // exceptional_refmarkorder, entries and cited are sorted + List num ; num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , cited ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } From a8f517e4ef6bb024683a3142e80342c38a2cd81a Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:21:34 +0100 Subject: [PATCH 0248/1068] cEntries in branches --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1e89d13630c..2b4fb538a29 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1603,17 +1603,21 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); - BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); - assert (cEntries.length == bibtexKeys[i].length) ; if (style.isSortByPosition()) { + BibEntry[] cEntries = + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); + assert (cEntries.length == bibtexKeys[i].length) ; List num ; num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, bibtexKeys[i], style, cns ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } else { // An exception: numbered entries that are NOT sorted by position // exceptional_refmarkorder, entries and cited are sorted + // + // BibEntry[] cEntries = + // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); + // assert (cEntries.length == bibtexKeys[i].length) ; List num ; num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , cited ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); From 782d6b1e2d7215eddc5c8bf4a76cb905256bc0af Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:23:18 +0100 Subject: [PATCH 0249/1068] for loop into branches --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2b4fb538a29..d4335ef06c6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1600,20 +1600,24 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - for (int i = 0; i < referenceMarkNames.size(); i++) { - final String namei = referenceMarkNames.get(i); + if (style.isSortByPosition()) { + for (int i = 0; i < referenceMarkNames.size(); i++) { + final String namei = referenceMarkNames.get(i); - if (style.isSortByPosition()) { BibEntry[] cEntries = mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); assert (cEntries.length == bibtexKeys[i].length) ; List num ; num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, bibtexKeys[i], style, cns ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); - } else { - // An exception: numbered entries that are NOT sorted by position - // exceptional_refmarkorder, entries and cited are sorted + } // for + } else { + // An exception: numbered entries that are NOT sorted by position + // exceptional_refmarkorder, entries and cited are sorted + for (int i = 0; i < referenceMarkNames.size(); i++) { + final String namei = referenceMarkNames.get(i); + // // BibEntry[] cEntries = // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); @@ -1621,8 +1625,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne List num ; num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , cited ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); - } - } // for + } // for + } uniquefiers.clear(); } else { From 79cd49d13548cd14ca71673c11d7c846feade59e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:24:08 +0100 Subject: [PATCH 0250/1068] minGroupingCount in branches --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d4335ef06c6..ced1ae61222 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1597,11 +1597,11 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // // For numbered citation style. Map( citedKey, number ) CitationNumberingState cns = new CitationNumberingState(); - final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); if (style.isSortByPosition()) { + final int minGroupingCount = + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); @@ -1615,6 +1615,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne } else { // An exception: numbered entries that are NOT sorted by position // exceptional_refmarkorder, entries and cited are sorted + final int minGroupingCount = + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); From c62e08cbd8367080ed11bcd89301d3a0ac6cd2b3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:24:56 +0100 Subject: [PATCH 0251/1068] cns into branch --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ced1ae61222..c6f2b711c26 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1594,12 +1594,10 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne uniquefiers.clear(); } else if (style.isNumberEntries()) { - // // For numbered citation style. Map( citedKey, number ) - CitationNumberingState cns = new CitationNumberingState(); - - if (style.isSortByPosition()) { + // // For numbered citation style. Map( citedKey, number ) + CitationNumberingState cns = new CitationNumberingState(); final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); for (int i = 0; i < referenceMarkNames.size(); i++) { From ee4bfcd4f7a254036e6a2c738d02a190def373d6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:36:57 +0100 Subject: [PATCH 0252/1068] extract rcmCitationMarkersForIsNumberEntriesIsSortByPosition --- .../org/jabref/gui/openoffice/OOBibBase.java | 54 +++++++++++++------ 1 file changed, 37 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c6f2b711c26..874845b9577 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1297,7 +1297,7 @@ private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] c return citMarkers; } - private class CitationNumberingState { + private static class CitationNumberingState { public Map numbers; public int lastNum; CitationNumberingState(){ @@ -1378,6 +1378,40 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry return num; } + private static String [] + rcmCitationMarkersForIsNumberEntriesIsSortByPosition( List referenceMarkNames, + String[][] bibtexKeys, + Map citeKeyToBibEntry, + OOBibStyle style ) + throws BibEntryNotFoundException + { + assert (style.isNumberEntries()); + assert (style.isSortByPosition()); + + final int nRefMarks = referenceMarkNames.size(); + assert( nRefMarks == bibtexKeys.length ); + String[] citMarkers = new String[nRefMarks]; + + // // For numbered citation style. Map( citedKey, number ) + CitationNumberingState cns = new CitationNumberingState(); + + final int minGroupingCount = + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + + for (int i = 0; i < referenceMarkNames.size(); i++) { + final String namei = referenceMarkNames.get(i); + + BibEntry[] cEntries = + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); + assert (cEntries.length == bibtexKeys[i].length) ; + + List num ; + num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, bibtexKeys[i], style, cns ); + citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); + } // for + return citMarkers; + } + /** * Resolve the citation key from a citation reference marker name, * and look up the index of the key in a list of keys. @@ -1583,7 +1617,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // } // - String[] citMarkers; // = new String[nRefMarks]; + String[] citMarkers = new String[nRefMarks]; // fill: // citMarkers[i] = what goes in the text @@ -1594,22 +1628,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne uniquefiers.clear(); } else if (style.isNumberEntries()) { - if (style.isSortByPosition()) { - // // For numbered citation style. Map( citedKey, number ) - CitationNumberingState cns = new CitationNumberingState(); - final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - for (int i = 0; i < referenceMarkNames.size(); i++) { - final String namei = referenceMarkNames.get(i); - - BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); - assert (cEntries.length == bibtexKeys[i].length) ; - List num ; - num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, bibtexKeys[i], style, cns ); - citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); - } // for + citMarkers = rcmCitationMarkersForIsNumberEntriesIsSortByPosition(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, style); } else { // An exception: numbered entries that are NOT sorted by position // exceptional_refmarkorder, entries and cited are sorted From dffe809c9c8e51b4bf105bc158529d9c9373ed1c Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:58:11 +0100 Subject: [PATCH 0253/1068] extract rcmCitationMarkersForIsNumberEntriesNotSortByPosition --- .../org/jabref/gui/openoffice/OOBibBase.java | 80 ++++++++++++------- 1 file changed, 50 insertions(+), 30 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 874845b9577..4045684886d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1412,6 +1412,49 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry return citMarkers; } + private String[] + rcmCitationMarkersForIsNumberEntriesNotSortByPosition( List referenceMarkNames, + String[][] bibtexKeys, + Map entries, + OOBibStyle style ) + { + assert( style.isNumberEntries() ); + assert( ! style.isSortByPosition() ); + + final int nRefMarks = referenceMarkNames.size(); + assert( nRefMarks == bibtexKeys.length ); + String[] citMarkers = new String[nRefMarks]; + + // An exception: numbered entries that are NOT sorted by position + // exceptional_refmarkorder, entries and cited are sorted + //if (style.isNumberEntries() && ! style.isSortByPosition()) { + // + // sort entries to order in bibliography + Map sortedEntries = sortEntriesByComparator( entries, entryComparator ); + // adjust order of cited to match + List sortedCited = new ArrayList( entries.size() ); + sortedCited.clear(); + for (BibEntry entry : sortedEntries.keySet()) { + sortedCited.add(entry.getCitationKey().orElse(null)); + } + //} + + final int minGroupingCount = + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + for (int i = 0; i < referenceMarkNames.size(); i++) { + final String namei = referenceMarkNames.get(i); + + // + // BibEntry[] cEntries = + // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); + // assert (cEntries.length == bibtexKeys[i].length) ; + List num ; + num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , sortedCited ); + citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); + } // for + return citMarkers; + } + /** * Resolve the citation key from a citation reference marker name, * and look up the index of the key in a list of keys. @@ -1421,8 +1464,8 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry * @return the (1-based) indices of the cited keys, -1 if a key is not found. * Returns Collections.emptyList() if the ref name could not be resolved as a citation. */ - private List findCitedEntryIndices(List keysCitedHere, - List orderedCiteKeys) + private static List findCitedEntryIndices(List keysCitedHere, + List orderedCiteKeys) { List result = new ArrayList<>(keysCitedHere.size()); for (String key : keysCitedHere) { @@ -1604,18 +1647,6 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne Map entries = findCitedEntries(databases, cited, citeKeyToBibEntry); // entries are now in same order as cited // - if (style.isNumberEntries() && ! style.isSortByPosition()) { - // - // sort entries to order in bibliography - entries = sortEntriesByComparator( entries, entryComparator ); - // - // adjust order of cited to match - cited.clear(); - for (BibEntry entry : entries.keySet()) { - cited.add(entry.getCitationKey().orElse(null)); - } - // - } // String[] citMarkers = new String[nRefMarks]; // fill: @@ -1631,21 +1662,9 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne if (style.isSortByPosition()) { citMarkers = rcmCitationMarkersForIsNumberEntriesIsSortByPosition(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, style); } else { - // An exception: numbered entries that are NOT sorted by position - // exceptional_refmarkorder, entries and cited are sorted - final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - for (int i = 0; i < referenceMarkNames.size(); i++) { - final String namei = referenceMarkNames.get(i); - // - // BibEntry[] cEntries = - // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); - // assert (cEntries.length == bibtexKeys[i].length) ; - List num ; - num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , cited ); - citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); - } // for + citMarkers = rcmCitationMarkersForIsNumberEntriesNotSortByPosition( referenceMarkNames, bibtexKeys, entries, style ); + } uniquefiers.clear(); @@ -1965,8 +1984,9 @@ public void rebuildBibTextSection(List databases, populateBibTextSection(documentConnection, entries, style, this.xUniquefiers); } - SortedMap sortEntriesByComparator( Map entries, - Comparator entryComparator ) + SortedMap + sortEntriesByComparator( Map entries, + Comparator entryComparator ) { SortedMap newMap = new TreeMap<>(entryComparator); for (Map.Entry kv : entries.entrySet()) { From 3caed6aefcf9e082aead9bb0859b677f9e4a9c8f Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Feb 2021 23:59:48 +0100 Subject: [PATCH 0254/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4045684886d..6706a22e64a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1662,9 +1662,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne if (style.isSortByPosition()) { citMarkers = rcmCitationMarkersForIsNumberEntriesIsSortByPosition(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, style); } else { - - citMarkers = rcmCitationMarkersForIsNumberEntriesNotSortByPosition( referenceMarkNames, bibtexKeys, entries, style ); - + citMarkers = rcmCitationMarkersForIsNumberEntriesNotSortByPosition(referenceMarkNames, bibtexKeys, entries, style ); } uniquefiers.clear(); From 333f99929c39d67d3c783fa56c37de825fe671f0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 24 Feb 2021 23:39:43 +0100 Subject: [PATCH 0255/1068] keep only a single CITE_PATTERN --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6706a22e64a..08bf81f6d93 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -102,10 +102,6 @@ class OOBibBase { private static final String BIB_CITATION = "JR_cite"; private static final Pattern CITE_PATTERN = - Pattern.compile(BIB_CITATION + "\\d*_(\\d*)_(.*)"); - - // Another pattern, to also recover the "i" part - private static final Pattern CITE_PATTERN2 = Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); private static final String CHAR_STYLE_NAME = "CharStyleName"; @@ -817,7 +813,7 @@ private static class ParsedRefMark { * */ private static Optional parseRefMarkName( String refMarkName ){ - Matcher citeMatcher = CITE_PATTERN2.matcher(refMarkName); + Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); if (!citeMatcher.find()) { return Optional.empty(); } From 77d12498afdcf51e110c711bbd36c5647737ffd0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 24 Feb 2021 23:41:58 +0100 Subject: [PATCH 0256/1068] drop GetSortedCitedEntriesResult --- .../org/jabref/gui/openoffice/OOBibBase.java | 80 ------------------- 1 file changed, 80 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 08bf81f6d93..2168596d428 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1173,86 +1173,6 @@ public List refreshCiteMarkers(List databases, return cEntries; } - private class GetSortedCitedEntriesResult { - List citedKeys; - Map entries; - List refMarkNames; - Map citeKeyToBibEntry; - public GetSortedCitedEntriesResult - ( - List citedKeys, - Map entries, - List refMarkNames, - Map citeKeyToBibEntry) - { - this.citedKeys = citedKeys; - this.entries = entries; - this.refMarkNames = refMarkNames; - this.citeKeyToBibEntry = citeKeyToBibEntry; - } - } - - /** - * - * @return GetSortedCitedEntriesResult where - * - * - * refMarkNames : jabRefReferenceMarkNamesSortedByPosition, - * except for style.isNumberEntries(), - * where we keep the order from xReferenceMarks.getElementNames() - * In any case: we apply filterIsJabRefReferenceMarkName. - * - * entries : from findCitedEntries() - * for style.isNumberEntries() reordered by entryComparator - * - * citedKeys : citeKey for each ref we found in the document. - * order: from findCitedKeys(), - * except for style.isNumberEntries() where reordered as entries - */ - /* -* private GetSortedCitedEntriesResult getSortedCitedEntries(DocumentConnection documentConnection, -* List databases, -* OOBibStyle style, -* XNameAccess xReferenceMarks ) -* throws NoSuchElementException, -* WrappedTargetException, -* NoDocumentException -* { -* -* // keys cited in the text -* List cited = findCitedKeys( documentConnection ); -* Map citeKeyToBibEntry = new HashMap<>(); -* Map entries = -* findCitedEntries(databases, cited, citeKeyToBibEntry); -* -* -* List names; -* if (style.isNumberEntries() && ! style.isSortByPosition()) { -* entries = sortEntriesByComparator( entries, entryComparator ); -* -* // Rebuild the list of cited keys according to the sort order: -* cited.clear(); -* for (BibEntry entry : entries.keySet()) { -* cited.add(entry.getCitationKey().orElse(null)); -* } -* // -* names = Arrays.asList(xReferenceMarks.getElementNames()); -* } else { -* // We need to sort the reference marks according to their -* // order of appearance: -* names = jabRefReferenceMarkNamesSortedByPosition; -* } -* -* // Remove all reference marks that don't look like JabRef citations: -* names = filterIsJabRefReferenceMarkName( names ); -* -* return new GetSortedCitedEntriesResult( cited, -* entries, -* names, -* citeKeyToBibEntry -* ); -* } - */ private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] cEntries, OOBibStyle style ) From 383121ec846f9d832e77f092626475690eb78e65 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 00:16:21 +0100 Subject: [PATCH 0257/1068] reimplement rcmCitationMarkerForIsCitationKeyCiteMarkers --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2168596d428..39bd8a650bc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1173,20 +1173,16 @@ public List refreshCiteMarkers(List databases, return cEntries; } - private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] cEntries, OOBibStyle style ) { - assert( style.isCitationKeyCiteMarkers() ); - StringBuilder sb = new StringBuilder(); - for (int j = 0; j < cEntries.length; j++) { - if (j > 0) { sb.append(','); } - Optional cejKey = cEntries[j].getCitationKey(); - sb.append(cejKey.orElse("")); - } - String citationMarker = sb.toString(); + String citationMarker = + Arrays.stream(cEntries) + .map( (c) -> c.getCitationKey().orElse("") ) + .collect(Collectors.joining(",")); + return citationMarker; } From 7aab13814610d88382e677de991e3799c6684640 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 08:27:54 +0100 Subject: [PATCH 0258/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 39bd8a650bc..7667ff5a462 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1196,6 +1196,7 @@ private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] c assert( style.isCitationKeyCiteMarkers() ); final int nRefMarks = referenceMarkNames.size(); assert( nRefMarks == bibtexKeys.length ); + String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); From 57d3d42709bf44c32e4d8c69f18cc6dd3833b8cd Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 08:54:09 +0100 Subject: [PATCH 0259/1068] rcmNumForIsNumberEntriesIsSortByPosition : use getCitationKey().get() for key --- .../org/jabref/gui/openoffice/OOBibBase.java | 22 +++---------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7667ff5a462..cdd1116fff7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1236,28 +1236,12 @@ private static class CitationNumberingState { * @return an int for each cEntry. (-1) for UndefinedBibtexEntry */ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry[] cEntries, - String[] keys, OOBibStyle style, CitationNumberingState cns ) { assert (style.isNumberEntries()); assert (style.isSortByPosition()); - assert (cEntries.length == keys.length ); - if ( true ){ - /* - * TODO: do we need a test case? - * - * If this never prints (or throws), we can drop the "keys" parameter. - */ - for (int j = 0; j < cEntries.length; j++) { - BibEntry cej = cEntries[j]; - String kj = keys[j]; - if ( kj != cej.getCitationKey().get() ){ - System.out.println - ( "keys != cEntries in rcmNumForIsNumberEntriesIsSortByPosition" ); - } - } - } + // // We have sorted the citation markers // according to their order of appearance, so @@ -1273,7 +1257,7 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry // for (int j = 0; j < cEntries.length; j++) { BibEntry cej = cEntries[j]; - String kj = keys[j]; // cej.getCitationKey().get() + String kj = cej.getCitationKey().get(); if (cej instanceof UndefinedBibtexEntry) { num.add(j, -1); // gets no cns.number } else { @@ -1319,7 +1303,7 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry assert (cEntries.length == bibtexKeys[i].length) ; List num ; - num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, bibtexKeys[i], style, cns ); + num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, style, cns ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } // for return citMarkers; From 9b9f79e523d74119568dccee4637466f4d2e807b Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 09:10:20 +0100 Subject: [PATCH 0260/1068] CitationNumberingState.getOrAllocateNumber --- .../org/jabref/gui/openoffice/OOBibBase.java | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index cdd1116fff7..54423b8888c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1210,6 +1210,11 @@ private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] c return citMarkers; } + /** + * Number source for (1-based) numbering of citations. + * + * + */ private static class CitationNumberingState { public Map numbers; public int lastNum; @@ -1218,13 +1223,28 @@ private static class CitationNumberingState { Map numbers = new HashMap<>(); int lastNum = 0; } + /** + * The first call returns 1. + */ + public int getOrAllocateNumber( String key ){ + int result; + if (numbers.containsKey(key)) { + // Already seen + result = numbers.get(key); + } else { + // First time to see. Allocate number. + lastNum++; + numbers.put(key, lastNum); + result = lastNum; + } + return result; + } } /** * Number citations. * * @param cEntries BibEntries to number. Numbering follows this order. - * @param keys : assert( keys[j] == cEntries[j].getCitationKey() ) * @param style * @param cns IN:keys already seen mapped to their number, and * lastNum the largest number already used. (0 for @@ -1261,15 +1281,7 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry if (cej instanceof UndefinedBibtexEntry) { num.add(j, -1); // gets no cns.number } else { - if (cns.numbers.containsKey(kj)) { - // already seen - num.add(j, cns.numbers.get(kj)); - } else { - // new - cns.lastNum++; // 1-based - num.add( j, cns.lastNum); - cns.numbers.put(kj, cns.lastNum); - } + num.add( j, cns.getOrAllocateNumber(kj) ); } } return num; From 1e268f330a60b558b87633b8b1c4836b04b220b4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 09:58:04 +0100 Subject: [PATCH 0261/1068] stream impl for rcmNumForIsNumberEntriesIsSortByPosition --- .../org/jabref/gui/openoffice/OOBibBase.java | 62 +++++++++++++------ 1 file changed, 44 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 54423b8888c..f904e4d73ef 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1241,17 +1241,31 @@ public int getOrAllocateNumber( String key ){ } } + /** + * Get number for a BibEntry. (-1) for UndefinedBibtexEntry + * + * BibEntry.getCitationKey() must not be Optional.empty(). + * + */ + private static int numberPossiblyUndefinedBibEntry( BibEntry ce, + CitationNumberingState cns ) + { + if (ce instanceof UndefinedBibtexEntry){ + return (-1); + } + + String key = ce.getCitationKey() + .orElseThrow(IllegalArgumentException::new); + + return cns.getOrAllocateNumber( key ); + + } /** * Number citations. * * @param cEntries BibEntries to number. Numbering follows this order. * @param style - * @param cns IN:keys already seen mapped to their number, and - * lastNum the largest number already used. (0 for - * none) - * - * OUT: the same, updated according to the numbers - * allocated here. + * @param cns INOUT Tracks keys already seen and their numbers. * * @return an int for each cEntry. (-1) for UndefinedBibtexEntry */ @@ -1262,29 +1276,41 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry assert (style.isNumberEntries()); assert (style.isSortByPosition()); + // Assumption: // // We have sorted the citation markers // according to their order of appearance, so // we simply count up for each marker // referring to a new entry: // - // num: Numbers for namei parts. (-1) for none. - // Passed to style.getNumCitationMarker() - List num = new ArrayList<>(cEntries.length); + // nums: Numbers for cEntries, (-1) for none. + // Passed to style.getNumCitationMarker() // // - // fill num while adjusting lastNum and filling numbers + // fill nums while adjusting lastNum and filling numbers // - for (int j = 0; j < cEntries.length; j++) { - BibEntry cej = cEntries[j]; - String kj = cej.getCitationKey().get(); - if (cej instanceof UndefinedBibtexEntry) { - num.add(j, -1); // gets no cns.number - } else { - num.add( j, cns.getOrAllocateNumber(kj) ); + if ( false ){ + List nums = new ArrayList<>(cEntries.length); + for (int j = 0; j < cEntries.length; j++) { + BibEntry cej = cEntries[j]; + String kj = cej.getCitationKey().get(); + int num = + (cej instanceof UndefinedBibtexEntry) + ? (-1) + : cns.getOrAllocateNumber(kj) + ; + nums.add(j,num); } + return nums; + } else { + // alt + List nums = + Arrays.stream( cEntries ) + .map( ce -> numberPossiblyUndefinedBibEntry(ce, cns) ) + .collect( Collectors.toList() ) + ; + return nums; } - return num; } private static String [] From 4be416a1a21bb24069b2c1d3bf7c6f2689001e60 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 10:03:02 +0100 Subject: [PATCH 0262/1068] format --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f904e4d73ef..2dc63ae4f38 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1263,11 +1263,12 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, /** * Number citations. * - * @param cEntries BibEntries to number. Numbering follows this order. - * @param style + * @param cEntries BibEntries to number. Numbering follows this order. + * @param style To assert we are in the right situation. * @param cns INOUT Tracks keys already seen and their numbers. + * OUT: Updated, the entries in cEntries are seen. * - * @return an int for each cEntry. (-1) for UndefinedBibtexEntry + * @return An int for each cEntry. (-1) for UndefinedBibtexEntry */ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry[] cEntries, OOBibStyle style, @@ -1278,9 +1279,8 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry // Assumption: // - // We have sorted the citation markers - // according to their order of appearance, so - // we simply count up for each marker + // We have sorted the citation markers according to their + // order of appearance, so we simply count up for each marker // referring to a new entry: // // nums: Numbers for cEntries, (-1) for none. From 6184d65eeeabea6e5b8ecd37217f85c4f9abeefa Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 10:05:02 +0100 Subject: [PATCH 0263/1068] rename rcmNumForIsNumberEntriesIsSortByPosition to numberPossiblyUndefinedBibEntres --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2dc63ae4f38..e59844b11df 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1270,9 +1270,9 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, * * @return An int for each cEntry. (-1) for UndefinedBibtexEntry */ - private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry[] cEntries, - OOBibStyle style, - CitationNumberingState cns ) + private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntries, + OOBibStyle style, + CitationNumberingState cns ) { assert (style.isNumberEntries()); assert (style.isSortByPosition()); @@ -1341,7 +1341,7 @@ private static List rcmNumForIsNumberEntriesIsSortByPosition( BibEntry assert (cEntries.length == bibtexKeys[i].length) ; List num ; - num = rcmNumForIsNumberEntriesIsSortByPosition( cEntries, style, cns ); + num = numberPossiblyUndefinedBibEntres( cEntries, style, cns ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } // for return citMarkers; From 6b3ff096244b84fea153b227285bfaca87c3ed00 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 10:07:37 +0100 Subject: [PATCH 0264/1068] drop style arg, move comment to call site --- .../org/jabref/gui/openoffice/OOBibBase.java | 30 ++++++++----------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e59844b11df..526c1351cfe 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1264,31 +1264,15 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, * Number citations. * * @param cEntries BibEntries to number. Numbering follows this order. - * @param style To assert we are in the right situation. * @param cns INOUT Tracks keys already seen and their numbers. * OUT: Updated, the entries in cEntries are seen. * * @return An int for each cEntry. (-1) for UndefinedBibtexEntry */ private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntries, - OOBibStyle style, CitationNumberingState cns ) { - assert (style.isNumberEntries()); - assert (style.isSortByPosition()); - // Assumption: - // - // We have sorted the citation markers according to their - // order of appearance, so we simply count up for each marker - // referring to a new entry: - // - // nums: Numbers for cEntries, (-1) for none. - // Passed to style.getNumCitationMarker() - // - // - // fill nums while adjusting lastNum and filling numbers - // if ( false ){ List nums = new ArrayList<>(cEntries.length); for (int j = 0; j < cEntries.length; j++) { @@ -1340,8 +1324,20 @@ private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntr mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); assert (cEntries.length == bibtexKeys[i].length) ; + // Assumption: + // + // We have sorted the citation markers according to their + // order of appearance, so we simply count up for each marker + // referring to a new entry: + // + // nums: Numbers for cEntries, (-1) for none. + // Passed to style.getNumCitationMarker() + // + // + // fill nums while adjusting lastNum and filling numbers + // List num ; - num = numberPossiblyUndefinedBibEntres( cEntries, style, cns ); + num = numberPossiblyUndefinedBibEntres( cEntries, cns ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } // for return citMarkers; From bc3073b465b4d58f4ecbbd03eadfa7ce50481697 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 10:10:42 +0100 Subject: [PATCH 0265/1068] join decl and init lines --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 526c1351cfe..47edb84da26 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1336,8 +1336,7 @@ private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntr // // fill nums while adjusting lastNum and filling numbers // - List num ; - num = numberPossiblyUndefinedBibEntres( cEntries, cns ); + List num = numberPossiblyUndefinedBibEntres( cEntries, cns ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } // for return citMarkers; From 55e5bc08547904a30e661af7dcd6c87d3eabbc20 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 10:31:31 +0100 Subject: [PATCH 0266/1068] num renamed to nums, move comments --- .../org/jabref/gui/openoffice/OOBibBase.java | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 47edb84da26..5bc79f7494b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1297,6 +1297,20 @@ private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntr } } + /** + * @param referenceMarkNames + * + * @param bibtexKeys Expects bibtexKeys[i] to correspond to + * referenceMarkNames.get(i) + * + * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. + * Must contain all bibtexKeys, but may map to UndefinedBibtexEntry. + * + * @return Numbered citation markers for bibtexKeys. + * + * Numbering is according to first encounter in bibtexKeys[i][j] (for(i){for(j){}} ) + * + */ private static String [] rcmCitationMarkersForIsNumberEntriesIsSortByPosition( List referenceMarkNames, String[][] bibtexKeys, @@ -1311,7 +1325,6 @@ private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntr assert( nRefMarks == bibtexKeys.length ); String[] citMarkers = new String[nRefMarks]; - // // For numbered citation style. Map( citedKey, number ) CitationNumberingState cns = new CitationNumberingState(); final int minGroupingCount = @@ -1324,20 +1337,12 @@ private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntr mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); assert (cEntries.length == bibtexKeys[i].length) ; - // Assumption: - // - // We have sorted the citation markers according to their - // order of appearance, so we simply count up for each marker - // referring to a new entry: // // nums: Numbers for cEntries, (-1) for none. // Passed to style.getNumCitationMarker() - // - // - // fill nums while adjusting lastNum and filling numbers - // - List num = numberPossiblyUndefinedBibEntres( cEntries, cns ); - citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); + List nums = numberPossiblyUndefinedBibEntres( cEntries, cns ); + + citMarkers[i] = style.getNumCitationMarker(nums, minGroupingCount, false); } // for return citMarkers; } From d600a50719e8ee506005eab7991234ad7d182456 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:05:12 +0100 Subject: [PATCH 0267/1068] use mapUndefinedBibentriesToNull --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5bc79f7494b..adea2c78127 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1721,8 +1721,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne String[] uniquif = new String[nCitedEntries]; BibEntry[] cEntries = mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, - namei, - true); + namei); + cEntries = mapUndefinedBibentriesToNull( cEntries ); for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; From b194b23aeadd1564b59d0269de7b6f8f1846c7ba Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:05:45 +0100 Subject: [PATCH 0268/1068] mapUndefinedBibentriesToNull and stream impl for mapCiteKeysToBibEntryArray --- .../org/jabref/gui/openoffice/OOBibBase.java | 78 +++++++++++++------ 1 file changed, 55 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index adea2c78127..80b916cab78 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1140,37 +1140,69 @@ public List refreshCiteMarkers(List databases, } } + private static BibEntry undefinedBibentryToNull( BibEntry cEntry ){ + if ( cEntry instanceof UndefinedBibtexEntry ){ + return null; + } + return cEntry; + } + private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ + Arrays.stream(cEntries) + .map( OOBibBase::undefinedBibentryToNull ) + .toArray(); + } private static BibEntry[] mapCiteKeysToBibEntryArray( String[] keys, // citeKeys Map citeKeyToBibEntry, - String referenceMarkName, // for reporting - boolean undefinedToNull // for undefined entries insert NULL + String referenceMarkName // for reporting + //boolean undefinedToNull // for undefined entries insert NULL ) throws BibEntryNotFoundException { - BibEntry[] cEntries = new BibEntry[keys.length]; - - // fill cEntries - for (int j = 0; j < keys.length; j++) { - String kj = keys[j]; - BibEntry tmpEntry = citeKeyToBibEntry.get( kj ); - if ( tmpEntry == null ){ - LOGGER.info("Citation key not found: '" + kj + '\''); - LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); - String msg = Localization.lang("Could not resolve BibTeX entry" - +" for citation marker '%0'.", - referenceMarkName - ); - throw new BibEntryNotFoundException(referenceMarkName, msg); - } else { - if ( undefinedToNull && tmpEntry instanceof UndefinedBibtexEntry ){ - tmpEntry = null; + if ( true ){ + + // check keys + Arrays.stream( keys ) + .filter( key -> null == citeKeyToBibEntry.get(key) ) + .forEachOrdered( key -> { + LOGGER.info("Citation key not found: '" + key + '\''); + LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); + String msg = Localization.lang("Could not resolve BibTeX entry" + +" for citation marker '%0'.", + referenceMarkName + ); + throw new BibEntryNotFoundException(referenceMarkName, msg); + }); + + // process keys + BibEntry[] cEntries = + Arrays.stream( keys ) + .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) + .toArray( BibEntry[]::new ); + return cEntries; + + } else { + BibEntry[] cEntries = new BibEntry[keys.length]; + + // fill cEntries + for (int j = 0; j < keys.length; j++) { + String kj = keys[j]; + BibEntry tmpEntry = citeKeyToBibEntry.get( kj ); + if ( tmpEntry == null ){ + LOGGER.info("Citation key not found: '" + kj + '\''); + LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); + String msg = Localization.lang("Could not resolve BibTeX entry" + +" for citation marker '%0'.", + referenceMarkName + ); + throw new BibEntryNotFoundException(referenceMarkName, msg); + } else { + cEntries[j] = tmpEntry; } - cEntries[j] = tmpEntry; - } - } // for j - return cEntries; + } // for j + return cEntries; + } } private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] cEntries, From b5dd5cc5ffa2b1e230de0453f651099964f1f41c Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:08:37 +0100 Subject: [PATCH 0269/1068] drop undefinedToNull arg in calls --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 80b916cab78..ab3547956e3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1234,7 +1234,7 @@ private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] c final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); assert (cEntries.length == bibtexKeys[i].length) ; citMarkers[i] = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); @@ -1366,7 +1366,7 @@ private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntr final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); assert (cEntries.length == bibtexKeys[i].length) ; // @@ -1646,7 +1646,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); assert (cEntries.length == bibtexKeys[i].length) ; // sort itcBlock From 4a5643bf5c8f5c0a0b5de7990c9c9b9a076109f9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:24:11 +0100 Subject: [PATCH 0270/1068] mapUndefinedBibentriesToNull corrected, add assertKeysInCiteKeyToBibEntry --- .../org/jabref/gui/openoffice/OOBibBase.java | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ab3547956e3..4b6c7489163 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1147,10 +1147,36 @@ private static BibEntry undefinedBibentryToNull( BibEntry cEntry ){ return cEntry; } private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ - Arrays.stream(cEntries) + return + Arrays.stream(cEntries) .map( OOBibBase::undefinedBibentryToNull ) - .toArray(); + .toArray( BibEntry[]::new ); } + + private static void + assertKeysInCiteKeyToBibEntry( String[] keys, // citeKeys + Map citeKeyToBibEntry, + String referenceMarkName // for reporting + ) + throws BibEntryNotFoundException + { + // check keys + List unresovedKeys = + Arrays.stream( keys ) + .filter( key -> null == citeKeyToBibEntry.get(key) ) + .collect(Collectors.toList()); + + for ( String key : unresovedKeys ){ + LOGGER.info("Citation key not found: '" + key + '\''); + LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); + String msg = Localization.lang("Could not resolve BibTeX entry" + +" for citation marker '%0'.", + referenceMarkName + ); + throw new BibEntryNotFoundException(referenceMarkName, msg); + } + } + private static BibEntry[] mapCiteKeysToBibEntryArray( String[] keys, // citeKeys Map citeKeyToBibEntry, From 9bee657767926ba03c65fd9fad406dcb8921d28b Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:25:32 +0100 Subject: [PATCH 0271/1068] use assertKeysInCiteKeyToBibEntry --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4b6c7489163..9eeeba2febe 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1186,19 +1186,7 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ throws BibEntryNotFoundException { if ( true ){ - - // check keys - Arrays.stream( keys ) - .filter( key -> null == citeKeyToBibEntry.get(key) ) - .forEachOrdered( key -> { - LOGGER.info("Citation key not found: '" + key + '\''); - LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); - String msg = Localization.lang("Could not resolve BibTeX entry" - +" for citation marker '%0'.", - referenceMarkName - ); - throw new BibEntryNotFoundException(referenceMarkName, msg); - }); + assertKeysInCiteKeyToBibEntry( keys, citeKeyToBibEntry, referenceMarkName ); // process keys BibEntry[] cEntries = From 15f8e7d616cc545440d9639d2d33e97331a1630a Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:28:01 +0100 Subject: [PATCH 0272/1068] inline mapCiteKeysToBibEntryArray and rcmCitationMarkerForIsCitationKeyCiteMarkers --- .../org/jabref/gui/openoffice/OOBibBase.java | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9eeeba2febe..c72d6a5107a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1219,18 +1219,6 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ } } - private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] cEntries, - OOBibStyle style ) - { - assert( style.isCitationKeyCiteMarkers() ); - - String citationMarker = - Arrays.stream(cEntries) - .map( (c) -> c.getCitationKey().orElse("") ) - .collect(Collectors.joining(",")); - - return citationMarker; - } private static String[] rcmCitationMarkersForIsCitationKeyCiteMarkers( List referenceMarkNames, @@ -1247,11 +1235,22 @@ private static String rcmCitationMarkerForIsCitationKeyCiteMarkers( BibEntry[] c for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); + // inline mapCiteKeysToBibEntryArray + assertKeysInCiteKeyToBibEntry( bibtexKeys[i], citeKeyToBibEntry, namei ); + BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); - assert (cEntries.length == bibtexKeys[i].length) ; + Arrays.stream( bibtexKeys[i] ) + .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) + .toArray( BibEntry[]::new ); + + // inline rcmCitationMarkerForIsCitationKeyCiteMarkers + String citationMarker = + Arrays.stream(cEntries) + .map( (c) -> c.getCitationKey().orElse("") ) + .collect(Collectors.joining(",")); + + citMarkers[i] = citationMarker; - citMarkers[i] = rcmCitationMarkerForIsCitationKeyCiteMarkers( cEntries, style ); } return citMarkers; } From afcc0b159f7579f5bd09b5242fe897626d8c59d7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:33:57 +0100 Subject: [PATCH 0273/1068] join consecutive streams --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c72d6a5107a..8a2d4dbe145 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1235,17 +1235,11 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); - // inline mapCiteKeysToBibEntryArray assertKeysInCiteKeyToBibEntry( bibtexKeys[i], citeKeyToBibEntry, namei ); - BibEntry[] cEntries = + String citationMarker = Arrays.stream( bibtexKeys[i] ) .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) - .toArray( BibEntry[]::new ); - - // inline rcmCitationMarkerForIsCitationKeyCiteMarkers - String citationMarker = - Arrays.stream(cEntries) .map( (c) -> c.getCitationKey().orElse("") ) .collect(Collectors.joining(",")); From 8f78effdda856df69b0ffc8097aa0511139517c2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:36:32 +0100 Subject: [PATCH 0274/1068] split loop --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8a2d4dbe145..5125e6704f3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1233,10 +1233,12 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < referenceMarkNames.size(); i++) { - final String namei = referenceMarkNames.get(i); - - assertKeysInCiteKeyToBibEntry( bibtexKeys[i], citeKeyToBibEntry, namei ); + assertKeysInCiteKeyToBibEntry( bibtexKeys[i], + citeKeyToBibEntry, + referenceMarkNames.get(i) ); + } + for (int i = 0; i < referenceMarkNames.size(); i++) { String citationMarker = Arrays.stream( bibtexKeys[i] ) .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) From f8b0aa0fca2a23a9c2ca97ccdb0cda827357f022 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:37:29 +0100 Subject: [PATCH 0275/1068] referenceMarkName --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5125e6704f3..4288899f7c6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1233,9 +1233,10 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < referenceMarkNames.size(); i++) { + final String referenceMarkName = referenceMarkNames.get(i); assertKeysInCiteKeyToBibEntry( bibtexKeys[i], citeKeyToBibEntry, - referenceMarkNames.get(i) ); + referenceMarkName ); } for (int i = 0; i < referenceMarkNames.size(); i++) { From 37e295820662cf3d5a88afc560ef1f9cb154154c Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:49:42 +0100 Subject: [PATCH 0276/1068] done rcmCitationMarkersForIsCitationKeyCiteMarkers --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4288899f7c6..91fbe0c3f78 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1231,7 +1231,6 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ final int nRefMarks = referenceMarkNames.size(); assert( nRefMarks == bibtexKeys.length ); - String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < referenceMarkNames.size(); i++) { final String referenceMarkName = referenceMarkNames.get(i); assertKeysInCiteKeyToBibEntry( bibtexKeys[i], @@ -1239,14 +1238,15 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ referenceMarkName ); } + String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < referenceMarkNames.size(); i++) { - String citationMarker = - Arrays.stream( bibtexKeys[i] ) - .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) - .map( (c) -> c.getCitationKey().orElse("") ) - .collect(Collectors.joining(",")); + String citationMarker = + Arrays.stream( bibtexKeys[i] ) + .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) + .map( (c) -> c.getCitationKey().orElse("") ) + .collect(Collectors.joining(",")); - citMarkers[i] = citationMarker; + citMarkers[i] = citationMarker; } return citMarkers; From cba25072078e790c0c74307bf284d5d50635d568 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:55:03 +0100 Subject: [PATCH 0277/1068] use nRefMarks, drop citationMarker --- .../org/jabref/gui/openoffice/OOBibBase.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 91fbe0c3f78..cd80aeac58e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1228,10 +1228,11 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ throws BibEntryNotFoundException { assert( style.isCitationKeyCiteMarkers() ); + final int nRefMarks = referenceMarkNames.size(); assert( nRefMarks == bibtexKeys.length ); - for (int i = 0; i < referenceMarkNames.size(); i++) { + for (int i = 0; i < nRefMarks; i++) { final String referenceMarkName = referenceMarkNames.get(i); assertKeysInCiteKeyToBibEntry( bibtexKeys[i], citeKeyToBibEntry, @@ -1239,15 +1240,12 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ } String[] citMarkers = new String[nRefMarks]; - for (int i = 0; i < referenceMarkNames.size(); i++) { - String citationMarker = - Arrays.stream( bibtexKeys[i] ) - .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) - .map( (c) -> c.getCitationKey().orElse("") ) - .collect(Collectors.joining(",")); - - citMarkers[i] = citationMarker; - + for (int i = 0; i < nRefMarks; i++) { + citMarkers[i] = + Arrays.stream( bibtexKeys[i] ) + .map( key -> citeKeyToBibEntry.get(key) ) + .map( (c) -> c.getCitationKey().orElse("") ) + .collect(Collectors.joining(",")); } return citMarkers; } From 5ef300171de104b898567abc1f63ec2b53fe568a Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 14:57:54 +0100 Subject: [PATCH 0278/1068] namei -> referenceMarkName --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index cd80aeac58e..fa700a16632 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1371,10 +1371,10 @@ private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntr style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); for (int i = 0; i < referenceMarkNames.size(); i++) { - final String namei = referenceMarkNames.get(i); + final String referenceMarkName = referenceMarkNames.get(i); BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); + mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, referenceMarkName ); assert (cEntries.length == bibtexKeys[i].length) ; // From 64ae0bf22a489c70ddc6fde197baebf094c783bb Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:02:47 +0100 Subject: [PATCH 0279/1068] extract assertAllKeysInCiteKeyToBibEntry --- .../org/jabref/gui/openoffice/OOBibBase.java | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index fa700a16632..cbb59aab601 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1219,6 +1219,23 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ } } + private static void + assertAllKeysInCiteKeyToBibEntry(List referenceMarkNames, + String[][] bibtexKeys, + Map citeKeyToBibEntry) + throws BibEntryNotFoundException + { + final int nRefMarks = referenceMarkNames.size(); + assert( nRefMarks == bibtexKeys.length ); + + for (int i = 0; i < nRefMarks; i++) { + final String referenceMarkName = referenceMarkNames.get(i); + assertKeysInCiteKeyToBibEntry( bibtexKeys[i], + citeKeyToBibEntry, + referenceMarkName ); + } + + } private static String[] rcmCitationMarkersForIsCitationKeyCiteMarkers( List referenceMarkNames, @@ -1231,13 +1248,7 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ final int nRefMarks = referenceMarkNames.size(); assert( nRefMarks == bibtexKeys.length ); - - for (int i = 0; i < nRefMarks; i++) { - final String referenceMarkName = referenceMarkNames.get(i); - assertKeysInCiteKeyToBibEntry( bibtexKeys[i], - citeKeyToBibEntry, - referenceMarkName ); - } + assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeys, citeKeyToBibEntry ); String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { From 7536630d4744ad7fba059c82b27d65de58c5c57f Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:10:03 +0100 Subject: [PATCH 0280/1068] inline numberPossiblyUndefinedBibEntres, mapCiteKeysToBibEntryArray --- .../org/jabref/gui/openoffice/OOBibBase.java | 92 ++++++++++--------- 1 file changed, 51 insertions(+), 41 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index cbb59aab601..05de2ed2b7c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1311,42 +1311,42 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, return cns.getOrAllocateNumber( key ); } - /** - * Number citations. - * - * @param cEntries BibEntries to number. Numbering follows this order. - * @param cns INOUT Tracks keys already seen and their numbers. - * OUT: Updated, the entries in cEntries are seen. - * - * @return An int for each cEntry. (-1) for UndefinedBibtexEntry - */ - private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntries, - CitationNumberingState cns ) - { - - if ( false ){ - List nums = new ArrayList<>(cEntries.length); - for (int j = 0; j < cEntries.length; j++) { - BibEntry cej = cEntries[j]; - String kj = cej.getCitationKey().get(); - int num = - (cej instanceof UndefinedBibtexEntry) - ? (-1) - : cns.getOrAllocateNumber(kj) - ; - nums.add(j,num); - } - return nums; - } else { - // alt - List nums = - Arrays.stream( cEntries ) - .map( ce -> numberPossiblyUndefinedBibEntry(ce, cns) ) - .collect( Collectors.toList() ) - ; - return nums; - } - } +// /** +// * Number citations. +// * +// * @param cEntries BibEntries to number. Numbering follows this order. +// * @param cns INOUT Tracks keys already seen and their numbers. +// * OUT: Updated, the entries in cEntries are seen. +// * +// * @return An int for each cEntry. (-1) for UndefinedBibtexEntry +// */ +// private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntries, +// CitationNumberingState cns ) +// { +// +// if ( false ){ +// List nums = new ArrayList<>(cEntries.length); +// for (int j = 0; j < cEntries.length; j++) { +// BibEntry cej = cEntries[j]; +// String kj = cej.getCitationKey().get(); +// int num = +// (cej instanceof UndefinedBibtexEntry) +// ? (-1) +// : cns.getOrAllocateNumber(kj) +// ; +// nums.add(j,num); +// } +// return nums; +// } else { +// // alt +// List nums = +// Arrays.stream( cEntries ) +// .map( ce -> numberPossiblyUndefinedBibEntry(ce, cns) ) +// .collect( Collectors.toList() ) +// ; +// return nums; +// } +// } /** * @param referenceMarkNames @@ -1374,6 +1374,8 @@ private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntr final int nRefMarks = referenceMarkNames.size(); assert( nRefMarks == bibtexKeys.length ); + assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeys, citeKeyToBibEntry ); + String[] citMarkers = new String[nRefMarks]; CitationNumberingState cns = new CitationNumberingState(); @@ -1384,14 +1386,22 @@ private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntr for (int i = 0; i < referenceMarkNames.size(); i++) { final String referenceMarkName = referenceMarkNames.get(i); + // BibEntry[] cEntries = + // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, referenceMarkName ); + // assert (cEntries.length == bibtexKeys[i].length); + // List nums = numberPossiblyUndefinedBibEntres( cEntries, cns ); + BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, referenceMarkName ); - assert (cEntries.length == bibtexKeys[i].length) ; + Arrays.stream( bibtexKeys[i] ) + .map( key -> citeKeyToBibEntry.get(key) ) + .toArray( BibEntry[]::new ); + List nums = + Arrays.stream( cEntries ) + .map( ce -> numberPossiblyUndefinedBibEntry(ce, cns) ) + .collect( Collectors.toList() ); - // // nums: Numbers for cEntries, (-1) for none. - // Passed to style.getNumCitationMarker() - List nums = numberPossiblyUndefinedBibEntres( cEntries, cns ); + citMarkers[i] = style.getNumCitationMarker(nums, minGroupingCount, false); } // for From d00ed7be9846cb5cb703ad8946b0f95de3bdcee9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:11:52 +0100 Subject: [PATCH 0281/1068] cleanup --- .../org/jabref/gui/openoffice/OOBibBase.java | 42 ------------------- 1 file changed, 42 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 05de2ed2b7c..2e8139da042 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1311,42 +1311,6 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, return cns.getOrAllocateNumber( key ); } -// /** -// * Number citations. -// * -// * @param cEntries BibEntries to number. Numbering follows this order. -// * @param cns INOUT Tracks keys already seen and their numbers. -// * OUT: Updated, the entries in cEntries are seen. -// * -// * @return An int for each cEntry. (-1) for UndefinedBibtexEntry -// */ -// private static List numberPossiblyUndefinedBibEntres( BibEntry[] cEntries, -// CitationNumberingState cns ) -// { -// -// if ( false ){ -// List nums = new ArrayList<>(cEntries.length); -// for (int j = 0; j < cEntries.length; j++) { -// BibEntry cej = cEntries[j]; -// String kj = cej.getCitationKey().get(); -// int num = -// (cej instanceof UndefinedBibtexEntry) -// ? (-1) -// : cns.getOrAllocateNumber(kj) -// ; -// nums.add(j,num); -// } -// return nums; -// } else { -// // alt -// List nums = -// Arrays.stream( cEntries ) -// .map( ce -> numberPossiblyUndefinedBibEntry(ce, cns) ) -// .collect( Collectors.toList() ) -// ; -// return nums; -// } -// } /** * @param referenceMarkNames @@ -1386,11 +1350,6 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, for (int i = 0; i < referenceMarkNames.size(); i++) { final String referenceMarkName = referenceMarkNames.get(i); - // BibEntry[] cEntries = - // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, referenceMarkName ); - // assert (cEntries.length == bibtexKeys[i].length); - // List nums = numberPossiblyUndefinedBibEntres( cEntries, cns ); - BibEntry[] cEntries = Arrays.stream( bibtexKeys[i] ) .map( key -> citeKeyToBibEntry.get(key) ) @@ -1402,7 +1361,6 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, // nums: Numbers for cEntries, (-1) for none. - citMarkers[i] = style.getNumCitationMarker(nums, minGroupingCount, false); } // for return citMarkers; From 4a21e02e2312dbed0dad8685388d3d81c7edd778 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:13:23 +0100 Subject: [PATCH 0282/1068] join consecutive streams --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2e8139da042..7ab7249dfec 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1350,17 +1350,13 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, for (int i = 0; i < referenceMarkNames.size(); i++) { final String referenceMarkName = referenceMarkNames.get(i); - BibEntry[] cEntries = - Arrays.stream( bibtexKeys[i] ) - .map( key -> citeKeyToBibEntry.get(key) ) - .toArray( BibEntry[]::new ); + // nums: Numbers for cEntries, (-1) for none. List nums = - Arrays.stream( cEntries ) + Arrays.stream( bibtexKeys[i] ) + .map( key -> citeKeyToBibEntry.get(key) ) // cEntries .map( ce -> numberPossiblyUndefinedBibEntry(ce, cns) ) .collect( Collectors.toList() ); - // nums: Numbers for cEntries, (-1) for none. - citMarkers[i] = style.getNumCitationMarker(nums, minGroupingCount, false); } // for return citMarkers; From 51599473fdb0fe31b77168046aca70a9efe25f83 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:14:05 +0100 Subject: [PATCH 0283/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7ab7249dfec..7d175c8a9ea 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1353,8 +1353,8 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, // nums: Numbers for cEntries, (-1) for none. List nums = Arrays.stream( bibtexKeys[i] ) - .map( key -> citeKeyToBibEntry.get(key) ) // cEntries - .map( ce -> numberPossiblyUndefinedBibEntry(ce, cns) ) + .map( key -> citeKeyToBibEntry.get(key) ) + .map( ce -> numberPossiblyUndefinedBibEntry(ce, cns) ) .collect( Collectors.toList() ); citMarkers[i] = style.getNumCitationMarker(nums, minGroupingCount, false); From 8bd66c9486748456722287245443b82b318349c6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:20:30 +0100 Subject: [PATCH 0284/1068] inline mapCiteKeysToBibEntryArray --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7d175c8a9ea..9bc0dab05f6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1625,11 +1625,17 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // normCitMarkers[i][j] = for unification String[][] normCitMarkers = new String[nRefMarks][]; + assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeys, citeKeyToBibEntry ); + for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); + // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); + Arrays.stream( bibtexKeys[i] ) + .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) + .toArray( BibEntry[]::new ); + assert (cEntries.length == bibtexKeys[i].length) ; // sort itcBlock From 260778bade39d70958eaed8acbc43e4e102a1a0d Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:23:16 +0100 Subject: [PATCH 0285/1068] cleanup --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9bc0dab05f6..4eadc883411 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1633,11 +1633,9 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne BibEntry[] cEntries = // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); Arrays.stream( bibtexKeys[i] ) - .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) + .map( key -> citeKeyToBibEntry.get(key) ) .toArray( BibEntry[]::new ); - assert (cEntries.length == bibtexKeys[i].length) ; - // sort itcBlock sortBibEntryArrayForMulticite( cEntries, style ); From 13f768beef043e9209082595d9ee510103978b8b Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:28:10 +0100 Subject: [PATCH 0286/1068] extract comparatorForMulticite --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4eadc883411..2231a3e074b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -628,17 +628,21 @@ public Optional getCurrentDocumentTitle() { * === insertEntry */ + private Comparator comparatorForMulticite(OOBibStyle style){ + if (style.getBooleanCitProperty( OOBibStyle.MULTI_CITE_CHRONOLOGICAL )) { + return this.yearAuthorTitleComparator; + } else { + return this.entryComparator; + } + } + private void sortBibEntryListForMulticite( List entries, OOBibStyle style ) { if (entries.size() <= 1){ return; } - if (style.getBooleanCitProperty( OOBibStyle.MULTI_CITE_CHRONOLOGICAL )) { - entries.sort(this.yearAuthorTitleComparator); - } else { - entries.sort(this.entryComparator); - } + entries.sort( comparatorForMulticite(style)); } private void sortBibEntryArrayForMulticite( BibEntry[] entries, OOBibStyle style ) @@ -646,11 +650,7 @@ private void sortBibEntryArrayForMulticite( BibEntry[] entries, if (entries.length <= 1) { return; } - if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { - Arrays.sort(entries, yearAuthorTitleComparator); - } else { - Arrays.sort(entries, entryComparator); - } + Arrays.sort(entries, comparatorForMulticite(style)); } private static int citationTypeFromOptions( boolean withText, boolean inParenthesis ) { From 66a69734a9405f6a5d47ce35263154fe88e4c375 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:36:57 +0100 Subject: [PATCH 0287/1068] inline sortBibEntryArrayForMulticite into stream --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2231a3e074b..ba2599a4d6c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1634,10 +1634,11 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); Arrays.stream( bibtexKeys[i] ) .map( key -> citeKeyToBibEntry.get(key) ) + .sorted( comparatorForMulticite(style) ) .toArray( BibEntry[]::new ); // sort itcBlock - sortBibEntryArrayForMulticite( cEntries, style ); + //sortBibEntryArrayForMulticite( cEntries, style ); // Update key list to match the new sorting: for (int j = 0; j < cEntries.length; j++) { From 5a88ff6a4ea9ded28ac78e3af9c952716dc7d945 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:37:39 +0100 Subject: [PATCH 0288/1068] drop sortBibEntryArrayForMulticite --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ba2599a4d6c..306b43d8ae5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -644,14 +644,6 @@ private void sortBibEntryListForMulticite( List entries, } entries.sort( comparatorForMulticite(style)); } - private void sortBibEntryArrayForMulticite( BibEntry[] entries, - OOBibStyle style ) - { - if (entries.length <= 1) { - return; - } - Arrays.sort(entries, comparatorForMulticite(style)); - } private static int citationTypeFromOptions( boolean withText, boolean inParenthesis ) { if ( !withText ){ @@ -1637,9 +1629,6 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne .sorted( comparatorForMulticite(style) ) .toArray( BibEntry[]::new ); - // sort itcBlock - //sortBibEntryArrayForMulticite( cEntries, style ); - // Update key list to match the new sorting: for (int j = 0; j < cEntries.length; j++) { bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); From 4db365d567ef39c05d4b0df25e99ffa0d14a6ac4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 15:52:47 +0100 Subject: [PATCH 0289/1068] bibtexKeys update as stream --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 306b43d8ae5..b26a335faa6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1626,13 +1626,14 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); Arrays.stream( bibtexKeys[i] ) .map( key -> citeKeyToBibEntry.get(key) ) - .sorted( comparatorForMulticite(style) ) + .sorted( comparatorForMulticite(style) ) // sort within referenceMark .toArray( BibEntry[]::new ); // Update key list to match the new sorting: - for (int j = 0; j < cEntries.length; j++) { - bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); - } + bibtexKeys[i] = + Arrays.stream( cEntries ) + .map( ce -> ce.getCitationKey().orElse(null) ) + .toArray( String[]::new ); citMarkers[i] = style.getCitationMarker( Arrays.asList(cEntries), // entries entries, // database From 907ed81410bc75e301c4f04facc8f9ccd354c882 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 16:00:36 +0100 Subject: [PATCH 0290/1068] normCitMarkers from stream --- .../org/jabref/gui/openoffice/OOBibBase.java | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b26a335faa6..e53b8ec6607 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1644,20 +1644,17 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: - // - // normCitMarker[ cEntries.length ] null if missing - String[] normCitMarker = new String[cEntries.length]; - for (int j = 0; j < cEntries.length; j++) { - List cej = Collections.singletonList(cEntries[j]); - normCitMarker[j] = - style.getCitationMarker( cej, // entries - entries, // database - true, // inParenthesis - null, // uniquefiers - new int[] {-1} // unlimAuthors - ); - } - normCitMarkers[i] = normCitMarker; + normCitMarkers[i] = + Arrays.stream( cEntries ) + .map( ce -> + style.getCitationMarker( Collections.singletonList(ce), + entries, // database + true, // inParenthesis + null, // uniquefiers + new int[] {-1} // unlimAuthors + ) + ) + .toArray( String[]::new ); } uniquefiers.clear(); From 5f712429541764ef81e930244574beb13b105624 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 16:01:34 +0100 Subject: [PATCH 0291/1068] dro namei --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e53b8ec6607..4a80a351683 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1620,10 +1620,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeys, citeKeyToBibEntry ); for (int i = 0; i < referenceMarkNames.size(); i++) { - final String namei = referenceMarkNames.get(i); BibEntry[] cEntries = - // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei ); Arrays.stream( bibtexKeys[i] ) .map( key -> citeKeyToBibEntry.get(key) ) .sorted( comparatorForMulticite(style) ) // sort within referenceMark From 561df2e54704ec3987989292abd19749365e6ffe Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 16:06:06 +0100 Subject: [PATCH 0292/1068] slip loop --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4a80a351683..67ce3fffb66 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1618,6 +1618,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne String[][] normCitMarkers = new String[nRefMarks][]; assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeys, citeKeyToBibEntry ); + BibEntry[][] cEntriesForAll = new BibEntry[nRefMarks][]; for (int i = 0; i < referenceMarkNames.size(); i++) { @@ -1626,20 +1627,30 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne .map( key -> citeKeyToBibEntry.get(key) ) .sorted( comparatorForMulticite(style) ) // sort within referenceMark .toArray( BibEntry[]::new ); + cEntriesForAll[i] = cEntries; + } + for (int i = 0; i < referenceMarkNames.size(); i++) { + BibEntry[] cEntries = cEntriesForAll[i]; // Update key list to match the new sorting: bibtexKeys[i] = Arrays.stream( cEntries ) .map( ce -> ce.getCitationKey().orElse(null) ) .toArray( String[]::new ); + } + for (int i = 0; i < referenceMarkNames.size(); i++) { + BibEntry[] cEntries = cEntriesForAll[i]; citMarkers[i] = style.getCitationMarker( Arrays.asList(cEntries), // entries entries, // database types[i] == OOBibBase.AUTHORYEAR_PAR, null, // uniquefiers null // unlimAuthors ); + } + for (int i = 0; i < referenceMarkNames.size(); i++) { + BibEntry[] cEntries = cEntriesForAll[i]; // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: normCitMarkers[i] = From 5476061e8fd4627f56c400fa8bfcba20ecdccc4f Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 18:52:54 +0100 Subject: [PATCH 0293/1068] extract rcmCitationMarkersForNormalStyle --- .../org/jabref/gui/openoffice/OOBibBase.java | 293 +++++++++++------- 1 file changed, 174 insertions(+), 119 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 67ce3fffb66..2ab92eec92a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1537,135 +1537,93 @@ private static List unresolvedKeysFromEntries( Map refreshCiteMarkersInternal(DocumentConnection documentConnection, - List databases, - OOBibStyle style, - final Map uniquefiers - ) - throws WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException - { - - // Normally we sort the reference marks according to their - // order of appearance: - List referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; - // - // Compute citation markers for all citations: - final int nRefMarks = referenceMarkNames.size(); - int[] types = new int[nRefMarks]; - String[][] bibtexKeys = new String[nRefMarks][]; - // - // fill: - // types[i] = ov.itcType - // bibtexKeys[i] = ov.citedKeys.toArray() - parseRefMarkNamesToArrays( referenceMarkNames, types, bibtexKeys ); - // - // An exception: numbered entries that are NOT sorted by position - // I think in this case we do not care, since numbering comes from - // order in cited - // - // if ( false ){ - // if (style.isNumberEntries() && ! style.isSortByPosition()) { - // XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); - // // isNumberEntries && !isSortByPosition - // referenceMarkNames = Arrays.asList(xReferenceMarks.getElementNames()); - // // Remove all reference marks that don't look like JabRef citations: - // referenceMarkNames = filterIsJabRefReferenceMarkName( referenceMarkNames ); - // } - // } - // - - - // keys cited in the text - List cited = findCitedKeys( documentConnection ); - Map citeKeyToBibEntry = new HashMap<>(); - Map entries = findCitedEntries(databases, cited, citeKeyToBibEntry); - // entries are now in same order as cited - // - // - String[] citMarkers = new String[nRefMarks]; - // fill: - // citMarkers[i] = what goes in the text - - // fill citMarkers - if (style.isCitationKeyCiteMarkers()) { - citMarkers = rcmCitationMarkersForIsCitationKeyCiteMarkers( referenceMarkNames, bibtexKeys, citeKeyToBibEntry, style ); - uniquefiers.clear(); - } else if (style.isNumberEntries()) { - - if (style.isSortByPosition()) { - citMarkers = rcmCitationMarkersForIsNumberEntriesIsSortByPosition(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, style); - } else { - citMarkers = rcmCitationMarkersForIsNumberEntriesNotSortByPosition(referenceMarkNames, bibtexKeys, entries, style ); - } - uniquefiers.clear(); - - } else { - - assert( !style.isCitationKeyCiteMarkers() ); - assert( !style.isNumberEntries() ); - // Citations in (Au1, Au2 2000) form - - // normCitMarkers[i][j] = for unification - String[][] normCitMarkers = new String[nRefMarks][]; - - assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeys, citeKeyToBibEntry ); - BibEntry[][] cEntriesForAll = new BibEntry[nRefMarks][]; - - for (int i = 0; i < referenceMarkNames.size(); i++) { + private class RcmCitationMarkersForNormalStyleResult{ + public String[] citMarkers; // main product + public String[][] bibtexKeys; // order within referenceMarks may have changed + RcmCitationMarkersForNormalStyleResult( String[] citMarkers, + String[][] bibtexKeys ) + { + this.citMarkers = citMarkers; + this.bibtexKeys = bibtexKeys; + } + } - BibEntry[] cEntries = - Arrays.stream( bibtexKeys[i] ) - .map( key -> citeKeyToBibEntry.get(key) ) - .sorted( comparatorForMulticite(style) ) // sort within referenceMark - .toArray( BibEntry[]::new ); - cEntriesForAll[i] = cEntries; - } + RcmCitationMarkersForNormalStyleResult + rcmCitationMarkersForNormalStyle(List referenceMarkNames, + String[][] bibtexKeysIn, + Map citeKeyToBibEntry, + int [] types, + Map entries, + final Map uniquefiers, + OOBibStyle style + ) + throws BibEntryNotFoundException + { + assert( !style.isCitationKeyCiteMarkers() ); + assert( !style.isNumberEntries() ); + // Citations in (Au1, Au2 2000) form - for (int i = 0; i < referenceMarkNames.size(); i++) { - BibEntry[] cEntries = cEntriesForAll[i]; - // Update key list to match the new sorting: - bibtexKeys[i] = - Arrays.stream( cEntries ) - .map( ce -> ce.getCitationKey().orElse(null) ) - .toArray( String[]::new ); - } + final int nRefMarks = referenceMarkNames.size(); + assert( bibtexKeysIn.length == nRefMarks ); + assert( types.length == nRefMarks ); + assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry ); + + BibEntry[][] cEntriesForAll = + Arrays.stream( bibtexKeysIn ) + .map( bibtexKeysOfARefererenceMark -> + Arrays.stream( bibtexKeysOfARefererenceMark ) + .map( key -> citeKeyToBibEntry.get(key) ) + .sorted( comparatorForMulticite(style) ) // sort within referenceMark + .toArray( BibEntry[]::new ) + ) + .toArray( BibEntry[][]::new ); + + // Update bibtexKeys to match the new sorting (within each referenceMark) + String[][] bibtexKeys = + Arrays.stream( cEntriesForAll ) + .map( cEntries -> + Arrays.stream( cEntries ) + .map( ce -> ce.getCitationKey().orElse(null) ) + .toArray( String[]::new ) + ) + .toArray( String[][]::new ); + + assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry ); + assert( bibtexKeys.length == nRefMarks ); - for (int i = 0; i < referenceMarkNames.size(); i++) { - BibEntry[] cEntries = cEntriesForAll[i]; + String[] citMarkers = new String[nRefMarks]; + for (int i = 0; i < nRefMarks; i++) { + BibEntry[] cEntries = cEntriesForAll[i]; + int type = types[i]; citMarkers[i] = style.getCitationMarker( Arrays.asList(cEntries), // entries entries, // database - types[i] == OOBibBase.AUTHORYEAR_PAR, + type == OOBibBase.AUTHORYEAR_PAR, null, // uniquefiers null // unlimAuthors ); - } + } - for (int i = 0; i < referenceMarkNames.size(); i++) { - BibEntry[] cEntries = cEntriesForAll[i]; - // We need "normalized" (in parenthesis) markers - // for uniqueness checking purposes: - normCitMarkers[i] = - Arrays.stream( cEntries ) - .map( ce -> - style.getCitationMarker( Collections.singletonList(ce), - entries, // database - true, // inParenthesis - null, // uniquefiers - new int[] {-1} // unlimAuthors - ) - ) - .toArray( String[]::new ); - } - uniquefiers.clear(); + // normCitMarkers[i][j] = for unification + String[][] normCitMarkers = new String[nRefMarks][]; + for (int i = 0; i < nRefMarks; i++) { + BibEntry[] cEntries = cEntriesForAll[i]; + // We need "normalized" (in parenthesis) markers + // for uniqueness checking purposes: + normCitMarkers[i] = + Arrays.stream( cEntries ) + .map( ce -> + style.getCitationMarker( Collections.singletonList(ce), + entries, // database + true, // inParenthesis + null, // uniquefiers + new int[] {-1} // unlimAuthors + ) + ) + .toArray( String[]::new ); + } + + uniquefiers.clear(); // The following block // changes: citMarkers[i], uniquefiers @@ -1788,6 +1746,103 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne } } // for i } // if normalStyle + return new RcmCitationMarkersForNormalStyleResult( citMarkers, bibtexKeys ); + } + + private List refreshCiteMarkersInternal(DocumentConnection documentConnection, + List databases, + OOBibStyle style, + final Map uniquefiers + ) + throws WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException + { + + // Normally we sort the reference marks according to their + // order of appearance: + List referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; + // + // Compute citation markers for all citations: + final int nRefMarks = referenceMarkNames.size(); + int[] types = new int[nRefMarks]; + String[][] bibtexKeys = new String[nRefMarks][]; + // + // fill: + // types[i] = ov.itcType + // bibtexKeys[i] = ov.citedKeys.toArray() + parseRefMarkNamesToArrays( referenceMarkNames, types, bibtexKeys ); + // + // An exception: numbered entries that are NOT sorted by position + // I think in this case we do not care, since numbering comes from + // order in cited + // + // if ( false ){ + // if (style.isNumberEntries() && ! style.isSortByPosition()) { + // XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); + // // isNumberEntries && !isSortByPosition + // referenceMarkNames = Arrays.asList(xReferenceMarks.getElementNames()); + // // Remove all reference marks that don't look like JabRef citations: + // referenceMarkNames = filterIsJabRefReferenceMarkName( referenceMarkNames ); + // } + // } + // + + + // keys cited in the text + List cited = findCitedKeys( documentConnection ); + Map citeKeyToBibEntry = new HashMap<>(); + Map entries = findCitedEntries(databases, cited, citeKeyToBibEntry); + // entries are now in same order as cited + // + // + String[] citMarkers = new String[nRefMarks]; + // fill: + // citMarkers[i] = what goes in the text + + + // fill citMarkers + uniquefiers.clear(); + if (style.isCitationKeyCiteMarkers()) { + citMarkers = + rcmCitationMarkersForIsCitationKeyCiteMarkers(referenceMarkNames, + bibtexKeys, + citeKeyToBibEntry, + style ); + } else if (style.isNumberEntries()) { + if (style.isSortByPosition()) { + citMarkers = + rcmCitationMarkersForIsNumberEntriesIsSortByPosition( + referenceMarkNames, + bibtexKeys, + citeKeyToBibEntry, + style); + } else { + citMarkers = + rcmCitationMarkersForIsNumberEntriesNotSortByPosition(referenceMarkNames, + bibtexKeys, + entries, + style ); + } + } else { + + RcmCitationMarkersForNormalStyleResult nsr = + rcmCitationMarkersForNormalStyle( referenceMarkNames, + bibtexKeys, + citeKeyToBibEntry, + types, + entries, + uniquefiers, + style + ); + citMarkers = nsr.citMarkers; + bibtexKeys = nsr.bibtexKeys; } From 2dbbaf4e60c6dc1cbef9333c36e05846492aa6be Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 19:46:52 +0100 Subject: [PATCH 0294/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2ab92eec92a..dfb16d27279 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1549,6 +1549,18 @@ private class RcmCitationMarkersForNormalStyleResult{ } } + /** + * Produce citMarkers for normal (!isCitationKeyCiteMarkers && ! + * isNumberEntries) styles. + * + * @param referenceMarkNames + * @param bibtexKeysIn + * @param citeKeyToBibEntry + * @param types + * @param entries + * @param uniquefiers Filled with new values + * @param style + */ RcmCitationMarkersForNormalStyleResult rcmCitationMarkersForNormalStyle(List referenceMarkNames, String[][] bibtexKeysIn, @@ -1560,6 +1572,8 @@ private class RcmCitationMarkersForNormalStyleResult{ ) throws BibEntryNotFoundException { + uniquefiers.clear(); + assert( !style.isCitationKeyCiteMarkers() ); assert( !style.isNumberEntries() ); // Citations in (Au1, Au2 2000) form @@ -1796,15 +1810,15 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // keys cited in the text - List cited = findCitedKeys( documentConnection ); - Map citeKeyToBibEntry = new HashMap<>(); - Map entries = findCitedEntries(databases, cited, citeKeyToBibEntry); + List cited = findCitedKeys( documentConnection ); + Map citeKeyToBibEntry = new HashMap<>(); + Map entries = findCitedEntries(databases, cited, citeKeyToBibEntry); // entries are now in same order as cited - // - // - String[] citMarkers = new String[nRefMarks]; - // fill: - // citMarkers[i] = what goes in the text + + + // citMarkers[i] = what goes in the text + String[] citMarkers = new String[nRefMarks]; + // fill citMarkers From b6f94966fbb180c9505821ca3105aa282ed3f568 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 19:52:54 +0100 Subject: [PATCH 0295/1068] drop variable 'cited' --- .../org/jabref/gui/openoffice/OOBibBase.java | 31 ++++++------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index dfb16d27279..81fd07b3287 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1785,37 +1785,26 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // // Compute citation markers for all citations: final int nRefMarks = referenceMarkNames.size(); - int[] types = new int[nRefMarks]; - String[][] bibtexKeys = new String[nRefMarks][]; - // + // fill: // types[i] = ov.itcType // bibtexKeys[i] = ov.citedKeys.toArray() + int[] types = new int[nRefMarks]; + String[][] bibtexKeys = new String[nRefMarks][]; parseRefMarkNamesToArrays( referenceMarkNames, types, bibtexKeys ); - // - // An exception: numbered entries that are NOT sorted by position - // I think in this case we do not care, since numbering comes from - // order in cited - // - // if ( false ){ - // if (style.isNumberEntries() && ! style.isSortByPosition()) { - // XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); - // // isNumberEntries && !isSortByPosition - // referenceMarkNames = Arrays.asList(xReferenceMarks.getElementNames()); - // // Remove all reference marks that don't look like JabRef citations: - // referenceMarkNames = filterIsJabRefReferenceMarkName( referenceMarkNames ); - // } - // } - // - // keys cited in the text - List cited = findCitedKeys( documentConnection ); + Map citeKeyToBibEntry = new HashMap<>(); - Map entries = findCitedEntries(databases, cited, citeKeyToBibEntry); + Map entries = + findCitedEntries(databases, + findCitedKeys( documentConnection ), + citeKeyToBibEntry /* citeKeyToBibEntry filled here */ + ); // entries are now in same order as cited + // citMarkers[i] = what goes in the text String[] citMarkers = new String[nRefMarks]; From 4c50aed3e557913c85a4aef081669c464caf98ef Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 20:03:52 +0100 Subject: [PATCH 0296/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 81fd07b3287..64c19856c25 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1799,19 +1799,18 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne Map entries = findCitedEntries(databases, findCitedKeys( documentConnection ), - citeKeyToBibEntry /* citeKeyToBibEntry filled here */ + citeKeyToBibEntry /* citeKeyToBibEntry filled here + * TODO: avoid modifying parameters + * ModifiesParameter + */ ); // entries are now in same order as cited - - - // citMarkers[i] = what goes in the text + // citMarkers[i] = what goes in the text at referenceMark[i] String[] citMarkers = new String[nRefMarks]; - - // fill citMarkers - uniquefiers.clear(); + uniquefiers.clear(); /* ModifiesParameter */ if (style.isCitationKeyCiteMarkers()) { citMarkers = rcmCitationMarkersForIsCitationKeyCiteMarkers(referenceMarkNames, @@ -1821,8 +1820,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { citMarkers = - rcmCitationMarkersForIsNumberEntriesIsSortByPosition( - referenceMarkNames, + rcmCitationMarkersForIsNumberEntriesIsSortByPosition(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, style); @@ -1833,24 +1831,26 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne entries, style ); } - } else { + } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { RcmCitationMarkersForNormalStyleResult nsr = - rcmCitationMarkersForNormalStyle( referenceMarkNames, - bibtexKeys, - citeKeyToBibEntry, - types, - entries, - uniquefiers, - style - ); + rcmCitationMarkersForNormalStyle(referenceMarkNames, + bibtexKeys, + citeKeyToBibEntry, + types, + entries, + uniquefiers, + style ); citMarkers = nsr.citMarkers; bibtexKeys = nsr.bibtexKeys; } - // Refresh all reference marks with the citation markers we computed: - rcmApplyNewCitationMarkers(documentConnection, referenceMarkNames, citMarkers, types, style ); + rcmApplyNewCitationMarkers(documentConnection, + referenceMarkNames, + citMarkers, + types, + style ); return unresolvedKeysFromEntries( entries ); } From 82e2ebf61914b6fdb7132b9443eec6e17cc160ca Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 20:43:10 +0100 Subject: [PATCH 0297/1068] FindCitedEntriesResult. findCitedEntries return type --- .../org/jabref/gui/openoffice/OOBibBase.java | 81 ++++++++++++------- 1 file changed, 52 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 64c19856c25..0b3e4cf9865 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1062,11 +1062,32 @@ private List findCitedKeys( DocumentConnection documentConnection ) * - citedKey in the entry is the same as the original citedKey * */ - private Map findCitedEntries(List databases, - List citedKeys, - Map citeKeyToBibEntry - ) + private class FindCitedEntriesResult { + /* + * entries : LinkedHashMap with iteration order as the + * citedKeys parameter of findCitedEntries + */ + Map entries; + /* + * citeKeyToBibEntry : HashMap (no order) + */ + Map citeKeyToBibEntry; + + FindCitedEntriesResult( Map entries, + Map citeKeyToBibEntry ) { + this.entries = entries; + this.citeKeyToBibEntry = citeKeyToBibEntry; + } + } + + private FindCitedEntriesResult + findCitedEntries(List databases, + List citedKeys + ) { + Map citeKeyToBibEntry = new HashMap<>(); + + // LinkedHashMap, iteration order as in citedKeys Map entries = new LinkedHashMap<>(); for (String citedKey : citedKeys) { boolean found = false; @@ -1086,7 +1107,7 @@ private Map findCitedEntries(List databases, citeKeyToBibEntry.put( citedKey, x ); } } - return entries; + return new FindCitedEntriesResult( entries, citeKeyToBibEntry ); } /** @@ -1795,15 +1816,12 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne - Map citeKeyToBibEntry = new HashMap<>(); - Map entries = + FindCitedEntriesResult fce = findCitedEntries(databases, - findCitedKeys( documentConnection ), - citeKeyToBibEntry /* citeKeyToBibEntry filled here - * TODO: avoid modifying parameters - * ModifiesParameter - */ + findCitedKeys( documentConnection ) ); + // Map citeKeyToBibEntry = new HashMap<>(); + // Map entries = // entries are now in same order as cited // citMarkers[i] = what goes in the text at referenceMark[i] @@ -1815,20 +1833,20 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne citMarkers = rcmCitationMarkersForIsCitationKeyCiteMarkers(referenceMarkNames, bibtexKeys, - citeKeyToBibEntry, + fce.citeKeyToBibEntry, style ); } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { citMarkers = rcmCitationMarkersForIsNumberEntriesIsSortByPosition(referenceMarkNames, bibtexKeys, - citeKeyToBibEntry, + fce.citeKeyToBibEntry, style); } else { citMarkers = rcmCitationMarkersForIsNumberEntriesNotSortByPosition(referenceMarkNames, bibtexKeys, - entries, + fce.entries, style ); } } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { @@ -1836,9 +1854,9 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne RcmCitationMarkersForNormalStyleResult nsr = rcmCitationMarkersForNormalStyle(referenceMarkNames, bibtexKeys, - citeKeyToBibEntry, + fce.citeKeyToBibEntry, types, - entries, + fce.entries, uniquefiers, style ); citMarkers = nsr.citMarkers; @@ -1852,7 +1870,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne types, style ); - return unresolvedKeysFromEntries( entries ); + return unresolvedKeysFromEntries( fce.entries ); } @@ -1970,22 +1988,27 @@ public void rebuildBibTextSection(List databases, { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - List cited = findCitedKeys(documentConnection); - Map citeKeyToBibEntry = new HashMap<>(); - Map entries = - // Although entries are redefined without use, this also - // updates citeKeyToBibEntry - findCitedEntries(databases, cited, citeKeyToBibEntry); + FindCitedEntriesResult fce = + findCitedEntries(databases, + findCitedKeys( documentConnection ) + ); + + //List cited = findCitedKeys(documentConnection); + + Map entries; + // // Although entries are redefined without use, this also + // // updates citeKeyToBibEntry + // findCitedEntries(databases, cited, citeKeyToBibEntry); if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: entries = sortEntriesByRefMarkNames( - jabRefReferenceMarkNamesSortedByPosition, - citeKeyToBibEntry, - entries - ); + jabRefReferenceMarkNamesSortedByPosition, + fce.citeKeyToBibEntry, + fce.entries + ); } else { - entries = sortEntriesByComparator( entries, entryComparator ); + entries = sortEntriesByComparator( fce.entries, entryComparator ); } clearBibTextSectionContent2(documentConnection); populateBibTextSection(documentConnection, entries, style, this.xUniquefiers); From 3e054fb31e5c25833ad079daf3c26ede00203394 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 20:51:14 +0100 Subject: [PATCH 0298/1068] cleanup --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0b3e4cf9865..47fc6b81eb0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1820,9 +1820,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne findCitedEntries(databases, findCitedKeys( documentConnection ) ); - // Map citeKeyToBibEntry = new HashMap<>(); - // Map entries = - // entries are now in same order as cited + // fce.entries are now in same order as returned by findCitedKeys // citMarkers[i] = what goes in the text at referenceMark[i] String[] citMarkers = new String[nRefMarks]; @@ -1993,12 +1991,7 @@ public void rebuildBibTextSection(List databases, findCitedKeys( documentConnection ) ); - //List cited = findCitedKeys(documentConnection); - Map entries; - // // Although entries are redefined without use, this also - // // updates citeKeyToBibEntry - // findCitedEntries(databases, cited, citeKeyToBibEntry); if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: From 64b9d76a858e103d78597b228992b2d19bdcbde1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 22:38:07 +0100 Subject: [PATCH 0299/1068] add question --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 47fc6b81eb0..9063bb96fb5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2128,6 +2128,8 @@ private void createBibTextSection2(DocumentConnection documentConnection, XTextCursor mxDocCursor = documentConnection.xText.createTextCursor(); if (end) { mxDocCursor.gotoEnd(false); + } else { + // where does mxDocCursor point to in this branch? } OOUtil.insertParagraphBreak(documentConnection.xText, mxDocCursor); // Create a new TextSection from the document factory and access it's XNamed interface From ea3fb8891b0ab5525938740ba0aefdeb53e98ec9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 22:38:22 +0100 Subject: [PATCH 0300/1068] this.atEnd --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9063bb96fb5..dcd2fd251c3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2181,10 +2181,10 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) // just above. // Try to create. LOGGER.warn( "Could not get section '"+ OOBibBase.BIB_SECTION_NAME + "'", ex ); - createBibTextSection2(documentConnection, atEnd); + createBibTextSection2(documentConnection, this.atEnd); } } else { - createBibTextSection2(documentConnection, atEnd); + createBibTextSection2(documentConnection, this.atEnd); } } From 5e7ca8b24173ea5488be7d621b923e8410dbf679 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 22:38:45 +0100 Subject: [PATCH 0301/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index dcd2fd251c3..6695fefd732 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2293,7 +2293,9 @@ private void insertReferenceMark(DocumentConnection documentConnection, Object bookmark; try { - bookmark = documentConnection.mxDocFactory.createInstance("com.sun.star.text.ReferenceMark"); + bookmark = + documentConnection.mxDocFactory + .createInstance("com.sun.star.text.ReferenceMark"); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -2311,8 +2313,10 @@ private void insertReferenceMark(DocumentConnection documentConnection, String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | - WrappedTargetException ex) { + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { throw new UndefinedCharacterFormatException(charStyle); } } From 4301442c748fb2f7ce4351c13deef70e09c04b7a Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 22:38:57 +0100 Subject: [PATCH 0302/1068] comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6695fefd732..0c3f66e3b9a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2391,6 +2391,15 @@ private XNameAccess getBookmarks(DocumentConnection documentConnection) { return xNamedBookmarks; } + /** + * Taking ref=position.getStart(), italicize the range (ref+start,ref+end) + * + * @param position : position.getStart() is out reference point. + * @param italicize : if false, applies Bold, not Italic + * @param start + * @param end + * + */ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, int end) throws UnknownPropertyException, PropertyVetoException, From af7c8a391342ebc859378786ff20d0ccf5135873 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 22:48:09 +0100 Subject: [PATCH 0303/1068] extract lookupEntriesInDatabases --- .../org/jabref/gui/openoffice/OOBibBase.java | 123 ++++++++++++------ 1 file changed, 81 insertions(+), 42 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0c3f66e3b9a..8e3970f7c13 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2418,6 +2418,19 @@ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, } } + List lookupEntriesInDatabases(List keys, List databases){ + List entries = new ArrayList<>(); + for (String key : keys) { + for (BibDatabase database : databases) { + Optional entry = database.getEntryByCitationKey(key); + if (entry.isPresent()) { + entries.add(entry.get()); + break; + } + } + } + return entries; + } /** * GUI action */ @@ -2445,58 +2458,83 @@ public void combineCiteMarkers(List databases, OOBibStyle style) int piv = 0; boolean madeModifications = false; XNameAccess nameAccess = documentConnection.getReferenceMarks(); + while (piv < (names.size() - 1)) { - XTextRange range1 = unoQI(XTextContent.class, nameAccess.getByName(names.get(piv))) - .getAnchor().getEnd(); - XTextRange range2 = unoQI(XTextContent.class, nameAccess.getByName(names.get(piv + 1))) - .getAnchor().getStart(); + XTextRange range1 = + unoQI(XTextContent.class, + nameAccess.getByName(names.get(piv))) + .getAnchor() + .getEnd(); + + XTextRange range2 = + unoQI(XTextContent.class, + nameAccess.getByName(names.get(piv + 1))) + .getAnchor() + .getStart(); + if (range1.getText() != range2.getText()) { + /* piv and (piv+1) belong to different XText entities? + * Maybe to different footnotes? + * Cannot combine accross boundaries skip. + */ piv++; continue; } - XTextCursor mxDocCursor = range1.getText().createTextCursorByRange(range1); + + // Start from end of text for piv. + XTextCursor mxDocCursor = + range1.getText().createTextCursorByRange(range1); + + // Select next character, and more, as long as we can and + // do not reach stat of (piv+1), which we now know to be + // under the same XText entity. mxDocCursor.goRight((short) 1, true); boolean couldExpand = true; while (couldExpand && (compare.compareRegionEnds(mxDocCursor, range2) > 0)) { couldExpand = mxDocCursor.goRight((short) 1, true); } + + // Take what we selected String cursorText = mxDocCursor.getString(); - // Check if the string contains no line breaks and only whitespace: - if ((cursorText.indexOf('\n') == -1) && cursorText.trim().isEmpty()) { - - // If we are supposed to set character format for citations, test this before - // making any changes. This way we can throw an exception before any reference - // marks are removed, preventing damage to the user's document: - if (style.isFormatCitations()) { - XPropertySet xCursorProps = unoQI(XPropertySet.class, mxDocCursor); - String charStyle = style.getCitationCharacterFormat(); - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | - WrappedTargetException ex) { - // Setting the character format failed, so we throw an exception that - // will result in an error message for the user: - throw new UndefinedCharacterFormatException(charStyle); - } - } - List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); - keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(piv + 1))); - removeReferenceMark(documentConnection, names.get(piv)); - removeReferenceMark(documentConnection, names.get(piv + 1)); - List entries = new ArrayList<>(); - for (String key : keys) { - for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(key); - if (entry.isPresent()) { - entries.add(entry.get()); - break; - } - } + // Check if the string contains line breaks and any non-whitespace. + if ((cursorText.indexOf('\n') != -1) || !cursorText.trim().isEmpty()){ + piv++; + continue; + } + + // If we are supposed to set character format for citations, test this before + // making any changes. This way we can throw an exception before any reference + // marks are removed, preventing damage to the user's document: + if (style.isFormatCitations()) { + XPropertySet xCursorProps = unoQI(XPropertySet.class, mxDocCursor); + String charStyle = style.getCitationCharacterFormat(); + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + // Setting the character format failed, so we throw an exception that + // will result in an error message for the user: + throw new UndefinedCharacterFormatException(charStyle); } - Collections.sort(entries, new FieldComparator(StandardField.YEAR)); - String keyString = String.join(",", entries.stream().map(entry -> entry.getCitationKey().orElse("")) - .collect(Collectors.toList())); + } + + List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); + keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(piv + 1))); + removeReferenceMark(documentConnection, names.get(piv)); + removeReferenceMark(documentConnection, names.get(piv + 1)); + + List entries = lookupEntriesInDatabases(keys, databases); + Collections.sort(entries, new FieldComparator(StandardField.YEAR)); + String keyString = + String.join(",", + entries.stream() + .map(entry -> + entry.getCitationKey().orElse("")) + .collect(Collectors.toList())); + // Insert bookmark: String bName = getUniqueReferenceMarkName(documentConnection, keyString, @@ -2505,9 +2543,10 @@ public void combineCiteMarkers(List databases, OOBibStyle style) insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); names.set(piv + 1, bName); madeModifications = true; - } - piv++; - } + + piv++; + } // while + if (madeModifications) { updateSortedReferenceMarks(); refreshCiteMarkers(databases, style); From 12c037b0f7bb6a44618607660cd2e2852d54af4d Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 22:53:15 +0100 Subject: [PATCH 0304/1068] extract testFormatCitations --- .../org/jabref/gui/openoffice/OOBibBase.java | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8e3970f7c13..46e9594e363 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2431,6 +2431,24 @@ List lookupEntriesInDatabases(List keys, List dat } return entries; } + + private void testFormatCitations(XTextCursor mxDocCursor, OOBibStyle style ) + throws UndefinedCharacterFormatException + { + XPropertySet xCursorProps = unoQI(XPropertySet.class, mxDocCursor); + String charStyle = style.getCitationCharacterFormat(); + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + // Setting the character format failed, so we throw an exception that + // will result in an error message for the user: + throw new UndefinedCharacterFormatException(charStyle); + } + } + /** * GUI action */ @@ -2507,18 +2525,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // making any changes. This way we can throw an exception before any reference // marks are removed, preventing damage to the user's document: if (style.isFormatCitations()) { - XPropertySet xCursorProps = unoQI(XPropertySet.class, mxDocCursor); - String charStyle = style.getCitationCharacterFormat(); - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - // Setting the character format failed, so we throw an exception that - // will result in an error message for the user: - throw new UndefinedCharacterFormatException(charStyle); - } + testFormatCitations( mxDocCursor, style ); } List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); From c0d16a40dbd94e9d676bc3cb511a7d3d4b9b8969 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 23:02:40 +0100 Subject: [PATCH 0305/1068] use Collectors.joining, direct .addAll, --- .../org/jabref/gui/openoffice/OOBibBase.java | 35 ++++++++++--------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 46e9594e363..949c93a6038 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2528,30 +2528,31 @@ public void combineCiteMarkers(List databases, OOBibStyle style) testFormatCitations( mxDocCursor, style ); } - List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); - keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(piv + 1))); + List keys = + parseRefMarkNameToUniqueCitationKeys(names.get(piv)) + .addAll(parseRefMarkNameToUniqueCitationKeys(names.get(piv + 1))); + removeReferenceMark(documentConnection, names.get(piv)); removeReferenceMark(documentConnection, names.get(piv + 1)); List entries = lookupEntriesInDatabases(keys, databases); Collections.sort(entries, new FieldComparator(StandardField.YEAR)); + String keyString = - String.join(",", - entries.stream() - .map(entry -> - entry.getCitationKey().orElse("")) - .collect(Collectors.toList())); - - // Insert bookmark: - String bName = getUniqueReferenceMarkName(documentConnection, - keyString, - OOBibBase.AUTHORYEAR_PAR - ); - insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); - names.set(piv + 1, bName); - madeModifications = true; + entries.stream() + .map( c -> c.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); - piv++; + // Insert reference mark: + String bName = getUniqueReferenceMarkName(documentConnection, + keyString, + OOBibBase.AUTHORYEAR_PAR + ); + insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); + names.set(piv + 1, bName); // <- put in the next-to-be-processed position + madeModifications = true; + + piv++; } // while if (madeModifications) { From 28422cc353eac80599f215036c85962e743960c4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 25 Feb 2021 23:17:02 +0100 Subject: [PATCH 0306/1068] reformat unCombineCiteMarkers --- .../org/jabref/gui/openoffice/OOBibBase.java | 77 ++++++++++--------- 1 file changed, 40 insertions(+), 37 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 949c93a6038..8ab4e067d64 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2521,9 +2521,11 @@ public void combineCiteMarkers(List databases, OOBibStyle style) continue; } - // If we are supposed to set character format for citations, test this before - // making any changes. This way we can throw an exception before any reference - // marks are removed, preventing damage to the user's document: + // If we are supposed to set character format for + // citations, test this before making any changes. This + // way we can throw an exception before any reference + // marks are removed, preventing damage to the user's + // document: if (style.isFormatCitations()) { testFormatCitations( mxDocCursor, style ); } @@ -2590,50 +2592,51 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) int piv = 0; boolean madeModifications = false; XNameAccess nameAccess = documentConnection.getReferenceMarks(); + while (piv < (names.size())) { - XTextRange range1 = unoQI(XTextContent.class, nameAccess.getByName(names.get(piv))) + XTextRange range1 = + unoQI(XTextContent.class, + nameAccess.getByName(names.get(piv))) .getAnchor(); - XTextCursor mxDocCursor = range1.getText().createTextCursorByRange(range1); - // - // If we are supposed to set character format for citations, test this before - // making any changes. This way we can throw an exception before any reference - // marks are removed, preventing damage to the user's document: + XTextCursor mxDocCursor = + range1.getText().createTextCursorByRange(range1); + + // If we are supposed to set character format for + // citations, test this before making any changes. This + // way we can throw an exception before any reference + // marks are removed, preventing damage to the user's + // document: if (style.isFormatCitations()) { - XPropertySet xCursorProps = unoQI(XPropertySet.class, mxDocCursor); - String charStyle = style.getCitationCharacterFormat(); - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | - WrappedTargetException ex) { - // Setting the character format failed, so we throw an exception that - // will result in an error message for the user: - throw new UndefinedCharacterFormatException(charStyle); - } + testFormatCitations( mxDocCursor, style ); } List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); - if (keys.size() > 1) { - removeReferenceMark(documentConnection, names.get(piv)); - // - // Insert bookmark for each key - int last = keys.size() - 1; - int i = 0; - for (String key : keys) { - String bName = getUniqueReferenceMarkName(documentConnection, - key, - OOBibBase.AUTHORYEAR_PAR - ); - insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); + if (keys.size() <= 1) { + piv++; + continue; + } + + removeReferenceMark(documentConnection, names.get(piv)); + + // Insert bookmark for each key + int last = keys.size() - 1; + int i = 0; + for (String key : keys) { + String bName = getUniqueReferenceMarkName(documentConnection, + key, + OOBibBase.AUTHORYEAR_PAR + ); + insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); + mxDocCursor.collapseToEnd(); + if (i != last) { + mxDocCursor.setString(" "); mxDocCursor.collapseToEnd(); - if (i != last) { - mxDocCursor.setString(" "); - mxDocCursor.collapseToEnd(); - } - i++; } - madeModifications = true; + i++; } + madeModifications = true; + piv++; } if (madeModifications) { From b3c589958aa6e03d5b4af98917c00e89f4ac468d Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 12:30:19 +0100 Subject: [PATCH 0307/1068] removed duplicate TODO --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8ab4e067d64..8712b5d3f07 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2582,7 +2582,6 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - // TODO: doesn't work for citations in footnotes/tables List names = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); From 69e47d0efc193a31f4e6c94e8d0b55bf8465252c Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 12:44:08 +0100 Subject: [PATCH 0308/1068] remove empty comments (and some more) --- .../org/jabref/gui/openoffice/OOBibBase.java | 42 +++++++++---------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8712b5d3f07..e7c2a360dc0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -225,7 +225,7 @@ public boolean checkDocumentConnection(){ if (null == this.mxDocFactory ){ res = false; } if (null == this.userProperties ){ res = false; } if (null == this.propertySet ){ res = false; } - // + if ( ! res ){ return false; } @@ -574,7 +574,7 @@ public void selectDocument() // TODO: maybe we should install an event handler for document // close: addCloseListener - // + // Reference: // https://www.openoffice.org/api/docs/common/ref/com/sun/star/ // util/XCloseBroadcaster.html#addCloseListener } @@ -735,11 +735,11 @@ public void applyCitationEntries( List citationEntries ) { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); // Leave exceptions to the caller. - // + // Note: not catching exceptions here means nothing is applied // after the first problematic entry. We might catch and - // collect messages here. - // + // collect messages here. + // try { for (CitationEntry entry : citationEntries) { Optional pageInfo = entry.getPageInfo(); @@ -916,7 +916,7 @@ public void insertEntry(List entries, // Setting the character format failed, so we // throw an exception that will result in an // error message for the user. - // + // Before that, delete the space we inserted: cursor.goLeft((short) 1, true); cursor.setString(""); @@ -947,10 +947,9 @@ public void insertEntry(List entries, ); insertReferenceMark(documentConnection, bName, citeText, cursor, withText, style); } - // + // Move to the right of the space and remember this // position: we will come back here in the end. - // cursor.collapseToEnd(); cursor.goRight((short) 1, false); XTextRange position = cursor.getEnd(); @@ -1375,6 +1374,10 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, return citMarkers; } + /** + * Produce citation markers for the case of `numbered entries` + * that are not sorted by position. + */ private String[] rcmCitationMarkersForIsNumberEntriesNotSortByPosition( List referenceMarkNames, String[][] bibtexKeys, @@ -1388,33 +1391,25 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, assert( nRefMarks == bibtexKeys.length ); String[] citMarkers = new String[nRefMarks]; - // An exception: numbered entries that are NOT sorted by position - // exceptional_refmarkorder, entries and cited are sorted - //if (style.isNumberEntries() && ! style.isSortByPosition()) { - // // sort entries to order in bibliography Map sortedEntries = sortEntriesByComparator( entries, entryComparator ); + // adjust order of cited to match List sortedCited = new ArrayList( entries.size() ); sortedCited.clear(); for (BibEntry entry : sortedEntries.keySet()) { sortedCited.add(entry.getCitationKey().orElse(null)); } - //} final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); - // - // BibEntry[] cEntries = - // mapCiteKeysToBibEntryArray( bibtexKeys[i], citeKeyToBibEntry, namei, false ); - // assert (cEntries.length == bibtexKeys[i].length) ; List num ; num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , sortedCited ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); - } // for + } return citMarkers; } @@ -1665,7 +1660,7 @@ private class RcmCitationMarkersForNormalStyleResult{ // uses: nRefMarks, normCitMarkers, bibtexKeys, // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) // citeKeyToBibEntry, entries, types - // + if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { // Only for normal citations. Numbered citations and // citeKeys are already unique. @@ -1803,7 +1798,7 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // Normally we sort the reference marks according to their // order of appearance: List referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; - // + // Compute citation markers for all citations: final int nRefMarks = referenceMarkNames.size(); @@ -2176,9 +2171,10 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) // NoSuchElementException: is thrown by child access // methods of collections, if the addressed child does // not exist. - // - // We got this exception from ts.getByName() despite the ts.hasByName() check - // just above. + + // We got this exception from ts.getByName() despite + // the ts.hasByName() check just above. + // Try to create. LOGGER.warn( "Could not get section '"+ OOBibBase.BIB_SECTION_NAME + "'", ex ); createBibTextSection2(documentConnection, this.atEnd); From d50f303413981d507f69e0f3bf0d3e35c00d8950 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 12:46:11 +0100 Subject: [PATCH 0309/1068] piv renamed to pivot --- .../org/jabref/gui/openoffice/OOBibBase.java | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e7c2a360dc0..e737dda51b2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2469,38 +2469,38 @@ public void combineCiteMarkers(List databases, OOBibStyle style) final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, documentConnection.xText); - int piv = 0; + int pivot = 0; boolean madeModifications = false; XNameAccess nameAccess = documentConnection.getReferenceMarks(); - while (piv < (names.size() - 1)) { + while (pivot < (names.size() - 1)) { XTextRange range1 = unoQI(XTextContent.class, - nameAccess.getByName(names.get(piv))) + nameAccess.getByName(names.get(pivot))) .getAnchor() .getEnd(); XTextRange range2 = unoQI(XTextContent.class, - nameAccess.getByName(names.get(piv + 1))) + nameAccess.getByName(names.get(pivot + 1))) .getAnchor() .getStart(); if (range1.getText() != range2.getText()) { - /* piv and (piv+1) belong to different XText entities? + /* pivot and (pivot+1) belong to different XText entities? * Maybe to different footnotes? * Cannot combine accross boundaries skip. */ - piv++; + pivot++; continue; } - // Start from end of text for piv. + // Start from end of text for pivot. XTextCursor mxDocCursor = range1.getText().createTextCursorByRange(range1); // Select next character, and more, as long as we can and - // do not reach stat of (piv+1), which we now know to be + // do not reach stat of (pivot+1), which we now know to be // under the same XText entity. mxDocCursor.goRight((short) 1, true); boolean couldExpand = true; @@ -2513,7 +2513,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // Check if the string contains line breaks and any non-whitespace. if ((cursorText.indexOf('\n') != -1) || !cursorText.trim().isEmpty()){ - piv++; + pivot++; continue; } @@ -2527,11 +2527,11 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } List keys = - parseRefMarkNameToUniqueCitationKeys(names.get(piv)) - .addAll(parseRefMarkNameToUniqueCitationKeys(names.get(piv + 1))); + parseRefMarkNameToUniqueCitationKeys(names.get(pivot)) + .addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); - removeReferenceMark(documentConnection, names.get(piv)); - removeReferenceMark(documentConnection, names.get(piv + 1)); + removeReferenceMark(documentConnection, names.get(pivot)); + removeReferenceMark(documentConnection, names.get(pivot + 1)); List entries = lookupEntriesInDatabases(keys, databases); Collections.sort(entries, new FieldComparator(StandardField.YEAR)); @@ -2547,10 +2547,10 @@ public void combineCiteMarkers(List databases, OOBibStyle style) OOBibBase.AUTHORYEAR_PAR ); insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); - names.set(piv + 1, bName); // <- put in the next-to-be-processed position + names.set(pivot + 1, bName); // <- put in the next-to-be-processed position madeModifications = true; - piv++; + pivot++; } // while if (madeModifications) { @@ -2584,14 +2584,14 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, documentConnection.xText); - int piv = 0; + int pivot = 0; boolean madeModifications = false; XNameAccess nameAccess = documentConnection.getReferenceMarks(); - while (piv < (names.size())) { + while (pivot < (names.size())) { XTextRange range1 = unoQI(XTextContent.class, - nameAccess.getByName(names.get(piv))) + nameAccess.getByName(names.get(pivot))) .getAnchor(); XTextCursor mxDocCursor = @@ -2606,13 +2606,13 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) testFormatCitations( mxDocCursor, style ); } - List keys = parseRefMarkNameToUniqueCitationKeys(names.get(piv)); + List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); if (keys.size() <= 1) { - piv++; + pivot++; continue; } - removeReferenceMark(documentConnection, names.get(piv)); + removeReferenceMark(documentConnection, names.get(pivot)); // Insert bookmark for each key int last = keys.size() - 1; @@ -2632,7 +2632,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) } madeModifications = true; - piv++; + pivot++; } if (madeModifications) { updateSortedReferenceMarks(); From edab208a13dba6649d71639f235c0e2cbf381e11 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 12:48:54 +0100 Subject: [PATCH 0310/1068] mxDocCursor renamed to textCursor --- .../org/jabref/gui/openoffice/OOBibBase.java | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e737dda51b2..d7424bbcdaf 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2120,13 +2120,13 @@ private void createBibTextSection2(DocumentConnection documentConnection, CreationException { - XTextCursor mxDocCursor = documentConnection.xText.createTextCursor(); + XTextCursor textCursor = documentConnection.xText.createTextCursor(); if (end) { - mxDocCursor.gotoEnd(false); + textCursor.gotoEnd(false); } else { - // where does mxDocCursor point to in this branch? + // where does textCursor point to in this branch? } - OOUtil.insertParagraphBreak(documentConnection.xText, mxDocCursor); + OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); // Create a new TextSection from the document factory and access it's XNamed interface XNamed xChildNamed; try { @@ -2141,7 +2141,7 @@ private void createBibTextSection2(DocumentConnection documentConnection, xChildNamed.setName(OOBibBase.BIB_SECTION_NAME); // Access the Child_Section's XTextContent interface and insert it into the document XTextContent xChildSection = unoQI(XTextContent.class, xChildNamed); - documentConnection.xText.insertTextContent(mxDocCursor, xChildSection, false); + documentConnection.xText.insertTextContent(textCursor, xChildSection, false); } private void clearBibTextSectionContent2(DocumentConnection documentConnection) @@ -2428,10 +2428,10 @@ List lookupEntriesInDatabases(List keys, List dat return entries; } - private void testFormatCitations(XTextCursor mxDocCursor, OOBibStyle style ) + private void testFormatCitations(XTextCursor textCursor, OOBibStyle style ) throws UndefinedCharacterFormatException { - XPropertySet xCursorProps = unoQI(XPropertySet.class, mxDocCursor); + XPropertySet xCursorProps = unoQI(XPropertySet.class, textCursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); @@ -2496,20 +2496,20 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } // Start from end of text for pivot. - XTextCursor mxDocCursor = + XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); // Select next character, and more, as long as we can and // do not reach stat of (pivot+1), which we now know to be // under the same XText entity. - mxDocCursor.goRight((short) 1, true); + textCursor.goRight((short) 1, true); boolean couldExpand = true; - while (couldExpand && (compare.compareRegionEnds(mxDocCursor, range2) > 0)) { - couldExpand = mxDocCursor.goRight((short) 1, true); + while (couldExpand && (compare.compareRegionEnds(textCursor, range2) > 0)) { + couldExpand = textCursor.goRight((short) 1, true); } // Take what we selected - String cursorText = mxDocCursor.getString(); + String cursorText = textCursor.getString(); // Check if the string contains line breaks and any non-whitespace. if ((cursorText.indexOf('\n') != -1) || !cursorText.trim().isEmpty()){ @@ -2523,7 +2523,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // marks are removed, preventing damage to the user's // document: if (style.isFormatCitations()) { - testFormatCitations( mxDocCursor, style ); + testFormatCitations( textCursor, style ); } List keys = @@ -2546,7 +2546,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) keyString, OOBibBase.AUTHORYEAR_PAR ); - insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); + insertReferenceMark(documentConnection, bName, "tmp", textCursor, true, style); names.set(pivot + 1, bName); // <- put in the next-to-be-processed position madeModifications = true; @@ -2594,7 +2594,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) nameAccess.getByName(names.get(pivot))) .getAnchor(); - XTextCursor mxDocCursor = + XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); // If we are supposed to set character format for @@ -2603,7 +2603,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) // marks are removed, preventing damage to the user's // document: if (style.isFormatCitations()) { - testFormatCitations( mxDocCursor, style ); + testFormatCitations( textCursor, style ); } List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); @@ -2622,11 +2622,11 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) key, OOBibBase.AUTHORYEAR_PAR ); - insertReferenceMark(documentConnection, bName, "tmp", mxDocCursor, true, style); - mxDocCursor.collapseToEnd(); + insertReferenceMark(documentConnection, bName, "tmp", textCursor, true, style); + textCursor.collapseToEnd(); if (i != last) { - mxDocCursor.setString(" "); - mxDocCursor.collapseToEnd(); + textCursor.setString(" "); + textCursor.collapseToEnd(); } i++; } From 12c8752748e9f2e419781070f572be60757331b7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 12:51:01 +0100 Subject: [PATCH 0311/1068] bName renamed to newName --- .../org/jabref/gui/openoffice/OOBibBase.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d7424bbcdaf..2a4242c0331 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -886,14 +886,14 @@ public void insertEntry(List entries, ); // Generate unique bookmark-name int citationType = citationTypeFromOptions( withText, inParenthesis ); - String bName = getUniqueReferenceMarkName( documentConnection, + String newName = getUniqueReferenceMarkName( documentConnection, keyString, citationType ); // If we should store metadata for page info, do that now: if (pageInfo != null) { LOGGER.info("Storing page info: " + pageInfo); - documentConnection.setCustomProperty(bName, pageInfo); + documentConnection.setCustomProperty(newName, pageInfo); } // insert space @@ -945,7 +945,7 @@ public void insertEntry(List entries, null, // uniquefiers null // unlimAuthors ); - insertReferenceMark(documentConnection, bName, citeText, cursor, withText, style); + insertReferenceMark(documentConnection, newName, citeText, cursor, withText, style); } // Move to the right of the space and remember this @@ -2542,12 +2542,12 @@ public void combineCiteMarkers(List databases, OOBibStyle style) .collect(Collectors.joining(",")); // Insert reference mark: - String bName = getUniqueReferenceMarkName(documentConnection, + String newName = getUniqueReferenceMarkName(documentConnection, keyString, OOBibBase.AUTHORYEAR_PAR ); - insertReferenceMark(documentConnection, bName, "tmp", textCursor, true, style); - names.set(pivot + 1, bName); // <- put in the next-to-be-processed position + insertReferenceMark(documentConnection, newName, "tmp", textCursor, true, style); + names.set(pivot + 1, newName); // <- put in the next-to-be-processed position madeModifications = true; pivot++; @@ -2618,11 +2618,11 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) int last = keys.size() - 1; int i = 0; for (String key : keys) { - String bName = getUniqueReferenceMarkName(documentConnection, + String newName = getUniqueReferenceMarkName(documentConnection, key, OOBibBase.AUTHORYEAR_PAR ); - insertReferenceMark(documentConnection, bName, "tmp", textCursor, true, style); + insertReferenceMark(documentConnection, newName, "tmp", textCursor, true, style); textCursor.collapseToEnd(); if (i != last) { textCursor.setString(" "); From 16c9ecc2c03ffca659a98d992a4b2cce329355a8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 13:14:41 +0100 Subject: [PATCH 0312/1068] List.addAll is not chainable --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2a4242c0331..b428edff292 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2527,8 +2527,8 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } List keys = - parseRefMarkNameToUniqueCitationKeys(names.get(pivot)) - .addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); + parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); + keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); removeReferenceMark(documentConnection, names.get(pivot)); removeReferenceMark(documentConnection, names.get(pivot + 1)); From fad06a914b103646f964496201ce14f54b5609f4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 13:15:20 +0100 Subject: [PATCH 0313/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b428edff292..12f2fbfcd0e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2528,7 +2528,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); - keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); + keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); removeReferenceMark(documentConnection, names.get(pivot)); removeReferenceMark(documentConnection, names.get(pivot + 1)); From 5eeaa7d6c32213fc0871c0e7df9dce945b70ab8b Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 14:14:23 +0100 Subject: [PATCH 0314/1068] untabify OpenOfficePanel.java --- .../gui/openoffice/OpenOfficePanel.java | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 4d35579f3a6..48c023c4b6b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -201,13 +201,13 @@ private void initPanel() { if (!unresolvedKeys.isEmpty()) { dialogService - .showErrorDialogAndWait( - Localization.lang - ("Unable to synchronize bibliography"), - Localization.lang - ("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - unresolvedKeys.get(0) ) - ); + .showErrorDialogAndWait( + Localization.lang + ("Unable to synchronize bibliography"), + Localization.lang + ("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", + unresolvedKeys.get(0) ) + ); } } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); @@ -254,7 +254,7 @@ private void initPanel() { try { ooBase.unCombineCiteMarkers(getBaseList(), style); } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(); + showNoDocumentErrorMessage(); } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | @@ -326,8 +326,8 @@ private void exportEntries() { BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase); this.frame.addTab(databaseContext, true); - } catch (NoDocumentException ex ) { - showNoDocumentErrorMessage(); + } catch (NoDocumentException ex ) { + showNoDocumentErrorMessage(); } catch (BibEntryNotFoundException ex) { LOGGER.debug("BibEntry not found", ex); dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), @@ -516,14 +516,14 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP style = loader.getUsedStyle(); } ooBase.insertEntry(entries, - database, - getBaseList(), - style, - inParenthesis, - withText, - pageInfo, + database, + getBaseList(), + style, + inParenthesis, + withText, + pageInfo, ooPrefs.getSyncWhenCiting() - ); + ); } catch (FileNotFoundException ex) { dialogService.showErrorDialogAndWait( @@ -603,10 +603,10 @@ private boolean checkThatEntriesHaveKeys(List entries) { private void showConnectionLostErrorMessage() { dialogService.showErrorDialogAndWait - (Localization.lang("Connection lost"), - Localization.lang - ("Connection to OpenOffice/LibreOffice has been lost. " - + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); + (Localization.lang("Connection lost"), + Localization.lang + ("Connection to OpenOffice/LibreOffice has been lost. " + + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); } private void showNoDocumentErrorMessage() { From fd054f78f6676240904f61b90999e3534359e18c Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 14:30:48 +0100 Subject: [PATCH 0315/1068] reviewdog --- .../org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- .../jabref/gui/openoffice/OpenOfficePanel.java | 18 ++++++++---------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 12f2fbfcd0e..f1a2531d82f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -28,12 +28,12 @@ import org.jabref.logic.bibtex.comparator.FieldComparatorStack; import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; +import org.jabref.logic.openoffice.CitationEntry; import org.jabref.logic.openoffice.OOBibStyle; import org.jabref.logic.openoffice.OOPreFormatter; import org.jabref.logic.openoffice.OOUtil; import org.jabref.logic.openoffice.UndefinedBibtexEntry; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; -import org.jabref.logic.openoffice.CitationEntry; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; @@ -58,8 +58,8 @@ import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XController; import com.sun.star.frame.XDesktop; -import com.sun.star.frame.XModel; import com.sun.star.frame.XFrame; +import com.sun.star.frame.XModel; import com.sun.star.lang.DisposedException; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.Locale; diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 48c023c4b6b..e30b02649a2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -202,11 +202,11 @@ private void initPanel() { if (!unresolvedKeys.isEmpty()) { dialogService .showErrorDialogAndWait( - Localization.lang - ("Unable to synchronize bibliography"), - Localization.lang - ("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - unresolvedKeys.get(0) ) + Localization.lang("Unable to synchronize bibliography"), + Localization.lang("Your OpenOffice/LibreOffice document references" + + " the citation key '%0'," + + " which could not be found in your current library.", + unresolvedKeys.get(0)) ); } } catch (UndefinedCharacterFormatException ex) { @@ -326,7 +326,7 @@ private void exportEntries() { BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase); this.frame.addTab(databaseContext, true); - } catch (NoDocumentException ex ) { + } catch (NoDocumentException ex) { showNoDocumentErrorMessage(); } catch (BibEntryNotFoundException ex) { LOGGER.debug("BibEntry not found", ex); @@ -602,10 +602,8 @@ private boolean checkThatEntriesHaveKeys(List entries) { } private void showConnectionLostErrorMessage() { - dialogService.showErrorDialogAndWait - (Localization.lang("Connection lost"), - Localization.lang - ("Connection to OpenOffice/LibreOffice has been lost. " + dialogService.showErrorDialogAndWait(Localization.lang("Connection lost"), + Localization.lang("Connection to OpenOffice/LibreOffice has been lost. " + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); } From 0513b83572e42419b30f7199a01199ac49ad5015 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 14:39:58 +0100 Subject: [PATCH 0316/1068] reviewdog --- .../gui/openoffice/ManageCitationsDialogViewModel.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 7d810d8a032..c4fdf3e97fb 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -36,13 +36,12 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, throws NoSuchElementException, WrappedTargetException, UnknownPropertyException, - NoDocumentException - { + NoDocumentException { this.ooBase = ooBase; this.dialogService = dialogService; List cts = ooBase.getCitationEntries(); - for ( CitationEntry entry : cts ) { + for (CitationEntry entry : cts) { CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); } @@ -56,15 +55,14 @@ public void storeSettings() { .collect(Collectors.toList()); try { - ooBase.applyCitationEntries( citationEntries ); + ooBase.applyCitationEntries(citationEntries); } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException | IllegalArgumentException | NoDocumentException ex - ) - { + ) { LOGGER.warn("Problem modifying citation", ex); dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex); } From 36754633c2531b44ffa4fefe70ff46200c269433 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 14:40:36 +0100 Subject: [PATCH 0317/1068] untabify --- .../openoffice/ManageCitationsDialogViewModel.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index c4fdf3e97fb..fb74180ed8d 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -32,15 +32,15 @@ public class ManageCitationsDialogViewModel { private final DialogService dialogService; public ManageCitationsDialogViewModel(OOBibBase ooBase, - DialogService dialogService) - throws NoSuchElementException, - WrappedTargetException, - UnknownPropertyException, - NoDocumentException { + DialogService dialogService) + throws NoSuchElementException, + WrappedTargetException, + UnknownPropertyException, + NoDocumentException { this.ooBase = ooBase; this.dialogService = dialogService; - List cts = ooBase.getCitationEntries(); + List cts = ooBase.getCitationEntries(); for (CitationEntry entry : cts) { CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); @@ -55,7 +55,7 @@ public void storeSettings() { .collect(Collectors.toList()); try { - ooBase.applyCitationEntries(citationEntries); + ooBase.applyCitationEntries(citationEntries); } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException From 8d4fcd15a53d3d047c966511273713abbd9951fb Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 14:54:12 +0100 Subject: [PATCH 0318/1068] reviewdog --- .../org/jabref/gui/openoffice/OOBibBase.java | 62 ++++++++----------- 1 file changed, 27 insertions(+), 35 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f1a2531d82f..de8b8f131ce 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2223,17 +2223,17 @@ private void populateBibTextSection(DocumentConnection documentConnection, (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT) ); - { - String refParaFormat = - (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); - insertFullReferenceAtCursor(documentConnection, - cursor, - entries, - style, - refParaFormat, - uniquefiers - ); - } + + String refParaFormat = + (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); + insertFullReferenceAtCursor(documentConnection, + cursor, + entries, + style, + refParaFormat, + uniquefiers + ); + insertBookMark(documentConnection, OOBibBase.BIB_SECTION_END_NAME, cursor); } @@ -2241,12 +2241,11 @@ private XTextContent insertBookMark(DocumentConnection documentConnection, String name, XTextCursor position) throws IllegalArgumentException, - CreationException - { + CreationException { Object bookmark; try { - bookmark = ( documentConnection.mxDocFactory - .createInstance("com.sun.star.text.Bookmark") ); + bookmark = (documentConnection.mxDocFactory + .createInstance("com.sun.star.text.Bookmark")); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -2341,8 +2340,7 @@ private void insertReferenceMark(DocumentConnection documentConnection, private void removeReferenceMark(DocumentConnection documentConnection, String name) throws NoSuchElementException, WrappedTargetException, - NoDocumentException - { + NoDocumentException { XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); if (xReferenceMarks.hasByName(name)) { Object referenceMark = xReferenceMarks.getByName(name); @@ -2362,8 +2360,7 @@ private void removeReferenceMark(DocumentConnection documentConnection, String n private XTextRange getBookmarkRange(DocumentConnection documentConnection, String name) throws NoSuchElementException, - WrappedTargetException - { + WrappedTargetException { XNameAccess xNamedBookmarks = getBookmarks(documentConnection); // retrieve bookmark by name @@ -2400,8 +2397,7 @@ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, - WrappedTargetException - { + WrappedTargetException { XTextRange range = position.getStart(); XTextCursor cursor = position.getText().createTextCursorByRange(range); cursor.goRight((short) start, false); @@ -2414,7 +2410,7 @@ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, } } - List lookupEntriesInDatabases(List keys, List databases){ + List lookupEntriesInDatabases(List keys, List databases) { List entries = new ArrayList<>(); for (String key : keys) { for (BibDatabase database : databases) { @@ -2428,9 +2424,8 @@ List lookupEntriesInDatabases(List keys, List dat return entries; } - private void testFormatCitations(XTextCursor textCursor, OOBibStyle style ) - throws UndefinedCharacterFormatException - { + private void testFormatCitations(XTextCursor textCursor, OOBibStyle style) + throws UndefinedCharacterFormatException { XPropertySet xCursorProps = unoQI(XPropertySet.class, textCursor); String charStyle = style.getCitationCharacterFormat(); try { @@ -2458,8 +2453,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) PropertyVetoException, CreationException, BibEntryNotFoundException, - NoDocumentException - { + NoDocumentException { DocumentConnection documentConnection = this.xDocumentConnection; // TODO: doesn't work for citations in footnotes/tables @@ -2512,7 +2506,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) String cursorText = textCursor.getString(); // Check if the string contains line breaks and any non-whitespace. - if ((cursorText.indexOf('\n') != -1) || !cursorText.trim().isEmpty()){ + if ((cursorText.indexOf('\n') != -1) || !cursorText.trim().isEmpty()) { pivot++; continue; } @@ -2523,7 +2517,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // marks are removed, preventing damage to the user's // document: if (style.isFormatCitations()) { - testFormatCitations( textCursor, style ); + testFormatCitations(textCursor, style); } List keys = @@ -2538,7 +2532,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) String keyString = entries.stream() - .map( c -> c.getCitationKey().orElse("")) + .map(c -> c.getCitationKey().orElse("")) .collect(Collectors.joining(",")); // Insert reference mark: @@ -2574,8 +2568,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) PropertyVetoException, CreationException, BibEntryNotFoundException, - NoDocumentException - { + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); List names = @@ -2603,7 +2596,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) // marks are removed, preventing damage to the user's // document: if (style.isFormatCitations()) { - testFormatCitations( textCursor, style ); + testFormatCitations(textCursor, style); } List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); @@ -2646,8 +2639,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) public BibDatabase generateDatabase(List databases) throws NoSuchElementException, WrappedTargetException, - NoDocumentException - { + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); BibDatabase resultDatabase = new BibDatabase(); From 093ddc82d8da27a13359686e751ba8a85673697d Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 15:32:58 +0100 Subject: [PATCH 0319/1068] reviewdog --- .../org/jabref/gui/openoffice/OOBibBase.java | 147 ++++++++---------- 1 file changed, 69 insertions(+), 78 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index de8b8f131ce..07c5c2f72e3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1522,9 +1522,9 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, } private static void parseRefMarkNamesToArrays( List referenceMarkNames, int[] types, String[][] bibtexKeys ) { - final int nRefMarks = referenceMarkNames.size(); - assert( types.length == nRefMarks ); - assert( bibtexKeys.length == nRefMarks ); + final int nRefMarks = referenceMarkNames.size(); + assert ( types.length == nRefMarks ); + assert ( bibtexKeys.length == nRefMarks ); for (int i = 0; i < nRefMarks; i++) { final String namei = referenceMarkNames.get(i); Optional op = parseRefMarkName( namei ); @@ -1538,7 +1538,7 @@ private static void parseRefMarkNamesToArrays( List referenceMarkNames, } } - private static List unresolvedKeysFromEntries( Map entries ){ + private static List unresolvedKeysFromEntries( Map entries ) { // Collect and return unresolved citation keys. // uses: entries List unresolvedKeys = new ArrayList<>(); @@ -1554,7 +1554,7 @@ private static List unresolvedKeysFromEntries( Map referenceMarkNames, String[][] bibtexKeysIn, Map citeKeyToBibEntry, - int [] types, + int[] types, Map entries, final Map uniquefiers, OOBibStyle style @@ -1603,7 +1603,7 @@ private class RcmCitationMarkersForNormalStyleResult{ Arrays.stream( bibtexKeysIn ) .map( bibtexKeysOfARefererenceMark -> Arrays.stream( bibtexKeysOfARefererenceMark ) - .map( key -> citeKeyToBibEntry.get(key) ) + .map( key -> citeKeyToBibEntry.get(key) ) .sorted( comparatorForMulticite(style) ) // sort within referenceMark .toArray( BibEntry[]::new ) ) @@ -1615,14 +1615,14 @@ private class RcmCitationMarkersForNormalStyleResult{ .map( cEntries -> Arrays.stream( cEntries ) .map( ce -> ce.getCitationKey().orElse(null) ) - .toArray( String[]::new ) + .toArray(String[]::new) ) - .toArray( String[][]::new ); + .toArray(String[][]::new); - assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry ); - assert( bibtexKeys.length == nRefMarks ); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); + assert(bibtexKeys.length == nRefMarks); - String[] citMarkers = new String[nRefMarks]; + String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { BibEntry[] cEntries = cEntriesForAll[i]; int type = types[i]; @@ -1641,7 +1641,7 @@ private class RcmCitationMarkersForNormalStyleResult{ // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: normCitMarkers[i] = - Arrays.stream( cEntries ) + Arrays.stream(cEntries) .map( ce -> style.getCitationMarker( Collections.singletonList(ce), entries, // database @@ -1650,7 +1650,7 @@ private class RcmCitationMarkersForNormalStyleResult{ new int[] {-1} // unlimAuthors ) ) - .toArray( String[]::new ); + .toArray(String[]::new); } uniquefiers.clear(); @@ -1723,10 +1723,10 @@ private class RcmCitationMarkersForNormalStyleResult{ boolean needsChange = false; int[] firstLimAuthors = new int[nCitedEntries]; String[] uniquif = new String[nCitedEntries]; - BibEntry[] cEntries = mapCiteKeysToBibEntryArray( bibtexKeys[i], - citeKeyToBibEntry, - namei); - cEntries = mapUndefinedBibentriesToNull( cEntries ); + BibEntry[] cEntries = mapCiteKeysToBibEntryArray(bibtexKeys[i], + citeKeyToBibEntry, + namei); + cEntries = mapUndefinedBibentriesToNull(cEntries); for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; @@ -1767,16 +1767,16 @@ private class RcmCitationMarkersForNormalStyleResult{ if (needsChange) { citMarkers[i] = - style.getCitationMarker( Arrays.asList(cEntries), - entries, - types[i] == OOBibBase.AUTHORYEAR_PAR, - uniquif, - firstLimAuthors - ); + style.getCitationMarker(Arrays.asList(cEntries), + entries, + types[i] == OOBibBase.AUTHORYEAR_PAR, + uniquif, + firstLimAuthors + ); } } // for i } // if normalStyle - return new RcmCitationMarkersForNormalStyleResult( citMarkers, bibtexKeys ); + return new RcmCitationMarkersForNormalStyleResult(citMarkers, bibtexKeys); } private List refreshCiteMarkersInternal(DocumentConnection documentConnection, @@ -1800,25 +1800,23 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne List referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; // Compute citation markers for all citations: - final int nRefMarks = referenceMarkNames.size(); + final int nRefMarks = referenceMarkNames.size(); // fill: // types[i] = ov.itcType // bibtexKeys[i] = ov.citedKeys.toArray() int[] types = new int[nRefMarks]; String[][] bibtexKeys = new String[nRefMarks][]; - parseRefMarkNamesToArrays( referenceMarkNames, types, bibtexKeys ); - - + parseRefMarkNamesToArrays(referenceMarkNames, types, bibtexKeys); FindCitedEntriesResult fce = findCitedEntries(databases, - findCitedKeys( documentConnection ) + findCitedKeys(documentConnection) ); // fce.entries are now in same order as returned by findCitedKeys // citMarkers[i] = what goes in the text at referenceMark[i] - String[] citMarkers = new String[nRefMarks]; + String[] citMarkers = new String[nRefMarks]; // fill citMarkers uniquefiers.clear(); /* ModifiesParameter */ @@ -1827,7 +1825,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne rcmCitationMarkersForIsCitationKeyCiteMarkers(referenceMarkNames, bibtexKeys, fce.citeKeyToBibEntry, - style ); + style + ); } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { citMarkers = @@ -1840,7 +1839,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne rcmCitationMarkersForIsNumberEntriesNotSortByPosition(referenceMarkNames, bibtexKeys, fce.entries, - style ); + style + ); } } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { @@ -1851,7 +1851,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne types, fce.entries, uniquefiers, - style ); + style + ); citMarkers = nsr.citMarkers; bibtexKeys = nsr.bibtexKeys; } @@ -1861,13 +1862,11 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne referenceMarkNames, citMarkers, types, - style ); + style); - return unresolvedKeysFromEntries( fce.entries ); + return unresolvedKeysFromEntries(fce.entries); } - - // Position as in a document on the screen. // Probably to get the correct order with // referenceMarks in footnotes @@ -1890,7 +1889,6 @@ private static Point findPositionOfTextRange(XTextViewCursor cursor, XTextRange List names = getJabRefReferenceMarkNames(documentConnection); - // find coordinates List positions = new ArrayList<>(names.size()); { @@ -1947,8 +1945,8 @@ public void updateSortedReferenceMarks() * * @return unresolvedKeys */ - public List updateDocumentActionHelper(List databases, - OOBibStyle style) + public List updateDocumentActionHelper(List databases, + OOBibStyle style) throws NoSuchElementException, WrappedTargetException, IllegalArgumentException, @@ -1959,8 +1957,7 @@ public List updateDocumentActionHelper(List databases, NoDocumentException, UndefinedCharacterFormatException, BibEntryNotFoundException, - IOException - { + IOException { updateSortedReferenceMarks(); List unresolvedKeys = refreshCiteMarkers(databases, style); rebuildBibTextSection(databases, style); @@ -1977,13 +1974,12 @@ public void rebuildBibTextSection(List databases, PropertyVetoException, UnknownPropertyException, UndefinedParagraphFormatException, - NoDocumentException - { + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); FindCitedEntriesResult fce = findCitedEntries(databases, - findCitedKeys( documentConnection ) + findCitedKeys(documentConnection) ); Map entries; @@ -1996,16 +1992,15 @@ public void rebuildBibTextSection(List databases, fce.entries ); } else { - entries = sortEntriesByComparator( fce.entries, entryComparator ); + entries = sortEntriesByComparator(fce.entries, entryComparator); } clearBibTextSectionContent2(documentConnection); populateBibTextSection(documentConnection, entries, style, this.xUniquefiers); } SortedMap - sortEntriesByComparator( Map entries, - Comparator entryComparator ) - { + sortEntriesByComparator(Map entries, + Comparator entryComparator) { SortedMap newMap = new TreeMap<>(entryComparator); for (Map.Entry kv : entries.entrySet()) { newMap.put(kv.getKey(), @@ -2025,24 +2020,25 @@ public void rebuildBibTextSection(List databases, sortEntriesByRefMarkNames(List referenceMarkNames, Map citeKeyToBibEntry, Map entries - ) - { + ) { // LinkedHashMap: iteration order is insertion-order, not // affected if a key is re-inserted. Map newList = new LinkedHashMap<>(); for (String name : referenceMarkNames) { - Optional op = parseRefMarkName( name ); - if ( ! op.isPresent() ){ continue; } + Optional op = parseRefMarkName(name); + if (!op.isPresent()) { + continue; + } List keys = op.get().citedKeys; // no need to look in the database again for (String key : keys) { - BibEntry origEntry = citeKeyToBibEntry.get(key); + BibEntry origEntry = citeKeyToBibEntry.get(key); if (origEntry != null) { if (!newList.containsKey(origEntry)) { - BibDatabase database = entries.get( origEntry ); + BibDatabase database = entries.get(origEntry); newList.put(origEntry, database); } } else { @@ -2055,7 +2051,6 @@ public void rebuildBibTextSection(List databases, return newList; } - /** * Only called from populateBibTextSection (and that from rebuildBibTextSection) */ @@ -2069,8 +2064,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, IllegalArgumentException, UnknownPropertyException, PropertyVetoException, - WrappedTargetException - { + WrappedTargetException { int number = 1; for (Map.Entry entry : entries.entrySet()) { @@ -2102,8 +2096,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // insert the actual details. Layout layout = style.getReferenceFormat(entry.getKey().getType()); layout.setPostFormatter(POSTFORMATTER); - OOUtil.insertFullReferenceAtCurrentLocation - (documentConnection.xText, + OOUtil.insertFullReferenceAtCurrentLocation( + documentConnection.xText, cursor, layout, parFormat, @@ -2117,8 +2111,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, private void createBibTextSection2(DocumentConnection documentConnection, boolean end) throws IllegalArgumentException, - CreationException - { + CreationException { XTextCursor textCursor = documentConnection.xText.createTextCursor(); if (end) { @@ -2148,8 +2141,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) throws NoSuchElementException, WrappedTargetException, IllegalArgumentException, - CreationException - { + CreationException { // Check if the section exists: XTextSectionsSupplier supplier = @@ -2167,7 +2159,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) cursor.gotoRange(section.getAnchor(), false); cursor.setString(""); return; - } catch ( NoSuchElementException ex ) { + } catch (NoSuchElementException ex) { // NoSuchElementException: is thrown by child access // methods of collections, if the addressed child does // not exist. @@ -2176,7 +2168,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) // the ts.hasByName() check just above. // Try to create. - LOGGER.warn( "Could not get section '"+ OOBibBase.BIB_SECTION_NAME + "'", ex ); + LOGGER.warn("Could not get section '" + OOBibBase.BIB_SECTION_NAME + "'", ex); createBibTextSection2(documentConnection, this.atEnd); } } else { @@ -2197,27 +2189,26 @@ private void populateBibTextSection(DocumentConnection documentConnection, UnknownPropertyException, UndefinedParagraphFormatException, IllegalArgumentException, - CreationException - { + CreationException { XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); XTextSection section = - ( (XTextSection) - ((Any) supplier - .getTextSections() - .getByName(OOBibBase.BIB_SECTION_NAME) - ) - .getObject() - ); + ((XTextSection) + ((Any) supplier + .getTextSections() + .getByName(OOBibBase.BIB_SECTION_NAME) + ) + .getObject() + ); XTextCursor cursor = documentConnection.xText .createTextCursorByRange(section.getAnchor()); - OOUtil.insertTextAtCurrentLocation - (documentConnection.xText, + OOUtil.insertTextAtCurrentLocation( + documentConnection.xText, cursor, (String) style.getProperty(OOBibStyle.TITLE), (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT) From 2c89e0e2a4e58beae7c3df8efae3e2d22ccc5fde Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 15:34:44 +0100 Subject: [PATCH 0320/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 53 ++++++++++--------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 07c5c2f72e3..66a32cf37e6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1521,37 +1521,40 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, } } - private static void parseRefMarkNamesToArrays( List referenceMarkNames, int[] types, String[][] bibtexKeys ) { - final int nRefMarks = referenceMarkNames.size(); - assert ( types.length == nRefMarks ); - assert ( bibtexKeys.length == nRefMarks ); - for (int i = 0; i < nRefMarks; i++) { - final String namei = referenceMarkNames.get(i); - Optional op = parseRefMarkName( namei ); - if ( !op.isPresent() ) { - assert( false ); - continue; - } - ParsedRefMark ov = op.get(); - types[i] = ov.itcType; // Remember the itcType in case we need to uniquefy. - bibtexKeys[i] = ov.citedKeys.stream().toArray(String[]::new); + private static void parseRefMarkNamesToArrays( List referenceMarkNames, + int[] types, + String[][] bibtexKeys ) + { + final int nRefMarks = referenceMarkNames.size(); + assert ( types.length == nRefMarks ); + assert ( bibtexKeys.length == nRefMarks ); + for (int i = 0; i < nRefMarks; i++) { + final String namei = referenceMarkNames.get(i); + Optional op = parseRefMarkName( namei ); + if ( !op.isPresent() ) { + assert( false ); + continue; } + ParsedRefMark ov = op.get(); + types[i] = ov.itcType; // Remember the itcType in case we need to uniquefy. + bibtexKeys[i] = ov.citedKeys.stream().toArray(String[]::new); } + } - private static List unresolvedKeysFromEntries( Map entries ) { - // Collect and return unresolved citation keys. - // uses: entries - List unresolvedKeys = new ArrayList<>(); - for (BibEntry entry : entries.keySet()) { - if (entry instanceof UndefinedBibtexEntry) { - String key = ((UndefinedBibtexEntry) entry).getKey(); - if (!unresolvedKeys.contains(key)) { - unresolvedKeys.add(key); - } + private static List unresolvedKeysFromEntries( Map entries ) { + // Collect and return unresolved citation keys. + // uses: entries + List unresolvedKeys = new ArrayList<>(); + for (BibEntry entry : entries.keySet()) { + if (entry instanceof UndefinedBibtexEntry) { + String key = ((UndefinedBibtexEntry) entry).getKey(); + if (!unresolvedKeys.contains(key)) { + unresolvedKeys.add(key); } } - return unresolvedKeys; } + return unresolvedKeys; + } private class RcmCitationMarkersForNormalStyleResult { From d67c230e2d1c1117094728db2cdcfc04cb324685 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 15:36:56 +0100 Subject: [PATCH 0321/1068] reviewdog --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 66a32cf37e6..3619f8ffc36 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1407,7 +1407,7 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, final String namei = referenceMarkNames.get(i); List num ; - num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]) , sortedCited ); + num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]), sortedCited ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } return citMarkers; @@ -1422,10 +1422,10 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, * @return the (1-based) indices of the cited keys, -1 if a key is not found. * Returns Collections.emptyList() if the ref name could not be resolved as a citation. */ - private static List findCitedEntryIndices(List keysCitedHere, + private static List findCitedEntryIndices(List keysCitedHere, List orderedCiteKeys) { - List result = new ArrayList<>(keysCitedHere.size()); + List result = new ArrayList<>(keysCitedHere.size()); for (String key : keysCitedHere) { int ind = orderedCiteKeys.indexOf(key); result.add(ind == -1 ? -1 : 1 + ind); @@ -1451,7 +1451,8 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, List referenceMarkNames, String[] citMarkers, int[] types, - OOBibStyle style ) + OOBibStyle style + ) throws NoDocumentException, NoSuchElementException, UndefinedCharacterFormatException, @@ -1460,9 +1461,9 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, WrappedTargetException, PropertyVetoException { - final int nRefMarks = referenceMarkNames.size(); - assert( citMarkers.length == nRefMarks ); - assert( types.length == nRefMarks ); + final int nRefMarks = referenceMarkNames.size(); + assert ( citMarkers.length == nRefMarks ); + assert ( types.length == nRefMarks ); XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); final boolean hadBibSection = From 44412bd3967f621f8d7cd1c3a36454959ad677ce Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 15:57:43 +0100 Subject: [PATCH 0322/1068] reviewdog --- .../org/jabref/gui/openoffice/OOBibBase.java | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3619f8ffc36..4520b5eb63e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1256,17 +1256,17 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ OOBibStyle style ) throws BibEntryNotFoundException { - assert( style.isCitationKeyCiteMarkers() ); + assert style.isCitationKeyCiteMarkers(); final int nRefMarks = referenceMarkNames.size(); - assert( nRefMarks == bibtexKeys.length ); + assert nRefMarks == bibtexKeys.length; assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeys, citeKeyToBibEntry ); String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { citMarkers[i] = Arrays.stream( bibtexKeys[i] ) - .map( key -> citeKeyToBibEntry.get(key) ) + .map( key -> citeKeyToBibEntry.get(key) ) .map( (c) -> c.getCitationKey().orElse("") ) .collect(Collectors.joining(",")); } @@ -1281,7 +1281,7 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ private static class CitationNumberingState { public Map numbers; public int lastNum; - CitationNumberingState(){ + CitationNumberingState() { // For numbered citation style. Map( citedKey, number ) Map numbers = new HashMap<>(); int lastNum = 0; @@ -1289,7 +1289,7 @@ private static class CitationNumberingState { /** * The first call returns 1. */ - public int getOrAllocateNumber( String key ){ + public int getOrAllocateNumber( String key ) { int result; if (numbers.containsKey(key)) { // Already seen @@ -1313,7 +1313,7 @@ public int getOrAllocateNumber( String key ){ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, CitationNumberingState cns ) { - if (ce instanceof UndefinedBibtexEntry){ + if (ce instanceof UndefinedBibtexEntry) { return (-1); } @@ -1338,21 +1338,21 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, * Numbering is according to first encounter in bibtexKeys[i][j] (for(i){for(j){}} ) * */ - private static String [] + private static String[] rcmCitationMarkersForIsNumberEntriesIsSortByPosition( List referenceMarkNames, String[][] bibtexKeys, - Map citeKeyToBibEntry, + Map citeKeyToBibEntry, OOBibStyle style ) throws BibEntryNotFoundException { - assert (style.isNumberEntries()); - assert (style.isSortByPosition()); + assert style.isNumberEntries(); + assert style.isSortByPosition(); final int nRefMarks = referenceMarkNames.size(); - assert( nRefMarks == bibtexKeys.length ); + assert ( nRefMarks == bibtexKeys.length ); assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeys, citeKeyToBibEntry ); - String[] citMarkers = new String[nRefMarks]; + String[] citMarkers = new String[nRefMarks]; CitationNumberingState cns = new CitationNumberingState(); @@ -1384,12 +1384,12 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, Map entries, OOBibStyle style ) { - assert( style.isNumberEntries() ); - assert( ! style.isSortByPosition() ); + assert style.isNumberEntries(); + assert !style.isSortByPosition(); final int nRefMarks = referenceMarkNames.size(); - assert( nRefMarks == bibtexKeys.length ); - String[] citMarkers = new String[nRefMarks]; + assert ( nRefMarks == bibtexKeys.length ); + String[] citMarkers = new String[nRefMarks]; // sort entries to order in bibliography Map sortedEntries = sortEntriesByComparator( entries, entryComparator ); From 426203563d8c4d0d3cf63ee7f280b18e54a8cfee Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 15:57:58 +0100 Subject: [PATCH 0323/1068] join decl and assignment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4520b5eb63e..b1ef432226d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1406,8 +1406,8 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); - List num ; - num = findCitedEntryIndices( Arrays.asList(bibtexKeys[i]), sortedCited ); + List num = + findCitedEntryIndices( Arrays.asList(bibtexKeys[i]), sortedCited ); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } return citMarkers; From 9e9433d566d2078d0671f84553094c71d47da7d1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 15:58:40 +0100 Subject: [PATCH 0324/1068] doc, explanation in assert --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b1ef432226d..0918265faaa 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1522,6 +1522,14 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, } } + /** + * For each name in referenceMarkNames fill types[i] and + * bibtexKeys[i] with values parsed from referenceMarkNames.get(i) + * + * @param referenceMarkNames Should only contain parsable names. + * @param types OUT Preallocated, same length as referenceMarkNames. + * @param bibtexKeys OUT First level must be same length as referenceMarkNames. + */ private static void parseRefMarkNamesToArrays( List referenceMarkNames, int[] types, String[][] bibtexKeys ) @@ -1533,7 +1541,11 @@ private static void parseRefMarkNamesToArrays( List referenceMarkNames, final String namei = referenceMarkNames.get(i); Optional op = parseRefMarkName( namei ); if ( !op.isPresent() ) { - assert( false ); + // We have a problem. We want types[i] and bibtexKeys[i] + // to correspond to referenceMarkNames.get(i). + // And do not want null in bibtexKeys (or error code in types) + // on return. + assert false : "parseRefMarkNamesToArrays expects parsable referenceMarkNames"; continue; } ParsedRefMark ov = op.get(); From 0bcb9eb53b81a8151c3b5f21d374c06fd0af1a82 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 16:00:22 +0100 Subject: [PATCH 0325/1068] assert is not a function --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0918265faaa..2dee7320ca9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1238,7 +1238,7 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ throws BibEntryNotFoundException { final int nRefMarks = referenceMarkNames.size(); - assert( nRefMarks == bibtexKeys.length ); + assert ( nRefMarks == bibtexKeys.length ); for (int i = 0; i < nRefMarks; i++) { final String referenceMarkName = referenceMarkNames.get(i); @@ -1606,13 +1606,13 @@ private class RcmCitationMarkersForNormalStyleResult { { uniquefiers.clear(); - assert( !style.isCitationKeyCiteMarkers() ); - assert( !style.isNumberEntries() ); + assert !style.isCitationKeyCiteMarkers(); + assert !style.isNumberEntries(); // Citations in (Au1, Au2 2000) form final int nRefMarks = referenceMarkNames.size(); - assert( bibtexKeysIn.length == nRefMarks ); - assert( types.length == nRefMarks ); + assert ( bibtexKeysIn.length == nRefMarks ); + assert ( types.length == nRefMarks ); assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry ); BibEntry[][] cEntriesForAll = @@ -1636,7 +1636,7 @@ private class RcmCitationMarkersForNormalStyleResult { .toArray(String[][]::new); assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); - assert(bibtexKeys.length == nRefMarks); + assert (bibtexKeys.length == nRefMarks); String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { From da1e0a844c295363d862c1a759446f4edbbe453d Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 16:03:40 +0100 Subject: [PATCH 0326/1068] add TODO comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2dee7320ca9..7aac2d8f566 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1189,6 +1189,7 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ } } + // TODO: is mapCiteKeysToBibEntryArray is still needed? private static BibEntry[] mapCiteKeysToBibEntryArray( String[] keys, // citeKeys Map citeKeyToBibEntry, From 7db2d17abe69b07bbd366d2c890d449c15046846 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 16:04:07 +0100 Subject: [PATCH 0327/1068] reviewdog --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7aac2d8f566..c9f7dc8398a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1204,7 +1204,7 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ // process keys BibEntry[] cEntries = Arrays.stream( keys ) - .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) + .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) .toArray( BibEntry[]::new ); return cEntries; @@ -1215,11 +1215,11 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ for (int j = 0; j < keys.length; j++) { String kj = keys[j]; BibEntry tmpEntry = citeKeyToBibEntry.get( kj ); - if ( tmpEntry == null ){ + if ( tmpEntry == null ) { LOGGER.info("Citation key not found: '" + kj + '\''); LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); String msg = Localization.lang("Could not resolve BibTeX entry" - +" for citation marker '%0'.", + + " for citation marker '%0'.", referenceMarkName ); throw new BibEntryNotFoundException(referenceMarkName, msg); @@ -1235,7 +1235,7 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ private static void assertAllKeysInCiteKeyToBibEntry(List referenceMarkNames, String[][] bibtexKeys, - Map citeKeyToBibEntry) + Map citeKeyToBibEntry) throws BibEntryNotFoundException { final int nRefMarks = referenceMarkNames.size(); @@ -1253,7 +1253,7 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ private static String[] rcmCitationMarkersForIsCitationKeyCiteMarkers( List referenceMarkNames, String[][] bibtexKeys, - Map citeKeyToBibEntry, + Map citeKeyToBibEntry, OOBibStyle style ) throws BibEntryNotFoundException { From d7dbe71c6d791ad31b38b178ec5d8e9d71bf6596 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 16:35:00 +0100 Subject: [PATCH 0328/1068] reviewdog, move method after constructor --- .../org/jabref/gui/openoffice/OOBibBase.java | 132 +++++++++--------- 1 file changed, 65 insertions(+), 67 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c9f7dc8398a..1878a9a6e79 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -348,32 +348,6 @@ private static T unoQI(Class zInterface, * Constructor */ - private XDesktop simpleBootstrap(Path loPath) - throws CreationException, - BootstrapException - { - // Get the office component context: - XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); - XMultiComponentFactory sem = context.getServiceManager(); - - // Create the desktop, which is the root frame of the - // hierarchy of frames that contain viewable components: - Object desktop; - try { - desktop = sem.createInstanceWithContext("com.sun.star.frame.Desktop", context); - } catch (Exception e) { - throw new CreationException(e.getMessage()); - } - XDesktop result = unoQI(XDesktop.class, desktop); - - // TODO: useless call? - if ( run_useless_parts ){ - unoQI(XComponentLoader.class, desktop); - } - - return result; - } - public OOBibBase(Path loPath, boolean atEnd, DialogService dialogService @@ -395,7 +369,7 @@ public OOBibBase(Path loPath, ayt.add(a); ayt.add(y); ayt.add(t); - this.entryComparator= new FieldComparatorStack<>(ayt); + this.entryComparator = new FieldComparatorStack<>(ayt); } { List> yat = new ArrayList<>(3); @@ -409,6 +383,31 @@ public OOBibBase(Path loPath, this.xDesktop = simpleBootstrap(loPath); } + private XDesktop simpleBootstrap(Path loPath) + throws CreationException, + BootstrapException + { + // Get the office component context: + XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); + XMultiComponentFactory sem = context.getServiceManager(); + + // Create the desktop, which is the root frame of the + // hierarchy of frames that contain viewable components: + Object desktop; + try { + desktop = sem.createInstanceWithContext("com.sun.star.frame.Desktop", context); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + XDesktop result = unoQI(XDesktop.class, desktop); + + // TODO: useless call? + if ( run_useless_parts ){ + unoQI(XComponentLoader.class, desktop); + } + + return result; + } /* * section: selectDocument() @@ -425,7 +424,7 @@ private static List getTextDocuments( XDesktop desktop ) while (compEnum.hasMoreElements()) { Object next = compEnum.nextElement(); - XComponent comp = unoQI(XComponent.class , next); + XComponent comp = unoQI(XComponent.class, next); XTextDocument doc = unoQI(XTextDocument.class, comp); if (doc != null) { result.add(doc); @@ -441,7 +440,7 @@ private static Optional getDocumentTitle(XTextDocument doc) { try { XFrame frame = doc.getCurrentController().getFrame(); - Object frame_title_obj = OOUtil.getProperty( frame , "Title"); + Object frame_title_obj = OOUtil.getProperty( frame, "Title" ); String frame_title_str = String.valueOf(frame_title_obj); return Optional.of(frame_title_str); } catch (UnknownPropertyException | WrappedTargetException e) { @@ -472,6 +471,7 @@ public String toString() { return description; } } + List viewModel = list.stream() .map( DocumentTitleViewModel::new ) @@ -536,7 +536,7 @@ public void selectDocument() // TODO: what is the point of the next line? Does it have a side effect? - if ( run_useless_parts ){ + if ( run_useless_parts ) { unoQI(XDocumentIndexesSupplier.class, component); } @@ -582,20 +582,20 @@ public void selectDocument() /* * TODO: GUI should be notified */ - private void forgetDocument(){ - this.xDocumentConnection = null ; + private void forgetDocument() { + this.xDocumentConnection = null ; } public boolean isConnectedToDocument() { return this.xDocumentConnection != null; } - public boolean checkDocumentConnection(){ - if (this.xDocumentConnection == null){ + public boolean checkDocumentConnection() { + if (this.xDocumentConnection == null) { return false; } boolean res = this.xDocumentConnection.checkDocumentConnection(); - if ( ! res ){ + if ( !res ) { forgetDocument(); } return res; @@ -604,7 +604,7 @@ public boolean checkDocumentConnection(){ private DocumentConnection getDocumentConnectionOrThrow() throws NoDocumentException { - if ( ! checkDocumentConnection() ){ + if ( !checkDocumentConnection() ) { throw new NoDocumentException("Not connected to document"); } return this.xDocumentConnection; @@ -615,21 +615,19 @@ private DocumentConnection getDocumentConnectionOrThrow() */ public Optional getCurrentDocumentTitle() { - if ( ! checkDocumentConnection() ){ + if ( !checkDocumentConnection() ) { return Optional.empty(); } else { - return this.xDocumentConnection.getDocumentTitle(); + return this.xDocumentConnection.getDocumentTitle(); } } - - /* * === insertEntry */ private Comparator comparatorForMulticite(OOBibStyle style){ - if (style.getBooleanCitProperty( OOBibStyle.MULTI_CITE_CHRONOLOGICAL )) { + if ( style.getBooleanCitProperty( OOBibStyle.MULTI_CITE_CHRONOLOGICAL ) ) { return this.yearAuthorTitleComparator; } else { return this.entryComparator; @@ -639,25 +637,25 @@ private Comparator comparatorForMulticite(OOBibStyle style){ private void sortBibEntryListForMulticite( List entries, OOBibStyle style ) { - if (entries.size() <= 1){ + if (entries.size() <= 1) { return; } - entries.sort( comparatorForMulticite(style)); + entries.sort( comparatorForMulticite(style) ); } private static int citationTypeFromOptions( boolean withText, boolean inParenthesis ) { - if ( !withText ){ - return OOBibBase.INVISIBLE_CIT ; + if ( !withText ) { + return OOBibBase.INVISIBLE_CIT; } return ( inParenthesis ? OOBibBase.AUTHORYEAR_PAR : OOBibBase.AUTHORYEAR_INTEXT ); } - - private static boolean isJabRefReferenceMarkName( String name ){ + private static boolean isJabRefReferenceMarkName( String name ) { return (CITE_PATTERN.matcher(name).find()); } + private static List filterIsJabRefReferenceMarkName( List names ) { return ( names .stream() @@ -790,10 +788,10 @@ private String getUniqueReferenceMarkName(DocumentConnection documentConnection, * */ private static class ParsedRefMark { - public String i ; // "", "0", "1" ... - public int itcType ; // in-text-citation type + public String i; // "", "0", "1" ... + public int itcType // in-text-citation type public List citedKeys; - ParsedRefMark( String i, int itcType, List citedKeys ){ + ParsedRefMark( String i, int itcType, List citedKeys ) { this.i = i; this.itcType = itcType; this.citedKeys = citedKeys; @@ -804,7 +802,7 @@ private static class ParsedRefMark { * Parse a refMarkName. * */ - private static Optional parseRefMarkName( String refMarkName ){ + private static Optional parseRefMarkName( String refMarkName ) { Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); if (!citeMatcher.find()) { return Optional.empty(); @@ -886,7 +884,7 @@ public void insertEntry(List entries, ); // Generate unique bookmark-name int citationType = citationTypeFromOptions( withText, inParenthesis ); - String newName = getUniqueReferenceMarkName( documentConnection, + String newName = getUniqueReferenceMarkName( documentConnection, keyString, citationType ); @@ -976,9 +974,9 @@ public void insertEntry(List entries, // Go back to the relevant position: try { cursor.gotoRange(position, false); - } catch ( com.sun.star.uno.RuntimeException ex ){ + } catch ( com.sun.star.uno.RuntimeException ex ) { LOGGER.warn("OOBibBase.insertEntry:" - +" Could not go back to end of in-text citation", ex); + + " Could not go back to end of in-text citation", ex); } } @@ -1002,8 +1000,8 @@ public void insertEntry(List entries, * If name does not match CITE_PATTERN, an empty List is returned. */ private List parseRefMarkNameToUniqueCitationKeys(String name) { - Optional< ParsedRefMark > op = parseRefMarkName( name ); - if ( op.isPresent() ){ + Optional op = parseRefMarkName( name ); + if ( op.isPresent() ) { return op.get().citedKeys.stream().distinct().collect(Collectors.toList()); } return new ArrayList<>(); @@ -1047,7 +1045,6 @@ private List findCitedKeys( DocumentConnection documentConnection ) return keys; } - /** * @return LinkedHashMap, from BibEntry to BibDatabase * Side effect: add citedKeys to citeKeyToBibEntry, using UndefinedBibtexEntry if not found. @@ -1084,7 +1081,7 @@ private class FindCitedEntriesResult { List citedKeys ) { - Map citeKeyToBibEntry = new HashMap<>(); + Map citeKeyToBibEntry = new HashMap<>(); // LinkedHashMap, iteration order as in citedKeys Map entries = new LinkedHashMap<>(); @@ -1152,13 +1149,14 @@ public List refreshCiteMarkers(List databases, } } - private static BibEntry undefinedBibentryToNull( BibEntry cEntry ){ - if ( cEntry instanceof UndefinedBibtexEntry ){ + private static BibEntry undefinedBibentryToNull( BibEntry cEntry ) { + if ( cEntry instanceof UndefinedBibtexEntry ) { return null; } return cEntry; } - private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ + + private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ) { return Arrays.stream(cEntries) .map( OOBibBase::undefinedBibentryToNull ) @@ -1166,10 +1164,10 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ } private static void - assertKeysInCiteKeyToBibEntry( String[] keys, // citeKeys - Map citeKeyToBibEntry, - String referenceMarkName // for reporting - ) + assertKeysInCiteKeyToBibEntry( String[] keys, // citeKeys + Map citeKeyToBibEntry, + String referenceMarkName // for reporting + ) throws BibEntryNotFoundException { // check keys @@ -1178,11 +1176,11 @@ private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ){ .filter( key -> null == citeKeyToBibEntry.get(key) ) .collect(Collectors.toList()); - for ( String key : unresovedKeys ){ + for ( String key : unresovedKeys ) { LOGGER.info("Citation key not found: '" + key + '\''); LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); String msg = Localization.lang("Could not resolve BibTeX entry" - +" for citation marker '%0'.", + + " for citation marker '%0'.", referenceMarkName ); throw new BibEntryNotFoundException(referenceMarkName, msg); From 10e5d462ce98df7c0c7a12ca6a9c173b519577dc Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 16:49:11 +0100 Subject: [PATCH 0329/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 51 ++++++++++--------- 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1878a9a6e79..12dc0cd0296 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -60,6 +60,7 @@ import com.sun.star.frame.XDesktop; import com.sun.star.frame.XFrame; import com.sun.star.frame.XModel; + import com.sun.star.lang.DisposedException; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.Locale; @@ -67,6 +68,7 @@ import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; + import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XDocumentIndexesSupplier; import com.sun.star.text.XFootnote; @@ -81,6 +83,7 @@ import com.sun.star.text.XTextSectionsSupplier; import com.sun.star.text.XTextViewCursor; import com.sun.star.text.XTextViewCursorSupplier; + import com.sun.star.uno.Any; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; @@ -132,6 +135,7 @@ private class DocumentConnection { public XComponent xCurrentComponent; public XPropertySet propertySet; public XPropertyContainer userProperties; + DocumentConnection(XMultiServiceFactory mxDocFactory, XTextDocument mxDoc, XText xText, @@ -140,13 +144,13 @@ private class DocumentConnection { XPropertySet propertySet, XPropertyContainer userProperties ) { - this.mxDocFactory = mxDocFactory ; - this.mxDoc = mxDoc ; - this.xText = xText ; - this.xViewCursorSupplier = xViewCursorSupplier ; - this.xCurrentComponent = xCurrentComponent ; - this.propertySet = propertySet ; - this.userProperties = userProperties ; + this.mxDocFactory = mxDocFactory; + this.mxDoc = mxDoc; + this.xText = xText; + this.xViewCursorSupplier = xViewCursorSupplier; + this.xCurrentComponent = xCurrentComponent; + this.propertySet = propertySet; + this.userProperties = userProperties; } public Optional getDocumentTitle() { @@ -209,26 +213,26 @@ private XNameAccess getReferenceMarks() try { XNameAccess res = supplier.getReferenceMarks(); return res; - } catch ( Exception ex ){ + } catch ( Exception ex ) { LOGGER.warn( "getReferenceMarks caught: ", ex ); throw new NoDocumentException("getReferenceMarks failed"); } } - public boolean checkDocumentConnection(){ - boolean res = true; + public boolean checkDocumentConnection() { + // These are set by selectDocument: - if (null == this.xCurrentComponent ){ res = false; } - if (null == this.mxDoc ){ res = false; } - if (null == this.xViewCursorSupplier ){ res = false; } - if (null == this.xText ){ res = false; } - if (null == this.mxDocFactory ){ res = false; } - if (null == this.userProperties ){ res = false; } - if (null == this.propertySet ){ res = false; } - - if ( ! res ){ - return false; - } + if ( null == this.xCurrentComponent + || null == this.mxDoc + || null == this.xViewCursorSupplier + || null == this.xText + || null == this.mxDocFactory + || null == this.userProperties + || null == this.propertySet ) + { + return false; + } + // Attempt to check document is really available // TODO try { @@ -247,7 +251,7 @@ List getReferenceMarknames() if (names == null) { return new ArrayList<>(); } - return Arrays.asList( names ); + return Arrays.asList( names ); } public String getCitationContext(String refMarkName, @@ -314,7 +318,7 @@ public String getCitationContext(String refMarkName, } // Get the cursor positioned by the user. - public XTextViewCursor getViewCursor(){ + public XTextViewCursor getViewCursor() { return this.xViewCursorSupplier.getViewCursor(); } @@ -347,7 +351,6 @@ private static T unoQI(Class zInterface, /* * Constructor */ - public OOBibBase(Path loPath, boolean atEnd, DialogService dialogService From 3f19c2bbbf8bb51c0b01a70912562bece5982777 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 17:14:01 +0100 Subject: [PATCH 0330/1068] add lost semicolon --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 12dc0cd0296..ecd4722c9fe 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -792,7 +792,7 @@ private String getUniqueReferenceMarkName(DocumentConnection documentConnection, */ private static class ParsedRefMark { public String i; // "", "0", "1" ... - public int itcType // in-text-citation type + public int itcType; // in-text-citation type public List citedKeys; ParsedRefMark( String i, int itcType, List citedKeys ) { this.i = i; From 639e272f64796682f41b7478cdce984808846b27 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 22:12:58 +0100 Subject: [PATCH 0331/1068] DocumantConnection is static now --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ecd4722c9fe..d4a26593680 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -127,7 +127,7 @@ class OOBibBase { private final Comparator yearAuthorTitleComparator; /* document-connection related */ - private class DocumentConnection { + private static class DocumentConnection { public XMultiServiceFactory mxDocFactory; public XTextDocument mxDoc; public XText xText; @@ -234,7 +234,6 @@ public boolean checkDocumentConnection() { } // Attempt to check document is really available - // TODO try { getReferenceMarks(); } catch (NoDocumentException ex ) { From 18856666e35e20449861582e5ae39448880b8e68 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 23:16:52 +0100 Subject: [PATCH 0332/1068] make stylechecker happy --- .../org/jabref/gui/openoffice/OOBibBase.java | 1840 ++++++++--------- 1 file changed, 859 insertions(+), 981 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d4a26593680..b4c213f1a18 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -34,7 +34,6 @@ import org.jabref.logic.openoffice.OOUtil; import org.jabref.logic.openoffice.UndefinedBibtexEntry; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; - import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; @@ -60,7 +59,6 @@ import com.sun.star.frame.XDesktop; import com.sun.star.frame.XFrame; import com.sun.star.frame.XModel; - import com.sun.star.lang.DisposedException; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.Locale; @@ -68,7 +66,6 @@ import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; - import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XDocumentIndexesSupplier; import com.sun.star.text.XFootnote; @@ -83,7 +80,6 @@ import com.sun.star.text.XTextSectionsSupplier; import com.sun.star.text.XTextViewCursor; import com.sun.star.text.XTextViewCursorSupplier; - import com.sun.star.uno.Any; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; @@ -92,129 +88,127 @@ import org.slf4j.LoggerFactory; /** - * Class for manipulating the Bibliography of the currently started - * document in OpenOffice. + * Class for manipulating the Bibliography of the currently started document in OpenOffice. */ @AllowedToUseAwt("Requires AWT for italics and bold") class OOBibBase { + private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); - private static final String BIB_SECTION_NAME = "JR_bib"; + private static final String BIB_SECTION_NAME = "JR_bib"; private static final String BIB_SECTION_END_NAME = "JR_bib_end"; private static final String BIB_CITATION = "JR_cite"; private static final Pattern CITE_PATTERN = - Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); private static final String CHAR_STYLE_NAME = "CharStyleName"; /* Types of in-text citation. (itcType) * Their numeric values are used in reference mark names. */ - private static final int AUTHORYEAR_PAR = 1; + private static final int AUTHORYEAR_PAR = 1; private static final int AUTHORYEAR_INTEXT = 2; - private static final int INVISIBLE_CIT = 3; + private static final int INVISIBLE_CIT = 3; private static final Logger LOGGER = - LoggerFactory.getLogger(OOBibBase.class); + LoggerFactory.getLogger(OOBibBase.class); + /* + * Shall we keep calls I suspect to be useless? + */ + private final boolean run_useless_parts = true; /* variables */ private final DialogService dialogService; - private final XDesktop xDesktop; - private final boolean atEnd; + private final XDesktop xDesktop; + private final boolean atEnd; private final Comparator entryComparator; private final Comparator yearAuthorTitleComparator; /* document-connection related */ private static class DocumentConnection { - public XMultiServiceFactory mxDocFactory; - public XTextDocument mxDoc; - public XText xText; + public XMultiServiceFactory mxDocFactory; + public XTextDocument mxDoc; + public XText xText; public XTextViewCursorSupplier xViewCursorSupplier; - public XComponent xCurrentComponent; - public XPropertySet propertySet; - public XPropertyContainer userProperties; + public XComponent xCurrentComponent; + public XPropertySet propertySet; + public XPropertyContainer userProperties; - DocumentConnection(XMultiServiceFactory mxDocFactory, - XTextDocument mxDoc, - XText xText, + DocumentConnection(XMultiServiceFactory mxDocFactory, + XTextDocument mxDoc, + XText xText, XTextViewCursorSupplier xViewCursorSupplier, - XComponent xCurrentComponent, - XPropertySet propertySet, - XPropertyContainer userProperties - ) { - this.mxDocFactory = mxDocFactory; - this.mxDoc = mxDoc; - this.xText = xText; + XComponent xCurrentComponent, + XPropertySet propertySet, + XPropertyContainer userProperties + ) { + this.mxDocFactory = mxDocFactory; + this.mxDoc = mxDoc; + this.xText = xText; this.xViewCursorSupplier = xViewCursorSupplier; - this.xCurrentComponent = xCurrentComponent; - this.propertySet = propertySet; - this.userProperties = userProperties; + this.xCurrentComponent = xCurrentComponent; + this.propertySet = propertySet; + this.userProperties = userProperties; } public Optional getDocumentTitle() { - return OOBibBase.getDocumentTitle( this.mxDoc ); + return OOBibBase.getDocumentTitle(this.mxDoc); } private Optional getCustomProperty(String property) - throws UnknownPropertyException, - WrappedTargetException - { + throws UnknownPropertyException, + WrappedTargetException { assert (this.propertySet != null); XPropertySetInfo psi = - this.propertySet - .getPropertySetInfo(); + this.propertySet + .getPropertySetInfo(); if (psi.hasPropertyByName(property)) { String v = - this.propertySet - .getPropertyValue(property) - .toString(); + this.propertySet + .getPropertyValue(property) + .toString(); return Optional.ofNullable(v); } return Optional.empty(); } private void setCustomProperty(String property, String value) - throws UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException - { + throws UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException { XPropertySetInfo psi = - this.propertySet - .getPropertySetInfo(); + this.propertySet + .getPropertySetInfo(); if (psi.hasPropertyByName(property)) { this.userProperties.removeProperty(property); } if (value != null) { this.userProperties - .addProperty(property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value) - ); + .addProperty(property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value) + ); } } /** - * - * @throws NoDocumentException - * + * @throws NoDocumentException If cannot get reference marks */ private XNameAccess getReferenceMarks() - throws NoDocumentException - { + throws NoDocumentException { XReferenceMarksSupplier supplier = - unoQI(XReferenceMarksSupplier.class, - this.xCurrentComponent); + unoQI(XReferenceMarksSupplier.class, + this.xCurrentComponent); try { - XNameAccess res = supplier.getReferenceMarks(); - return res; - } catch ( Exception ex ) { - LOGGER.warn( "getReferenceMarks caught: ", ex ); + return supplier.getReferenceMarks(); + } catch (Exception ex) { + LOGGER.warn("getReferenceMarks caught: ", ex); throw new NoDocumentException("getReferenceMarks failed"); } } @@ -222,53 +216,50 @@ private XNameAccess getReferenceMarks() public boolean checkDocumentConnection() { // These are set by selectDocument: - if ( null == this.xCurrentComponent - || null == this.mxDoc - || null == this.xViewCursorSupplier - || null == this.xText - || null == this.mxDocFactory - || null == this.userProperties - || null == this.propertySet ) - { - return false; - } + if (null == this.xCurrentComponent + || null == this.mxDoc + || null == this.xViewCursorSupplier + || null == this.xText + || null == this.mxDocFactory + || null == this.userProperties + || null == this.propertySet) { + return false; + } // Attempt to check document is really available try { getReferenceMarks(); - } catch (NoDocumentException ex ) { + } catch (NoDocumentException ex) { return false; } return true; } List getReferenceMarknames() - throws NoDocumentException - { + throws NoDocumentException { XNameAccess nameAccess = getReferenceMarks(); String[] names = nameAccess.getElementNames(); if (names == null) { return new ArrayList<>(); } - return Arrays.asList( names ); + return Arrays.asList(names); } public String getCitationContext(String refMarkName, int charBefore, int charAfter, boolean htmlMarkup) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException - { + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException { XNameAccess nameAccess = getReferenceMarks(); Object referenceMark = nameAccess.getByName(refMarkName); XTextContent bookmark = unoQI(XTextContent.class, referenceMark); XTextCursor cursor = - bookmark.getAnchor() // the text range to which the content is attached. - .getText() - .createTextCursorByRange(bookmark.getAnchor()); + bookmark.getAnchor() // the text range to which the content is attached. + .getText() + .createTextCursorByRange(bookmark.getAnchor()); String citPart = cursor.getString(); @@ -280,7 +271,7 @@ public String getCitationContext(String refMarkName, // If we are close to charBefore and see a space, // then cut here. Might avoid cutting a word in half. if ((i >= (charBefore - flex)) - && Character.isWhitespace(cursor.getString().charAt(0))) { + && Character.isWhitespace(cursor.getString().charAt(0))) { break; } } catch (IndexOutOfBoundsException ex) { @@ -309,9 +300,9 @@ public String getCitationContext(String refMarkName, String result = cursor.getString(); if (htmlMarkup) { result = - result.substring(0, addedBefore) - + "" + citPart + "" - + result.substring(lengthWithBefore); + result.substring(0, addedBefore) + + "" + citPart + "" + + result.substring(lengthWithBefore); } return result.trim(); } @@ -320,7 +311,6 @@ public String getCitationContext(String refMarkName, public XTextViewCursor getViewCursor() { return this.xViewCursorSupplier.getViewCursor(); } - } // end DocumentConnection private DocumentConnection xDocumentConnection; @@ -331,67 +321,42 @@ public XTextViewCursor getViewCursor() { private List jabRefReferenceMarkNamesSortedByPosition; - /** unoQI : short for UnoRuntime.queryInterface - * - * Returns: a reference to the requested UNO interface type if - * available, otherwise null - */ - private static T unoQI(Class zInterface, - Object object) - { - return UnoRuntime.queryInterface( zInterface, object ); - } - - /* - * Shall we keep calls I suspect to be useless? - */ - private final boolean run_useless_parts = true; - /* * Constructor */ public OOBibBase(Path loPath, boolean atEnd, DialogService dialogService - ) throws IllegalAccessException, - InvocationTargetException, - BootstrapException, - CreationException, - IOException, - ClassNotFoundException - { + ) throws BootstrapException, + CreationException { this.dialogService = dialogService; - { + FieldComparator a = new FieldComparator(StandardField.AUTHOR); FieldComparator y = new FieldComparator(StandardField.YEAR); FieldComparator t = new FieldComparator(StandardField.TITLE); - { List> ayt = new ArrayList<>(3); ayt.add(a); ayt.add(y); ayt.add(t); this.entryComparator = new FieldComparatorStack<>(ayt); - } - { + List> yat = new ArrayList<>(3); yat.add(y); yat.add(a); yat.add(t); this.yearAuthorTitleComparator = new FieldComparatorStack<>(yat); - } - } - this.atEnd = atEnd; + + this.atEnd = atEnd; this.xDesktop = simpleBootstrap(loPath); } private XDesktop simpleBootstrap(Path loPath) - throws CreationException, - BootstrapException - { + throws CreationException, + BootstrapException { // Get the office component context: - XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); - XMultiComponentFactory sem = context.getServiceManager(); + XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); + XMultiComponentFactory sem = context.getServiceManager(); // Create the desktop, which is the root frame of the // hierarchy of frames that contain viewable components: @@ -404,29 +369,39 @@ private XDesktop simpleBootstrap(Path loPath) XDesktop result = unoQI(XDesktop.class, desktop); // TODO: useless call? - if ( run_useless_parts ){ + if (run_useless_parts) { unoQI(XComponentLoader.class, desktop); } return result; } + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if available, + * otherwise null + */ + private static T unoQI(Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + /* * section: selectDocument() */ - private static List getTextDocuments( XDesktop desktop ) - throws NoSuchElementException, - WrappedTargetException - { + private static List getTextDocuments(XDesktop desktop) + throws NoSuchElementException, + WrappedTargetException { List result = new ArrayList<>(); - XEnumerationAccess enumAccess = desktop.getComponents(); - XEnumeration compEnum = enumAccess.createEnumeration(); + XEnumerationAccess enumAccess = desktop.getComponents(); + XEnumeration compEnum = enumAccess.createEnumeration(); while (compEnum.hasMoreElements()) { - Object next = compEnum.nextElement(); - XComponent comp = unoQI(XComponent.class, next); + Object next = compEnum.nextElement(); + XComponent comp = unoQI(XComponent.class, next); XTextDocument doc = unoQI(XTextDocument.class, comp); if (doc != null) { result.add(doc); @@ -441,10 +416,10 @@ private static Optional getDocumentTitle(XTextDocument doc) { } try { - XFrame frame = doc.getCurrentController().getFrame(); - Object frame_title_obj = OOUtil.getProperty( frame, "Title" ); + XFrame frame = doc.getCurrentController().getFrame(); + Object frame_title_obj = OOUtil.getProperty(frame, "Title"); String frame_title_str = String.valueOf(frame_title_obj); - return Optional.of(frame_title_str); + return Optional.of(frame_title_str); } catch (UnknownPropertyException | WrappedTargetException e) { LOGGER.warn("Could not get document title", e); return Optional.empty(); @@ -452,16 +427,15 @@ private static Optional getDocumentTitle(XTextDocument doc) { } private static XTextDocument selectDocumentDialog(List list, - DialogService dialogService) - { + DialogService dialogService) { class DocumentTitleViewModel { private final XTextDocument xTextDocument; - private final String description; + private final String description; public DocumentTitleViewModel(XTextDocument xTextDocument) { this.xTextDocument = xTextDocument; - this.description = OOBibBase.getDocumentTitle(xTextDocument).orElse(""); + this.description = OOBibBase.getDocumentTitle(xTextDocument).orElse(""); } public XTextDocument getXtextDocument() { @@ -475,46 +449,38 @@ public String toString() { } List viewModel = - list.stream() - .map( DocumentTitleViewModel::new ) - .collect(Collectors.toList()); + list.stream() + .map(DocumentTitleViewModel::new) + .collect(Collectors.toList()); // This whole method is part of a background task when // auto-detecting instances, so we need to show dialog in FX // thread Optional selectedDocument = - dialogService - .showChoiceDialogAndWait( - Localization.lang("Select document"), - Localization.lang("Found documents:"), - Localization.lang("Use selected document"), - viewModel - ); + dialogService + .showChoiceDialogAndWait( + Localization.lang("Select document"), + Localization.lang("Found documents:"), + Localization.lang("Use selected document"), + viewModel + ); return - selectedDocument - .map( DocumentTitleViewModel::getXtextDocument ) - .orElse(null); + selectedDocument + .map(DocumentTitleViewModel::getXtextDocument) + .orElse(null); } - /** Choose a document to work with. - * - * inititalized fields: - * - this.xCurrentComponent - * - this.mxDoc - * - this.xViewCursorSupplier - * - this.xText - * - this.mxDocFactory - * - this.userProperties - * - this.propertySet - * + /** + * Choose a document to work with. + *

+ * inititalized fields: - this.xCurrentComponent - this.mxDoc - this.xViewCursorSupplier - this.xText - this.mxDocFactory - this.userProperties - this.propertySet */ public void selectDocument() - throws NoDocumentException, - NoSuchElementException, - WrappedTargetException - { + throws NoDocumentException, + NoSuchElementException, + WrappedTargetException { XTextDocument mxDoc; - { + XTextDocument selected; List textDocumentList = getTextDocuments(this.xDesktop); if (textDocumentList.isEmpty()) { @@ -525,29 +491,27 @@ public void selectDocument() } else { // Bring up a dialog selected = - OOBibBase.selectDocumentDialog(textDocumentList, - this.dialogService); + OOBibBase.selectDocumentDialog(textDocumentList, + this.dialogService); } if (selected == null) { return; } mxDoc = selected; - } - XComponent component = unoQI(XComponent.class, mxDoc); + XComponent component = unoQI(XComponent.class, mxDoc); // TODO: what is the point of the next line? Does it have a side effect? - if ( run_useless_parts ) { + if (run_useless_parts) { unoQI(XDocumentIndexesSupplier.class, component); } XTextViewCursorSupplier viewCursorSupplier; - { - XModel mo = unoQI(XModel.class, component); + + XModel mo = unoQI(XModel.class, component); XController co = mo.getCurrentController(); viewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); - } // get a reference to the body text of the document XText text = mxDoc.getText(); @@ -556,23 +520,22 @@ public void selectDocument() XMultiServiceFactory mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); XPropertyContainer userProperties; - { + XDocumentPropertiesSupplier supp = - unoQI(XDocumentPropertiesSupplier.class, mxDoc); + unoQI(XDocumentPropertiesSupplier.class, mxDoc); userProperties = supp.getDocumentProperties().getUserDefinedProperties(); - } XPropertySet propertySet = unoQI(XPropertySet.class, userProperties); this.xDocumentConnection = new DocumentConnection( - mxDocFactory, - mxDoc, - text, - viewCursorSupplier, - component, - propertySet, - userProperties - ); + mxDocFactory, + mxDoc, + text, + viewCursorSupplier, + component, + propertySet, + userProperties + ); // TODO: maybe we should install an event handler for document // close: addCloseListener @@ -585,7 +548,7 @@ public void selectDocument() * TODO: GUI should be notified */ private void forgetDocument() { - this.xDocumentConnection = null ; + this.xDocumentConnection = null; } public boolean isConnectedToDocument() { @@ -597,16 +560,15 @@ public boolean checkDocumentConnection() { return false; } boolean res = this.xDocumentConnection.checkDocumentConnection(); - if ( !res ) { + if (!res) { forgetDocument(); } return res; } private DocumentConnection getDocumentConnectionOrThrow() - throws NoDocumentException - { - if ( !checkDocumentConnection() ) { + throws NoDocumentException { + if (!checkDocumentConnection()) { throw new NoDocumentException("Not connected to document"); } return this.xDocumentConnection; @@ -617,7 +579,7 @@ private DocumentConnection getDocumentConnectionOrThrow() */ public Optional getCurrentDocumentTitle() { - if ( !checkDocumentConnection() ) { + if (!checkDocumentConnection()) { return Optional.empty(); } else { return this.xDocumentConnection.getDocumentTitle(); @@ -628,80 +590,76 @@ public Optional getCurrentDocumentTitle() { * === insertEntry */ - private Comparator comparatorForMulticite(OOBibStyle style){ - if ( style.getBooleanCitProperty( OOBibStyle.MULTI_CITE_CHRONOLOGICAL ) ) { + private Comparator comparatorForMulticite(OOBibStyle style) { + if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { return this.yearAuthorTitleComparator; } else { return this.entryComparator; } } - private void sortBibEntryListForMulticite( List entries, - OOBibStyle style ) - { + private void sortBibEntryListForMulticite(List entries, + OOBibStyle style) { if (entries.size() <= 1) { return; } - entries.sort( comparatorForMulticite(style) ); + entries.sort(comparatorForMulticite(style)); } - private static int citationTypeFromOptions( boolean withText, boolean inParenthesis ) { - if ( !withText ) { + private static int citationTypeFromOptions(boolean withText, boolean inParenthesis) { + if (!withText) { return OOBibBase.INVISIBLE_CIT; } - return ( inParenthesis - ? OOBibBase.AUTHORYEAR_PAR - : OOBibBase.AUTHORYEAR_INTEXT ); + return (inParenthesis + ? OOBibBase.AUTHORYEAR_PAR + : OOBibBase.AUTHORYEAR_INTEXT); } - private static boolean isJabRefReferenceMarkName( String name ) { + private static boolean isJabRefReferenceMarkName(String name) { return (CITE_PATTERN.matcher(name).find()); } - private static List filterIsJabRefReferenceMarkName( List names ) { - return ( names - .stream() - .filter( OOBibBase::isJabRefReferenceMarkName ) - .collect(Collectors.toList()) - ); + private static List filterIsJabRefReferenceMarkName(List names) { + return (names + .stream() + .filter(OOBibBase::isJabRefReferenceMarkName) + .collect(Collectors.toList()) + ); } /* * called from getCitationEntries(...) */ private List getJabRefReferenceMarkNames(DocumentConnection documentConnection) - throws NoDocumentException - { - return filterIsJabRefReferenceMarkName( documentConnection.getReferenceMarknames() ); + throws NoDocumentException { + return filterIsJabRefReferenceMarkName(documentConnection.getReferenceMarknames()); } /** * */ public List getCitationEntries() - throws NoSuchElementException, - UnknownPropertyException, - WrappedTargetException, - NoDocumentException - { - return this.getCitationEntriesImpl( this.getDocumentConnectionOrThrow() ); - } - - private List getCitationEntriesImpl( DocumentConnection documentConnection ) - throws NoSuchElementException, - UnknownPropertyException, - WrappedTargetException, - NoDocumentException - { + throws NoSuchElementException, + UnknownPropertyException, + WrappedTargetException, + NoDocumentException { + return this.getCitationEntriesImpl(this.getDocumentConnectionOrThrow()); + } + + private List getCitationEntriesImpl(DocumentConnection documentConnection) + throws NoSuchElementException, + UnknownPropertyException, + WrappedTargetException, + NoDocumentException { List names = this.getJabRefReferenceMarkNames(documentConnection); List citations = new ArrayList(names.size()); for (String name : names) { CitationEntry entry = - new CitationEntry(name, - documentConnection.getCitationContext(name, 30, 30, true), - documentConnection.getCustomProperty(name) - ); + new CitationEntry(name, + documentConnection.getCitationContext(name, 30, 30, true), + documentConnection.getCustomProperty(name) + ); citations.add(entry); } return citations; @@ -709,30 +667,24 @@ private List getCitationEntriesImpl( DocumentConnection documentC /** * Apply editable parts of citationEntries to the document. - * + *

* - Currently the only editable part is pageInfo. - * - * Since the only call to applyCitationEntries() only changes - * pageInfo w.r.t those returned by getCitationEntries(), we can - * do with the following restrictions: - * + *

+ * Since the only call to applyCitationEntries() only changes pageInfo w.r.t those returned by getCitationEntries(), we can do with the following restrictions: + *

* - Missing pageInfo means no action. - * - * - Missing CitationEntry means no action (no attempt to - * remove citation from the text). - * - * - Reference to citation not present in the text evokes - * no error, and setCustomProperty() is called. - * + *

+ * - Missing CitationEntry means no action (no attempt to remove citation from the text). + *

+ * - Reference to citation not present in the text evokes no error, and setCustomProperty() is called. */ - public void applyCitationEntries( List citationEntries ) - throws UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException, - NoDocumentException - { + public void applyCitationEntries(List citationEntries) + throws UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException, + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); // Leave exceptions to the caller. @@ -744,7 +696,7 @@ public void applyCitationEntries( List citationEntries ) for (CitationEntry entry : citationEntries) { Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { - documentConnection.setCustomProperty( entry.getRefMarkName(), pageInfo.get() ); + documentConnection.setCustomProperty(entry.getRefMarkName(), pageInfo.get()); } else { // TODO: if pageInfo is not present, or is empty: // maybe we should remove it from the document. @@ -763,18 +715,14 @@ public void applyCitationEntries( List citationEntries ) } /** - * - * The first occurrence of bibtexKey gets no serial number, the - * second gets 0, the third 1 ... - * + * The first occurrence of bibtexKey gets no serial number, the second gets 0, the third 1 ... + *

* Or the first unused in this series, after removals. - * */ private String getUniqueReferenceMarkName(DocumentConnection documentConnection, String bibtexKey, int itcType) - throws NoDocumentException - { + throws NoDocumentException { XNameAccess xNamedRefMarks = xDocumentConnection.getReferenceMarks(); int i = 0; String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; @@ -786,49 +734,43 @@ private String getUniqueReferenceMarkName(DocumentConnection documentConnection, } /** - * This is what we get back from parsing a refMarkName - * + * This is what we get back from parsing a refMarkName */ private static class ParsedRefMark { public String i; // "", "0", "1" ... public int itcType; // in-text-citation type public List citedKeys; - ParsedRefMark( String i, int itcType, List citedKeys ) { - this.i = i; - this.itcType = itcType; + + ParsedRefMark(String i, int itcType, List citedKeys) { + this.i = i; + this.itcType = itcType; this.citedKeys = citedKeys; } } /** * Parse a refMarkName. - * */ - private static Optional parseRefMarkName( String refMarkName ) { + private static Optional parseRefMarkName(String refMarkName) { Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); if (!citeMatcher.find()) { return Optional.empty(); } - List keys = Arrays.asList( citeMatcher.group(3).split(",") ); + List keys = Arrays.asList(citeMatcher.group(3).split(",")); String i = citeMatcher.group(1); - int itcType = Integer.parseInt( citeMatcher.group(2) ); - return( Optional.of( new OOBibBase.ParsedRefMark( i, itcType, keys ) ) ); + int itcType = Integer.parseInt(citeMatcher.group(2)); + return (Optional.of(new OOBibBase.ParsedRefMark(i, itcType, keys))); } /** - * This method inserts a cite marker in the text (at the cursor) for the given - * BibEntry, and may refresh the bibliography. + * This method inserts a cite marker in the text (at the cursor) for the given BibEntry, and may refresh the bibliography. * * @param entries The entries to cite. * @param database The database the entry belongs to. * @param style The bibliography style we are using. - * @param inParenthesis Indicates whether it is an in-text citation - * or a citation in parenthesis. - * This is not relevant if numbered citations are used. - * @param withText Indicates whether this should be a normal citation (true) - * or an empty (invisible) citation (false). + * @param inParenthesis Indicates whether it is an in-text citation or a citation in parenthesis. This is not relevant if numbered citations are used. + * @param withText Indicates whether this should be a normal citation (true) or an empty (invisible) citation (false). * @param sync Indicates whether the reference list should be refreshed. - * * @throws IllegalTypeException * @throws PropertyExistException * @throws NotRemoveableException @@ -840,55 +782,50 @@ private static Optional parseRefMarkName( String refMarkName ) { * @throws PropertyVetoException * @throws CreationException * @throws BibEntryNotFoundException - * @throws UndefinedParagraphFormatException - * - * TODO: https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html - * Group changes into a single Undo context. - * + * @throws UndefinedParagraphFormatException TODO: https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html Group changes into a single Undo context. */ - public void insertEntry(List entries, - BibDatabase database, + public void insertEntry(List entries, + BibDatabase database, List allBases, - OOBibStyle style, - boolean inParenthesis, - boolean withText, - String pageInfo, - boolean sync - ) - throws IllegalArgumentException, - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - UndefinedCharacterFormatException, - WrappedTargetException, - NoSuchElementException, - PropertyVetoException, - IOException, - CreationException, - BibEntryNotFoundException, - UndefinedParagraphFormatException, - NoDocumentException - { + OOBibStyle style, + boolean inParenthesis, + boolean withText, + String pageInfo, + boolean sync + ) + throws IllegalArgumentException, + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + UndefinedCharacterFormatException, + WrappedTargetException, + NoSuchElementException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException, + UndefinedParagraphFormatException, + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { // Get the cursor positioned by the user. XTextCursor cursor = documentConnection.getViewCursor(); - sortBibEntryListForMulticite( entries, style ); + sortBibEntryListForMulticite(entries, style); String keyString = - String.join(",", + String.join(",", entries.stream() - .map( entry -> entry.getCitationKey().orElse("") ) - .collect( Collectors.toList() ) - ); + .map(entry -> entry.getCitationKey().orElse("")) + .collect(Collectors.toList()) + ); // Generate unique bookmark-name - int citationType = citationTypeFromOptions( withText, inParenthesis ); - String newName = getUniqueReferenceMarkName( documentConnection, - keyString, - citationType ); + int citationType = citationTypeFromOptions(withText, inParenthesis); + String newName = getUniqueReferenceMarkName(documentConnection, + keyString, + citationType); // If we should store metadata for page info, do that now: if (pageInfo != null) { @@ -898,37 +835,36 @@ public void insertEntry(List entries, // insert space cursor - .getText() - .insertString(cursor, " ", false); + .getText() + .insertString(cursor, " ", false); // format the space inserted - if ( style.isFormatCitations() ) { + if (style.isFormatCitations()) { XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); - String charStyle = style.getCitationCharacterFormat(); + String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch ( UnknownPropertyException + } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | WrappedTargetException ex - ) - { - // Setting the character format failed, so we - // throw an exception that will result in an - // error message for the user. - - // Before that, delete the space we inserted: - cursor.goLeft((short) 1, true); - cursor.setString(""); - throw new UndefinedCharacterFormatException(charStyle); - } + ) { + // Setting the character format failed, so we + // throw an exception that will result in an + // error message for the user. + + // Before that, delete the space we inserted: + cursor.goLeft((short) 1, true); + cursor.setString(""); + throw new UndefinedCharacterFormatException(charStyle); + } } // go back to before the space cursor.goLeft((short) 1, false); // Insert bookmark and text - { + // Create a BibEntry to BibDatabase map (to make // style.getCitationMarker happy?) Map databaseMap = new HashMap<>(); @@ -937,16 +873,15 @@ public void insertEntry(List entries, } // the text we insert? String citeText = - style.isNumberEntries() - ? "-" // A dash only. Presumably we expect a refresh later. - : style.getCitationMarker(entries, - databaseMap, - inParenthesis, - null, // uniquefiers - null // unlimAuthors - ); + style.isNumberEntries() + ? "-" // A dash only. Presumably we expect a refresh later. + : style.getCitationMarker(entries, + databaseMap, + inParenthesis, + null, // uniquefiers + null // unlimAuthors + ); insertReferenceMark(documentConnection, newName, citeText, cursor, withText, style); - } // Move to the right of the space and remember this // position: we will come back here in the end. @@ -976,12 +911,11 @@ public void insertEntry(List entries, // Go back to the relevant position: try { cursor.gotoRange(position, false); - } catch ( com.sun.star.uno.RuntimeException ex ) { + } catch (com.sun.star.uno.RuntimeException ex) { LOGGER.warn("OOBibBase.insertEntry:" - + " Could not go back to end of in-text citation", ex); + + " Could not go back to end of in-text citation", ex); } } - } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference @@ -990,53 +924,46 @@ public void insertEntry(List entries, } } - /** * Extract the list of citation keys from a reference mark name. * * @param name The reference mark name. - * @return The list of citation keys encoded in the name. - * In case of duplicated citation keys, only the first occurrence. - * Otherwise their order is preserved. - * - * If name does not match CITE_PATTERN, an empty List is returned. - */ + * @return The list of citation keys encoded in the name. In case of duplicated citation keys, + * only the first occurrence. Otherwise their order is preserved. + * If name does not match CITE_PATTERN, an empty list of strings is returned. + * */ private List parseRefMarkNameToUniqueCitationKeys(String name) { - Optional op = parseRefMarkName( name ); - if ( op.isPresent() ) { + Optional op = parseRefMarkName(name); + if (op.isPresent()) { return op.get().citedKeys.stream().distinct().collect(Collectors.toList()); } return new ArrayList<>(); } /** - * Extract citation keys from names of referenceMarks in the document. - * - * Each citation key is listed only once, in the order of first appearance. - * - * doc.referenceMarks.names.map(parse).flatten.unique - * + * Extract citation keys from names of referenceMarks in the document. + *

+ * Each citation key is listed only once, in the order of first appearance. + *

+ * doc.referenceMarks.names.map(parse).flatten.unique */ - private List findCitedKeys( DocumentConnection documentConnection ) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException - { + private List findCitedKeys(DocumentConnection documentConnection) + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException { - List names = getJabRefReferenceMarkNames( documentConnection ); + List names = getJabRefReferenceMarkNames(documentConnection); - { // assert it supports XTextContent XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); for (String name1 : names) { Object bookmark = xNamedMarks.getByName(name1); assert (null != unoQI(XTextContent.class, bookmark)); } - } List keys = new ArrayList<>(); for (String name1 : names) { - List newKeys = parseRefMarkNameToUniqueCitationKeys( name1 ); + List newKeys = parseRefMarkNameToUniqueCitationKeys(name1); for (String key : newKeys) { if (!keys.contains(key)) { keys.add(key); @@ -1048,17 +975,20 @@ private List findCitedKeys( DocumentConnection documentConnection ) } /** - * @return LinkedHashMap, from BibEntry to BibDatabase - * Side effect: add citedKeys to citeKeyToBibEntry, using UndefinedBibtexEntry if not found. + * @return LinkedHashMap, from BibEntry to BibDatabase. + * Side effect: adds citedKeys to citeKeyToBibEntry, + * using UndefinedBibtexEntry if not found. * - * If a citedKey is not found, BibEntry is new UndefinedBibtexEntry(citedKey), BibDatabase is null. - * If citedKey is found, then - * BibEntry is what we found, BibDatabase is the database we found it in. + * If a citedKey is not found, then + * BibEntry is new UndefinedBibtexEntry(citedKey), + * and BibDatabase is null. + * If citedKey is found, then BibEntry is what we found, + * BibDatabase is the database we found it in. * - * So: - * - result has an entry for each citedKey, in the same order as in citedKeys - * - citedKey in the entry is the same as the original citedKey + * So: result has an entry for each citedKey, + * in the same order as in citedKeys * + * citedKey in the entry is the same as the original citedKey */ private class FindCitedEntriesResult { /* @@ -1071,18 +1001,17 @@ private class FindCitedEntriesResult { */ Map citeKeyToBibEntry; - FindCitedEntriesResult( Map entries, - Map citeKeyToBibEntry ) { - this.entries = entries; + FindCitedEntriesResult(Map entries, + Map citeKeyToBibEntry) { + this.entries = entries; this.citeKeyToBibEntry = citeKeyToBibEntry; } } private FindCitedEntriesResult - findCitedEntries(List databases, - List citedKeys - ) - { + findCitedEntries(List databases, + List citedKeys + ) { Map citeKeyToBibEntry = new HashMap<>(); // LinkedHashMap, iteration order as in citedKeys @@ -1093,7 +1022,7 @@ private class FindCitedEntriesResult { Optional entry = database.getEntryByCitationKey(citedKey); if (entry.isPresent()) { entries.put(entry.get(), database); - citeKeyToBibEntry.put( citedKey, entry.get() ); + citeKeyToBibEntry.put(citedKey, entry.get()); found = true; break; } @@ -1102,10 +1031,10 @@ private class FindCitedEntriesResult { if (!found) { BibEntry x = new UndefinedBibtexEntry(citedKey); entries.put(x, null); - citeKeyToBibEntry.put( citedKey, x ); + citeKeyToBibEntry.put(citedKey, x); } } - return new FindCitedEntriesResult( entries, citeKeyToBibEntry ); + return new FindCitedEntriesResult(entries, citeKeyToBibEntry); } /** @@ -1126,23 +1055,22 @@ private class FindCitedEntriesResult { */ public List refreshCiteMarkers(List databases, OOBibStyle style) - throws WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - IOException, - CreationException, - BibEntryNotFoundException, - NoDocumentException - { + throws WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { return refreshCiteMarkersInternal(documentConnection, - databases, - style, - this.xUniquefiers); + databases, + style, + this.xUniquefiers); } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference @@ -1151,146 +1079,139 @@ public List refreshCiteMarkers(List databases, } } - private static BibEntry undefinedBibentryToNull( BibEntry cEntry ) { - if ( cEntry instanceof UndefinedBibtexEntry ) { + private static BibEntry undefinedBibentryToNull(BibEntry cEntry) { + if (cEntry instanceof UndefinedBibtexEntry) { return null; } return cEntry; } - private static BibEntry[] mapUndefinedBibentriesToNull( BibEntry[] cEntries ) { + private static BibEntry[] mapUndefinedBibentriesToNull(BibEntry[] cEntries) { return - Arrays.stream(cEntries) - .map( OOBibBase::undefinedBibentryToNull ) - .toArray( BibEntry[]::new ); + Arrays.stream(cEntries) + .map(OOBibBase::undefinedBibentryToNull) + .toArray(BibEntry[]::new); } private static void - assertKeysInCiteKeyToBibEntry( String[] keys, // citeKeys - Map citeKeyToBibEntry, - String referenceMarkName // for reporting - ) - throws BibEntryNotFoundException - { + assertKeysInCiteKeyToBibEntry(String[] keys, // citeKeys + Map citeKeyToBibEntry, + String referenceMarkName // for reporting + ) + throws BibEntryNotFoundException { // check keys List unresovedKeys = - Arrays.stream( keys ) - .filter( key -> null == citeKeyToBibEntry.get(key) ) - .collect(Collectors.toList()); + Arrays.stream(keys) + .filter(key -> null == citeKeyToBibEntry.get(key)) + .collect(Collectors.toList()); - for ( String key : unresovedKeys ) { + for (String key : unresovedKeys) { LOGGER.info("Citation key not found: '" + key + '\''); LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); String msg = Localization.lang("Could not resolve BibTeX entry" - + " for citation marker '%0'.", - referenceMarkName - ); + + " for citation marker '%0'.", + referenceMarkName + ); throw new BibEntryNotFoundException(referenceMarkName, msg); } } // TODO: is mapCiteKeysToBibEntryArray is still needed? private static BibEntry[] - mapCiteKeysToBibEntryArray( String[] keys, // citeKeys - Map citeKeyToBibEntry, - String referenceMarkName // for reporting - //boolean undefinedToNull // for undefined entries insert NULL - ) - throws BibEntryNotFoundException - { - if ( true ){ - assertKeysInCiteKeyToBibEntry( keys, citeKeyToBibEntry, referenceMarkName ); + mapCiteKeysToBibEntryArray(String[] keys, // citeKeys + Map citeKeyToBibEntry, + String referenceMarkName // for reporting + // boolean undefinedToNull // for undefined entries insert NULL + ) + throws BibEntryNotFoundException { + if (true) { + assertKeysInCiteKeyToBibEntry(keys, citeKeyToBibEntry, referenceMarkName); // process keys BibEntry[] cEntries = - Arrays.stream( keys ) - .map( key -> (BibEntry) citeKeyToBibEntry.get(key) ) - .toArray( BibEntry[]::new ); + Arrays.stream(keys) + .map(key -> (BibEntry) citeKeyToBibEntry.get(key)) + .toArray(BibEntry[]::new); return cEntries; - } else { BibEntry[] cEntries = new BibEntry[keys.length]; // fill cEntries for (int j = 0; j < keys.length; j++) { String kj = keys[j]; - BibEntry tmpEntry = citeKeyToBibEntry.get( kj ); - if ( tmpEntry == null ) { + BibEntry tmpEntry = citeKeyToBibEntry.get(kj); + if (tmpEntry == null) { LOGGER.info("Citation key not found: '" + kj + '\''); LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); String msg = Localization.lang("Could not resolve BibTeX entry" - + " for citation marker '%0'.", - referenceMarkName - ); + + " for citation marker '%0'.", + referenceMarkName + ); throw new BibEntryNotFoundException(referenceMarkName, msg); } else { cEntries[j] = tmpEntry; } - } // for j return cEntries; } } private static void - assertAllKeysInCiteKeyToBibEntry(List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry) - throws BibEntryNotFoundException - { + assertAllKeysInCiteKeyToBibEntry(List referenceMarkNames, + String[][] bibtexKeys, + Map citeKeyToBibEntry) + throws BibEntryNotFoundException { final int nRefMarks = referenceMarkNames.size(); - assert ( nRefMarks == bibtexKeys.length ); + assert (nRefMarks == bibtexKeys.length); for (int i = 0; i < nRefMarks; i++) { final String referenceMarkName = referenceMarkNames.get(i); - assertKeysInCiteKeyToBibEntry( bibtexKeys[i], - citeKeyToBibEntry, - referenceMarkName ); + assertKeysInCiteKeyToBibEntry(bibtexKeys[i], + citeKeyToBibEntry, + referenceMarkName); } - } private static String[] - rcmCitationMarkersForIsCitationKeyCiteMarkers( List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry, - OOBibStyle style ) - throws BibEntryNotFoundException - { + rcmCitationMarkersForIsCitationKeyCiteMarkers(List referenceMarkNames, + String[][] bibtexKeys, + Map citeKeyToBibEntry, + OOBibStyle style) + throws BibEntryNotFoundException { assert style.isCitationKeyCiteMarkers(); final int nRefMarks = referenceMarkNames.size(); assert nRefMarks == bibtexKeys.length; - assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeys, citeKeyToBibEntry ); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { citMarkers[i] = - Arrays.stream( bibtexKeys[i] ) - .map( key -> citeKeyToBibEntry.get(key) ) - .map( (c) -> c.getCitationKey().orElse("") ) - .collect(Collectors.joining(",")); + Arrays.stream(bibtexKeys[i]) + .map(key -> citeKeyToBibEntry.get(key)) + .map((c) -> c.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); } return citMarkers; } /** - * Number source for (1-based) numbering of citations. - * - * + * Number source for (1-based) numbering of citations. */ private static class CitationNumberingState { public Map numbers; public int lastNum; + CitationNumberingState() { - // For numbered citation style. Map( citedKey, number ) + // For numbered citation style. Map(citedKey, number ) Map numbers = new HashMap<>(); int lastNum = 0; } + /** - * The first call returns 1. + * The first call returns 1. */ - public int getOrAllocateNumber( String key ) { + public int getOrAllocateNumber(String key) { int result; if (numbers.containsKey(key)) { // Already seen @@ -1306,69 +1227,58 @@ public int getOrAllocateNumber( String key ) { } /** - * Get number for a BibEntry. (-1) for UndefinedBibtexEntry - * - * BibEntry.getCitationKey() must not be Optional.empty(). - * + * Get number for a BibEntry. (-1) for UndefinedBibtexEntry + *

+ * BibEntry.getCitationKey() must not be Optional.empty(). */ - private static int numberPossiblyUndefinedBibEntry( BibEntry ce, - CitationNumberingState cns ) - { + private static int numberPossiblyUndefinedBibEntry(BibEntry ce, + CitationNumberingState cns) { if (ce instanceof UndefinedBibtexEntry) { return (-1); } String key = ce.getCitationKey() - .orElseThrow(IllegalArgumentException::new); - - return cns.getOrAllocateNumber( key ); + .orElseThrow(IllegalArgumentException::new); + return cns.getOrAllocateNumber(key); } /** - * @param referenceMarkNames - * - * @param bibtexKeys Expects bibtexKeys[i] to correspond to - * referenceMarkNames.get(i) - * - * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. - * Must contain all bibtexKeys, but may map to UndefinedBibtexEntry. - * - * @return Numbered citation markers for bibtexKeys. - * - * Numbering is according to first encounter in bibtexKeys[i][j] (for(i){for(j){}} ) - * + * @param referenceMarkNames + * @param bibtexKeys Expects bibtexKeys[i] to correspond to referenceMarkNames.get(i) + * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. Must contain all bibtexKeys, but may map to UndefinedBibtexEntry. + * @return Numbered citation markers for bibtexKeys. + * Numbering is according to first encounter in bibtexKeys[i][j] (for(i){for(j){}} ) */ private static String[] - rcmCitationMarkersForIsNumberEntriesIsSortByPosition( List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry, - OOBibStyle style ) - throws BibEntryNotFoundException - { + rcmCitationMarkersForIsNumberEntriesIsSortByPosition(List referenceMarkNames, + String[][] bibtexKeys, + Map citeKeyToBibEntry, + OOBibStyle style) + throws BibEntryNotFoundException { assert style.isNumberEntries(); assert style.isSortByPosition(); final int nRefMarks = referenceMarkNames.size(); - assert ( nRefMarks == bibtexKeys.length ); - assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeys, citeKeyToBibEntry ); + assert (nRefMarks == bibtexKeys.length); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); String[] citMarkers = new String[nRefMarks]; CitationNumberingState cns = new CitationNumberingState(); final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); for (int i = 0; i < referenceMarkNames.size(); i++) { final String referenceMarkName = referenceMarkNames.get(i); // nums: Numbers for cEntries, (-1) for none. List nums = - Arrays.stream( bibtexKeys[i] ) - .map( key -> citeKeyToBibEntry.get(key) ) - .map( ce -> numberPossiblyUndefinedBibEntry(ce, cns) ) - .collect( Collectors.toList() ); + Arrays.stream(bibtexKeys[i]) + .map(key -> citeKeyToBibEntry.get(key)) + .map(ce -> numberPossiblyUndefinedBibEntry(ce, cns)) + .collect(Collectors.toList()); citMarkers[i] = style.getNumCitationMarker(nums, minGroupingCount, false); } // for @@ -1376,56 +1286,51 @@ private static int numberPossiblyUndefinedBibEntry( BibEntry ce, } /** - * Produce citation markers for the case of `numbered entries` - * that are not sorted by position. + * Produce citation markers for the case of `numbered entries` that are not sorted by position. */ private String[] - rcmCitationMarkersForIsNumberEntriesNotSortByPosition( List referenceMarkNames, - String[][] bibtexKeys, - Map entries, - OOBibStyle style ) - { + rcmCitationMarkersForIsNumberEntriesNotSortByPosition(List referenceMarkNames, + String[][] bibtexKeys, + Map entries, + OOBibStyle style) { assert style.isNumberEntries(); assert !style.isSortByPosition(); final int nRefMarks = referenceMarkNames.size(); - assert ( nRefMarks == bibtexKeys.length ); + assert (nRefMarks == bibtexKeys.length); String[] citMarkers = new String[nRefMarks]; // sort entries to order in bibliography - Map sortedEntries = sortEntriesByComparator( entries, entryComparator ); + Map sortedEntries = sortEntriesByComparator(entries, entryComparator); // adjust order of cited to match - List sortedCited = new ArrayList( entries.size() ); + List sortedCited = new ArrayList(entries.size()); sortedCited.clear(); for (BibEntry entry : sortedEntries.keySet()) { sortedCited.add(entry.getCitationKey().orElse(null)); } final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); for (int i = 0; i < referenceMarkNames.size(); i++) { final String namei = referenceMarkNames.get(i); List num = - findCitedEntryIndices( Arrays.asList(bibtexKeys[i]), sortedCited ); + findCitedEntryIndices(Arrays.asList(bibtexKeys[i]), sortedCited); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); } return citMarkers; } /** - * Resolve the citation key from a citation reference marker name, - * and look up the index of the key in a list of keys. + * Resolve the citation key from a citation reference marker name, and look up the index of the key in a list of keys. * - * @param keysCitedHere The citation keys needing indices. - * @param orderedCiteKeys A List of citation keys representing the entries in the bibliography. - * @return the (1-based) indices of the cited keys, -1 if a key is not found. - * Returns Collections.emptyList() if the ref name could not be resolved as a citation. + * @param keysCitedHere The citation keys needing indices. + * @param orderedCiteKeys A List of citation keys representing the entries in the bibliography. + * @return the (1-based) indices of the cited keys, -1 if a key is not found. Returns Collections.emptyList() if the ref name could not be resolved as a citation. */ private static List findCitedEntryIndices(List keysCitedHere, - List orderedCiteKeys) - { + List orderedCiteKeys) { List result = new ArrayList<>(keysCitedHere.size()); for (String key : keysCitedHere) { int ind = orderedCiteKeys.indexOf(key); @@ -1435,40 +1340,35 @@ private static List findCitedEntryIndices(List keysCitedHere, } /** - * Visit each reference mark in referenceMarkNames, - * remove its text content, - * call insertReferenceMark. + * Visit each reference mark in referenceMarkNames, remove its text content, call insertReferenceMark. + *

+ * After each insertReferenceMark call check if we lost the OOBibBase.BIB_SECTION_NAME bookmark and recrate it if we did. * - * After each insertReferenceMark call check if we lost the - * OOBibBase.BIB_SECTION_NAME bookmark and recrate it if we did. - * - * @param referenceMarkNames Reference mark names - * @param citMarkers Corresponding text for each reference mark, - * that replaces the old text. - * @param types itcType codes for each reference mark. + * @param referenceMarkNames Reference mark names + * @param citMarkers Corresponding text for each reference mark, that replaces the old text. + * @param types itcType codes for each reference mark. * @param style */ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, List referenceMarkNames, - String[] citMarkers, - int[] types, - OOBibStyle style - ) - throws NoDocumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - CreationException, - WrappedTargetException, - PropertyVetoException - { + String[] citMarkers, + int[] types, + OOBibStyle style + ) + throws NoDocumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + CreationException, + WrappedTargetException, + PropertyVetoException { final int nRefMarks = referenceMarkNames.size(); - assert ( citMarkers.length == nRefMarks ); - assert ( types.length == nRefMarks ); + assert (citMarkers.length == nRefMarks); + assert (types.length == nRefMarks); XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); final boolean hadBibSection = - (getBookmarkRange(documentConnection, OOBibBase.BIB_SECTION_NAME) != null); + (getBookmarkRange(documentConnection, OOBibBase.BIB_SECTION_NAME) != null); // If we are supposed to set character format for citations, // must run a test before we delete old citation @@ -1483,10 +1383,10 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, XTextContent bookmark = unoQI(XTextContent.class, referenceMark); XTextCursor cursor = - bookmark - .getAnchor() - .getText() - .createTextCursorByRange(bookmark.getAnchor()); + bookmark + .getAnchor() + .getText() + .createTextCursorByRange(bookmark.getAnchor()); if (mustTestCharFormat) { mustTestCharFormat = false; // need to do this only once @@ -1495,9 +1395,9 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { throw new UndefinedCharacterFormatException(charStyle); } } @@ -1505,15 +1405,15 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, documentConnection.xText.removeTextContent(bookmark); insertReferenceMark(documentConnection, - referenceMarkNames.get(i), - citMarkers[i], - cursor, - types[i] != OOBibBase.INVISIBLE_CIT, - style - ); + referenceMarkNames.get(i), + citMarkers[i], + cursor, + types[i] != OOBibBase.INVISIBLE_CIT, + style + ); if (hadBibSection && (getBookmarkRange(documentConnection, - OOBibBase.BIB_SECTION_NAME) == null)) { + OOBibBase.BIB_SECTION_NAME) == null)) { // We have overwritten the marker for the start of the reference list. // We need to add it again. cursor.collapseToEnd(); @@ -1524,24 +1424,22 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, } /** - * For each name in referenceMarkNames fill types[i] and - * bibtexKeys[i] with values parsed from referenceMarkNames.get(i) + * For each name in referenceMarkNames fill types[i] and bibtexKeys[i] with values parsed from referenceMarkNames.get(i) * - * @param referenceMarkNames Should only contain parsable names. - * @param types OUT Preallocated, same length as referenceMarkNames. - * @param bibtexKeys OUT First level must be same length as referenceMarkNames. + * @param referenceMarkNames Should only contain parsable names. + * @param types OUT Preallocated, same length as referenceMarkNames. + * @param bibtexKeys OUT First level must be same length as referenceMarkNames. */ - private static void parseRefMarkNamesToArrays( List referenceMarkNames, - int[] types, - String[][] bibtexKeys ) - { + private static void parseRefMarkNamesToArrays(List referenceMarkNames, + int[] types, + String[][] bibtexKeys) { final int nRefMarks = referenceMarkNames.size(); - assert ( types.length == nRefMarks ); - assert ( bibtexKeys.length == nRefMarks ); + assert (types.length == nRefMarks); + assert (bibtexKeys.length == nRefMarks); for (int i = 0; i < nRefMarks; i++) { final String namei = referenceMarkNames.get(i); - Optional op = parseRefMarkName( namei ); - if ( !op.isPresent() ) { + Optional op = parseRefMarkName(namei); + if (!op.isPresent()) { // We have a problem. We want types[i] and bibtexKeys[i] // to correspond to referenceMarkNames.get(i). // And do not want null in bibtexKeys (or error code in types) @@ -1550,12 +1448,12 @@ private static void parseRefMarkNamesToArrays( List referenceMarkNames, continue; } ParsedRefMark ov = op.get(); - types[i] = ov.itcType; // Remember the itcType in case we need to uniquefy. + types[i] = ov.itcType; // Remember the itcType in case we need to uniquefy. bibtexKeys[i] = ov.citedKeys.stream().toArray(String[]::new); } } - private static List unresolvedKeysFromEntries( Map entries ) { + private static List unresolvedKeysFromEntries(Map entries) { // Collect and return unresolved citation keys. // uses: entries List unresolvedKeys = new ArrayList<>(); @@ -1570,41 +1468,38 @@ private static List unresolvedKeysFromEntries( Map referenceMarkNames, - String[][] bibtexKeysIn, - Map citeKeyToBibEntry, - int[] types, - Map entries, - final Map uniquefiers, - OOBibStyle style - ) - throws BibEntryNotFoundException - { + rcmCitationMarkersForNormalStyle(List referenceMarkNames, + String[][] bibtexKeysIn, + Map citeKeyToBibEntry, + int[] types, + Map entries, + final Map uniquefiers, + OOBibStyle style + ) + throws BibEntryNotFoundException { uniquefiers.clear(); assert !style.isCitationKeyCiteMarkers(); @@ -1612,29 +1507,29 @@ private class RcmCitationMarkersForNormalStyleResult { // Citations in (Au1, Au2 2000) form final int nRefMarks = referenceMarkNames.size(); - assert ( bibtexKeysIn.length == nRefMarks ); - assert ( types.length == nRefMarks ); - assertAllKeysInCiteKeyToBibEntry( referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry ); + assert (bibtexKeysIn.length == nRefMarks); + assert (types.length == nRefMarks); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); BibEntry[][] cEntriesForAll = - Arrays.stream( bibtexKeysIn ) - .map( bibtexKeysOfARefererenceMark -> - Arrays.stream( bibtexKeysOfARefererenceMark ) - .map( key -> citeKeyToBibEntry.get(key) ) - .sorted( comparatorForMulticite(style) ) // sort within referenceMark - .toArray( BibEntry[]::new ) - ) - .toArray( BibEntry[][]::new ); + Arrays.stream(bibtexKeysIn) + .map(bibtexKeysOfARefererenceMark -> + Arrays.stream(bibtexKeysOfARefererenceMark) + .map(key -> citeKeyToBibEntry.get(key)) + .sorted(comparatorForMulticite(style)) // sort within referenceMark + .toArray(BibEntry[]::new) + ) + .toArray(BibEntry[][]::new); // Update bibtexKeys to match the new sorting (within each referenceMark) String[][] bibtexKeys = - Arrays.stream( cEntriesForAll ) - .map( cEntries -> - Arrays.stream( cEntries ) - .map( ce -> ce.getCitationKey().orElse(null) ) - .toArray(String[]::new) - ) - .toArray(String[][]::new); + Arrays.stream(cEntriesForAll) + .map(cEntries -> + Arrays.stream(cEntries) + .map(ce -> ce.getCitationKey().orElse(null)) + .toArray(String[]::new) + ) + .toArray(String[][]::new); assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); assert (bibtexKeys.length == nRefMarks); @@ -1642,13 +1537,13 @@ private class RcmCitationMarkersForNormalStyleResult { String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { BibEntry[] cEntries = cEntriesForAll[i]; - int type = types[i]; - citMarkers[i] = style.getCitationMarker( Arrays.asList(cEntries), // entries - entries, // database - type == OOBibBase.AUTHORYEAR_PAR, - null, // uniquefiers - null // unlimAuthors - ); + int type = types[i]; + citMarkers[i] = style.getCitationMarker(Arrays.asList(cEntries), // entries + entries, // database + type == OOBibBase.AUTHORYEAR_PAR, + null, // uniquefiers + null // unlimAuthors + ); } // normCitMarkers[i][j] = for unification @@ -1658,159 +1553,154 @@ private class RcmCitationMarkersForNormalStyleResult { // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: normCitMarkers[i] = - Arrays.stream(cEntries) - .map( ce -> - style.getCitationMarker( Collections.singletonList(ce), - entries, // database - true, // inParenthesis - null, // uniquefiers - new int[] {-1} // unlimAuthors - ) - ) - .toArray(String[]::new); + Arrays.stream(cEntries) + .map(ce -> + style.getCitationMarker(Collections.singletonList(ce), + entries, // database + true, // inParenthesis + null, // uniquefiers + new int[] {-1} // unlimAuthors + ) + ) + .toArray(String[]::new); } uniquefiers.clear(); - // The following block - // changes: citMarkers[i], uniquefiers - // uses: nRefMarks, normCitMarkers, bibtexKeys, - // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) - // citeKeyToBibEntry, entries, types - - if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { - // Only for normal citations. Numbered citations and - // citeKeys are already unique. - - // See if there are duplicate citations marks referring to - // different entries. If so, we need to use uniquefiers: - - // refKeys: normCitMarker to list of bibtexkeys sharing it. - // The entries in the lists are ordered as in - // normCitMarkers[i][j] - Map> refKeys = new HashMap<>(); - - for (int i = 0; i < nRefMarks; i++) { - // Compare normalized markers, since the actual - // markers can be different. - String[] markers = normCitMarkers[i]; - for (int j = 0; j < markers.length; j++) { - String marker = markers[j]; - String currentKey = bibtexKeys[i][j]; - if (refKeys.containsKey(marker)) { - // Ok, we have seen this exact marker before. - if (!refKeys.get(marker).contains(currentKey)) { - // ... but not for this entry. - refKeys.get(marker).add(currentKey); - } - } else { - // add as new entry - List l = new ArrayList<>(1); - l.add(currentKey); - refKeys.put(marker, l); + // The following block + // changes: citMarkers[i], uniquefiers + // uses: nRefMarks, normCitMarkers, bibtexKeys, + // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) + // citeKeyToBibEntry, entries, types + + if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { + // Only for normal citations. Numbered citations and + // citeKeys are already unique. + + // See if there are duplicate citations marks referring to + // different entries. If so, we need to use uniquefiers: + + // refKeys: normCitMarker to list of bibtexkeys sharing it. + // The entries in the lists are ordered as in + // normCitMarkers[i][j] + Map> refKeys = new HashMap<>(); + + for (int i = 0; i < nRefMarks; i++) { + // Compare normalized markers, since the actual + // markers can be different. + String[] markers = normCitMarkers[i]; + for (int j = 0; j < markers.length; j++) { + String marker = markers[j]; + String currentKey = bibtexKeys[i][j]; + if (refKeys.containsKey(marker)) { + // Ok, we have seen this exact marker before. + if (!refKeys.get(marker).contains(currentKey)) { + // ... but not for this entry. + refKeys.get(marker).add(currentKey); } + } else { + // add as new entry + List l = new ArrayList<>(1); + l.add(currentKey); + refKeys.put(marker, l); } } + } - // Go through the collected lists and see where we need to - // uniquefy: - for (Map.Entry> stringListEntry : refKeys.entrySet()) { - List clashingKeys = stringListEntry.getValue(); - if (clashingKeys.size() > 1) { - // This marker appears for more than one unique entry: - int uniq = 'a'; - for (String key : clashingKeys) { - // Update the map of uniquefiers for the - // benefit of both the following generation of - // new citation markers, and for the method - // that builds the bibliography: - uniquefiers.put(key, String.valueOf((char) uniq)); - uniq++; - } + // Go through the collected lists and see where we need to + // uniquefy: + for (Map.Entry> stringListEntry : refKeys.entrySet()) { + List clashingKeys = stringListEntry.getValue(); + if (clashingKeys.size() > 1) { + // This marker appears for more than one unique entry: + int uniq = 'a'; + for (String key : clashingKeys) { + // Update the map of uniquefiers for the + // benefit of both the following generation of + // new citation markers, and for the method + // that builds the bibliography: + uniquefiers.put(key, String.valueOf((char) uniq)); + uniq++; } } + } - // Finally, go through all citation markers, and update - // those referring to entries in our current list: - final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); - Set seenBefore = new HashSet<>(); - for (int i = 0; i < nRefMarks; i++) { - final String namei = referenceMarkNames.get(i); - final int nCitedEntries = bibtexKeys[i].length; - boolean needsChange = false; - int[] firstLimAuthors = new int[nCitedEntries]; - String[] uniquif = new String[nCitedEntries]; - BibEntry[] cEntries = mapCiteKeysToBibEntryArray(bibtexKeys[i], - citeKeyToBibEntry, - namei); - cEntries = mapUndefinedBibentriesToNull(cEntries); - - for (int j = 0; j < nCitedEntries; j++) { - String currentKey = bibtexKeys[i][j]; - - // firstLimAuthors will be (-1) except at the first - // refMark it appears at, where a positive maxAuthorsFirst - // may override. This is why: - // https://discourse.jabref.org/t/ - // number-of-authors-in-citations-style-libreoffice/747/3 - // "Some citation styles require to list the full - // names of the first 4 authors for the first - // time. Later it is sufficient to have only maybe - // (Author A and Author B 2019 et al.)" - firstLimAuthors[j] = -1; - if (maxAuthorsFirst > 0) { - if (!seenBefore.contains(currentKey)) { - firstLimAuthors[j] = maxAuthorsFirst; - } - seenBefore.add(currentKey); - } - - { - String uniq = uniquefiers.get(currentKey); - if (uniq == null) { - uniquif[j] = ""; - } else { - uniquif[j] = uniq; - needsChange = true; - } + // Finally, go through all citation markers, and update + // those referring to entries in our current list: + final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); + Set seenBefore = new HashSet<>(); + for (int i = 0; i < nRefMarks; i++) { + final String namei = referenceMarkNames.get(i); + final int nCitedEntries = bibtexKeys[i].length; + boolean needsChange = false; + int[] firstLimAuthors = new int[nCitedEntries]; + String[] uniquif = new String[nCitedEntries]; + BibEntry[] cEntries = mapCiteKeysToBibEntryArray(bibtexKeys[i], + citeKeyToBibEntry, + namei); + cEntries = mapUndefinedBibentriesToNull(cEntries); + + for (int j = 0; j < nCitedEntries; j++) { + String currentKey = bibtexKeys[i][j]; + + // firstLimAuthors will be (-1) except at the first + // refMark it appears at, where a positive maxAuthorsFirst + // may override. This is why: + // https://discourse.jabref.org/t/ + // number-of-authors-in-citations-style-libreoffice/747/3 + // "Some citation styles require to list the full + // names of the first 4 authors for the first + // time. Later it is sufficient to have only maybe + // (Author A and Author B 2019 et al.)" + firstLimAuthors[j] = -1; + if (maxAuthorsFirst > 0) { + if (!seenBefore.contains(currentKey)) { + firstLimAuthors[j] = maxAuthorsFirst; } + seenBefore.add(currentKey); + } - if (firstLimAuthors[j] > 0) { + String uniq = uniquefiers.get(currentKey); + if (uniq == null) { + uniquif[j] = ""; + } else { + uniquif[j] = uniq; needsChange = true; } + if (firstLimAuthors[j] > 0) { + needsChange = true; + } + } // for j - } // for j - - if (needsChange) { - citMarkers[i] = + if (needsChange) { + citMarkers[i] = style.getCitationMarker(Arrays.asList(cEntries), - entries, - types[i] == OOBibBase.AUTHORYEAR_PAR, - uniquif, - firstLimAuthors - ); - } - } // for i - } // if normalStyle - return new RcmCitationMarkersForNormalStyleResult(citMarkers, bibtexKeys); + entries, + types[i] == OOBibBase.AUTHORYEAR_PAR, + uniquif, + firstLimAuthors + ); + } + } // for i + } // if normalStyle + return new RcmCitationMarkersForNormalStyleResult(citMarkers, bibtexKeys); } private List refreshCiteMarkersInternal(DocumentConnection documentConnection, List databases, OOBibStyle style, final Map uniquefiers - ) - throws WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException - { + ) + throws WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { // Normally we sort the reference marks according to their // order of appearance: @@ -1822,14 +1712,14 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // fill: // types[i] = ov.itcType // bibtexKeys[i] = ov.citedKeys.toArray() - int[] types = new int[nRefMarks]; + int[] types = new int[nRefMarks]; String[][] bibtexKeys = new String[nRefMarks][]; parseRefMarkNamesToArrays(referenceMarkNames, types, bibtexKeys); FindCitedEntriesResult fce = - findCitedEntries(databases, - findCitedKeys(documentConnection) - ); + findCitedEntries(databases, + findCitedKeys(documentConnection) + ); // fce.entries are now in same order as returned by findCitedKeys // citMarkers[i] = what goes in the text at referenceMark[i] @@ -1838,48 +1728,48 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // fill citMarkers uniquefiers.clear(); /* ModifiesParameter */ if (style.isCitationKeyCiteMarkers()) { - citMarkers = - rcmCitationMarkersForIsCitationKeyCiteMarkers(referenceMarkNames, - bibtexKeys, - fce.citeKeyToBibEntry, - style - ); + citMarkers = + rcmCitationMarkersForIsCitationKeyCiteMarkers(referenceMarkNames, + bibtexKeys, + fce.citeKeyToBibEntry, + style + ); } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { citMarkers = - rcmCitationMarkersForIsNumberEntriesIsSortByPosition(referenceMarkNames, - bibtexKeys, - fce.citeKeyToBibEntry, - style); + rcmCitationMarkersForIsNumberEntriesIsSortByPosition(referenceMarkNames, + bibtexKeys, + fce.citeKeyToBibEntry, + style); } else { citMarkers = - rcmCitationMarkersForIsNumberEntriesNotSortByPosition(referenceMarkNames, - bibtexKeys, - fce.entries, - style - ); + rcmCitationMarkersForIsNumberEntriesNotSortByPosition(referenceMarkNames, + bibtexKeys, + fce.entries, + style + ); } } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { RcmCitationMarkersForNormalStyleResult nsr = - rcmCitationMarkersForNormalStyle(referenceMarkNames, - bibtexKeys, - fce.citeKeyToBibEntry, - types, - fce.entries, - uniquefiers, - style - ); + rcmCitationMarkersForNormalStyle(referenceMarkNames, + bibtexKeys, + fce.citeKeyToBibEntry, + types, + fce.entries, + uniquefiers, + style + ); citMarkers = nsr.citMarkers; bibtexKeys = nsr.bibtexKeys; } // Refresh all reference marks with the citation markers we computed: rcmApplyNewCitationMarkers(documentConnection, - referenceMarkNames, - citMarkers, - types, - style); + referenceMarkNames, + citMarkers, + types, + style); return unresolvedKeysFromEntries(fce.entries); } @@ -1898,17 +1788,16 @@ private static Point findPositionOfTextRange(XTextViewCursor cursor, XTextRange * */ private List - getJabRefReferenceMarkNamesSortedByPosition(DocumentConnection documentConnection) - throws WrappedTargetException, - NoSuchElementException, - NoDocumentException - { + getJabRefReferenceMarkNamesSortedByPosition(DocumentConnection documentConnection) + throws WrappedTargetException, + NoSuchElementException, + NoDocumentException { List names = getJabRefReferenceMarkNames(documentConnection); // find coordinates List positions = new ArrayList<>(names.size()); - { + XNameAccess nameAccess = documentConnection.getReferenceMarks(); XTextViewCursor viewCursor = documentConnection.getViewCursor(); // initialPos: to be restored before return @@ -1916,7 +1805,7 @@ private static Point findPositionOfTextRange(XTextViewCursor cursor, XTextRange for (String name : names) { XTextContent textContent = - unoQI(XTextContent.class, nameAccess.getByName(name)); + unoQI(XTextContent.class, nameAccess.getByName(name)); XTextRange range = textContent.getAnchor(); // Adjust range if we are inside a footnote: @@ -1930,7 +1819,6 @@ private static Point findPositionOfTextRange(XTextViewCursor cursor, XTextRange } // restore cursor position viewCursor.gotoRange(initialPos, false); - } // order by position Set set = new TreeSet<>(); @@ -1948,13 +1836,12 @@ private static Point findPositionOfTextRange(XTextViewCursor cursor, XTextRange } public void updateSortedReferenceMarks() - throws WrappedTargetException, - NoSuchElementException, - NoDocumentException - { + throws WrappedTargetException, + NoSuchElementException, + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); this.jabRefReferenceMarkNamesSortedByPosition = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); } /** @@ -1964,50 +1851,49 @@ public void updateSortedReferenceMarks() */ public List updateDocumentActionHelper(List databases, OOBibStyle style) - throws NoSuchElementException, - WrappedTargetException, - IllegalArgumentException, - CreationException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - NoDocumentException, - UndefinedCharacterFormatException, - BibEntryNotFoundException, - IOException { + throws NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException, + NoDocumentException, + UndefinedCharacterFormatException, + BibEntryNotFoundException, + IOException { updateSortedReferenceMarks(); List unresolvedKeys = refreshCiteMarkers(databases, style); rebuildBibTextSection(databases, style); return unresolvedKeys; } - public void rebuildBibTextSection(List databases, OOBibStyle style) - throws NoSuchElementException, - WrappedTargetException, - IllegalArgumentException, - CreationException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - NoDocumentException { + throws NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException, + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); FindCitedEntriesResult fce = - findCitedEntries(databases, - findCitedKeys(documentConnection) - ); + findCitedEntries(databases, + findCitedKeys(documentConnection) + ); Map entries; if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: entries = sortEntriesByRefMarkNames( - jabRefReferenceMarkNamesSortedByPosition, - fce.citeKeyToBibEntry, - fce.entries - ); + jabRefReferenceMarkNamesSortedByPosition, + fce.citeKeyToBibEntry, + fce.entries + ); } else { entries = sortEntriesByComparator(fce.entries, entryComparator); } @@ -2016,28 +1902,26 @@ public void rebuildBibTextSection(List databases, } SortedMap - sortEntriesByComparator(Map entries, - Comparator entryComparator) { + sortEntriesByComparator(Map entries, + Comparator entryComparator) { SortedMap newMap = new TreeMap<>(entryComparator); for (Map.Entry kv : entries.entrySet()) { newMap.put(kv.getKey(), - kv.getValue()); + kv.getValue()); } return newMap; } /** * @param referenceMarkNames - * @param citeKeyToBibEntry Helps to find the entries - * - * @return LinkedHashMap from BibEntry to BibDatabase with - * iteration order as first appearance in referenceMarkNames. + * @param citeKeyToBibEntry Helps to find the entries + * @return LinkedHashMap from BibEntry to BibDatabase with iteration order as first appearance in referenceMarkNames. */ private Map - sortEntriesByRefMarkNames(List referenceMarkNames, - Map citeKeyToBibEntry, - Map entries - ) { + sortEntriesByRefMarkNames(List referenceMarkNames, + Map citeKeyToBibEntry, + Map entries + ) { // LinkedHashMap: iteration order is insertion-order, not // affected if a key is re-inserted. @@ -2069,7 +1953,7 @@ public void rebuildBibTextSection(List databases, } /** - * Only called from populateBibTextSection (and that from rebuildBibTextSection) + * Only called from populateBibTextSection (and that from rebuildBibTextSection) */ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, XTextCursor cursor, @@ -2078,10 +1962,10 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, String parFormat, final Map uniquefiers) throws UndefinedParagraphFormatException, - IllegalArgumentException, - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { + IllegalArgumentException, + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { int number = 1; for (Map.Entry entry : entries.entrySet()) { @@ -2100,35 +1984,35 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); int minGroupingCount = 2; String marker = style.getNumCitationMarker(Collections.singletonList(number++), - minGroupingCount, - true); + minGroupingCount, + true); OOUtil.insertTextAtCurrentLocation(documentConnection.xText, - cursor, - marker, - Collections.emptyList() - ); + cursor, + marker, + Collections.emptyList() + ); } // insert the actual details. Layout layout = style.getReferenceFormat(entry.getKey().getType()); layout.setPostFormatter(POSTFORMATTER); OOUtil.insertFullReferenceAtCurrentLocation( - documentConnection.xText, - cursor, - layout, - parFormat, - entry.getKey(), - entry.getValue(), - uniquefiers.get(entry.getKey().getCitationKey().orElse(null)) - ); + documentConnection.xText, + cursor, + layout, + parFormat, + entry.getKey(), + entry.getValue(), + uniquefiers.get(entry.getKey().getCitationKey().orElse(null)) + ); } } private void createBibTextSection2(DocumentConnection documentConnection, boolean end) throws IllegalArgumentException, - CreationException { + CreationException { XTextCursor textCursor = documentConnection.xText.createTextCursor(); if (end) { @@ -2141,9 +2025,9 @@ private void createBibTextSection2(DocumentConnection documentConnection, XNamed xChildNamed; try { xChildNamed = unoQI(XNamed.class, - (documentConnection.mxDocFactory - .createInstance("com.sun.star.text.TextSection")) - ); + (documentConnection.mxDocFactory + .createInstance("com.sun.star.text.TextSection")) + ); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -2155,14 +2039,14 @@ private void createBibTextSection2(DocumentConnection documentConnection, } private void clearBibTextSectionContent2(DocumentConnection documentConnection) - throws NoSuchElementException, - WrappedTargetException, - IllegalArgumentException, - CreationException { + throws NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException { // Check if the section exists: XTextSectionsSupplier supplier = - unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); + unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); com.sun.star.container.XNameAccess ts = supplier.getTextSections(); @@ -2172,7 +2056,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) XTextSection section = (XTextSection) a.getObject(); // Clear it: XTextCursor cursor = - documentConnection.xText.createTextCursorByRange(section.getAnchor()); + documentConnection.xText.createTextCursorByRange(section.getAnchor()); cursor.gotoRange(section.getAnchor(), false); cursor.setString(""); return; @@ -2200,47 +2084,46 @@ private void populateBibTextSection(DocumentConnection documentConnection, Map entries, OOBibStyle style, final Map uniquefiers) - throws NoSuchElementException, - WrappedTargetException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - IllegalArgumentException, - CreationException { + throws NoSuchElementException, + WrappedTargetException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException, + IllegalArgumentException, + CreationException { XTextSectionsSupplier supplier = - unoQI(XTextSectionsSupplier.class, - documentConnection.mxDoc); + unoQI(XTextSectionsSupplier.class, + documentConnection.mxDoc); XTextSection section = - ((XTextSection) - ((Any) supplier - .getTextSections() - .getByName(OOBibBase.BIB_SECTION_NAME) - ) - .getObject() - ); + ((XTextSection) + ((Any) supplier + .getTextSections() + .getByName(OOBibBase.BIB_SECTION_NAME) + ) + .getObject() + ); XTextCursor cursor = - documentConnection.xText - .createTextCursorByRange(section.getAnchor()); + documentConnection.xText + .createTextCursorByRange(section.getAnchor()); OOUtil.insertTextAtCurrentLocation( - documentConnection.xText, - cursor, - (String) style.getProperty(OOBibStyle.TITLE), - (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT) - ); - + documentConnection.xText, + cursor, + (String) style.getProperty(OOBibStyle.TITLE), + (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT) + ); String refParaFormat = - (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); + (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); insertFullReferenceAtCursor(documentConnection, - cursor, - entries, - style, - refParaFormat, - uniquefiers - ); + cursor, + entries, + style, + refParaFormat, + uniquefiers + ); insertBookMark(documentConnection, OOBibBase.BIB_SECTION_END_NAME, cursor); } @@ -2248,12 +2131,12 @@ private void populateBibTextSection(DocumentConnection documentConnection, private XTextContent insertBookMark(DocumentConnection documentConnection, String name, XTextCursor position) - throws IllegalArgumentException, - CreationException { + throws IllegalArgumentException, + CreationException { Object bookmark; try { bookmark = (documentConnection.mxDocFactory - .createInstance("com.sun.star.text.Bookmark")); + .createInstance("com.sun.star.text.Bookmark")); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -2278,11 +2161,11 @@ private void insertReferenceMark(DocumentConnection documentConnection, boolean withText, OOBibStyle style) throws UnknownPropertyException, - WrappedTargetException, - PropertyVetoException, - IllegalArgumentException, - UndefinedCharacterFormatException, - CreationException { + WrappedTargetException, + PropertyVetoException, + IllegalArgumentException, + UndefinedCharacterFormatException, + CreationException { // Check if there is "page info" stored for this citation. If so, insert it into // the citation text before inserting the citation: @@ -2297,8 +2180,8 @@ private void insertReferenceMark(DocumentConnection documentConnection, Object bookmark; try { bookmark = - documentConnection.mxDocFactory - .createInstance("com.sun.star.text.ReferenceMark"); + documentConnection.mxDocFactory + .createInstance("com.sun.star.text.ReferenceMark"); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -2317,9 +2200,9 @@ private void insertReferenceMark(DocumentConnection documentConnection, try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { throw new UndefinedCharacterFormatException(charStyle); } } @@ -2346,9 +2229,9 @@ private void insertReferenceMark(DocumentConnection documentConnection, } private void removeReferenceMark(DocumentConnection documentConnection, String name) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException { + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException { XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); if (xReferenceMarks.hasByName(name)) { Object referenceMark = xReferenceMarks.getByName(name); @@ -2367,8 +2250,8 @@ private void removeReferenceMark(DocumentConnection documentConnection, String n */ private XTextRange getBookmarkRange(DocumentConnection documentConnection, String name) - throws NoSuchElementException, - WrappedTargetException { + throws NoSuchElementException, + WrappedTargetException { XNameAccess xNamedBookmarks = getBookmarks(documentConnection); // retrieve bookmark by name @@ -2384,28 +2267,27 @@ private XNameAccess getBookmarks(DocumentConnection documentConnection) { // query XBookmarksSupplier from document model // and get bookmarks collection XBookmarksSupplier xBookmarksSupplier = - unoQI(XBookmarksSupplier.class, - documentConnection.xCurrentComponent - ); + unoQI(XBookmarksSupplier.class, + documentConnection.xCurrentComponent + ); XNameAccess xNamedBookmarks = - xBookmarksSupplier.getBookmarks(); + xBookmarksSupplier.getBookmarks(); return xNamedBookmarks; } /** - * Taking ref=position.getStart(), italicize the range (ref+start,ref+end) - * - * @param position : position.getStart() is out reference point. - * @param italicize : if false, applies Bold, not Italic - * @param start - * @param end + * Taking ref=position.getStart(), italicize the range (ref+start,ref+end) * + * @param position : position.getStart() is out reference point. + * @param italicize : if false, applies Bold, not Italic + * @param start + * @param end */ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, int end) throws UnknownPropertyException, - PropertyVetoException, - IllegalArgumentException, - WrappedTargetException { + PropertyVetoException, + IllegalArgumentException, + WrappedTargetException { XTextRange range = position.getStart(); XTextCursor cursor = position.getText().createTextCursorByRange(range); cursor.goRight((short) start, false); @@ -2433,15 +2315,15 @@ List lookupEntriesInDatabases(List keys, List dat } private void testFormatCitations(XTextCursor textCursor, OOBibStyle style) - throws UndefinedCharacterFormatException { + throws UndefinedCharacterFormatException { XPropertySet xCursorProps = unoQI(XPropertySet.class, textCursor); String charStyle = style.getCitationCharacterFormat(); try { xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { // Setting the character format failed, so we throw an exception that // will result in an error message for the user: throw new UndefinedCharacterFormatException(charStyle); @@ -2449,27 +2331,27 @@ private void testFormatCitations(XTextCursor textCursor, OOBibStyle style) } /** - * GUI action + * GUI action */ public void combineCiteMarkers(List databases, OOBibStyle style) throws IOException, - WrappedTargetException, - NoSuchElementException, - IllegalArgumentException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException { + WrappedTargetException, + NoSuchElementException, + IllegalArgumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { DocumentConnection documentConnection = this.xDocumentConnection; // TODO: doesn't work for citations in footnotes/tables List names = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - documentConnection.xText); + documentConnection.xText); int pivot = 0; boolean madeModifications = false; @@ -2477,16 +2359,16 @@ public void combineCiteMarkers(List databases, OOBibStyle style) while (pivot < (names.size() - 1)) { XTextRange range1 = - unoQI(XTextContent.class, - nameAccess.getByName(names.get(pivot))) - .getAnchor() - .getEnd(); + unoQI(XTextContent.class, + nameAccess.getByName(names.get(pivot))) + .getAnchor() + .getEnd(); XTextRange range2 = - unoQI(XTextContent.class, - nameAccess.getByName(names.get(pivot + 1))) - .getAnchor() - .getStart(); + unoQI(XTextContent.class, + nameAccess.getByName(names.get(pivot + 1))) + .getAnchor() + .getStart(); if (range1.getText() != range2.getText()) { /* pivot and (pivot+1) belong to different XText entities? @@ -2499,7 +2381,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // Start from end of text for pivot. XTextCursor textCursor = - range1.getText().createTextCursorByRange(range1); + range1.getText().createTextCursorByRange(range1); // Select next character, and more, as long as we can and // do not reach stat of (pivot+1), which we now know to be @@ -2529,7 +2411,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } List keys = - parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); + parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); removeReferenceMark(documentConnection, names.get(pivot)); @@ -2539,15 +2421,15 @@ public void combineCiteMarkers(List databases, OOBibStyle style) Collections.sort(entries, new FieldComparator(StandardField.YEAR)); String keyString = - entries.stream() - .map(c -> c.getCitationKey().orElse("")) - .collect(Collectors.joining(",")); + entries.stream() + .map(c -> c.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); // Insert reference mark: String newName = getUniqueReferenceMarkName(documentConnection, - keyString, - OOBibBase.AUTHORYEAR_PAR - ); + keyString, + OOBibBase.AUTHORYEAR_PAR + ); insertReferenceMark(documentConnection, newName, "tmp", textCursor, true, style); names.set(pivot + 1, newName); // <- put in the next-to-be-processed position madeModifications = true; @@ -2562,28 +2444,26 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } /** - * GUI action. - * Do the opposite of combineCiteMarkers. - * Combined markers are split, with a space inserted between. + * GUI action. Do the opposite of combineCiteMarkers. Combined markers are split, with a space inserted between. */ public void unCombineCiteMarkers(List databases, OOBibStyle style) - throws IOException, - WrappedTargetException, - NoSuchElementException, - IllegalArgumentException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException { + throws IOException, + WrappedTargetException, + NoSuchElementException, + IllegalArgumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); List names = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - documentConnection.xText); + documentConnection.xText); int pivot = 0; boolean madeModifications = false; @@ -2591,12 +2471,12 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) while (pivot < (names.size())) { XTextRange range1 = - unoQI(XTextContent.class, - nameAccess.getByName(names.get(pivot))) - .getAnchor(); + unoQI(XTextContent.class, + nameAccess.getByName(names.get(pivot))) + .getAnchor(); XTextCursor textCursor = - range1.getText().createTextCursorByRange(range1); + range1.getText().createTextCursorByRange(range1); // If we are supposed to set character format for // citations, test this before making any changes. This @@ -2620,9 +2500,9 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) int i = 0; for (String key : keys) { String newName = getUniqueReferenceMarkName(documentConnection, - key, - OOBibBase.AUTHORYEAR_PAR - ); + key, + OOBibBase.AUTHORYEAR_PAR + ); insertReferenceMark(documentConnection, newName, "tmp", textCursor, true, style); textCursor.collapseToEnd(); if (i != last) { @@ -2645,9 +2525,9 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) * Used from GUI. */ public BibDatabase generateDatabase(List databases) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException { + throws NoSuchElementException, + WrappedTargetException, + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); BibDatabase resultDatabase = new BibDatabase(); @@ -2682,7 +2562,6 @@ public BibDatabase generateDatabase(List databases) return resultDatabase; } - private static class ComparableMark implements Comparable { private final String name; @@ -2725,5 +2604,4 @@ public int hashCode() { return Objects.hash(position, name); } } - } From c0734bb648c566674fca2c2912e1a72550b96a3c Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 23:41:07 +0100 Subject: [PATCH 0333/1068] shorten long comments --- .../org/jabref/gui/openoffice/OOBibBase.java | 95 ++++++++++++------- 1 file changed, 60 insertions(+), 35 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b4c213f1a18..414f6b520ac 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -88,7 +88,8 @@ import org.slf4j.LoggerFactory; /** - * Class for manipulating the Bibliography of the currently started document in OpenOffice. + * Class for manipulating the Bibliography of the currently started + * document in OpenOffice. */ @AllowedToUseAwt("Requires AWT for italics and bold") class OOBibBase { @@ -472,8 +473,6 @@ public String toString() { /** * Choose a document to work with. - *

- * inititalized fields: - this.xCurrentComponent - this.mxDoc - this.xViewCursorSupplier - this.xText - this.mxDocFactory - this.userProperties - this.propertySet */ public void selectDocument() throws NoDocumentException, @@ -667,16 +666,20 @@ private List getCitationEntriesImpl(DocumentConnection documentCo /** * Apply editable parts of citationEntries to the document. - *

+ * * - Currently the only editable part is pageInfo. - *

- * Since the only call to applyCitationEntries() only changes pageInfo w.r.t those returned by getCitationEntries(), we can do with the following restrictions: - *

+ * + * Since the only call to applyCitationEntries() only changes + * pageInfo w.r.t those returned by getCitationEntries(), we can + * do with the following restrictions: + * * - Missing pageInfo means no action. - *

- * - Missing CitationEntry means no action (no attempt to remove citation from the text). - *

- * - Reference to citation not present in the text evokes no error, and setCustomProperty() is called. + * + * - Missing CitationEntry means no action (no attempt to remove + citation from the text). + * + * - Reference to citation not present in the text evokes no + error, and setCustomProperty() is called. */ public void applyCitationEntries(List citationEntries) throws UnknownPropertyException, @@ -715,8 +718,9 @@ public void applyCitationEntries(List citationEntries) } /** - * The first occurrence of bibtexKey gets no serial number, the second gets 0, the third 1 ... - *

+ * The first occurrence of bibtexKey gets no serial number, the + * second gets 0, the third 1 ... + * * Or the first unused in this series, after removals. */ private String getUniqueReferenceMarkName(DocumentConnection documentConnection, @@ -763,14 +767,19 @@ private static Optional parseRefMarkName(String refMarkName) { } /** - * This method inserts a cite marker in the text (at the cursor) for the given BibEntry, and may refresh the bibliography. + * This method inserts a cite marker in the text (at the cursor) + * for the given BibEntry, and may refresh the bibliography. * * @param entries The entries to cite. * @param database The database the entry belongs to. * @param style The bibliography style we are using. - * @param inParenthesis Indicates whether it is an in-text citation or a citation in parenthesis. This is not relevant if numbered citations are used. - * @param withText Indicates whether this should be a normal citation (true) or an empty (invisible) citation (false). - * @param sync Indicates whether the reference list should be refreshed. + * @param inParenthesis Indicates whether it is an in-text + * citation or a citation in parenthesis. This is not relevant if + * numbered citations are used. + * @param withText Indicates whether this should be a normal + * citation (true) or an empty (invisible) citation (false). + * @param sync Indicates whether the reference list should be + * refreshed. * @throws IllegalTypeException * @throws PropertyExistException * @throws NotRemoveableException @@ -782,7 +791,11 @@ private static Optional parseRefMarkName(String refMarkName) { * @throws PropertyVetoException * @throws CreationException * @throws BibEntryNotFoundException - * @throws UndefinedParagraphFormatException TODO: https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html Group changes into a single Undo context. + * @throws UndefinedParagraphFormatException + * + * TODO: + * https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html + * Group changes into a single Undo context. */ public void insertEntry(List entries, BibDatabase database, @@ -942,9 +955,9 @@ private List parseRefMarkNameToUniqueCitationKeys(String name) { /** * Extract citation keys from names of referenceMarks in the document. - *

+ * * Each citation key is listed only once, in the order of first appearance. - *

+ * * doc.referenceMarks.names.map(parse).flatten.unique */ private List findCitedKeys(DocumentConnection documentConnection) @@ -1228,7 +1241,7 @@ public int getOrAllocateNumber(String key) { /** * Get number for a BibEntry. (-1) for UndefinedBibtexEntry - *

+ * * BibEntry.getCitationKey() must not be Optional.empty(). */ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, @@ -1245,10 +1258,13 @@ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, /** * @param referenceMarkNames - * @param bibtexKeys Expects bibtexKeys[i] to correspond to referenceMarkNames.get(i) - * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. Must contain all bibtexKeys, but may map to UndefinedBibtexEntry. - * @return Numbered citation markers for bibtexKeys. - * Numbering is according to first encounter in bibtexKeys[i][j] (for(i){for(j){}} ) + * @param bibtexKeys Expects bibtexKeys[i] to correspond to + * referenceMarkNames.get(i) + * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. Must + * contain all bibtexKeys, but may map to UndefinedBibtexEntry. + * @return Numbered citation markers for bibtexKeys. Numbering is + * according to first encounter in bibtexKeys[i][j] + * (for(i){for(j){}} ) */ private static String[] rcmCitationMarkersForIsNumberEntriesIsSortByPosition(List referenceMarkNames, @@ -1323,11 +1339,15 @@ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, } /** - * Resolve the citation key from a citation reference marker name, and look up the index of the key in a list of keys. + * Resolve the citation key from a citation reference marker name, + * and look up the index of the key in a list of keys. * * @param keysCitedHere The citation keys needing indices. - * @param orderedCiteKeys A List of citation keys representing the entries in the bibliography. - * @return the (1-based) indices of the cited keys, -1 if a key is not found. Returns Collections.emptyList() if the ref name could not be resolved as a citation. + * @param orderedCiteKeys A List of citation keys representing the + * entries in the bibliography. + * @return the (1-based) indices of the cited keys, -1 if a key is + * not found. Returns Collections.emptyList() if the ref name + * could not be resolved as a citation. */ private static List findCitedEntryIndices(List keysCitedHere, List orderedCiteKeys) { @@ -1340,13 +1360,16 @@ private static List findCitedEntryIndices(List keysCitedHere, } /** - * Visit each reference mark in referenceMarkNames, remove its text content, call insertReferenceMark. - *

- * After each insertReferenceMark call check if we lost the OOBibBase.BIB_SECTION_NAME bookmark and recrate it if we did. + * Visit each reference mark in referenceMarkNames, remove its + * text content, call insertReferenceMark. + * + * After each insertReferenceMark call check if we lost the + * OOBibBase.BIB_SECTION_NAME bookmark and recrate it if we did. * * @param referenceMarkNames Reference mark names - * @param citMarkers Corresponding text for each reference mark, that replaces the old text. - * @param types itcType codes for each reference mark. + * @param citMarkers Corresponding text for each reference mark, + * that replaces the old text. + * @param types itcType codes for each reference mark. * @param style */ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, @@ -1424,7 +1447,8 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, } /** - * For each name in referenceMarkNames fill types[i] and bibtexKeys[i] with values parsed from referenceMarkNames.get(i) + * For each name in referenceMarkNames fill types[i] and + * bibtexKeys[i] with values parsed from referenceMarkNames.get(i) * * @param referenceMarkNames Should only contain parsable names. * @param types OUT Preallocated, same length as referenceMarkNames. @@ -1915,7 +1939,8 @@ public void rebuildBibTextSection(List databases, /** * @param referenceMarkNames * @param citeKeyToBibEntry Helps to find the entries - * @return LinkedHashMap from BibEntry to BibDatabase with iteration order as first appearance in referenceMarkNames. + * @return LinkedHashMap from BibEntry to BibDatabase with + * iteration order as first appearance in referenceMarkNames. */ private Map sortEntriesByRefMarkNames(List referenceMarkNames, From e1d638184725779f75be964e891525421e10672e Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 23:41:30 +0100 Subject: [PATCH 0334/1068] untabify --- .../openoffice/ManageCitationsDialogView.java | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index 33befd351f1..bcf734a1e76 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -57,28 +57,28 @@ public ManageCitationsDialogView(OOBibBase ooBase) { @FXML private void initialize() - throws NoSuchElementException, - WrappedTargetException, - UnknownPropertyException, - NoDocumentException + throws NoSuchElementException, + WrappedTargetException, + UnknownPropertyException, + NoDocumentException { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); citation.setCellValueFactory(cellData -> - cellData.getValue() - .citationProperty() - ); + cellData.getValue() + .citationProperty() + ); new ValueTableCellFactory() - .withGraphic(this::getText) - .install(citation); + .withGraphic(this::getText) + .install(citation); extraInfo.setCellValueFactory(cellData - -> - cellData.getValue() - .extraInformationProperty() - ); + -> + cellData.getValue() + .extraInformationProperty() + ); extraInfo.setEditable(true); citationsTableView.setEditable(true); From 2a1454d136d26faec32906936189c0b7d9d2d0a0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 23:44:43 +0100 Subject: [PATCH 0335/1068] unused import --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 414f6b520ac..abe5ad7df2e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1,7 +1,6 @@ package org.jabref.gui.openoffice; import java.io.IOException; -import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; From ae005effaf98f9d0370868d7d572e9a56c6ea56d Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 23:44:52 +0100 Subject: [PATCH 0336/1068] unused imports --- .../jabref/gui/openoffice/ManageCitationsDialogViewModel.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index fb74180ed8d..1abc45524d8 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -1,7 +1,6 @@ package org.jabref.gui.openoffice; import java.util.List; -import java.util.Optional; import java.util.stream.Collectors; import javafx.beans.property.ListProperty; @@ -17,7 +16,6 @@ import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.WrappedTargetException; import org.slf4j.Logger; From 2732e442110d910b56c8382f9c20b9b164d5dd89 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 23:45:05 +0100 Subject: [PATCH 0337/1068] style --- .../org/jabref/gui/openoffice/ManageCitationsDialogView.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index bcf734a1e76..64d95322472 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -60,8 +60,7 @@ private void initialize() throws NoSuchElementException, WrappedTargetException, UnknownPropertyException, - NoDocumentException - { + NoDocumentException { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); From 8afdab26b0e92b0486e4220935651d2eb056e1cd Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 26 Feb 2021 23:47:57 +0100 Subject: [PATCH 0338/1068] checkstyle --- .../jabref/gui/openoffice/ManageCitationsDialogViewModel.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 1abc45524d8..63132c58b32 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -35,7 +35,7 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, WrappedTargetException, UnknownPropertyException, NoDocumentException { - this.ooBase = ooBase; + this.ooBase = ooBase; this.dialogService = dialogService; List cts = ooBase.getCitationEntries(); From d35803d9068010fd33c35221fff79fb4141b805e Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Feb 2021 00:01:49 +0100 Subject: [PATCH 0339/1068] drop run_useless_parts --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index abe5ad7df2e..8d0686e1e0f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -93,7 +93,6 @@ @AllowedToUseAwt("Requires AWT for italics and bold") class OOBibBase { - private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); private static final String BIB_SECTION_NAME = "JR_bib"; @@ -115,10 +114,6 @@ class OOBibBase { private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); - /* - * Shall we keep calls I suspect to be useless? - */ - private final boolean run_useless_parts = true; /* variables */ private final DialogService dialogService; private final XDesktop xDesktop; @@ -368,10 +363,7 @@ private XDesktop simpleBootstrap(Path loPath) } XDesktop result = unoQI(XDesktop.class, desktop); - // TODO: useless call? - if (run_useless_parts) { - unoQI(XComponentLoader.class, desktop); - } + unoQI(XComponentLoader.class, desktop); return result; } @@ -500,10 +492,7 @@ public void selectDocument() XComponent component = unoQI(XComponent.class, mxDoc); - // TODO: what is the point of the next line? Does it have a side effect? - if (run_useless_parts) { - unoQI(XDocumentIndexesSupplier.class, component); - } + unoQI(XDocumentIndexesSupplier.class, component); XTextViewCursorSupplier viewCursorSupplier; From bf9d6e539391280f687ba90808e446bf15971ec0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Feb 2021 09:13:16 +0100 Subject: [PATCH 0340/1068] comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8d0686e1e0f..9927a90c82f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -121,7 +121,9 @@ class OOBibBase { private final Comparator entryComparator; private final Comparator yearAuthorTitleComparator; - /* document-connection related */ + /** + * Document-connection related variables. + */ private static class DocumentConnection { public XMultiServiceFactory mxDocFactory; public XTextDocument mxDoc; From 09f2397c4db72d746b7988065c215edcd2062394 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Feb 2021 09:13:50 +0100 Subject: [PATCH 0341/1068] comments --- .../org/jabref/gui/openoffice/OOBibBase.java | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9927a90c82f..37e57c859bd 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -242,6 +242,18 @@ List getReferenceMarknames() return Arrays.asList(names); } + /** + * Get the text belonging to refMarkName with up to + * charBefore and charAfter characters of context. + * + * The actual contaxt may be smaller than requested. + * + * @param refMarkName Name of a reference mark. + * @param charBefore + * @param charAfter Number of characters requested. + * @param htmlMarkup If true, the text belonging to the + * reference mark is surrounded by bold html tag. + */ public String getCitationContext(String refMarkName, int charBefore, int charAfter, @@ -304,18 +316,31 @@ public String getCitationContext(String refMarkName, return result.trim(); } - // Get the cursor positioned by the user. + /** + * Get the cursor positioned by the user. + * + */ public XTextViewCursor getViewCursor() { return this.xViewCursorSupplier.getViewCursor(); } } // end DocumentConnection + /** + * Created when connected to a document. + * + * Cleared (to null) when we discover we lost the connection. + */ private DocumentConnection xDocumentConnection; + /* * xUniquefiers : maps bibtexkeys to letters ("a", "b") */ private final Map xUniquefiers = new HashMap<>(); + /** + * + * + */ private List jabRefReferenceMarkNamesSortedByPosition; /* From 7d574d30310ea42325423e33a83bddbe895716ea Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Feb 2021 09:14:27 +0100 Subject: [PATCH 0342/1068] getUniqueReferenceMarkName did not use documentConnection --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 37e57c859bd..92b68d1883b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -742,7 +742,7 @@ private String getUniqueReferenceMarkName(DocumentConnection documentConnection, String bibtexKey, int itcType) throws NoDocumentException { - XNameAccess xNamedRefMarks = xDocumentConnection.getReferenceMarks(); + XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); int i = 0; String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; while (xNamedRefMarks.hasByName(name)) { From 6fb897ef5ed24eb8488663d6f16073e22ae4a26f Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Feb 2021 19:34:15 +0100 Subject: [PATCH 0343/1068] refactor: Act on IDEA suggestions removeReferenceMark, getBookmarks, getBookmarkRange moved into DocumentConnection italicizeOrBold lost its italicize argument, renamed to italicizeRangeFromPosition --- .../org/jabref/gui/openoffice/OOBibBase.java | 748 ++++++++++-------- 1 file changed, 399 insertions(+), 349 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 92b68d1883b..6d7d80806e4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -132,6 +132,7 @@ private static class DocumentConnection { public XComponent xCurrentComponent; public XPropertySet propertySet; public XPropertyContainer userProperties; + private final Logger LOGGER; DocumentConnection(XMultiServiceFactory mxDocFactory, XTextDocument mxDoc, @@ -139,7 +140,8 @@ private static class DocumentConnection { XTextViewCursorSupplier xViewCursorSupplier, XComponent xCurrentComponent, XPropertySet propertySet, - XPropertyContainer userProperties + XPropertyContainer userProperties, + Logger LOGGER ) { this.mxDocFactory = mxDocFactory; this.mxDoc = mxDoc; @@ -148,6 +150,7 @@ private static class DocumentConnection { this.xCurrentComponent = xCurrentComponent; this.propertySet = propertySet; this.userProperties = userProperties; + this.LOGGER = LOGGER; } public Optional getDocumentTitle() { @@ -210,7 +213,7 @@ private XNameAccess getReferenceMarks() } } - public boolean checkDocumentConnection() { + public boolean documentConnectionMissing() { // These are set by selectDocument: if (null == this.xCurrentComponent @@ -220,16 +223,16 @@ public boolean checkDocumentConnection() { || null == this.mxDocFactory || null == this.userProperties || null == this.propertySet) { - return false; + return true; } // Attempt to check document is really available try { getReferenceMarks(); } catch (NoDocumentException ex) { - return false; + return true; } - return true; + return false; } List getReferenceMarknames() @@ -242,14 +245,33 @@ List getReferenceMarknames() return Arrays.asList(names); } + /** + * Remove the named reference mark. + */ + public void removeReferenceMark(String name) + throws WrappedTargetException, + NoDocumentException { + XNameAccess xReferenceMarks = this.getReferenceMarks(); + if (xReferenceMarks.hasByName(name)) { + try { + Object referenceMark = xReferenceMarks.getByName(name); + XTextContent bookmark = unoQI(XTextContent.class, referenceMark); + this.xText.removeTextContent(bookmark); + } catch (NoSuchElementException ex) { + LOGGER.warn(String.format("referenceMark got NoSuchElementException" + + " for '%s'", name)); + } + } + } + /** * Get the text belonging to refMarkName with up to * charBefore and charAfter characters of context. * - * The actual contaxt may be smaller than requested. + * The actual context may be smaller than requested. * * @param refMarkName Name of a reference mark. - * @param charBefore + * @param charBefore Number of characters requested. * @param charAfter Number of characters requested. * @param htmlMarkup If true, the text belonging to the * reference mark is surrounded by bold html tag. @@ -323,6 +345,37 @@ public String getCitationContext(String refMarkName, public XTextViewCursor getViewCursor() { return this.xViewCursorSupplier.getViewCursor(); } + + public XNameAccess getBookmarks() { + // query XBookmarksSupplier from document model + // and get bookmarks collection + XBookmarksSupplier xBookmarksSupplier = + unoQI(XBookmarksSupplier.class, + this.xCurrentComponent + ); + return xBookmarksSupplier.getBookmarks(); + } + + /** + * Get the XTextRange corresponding to the named bookmark. + * + * @param name The name of the bookmark to find. + * @return The XTextRange for the bookmark, or null. + */ + public XTextRange getBookmarkRange(String name) + throws NoSuchElementException, + WrappedTargetException { + XNameAccess xNamedBookmarks = this.getBookmarks(); + + // retrieve bookmark by name + if (!xNamedBookmarks.hasByName(name)) { + return null; + } + Object foundBookmark = xNamedBookmarks.getByName(name); + XTextContent xFoundBookmark = unoQI(XTextContent.class, foundBookmark); + return xFoundBookmark.getAnchor(); + } + } // end DocumentConnection /** @@ -333,9 +386,10 @@ public XTextViewCursor getViewCursor() { private DocumentConnection xDocumentConnection; /* - * xUniquefiers : maps bibtexkeys to letters ("a", "b") + * xUniqueLetters : maps bibtexkeys to letters ("a", "b") that + * make the citation markers unique. */ - private final Map xUniquefiers = new HashMap<>(); + private final Map xUniqueLetters = new HashMap<>(); /** * @@ -548,7 +602,8 @@ public void selectDocument() viewCursorSupplier, component, propertySet, - userProperties + userProperties, + LOGGER ); // TODO: maybe we should install an event handler for document @@ -569,12 +624,15 @@ public boolean isConnectedToDocument() { return this.xDocumentConnection != null; } - public boolean checkDocumentConnection() { + /** + * @return true if we are connected to a document + */ + public boolean documentConnectionMissing() { if (this.xDocumentConnection == null) { return false; } - boolean res = this.xDocumentConnection.checkDocumentConnection(); - if (!res) { + boolean res = this.xDocumentConnection.documentConnectionMissing(); + if (res) { forgetDocument(); } return res; @@ -582,7 +640,7 @@ public boolean checkDocumentConnection() { private DocumentConnection getDocumentConnectionOrThrow() throws NoDocumentException { - if (!checkDocumentConnection()) { + if (documentConnectionMissing()) { throw new NoDocumentException("Not connected to document"); } return this.xDocumentConnection; @@ -593,7 +651,7 @@ private DocumentConnection getDocumentConnectionOrThrow() */ public Optional getCurrentDocumentTitle() { - if (!checkDocumentConnection()) { + if (documentConnectionMissing()) { return Optional.empty(); } else { return this.xDocumentConnection.getDocumentTitle(); @@ -601,7 +659,7 @@ public Optional getCurrentDocumentTitle() { } /* - * === insertEntry + * insertEntry */ private Comparator comparatorForMulticite(OOBibStyle style) { @@ -667,7 +725,7 @@ private List getCitationEntriesImpl(DocumentConnection documentCo NoDocumentException { List names = this.getJabRefReferenceMarkNames(documentConnection); - List citations = new ArrayList(names.size()); + List citations = new ArrayList<>(names.size()); for (String name : names) { CitationEntry entry = new CitationEntry(name, @@ -715,21 +773,10 @@ public void applyCitationEntries(List citationEntries) Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { documentConnection.setCustomProperty(entry.getRefMarkName(), pageInfo.get()); - } else { - // TODO: if pageInfo is not present, or is empty: - // maybe we should remove it from the document. } + // TODO: if pageInfo is not present, or is empty: + // maybe we should remove it from the document. } - // } catch (UnknownPropertyException - // | NotRemoveableException - // | PropertyExistException - // | IllegalTypeException - // | IllegalArgumentException ex) - // { - // LOGGER.warn("Problem modifying citation", ex); - // dialogService.showErrorDialogAndWait( - // Localization.lang("Problem modifying citation"), ex); - // } } /** @@ -754,6 +801,9 @@ private String getUniqueReferenceMarkName(DocumentConnection documentConnection, /** * This is what we get back from parsing a refMarkName + * + * TODO: We have one itcType per refMarkName. Merge reduces the + * number of itcType values. */ private static class ParsedRefMark { public String i; // "", "0", "1" ... @@ -795,18 +845,6 @@ private static Optional parseRefMarkName(String refMarkName) { * citation (true) or an empty (invisible) citation (false). * @param sync Indicates whether the reference list should be * refreshed. - * @throws IllegalTypeException - * @throws PropertyExistException - * @throws NotRemoveableException - * @throws UnknownPropertyException - * @throws UndefinedCharacterFormatException - * @throws NoSuchElementException - * @throws WrappedTargetException - * @throws IOException - * @throws PropertyVetoException - * @throws CreationException - * @throws BibEntryNotFoundException - * @throws UndefinedParagraphFormatException * * TODO: * https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html @@ -844,11 +882,9 @@ public void insertEntry(List entries, sortBibEntryListForMulticite(entries, style); String keyString = - String.join(",", - entries.stream() - .map(entry -> entry.getCitationKey().orElse("")) - .collect(Collectors.toList()) - ); + entries.stream() + .map(entry -> entry.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); // Generate unique bookmark-name int citationType = citationTypeFromOptions(withText, inParenthesis); String newName = getUniqueReferenceMarkName(documentConnection, @@ -906,8 +942,8 @@ public void insertEntry(List entries, : style.getCitationMarker(entries, databaseMap, inParenthesis, - null, // uniquefiers - null // unlimAuthors + null, + null ); insertReferenceMark(documentConnection, newName, citeText, cursor, withText, style); @@ -918,7 +954,7 @@ public void insertEntry(List entries, XTextRange position = cursor.getEnd(); if (sync) { - // To account for numbering and for uniqiefiers, we + // To account for numbering and for uniqueLetters, we // must refresh the cite markers: updateSortedReferenceMarks(); refreshCiteMarkers(allBases, style); @@ -962,10 +998,11 @@ public void insertEntry(List entries, * */ private List parseRefMarkNameToUniqueCitationKeys(String name) { Optional op = parseRefMarkName(name); - if (op.isPresent()) { - return op.get().citedKeys.stream().distinct().collect(Collectors.toList()); - } - return new ArrayList<>(); + return op.map(parsedRefMark -> + parsedRefMark.citedKeys.stream() + .distinct() + .collect(Collectors.toList())) + .orElseGet(ArrayList::new); } /** @@ -982,13 +1019,14 @@ private List findCitedKeys(DocumentConnection documentConnection) List names = getJabRefReferenceMarkNames(documentConnection); - // assert it supports XTextContent - XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); - for (String name1 : names) { - Object bookmark = xNamedMarks.getByName(name1); - assert (null != unoQI(XTextContent.class, bookmark)); - } + // assert it supports XTextContent + XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); + for (String name1 : names) { + Object bookmark = xNamedMarks.getByName(name1); + assert (null != unoQI(XTextContent.class, bookmark)); + } + // List keys = new ArrayList<>(); for (String name1 : names) { List newKeys = parseRefMarkNameToUniqueCitationKeys(name1); @@ -1002,23 +1040,7 @@ private List findCitedKeys(DocumentConnection documentConnection) return keys; } - /** - * @return LinkedHashMap, from BibEntry to BibDatabase. - * Side effect: adds citedKeys to citeKeyToBibEntry, - * using UndefinedBibtexEntry if not found. - * - * If a citedKey is not found, then - * BibEntry is new UndefinedBibtexEntry(citedKey), - * and BibDatabase is null. - * If citedKey is found, then BibEntry is what we found, - * BibDatabase is the database we found it in. - * - * So: result has an entry for each citedKey, - * in the same order as in citedKeys - * - * citedKey in the entry is the same as the original citedKey - */ - private class FindCitedEntriesResult { + private static class FindCitedEntriesResult { /* * entries : LinkedHashMap with iteration order as the * citedKeys parameter of findCitedEntries @@ -1036,6 +1058,22 @@ private class FindCitedEntriesResult { } } + /** + * @return LinkedHashMap, from BibEntry to BibDatabase. + * Side effect: adds citedKeys to citeKeyToBibEntry, + * using UndefinedBibtexEntry if not found. + * + * If a citedKey is not found, then + * BibEntry is new UndefinedBibtexEntry(citedKey), + * and BibDatabase is null. + * If citedKey is found, then BibEntry is what we found, + * BibDatabase is the database we found it in. + * + * So: result has an entry for each citedKey, + * in the same order as in citedKeys + * + * citedKey in the entry is the same as the original citedKey + */ private FindCitedEntriesResult findCitedEntries(List databases, List citedKeys @@ -1071,15 +1109,6 @@ private class FindCitedEntriesResult { * @param databases The databases to get entries from. * @param style The bibliography style to use. * @return A list of those referenced citation keys that could not be resolved. - * @throws UndefinedCharacterFormatException - * @throws NoSuchElementException - * @throws IllegalArgumentException - * @throws WrappedTargetException - * @throws BibEntryNotFoundException - * @throws CreationException - * @throws IOException - * @throws PropertyVetoException - * @throws UnknownPropertyException */ public List refreshCiteMarkers(List databases, OOBibStyle style) @@ -1098,7 +1127,7 @@ public List refreshCiteMarkers(List databases, return refreshCiteMarkersInternal(documentConnection, databases, style, - this.xUniquefiers); + this.xUniqueLetters); } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference @@ -1128,12 +1157,12 @@ private static BibEntry[] mapUndefinedBibentriesToNull(BibEntry[] cEntries) { ) throws BibEntryNotFoundException { // check keys - List unresovedKeys = + List unresolvedKeys = Arrays.stream(keys) .filter(key -> null == citeKeyToBibEntry.get(key)) .collect(Collectors.toList()); - for (String key : unresovedKeys) { + for (String key : unresolvedKeys) { LOGGER.info("Citation key not found: '" + key + '\''); LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); String msg = Localization.lang("Could not resolve BibTeX entry" @@ -1152,36 +1181,13 @@ private static BibEntry[] mapUndefinedBibentriesToNull(BibEntry[] cEntries) { // boolean undefinedToNull // for undefined entries insert NULL ) throws BibEntryNotFoundException { - if (true) { assertKeysInCiteKeyToBibEntry(keys, citeKeyToBibEntry, referenceMarkName); // process keys - BibEntry[] cEntries = + return Arrays.stream(keys) - .map(key -> (BibEntry) citeKeyToBibEntry.get(key)) + .map(citeKeyToBibEntry::get) .toArray(BibEntry[]::new); - return cEntries; - } else { - BibEntry[] cEntries = new BibEntry[keys.length]; - - // fill cEntries - for (int j = 0; j < keys.length; j++) { - String kj = keys[j]; - BibEntry tmpEntry = citeKeyToBibEntry.get(kj); - if (tmpEntry == null) { - LOGGER.info("Citation key not found: '" + kj + '\''); - LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); - String msg = Localization.lang("Could not resolve BibTeX entry" - + " for citation marker '%0'.", - referenceMarkName - ); - throw new BibEntryNotFoundException(referenceMarkName, msg); - } else { - cEntries[j] = tmpEntry; - } - } // for j - return cEntries; - } } private static void @@ -1216,7 +1222,7 @@ private static BibEntry[] mapUndefinedBibentriesToNull(BibEntry[] cEntries) { for (int i = 0; i < nRefMarks; i++) { citMarkers[i] = Arrays.stream(bibtexKeys[i]) - .map(key -> citeKeyToBibEntry.get(key)) + .map(citeKeyToBibEntry::get) .map((c) -> c.getCitationKey().orElse("")) .collect(Collectors.joining(",")); } @@ -1232,8 +1238,8 @@ private static class CitationNumberingState { CitationNumberingState() { // For numbered citation style. Map(citedKey, number ) - Map numbers = new HashMap<>(); - int lastNum = 0; + this.numbers = new HashMap<>(); + this.lastNum = 0; } /** @@ -1272,7 +1278,7 @@ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, } /** - * @param referenceMarkNames + * @param referenceMarkNames Names of reference marks. * @param bibtexKeys Expects bibtexKeys[i] to correspond to * referenceMarkNames.get(i) * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. Must @@ -1302,16 +1308,15 @@ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); for (int i = 0; i < referenceMarkNames.size(); i++) { - final String referenceMarkName = referenceMarkNames.get(i); - // nums: Numbers for cEntries, (-1) for none. - List nums = + // numbers: Numbers for cEntries, (-1) for none. + List numbers = Arrays.stream(bibtexKeys[i]) - .map(key -> citeKeyToBibEntry.get(key)) + .map(citeKeyToBibEntry::get) .map(ce -> numberPossiblyUndefinedBibEntry(ce, cns)) .collect(Collectors.toList()); - citMarkers[i] = style.getNumCitationMarker(nums, minGroupingCount, false); + citMarkers[i] = style.getNumCitationMarker(numbers, minGroupingCount, false); } // for return citMarkers; } @@ -1335,8 +1340,7 @@ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, Map sortedEntries = sortEntriesByComparator(entries, entryComparator); // adjust order of cited to match - List sortedCited = new ArrayList(entries.size()); - sortedCited.clear(); + List sortedCited = new ArrayList<>(entries.size()); for (BibEntry entry : sortedEntries.keySet()) { sortedCited.add(entry.getCitationKey().orElse(null)); } @@ -1344,8 +1348,6 @@ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); for (int i = 0; i < referenceMarkNames.size(); i++) { - final String namei = referenceMarkNames.get(i); - List num = findCitedEntryIndices(Arrays.asList(bibtexKeys[i]), sortedCited); citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); @@ -1379,13 +1381,13 @@ private static List findCitedEntryIndices(List keysCitedHere, * text content, call insertReferenceMark. * * After each insertReferenceMark call check if we lost the - * OOBibBase.BIB_SECTION_NAME bookmark and recrate it if we did. + * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. * * @param referenceMarkNames Reference mark names * @param citMarkers Corresponding text for each reference mark, * that replaces the old text. * @param types itcType codes for each reference mark. - * @param style + * @param style Bibliography style to use. */ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, List referenceMarkNames, @@ -1406,7 +1408,7 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); final boolean hadBibSection = - (getBookmarkRange(documentConnection, OOBibBase.BIB_SECTION_NAME) != null); + (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); // If we are supposed to set character format for citations, // must run a test before we delete old citation @@ -1428,16 +1430,7 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, if (mustTestCharFormat) { mustTestCharFormat = false; // need to do this only once - XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); - String charStyle = style.getCitationCharacterFormat(); - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - throw new UndefinedCharacterFormatException(charStyle); - } + testFormatCitations(cursor, style); } documentConnection.xText.removeTextContent(bookmark); @@ -1450,8 +1443,8 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, style ); - if (hadBibSection && (getBookmarkRange(documentConnection, - OOBibBase.BIB_SECTION_NAME) == null)) { + if (hadBibSection + && (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { // We have overwritten the marker for the start of the reference list. // We need to add it again. cursor.collapseToEnd(); @@ -1462,11 +1455,11 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, } /** - * For each name in referenceMarkNames fill types[i] and - * bibtexKeys[i] with values parsed from referenceMarkNames.get(i) + * For each name in referenceMarkNames set types[i] and + * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) * * @param referenceMarkNames Should only contain parsable names. - * @param types OUT Preallocated, same length as referenceMarkNames. + * @param types OUT Must be same length as referenceMarkNames. * @param bibtexKeys OUT First level must be same length as referenceMarkNames. */ private static void parseRefMarkNamesToArrays(List referenceMarkNames, @@ -1476,9 +1469,9 @@ private static void parseRefMarkNamesToArrays(List referenceMarkNames, assert (types.length == nRefMarks); assert (bibtexKeys.length == nRefMarks); for (int i = 0; i < nRefMarks; i++) { - final String namei = referenceMarkNames.get(i); - Optional op = parseRefMarkName(namei); - if (!op.isPresent()) { + final String name = referenceMarkNames.get(i); + Optional op = parseRefMarkName(name); + if (op.isEmpty()) { // We have a problem. We want types[i] and bibtexKeys[i] // to correspond to referenceMarkNames.get(i). // And do not want null in bibtexKeys (or error code in types) @@ -1487,8 +1480,8 @@ private static void parseRefMarkNamesToArrays(List referenceMarkNames, continue; } ParsedRefMark ov = op.get(); - types[i] = ov.itcType; // Remember the itcType in case we need to uniquefy. - bibtexKeys[i] = ov.citedKeys.stream().toArray(String[]::new); + types[i] = ov.itcType; + bibtexKeys[i] = ov.citedKeys.toArray(String[]::new); } } @@ -1507,39 +1500,29 @@ private static List unresolvedKeysFromEntries(Map return unresolvedKeys; } - private class RcmCitationMarkersForNormalStyleResult { - public String[] citMarkers; // main product - public String[][] bibtexKeys; // order within referenceMarks may have changed - - RcmCitationMarkersForNormalStyleResult(String[] citMarkers, - String[][] bibtexKeys) { - this.citMarkers = citMarkers; - this.bibtexKeys = bibtexKeys; - } - } /** * Produce citMarkers for normal (!isCitationKeyCiteMarkers && ! isNumberEntries) styles. * - * @param referenceMarkNames - * @param bibtexKeysIn - * @param citeKeyToBibEntry - * @param types - * @param entries - * @param uniquefiers Filled with new values - * @param style + * @param referenceMarkNames Names of reference marks. + * @param bibtexKeysIn Bibtex citation keys. + * @param citeKeyToBibEntry Maps citation keys to BibEntry. + * @param itcTypes Citation types. + * @param entries Map BibEntry to BibDatabase. + * @param uniqueLetters Filled with new values here. + * @param style Bibliography style. */ - RcmCitationMarkersForNormalStyleResult + String[] rcmCitationMarkersForNormalStyle(List referenceMarkNames, String[][] bibtexKeysIn, Map citeKeyToBibEntry, - int[] types, + int[] itcTypes, Map entries, - final Map uniquefiers, + final Map uniqueLetters, OOBibStyle style ) throws BibEntryNotFoundException { - uniquefiers.clear(); + uniqueLetters.clear(); assert !style.isCitationKeyCiteMarkers(); assert !style.isNumberEntries(); @@ -1547,14 +1530,14 @@ private class RcmCitationMarkersForNormalStyleResult { final int nRefMarks = referenceMarkNames.size(); assert (bibtexKeysIn.length == nRefMarks); - assert (types.length == nRefMarks); + assert (itcTypes.length == nRefMarks); assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); BibEntry[][] cEntriesForAll = Arrays.stream(bibtexKeysIn) - .map(bibtexKeysOfARefererenceMark -> - Arrays.stream(bibtexKeysOfARefererenceMark) - .map(key -> citeKeyToBibEntry.get(key)) + .map(bibtexKeysOfAReferenceMark -> + Arrays.stream(bibtexKeysOfAReferenceMark) + .map(citeKeyToBibEntry::get) .sorted(comparatorForMulticite(style)) // sort within referenceMark .toArray(BibEntry[]::new) ) @@ -1576,12 +1559,12 @@ private class RcmCitationMarkersForNormalStyleResult { String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { BibEntry[] cEntries = cEntriesForAll[i]; - int type = types[i]; + int type = itcTypes[i]; citMarkers[i] = style.getCitationMarker(Arrays.asList(cEntries), // entries entries, // database type == OOBibBase.AUTHORYEAR_PAR, - null, // uniquefiers - null // unlimAuthors + null, + null ); } @@ -1594,20 +1577,21 @@ private class RcmCitationMarkersForNormalStyleResult { normCitMarkers[i] = Arrays.stream(cEntries) .map(ce -> - style.getCitationMarker(Collections.singletonList(ce), - entries, // database - true, // inParenthesis - null, // uniquefiers - new int[] {-1} // unlimAuthors + style.getCitationMarker( + Collections.singletonList(ce), + entries, + true, + null, + new int[] {-1} // no limit on authors ) ) .toArray(String[]::new); } - uniquefiers.clear(); + uniqueLetters.clear(); // The following block - // changes: citMarkers[i], uniquefiers + // changes: citMarkers[i], uniqueLetters // uses: nRefMarks, normCitMarkers, bibtexKeys, // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) // citeKeyToBibEntry, entries, types @@ -1617,7 +1601,7 @@ private class RcmCitationMarkersForNormalStyleResult { // citeKeys are already unique. // See if there are duplicate citations marks referring to - // different entries. If so, we need to use uniquefiers: + // different entries. If so, we need to use uniqueLetters: // refKeys: normCitMarker to list of bibtexkeys sharing it. // The entries in the lists are ordered as in @@ -1647,19 +1631,19 @@ private class RcmCitationMarkersForNormalStyleResult { } // Go through the collected lists and see where we need to - // uniquefy: + // add unique letters to the year. for (Map.Entry> stringListEntry : refKeys.entrySet()) { List clashingKeys = stringListEntry.getValue(); if (clashingKeys.size() > 1) { // This marker appears for more than one unique entry: - int uniq = 'a'; + int nextUniqueLetter = 'a'; for (String key : clashingKeys) { - // Update the map of uniquefiers for the + // Update the map of uniqueLetters for the // benefit of both the following generation of // new citation markers, and for the method // that builds the bibliography: - uniquefiers.put(key, String.valueOf((char) uniq)); - uniq++; + uniqueLetters.put(key, String.valueOf((char) nextUniqueLetter)); + nextUniqueLetter++; } } } @@ -1669,14 +1653,15 @@ private class RcmCitationMarkersForNormalStyleResult { final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); for (int i = 0; i < nRefMarks; i++) { - final String namei = referenceMarkNames.get(i); + final String referenceMarkName = referenceMarkNames.get(i); final int nCitedEntries = bibtexKeys[i].length; boolean needsChange = false; int[] firstLimAuthors = new int[nCitedEntries]; - String[] uniquif = new String[nCitedEntries]; - BibEntry[] cEntries = mapCiteKeysToBibEntryArray(bibtexKeys[i], - citeKeyToBibEntry, - namei); + String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; + BibEntry[] cEntries = + mapCiteKeysToBibEntryArray(bibtexKeys[i], + citeKeyToBibEntry, + referenceMarkName); cEntries = mapUndefinedBibentriesToNull(cEntries); for (int j = 0; j < nCitedEntries; j++) { @@ -1699,11 +1684,11 @@ private class RcmCitationMarkersForNormalStyleResult { seenBefore.add(currentKey); } - String uniq = uniquefiers.get(currentKey); - if (uniq == null) { - uniquif[j] = ""; + String uniqueLetterForKey = uniqueLetters.get(currentKey); + if (uniqueLetterForKey == null) { + uniqueLetterForCitedEntry[j] = ""; } else { - uniquif[j] = uniq; + uniqueLetterForCitedEntry[j] = uniqueLetterForKey; needsChange = true; } @@ -1716,20 +1701,20 @@ private class RcmCitationMarkersForNormalStyleResult { citMarkers[i] = style.getCitationMarker(Arrays.asList(cEntries), entries, - types[i] == OOBibBase.AUTHORYEAR_PAR, - uniquif, + itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, + uniqueLetterForCitedEntry, firstLimAuthors ); } } // for i } // if normalStyle - return new RcmCitationMarkersForNormalStyleResult(citMarkers, bibtexKeys); + return citMarkers; } private List refreshCiteMarkersInternal(DocumentConnection documentConnection, List databases, OOBibStyle style, - final Map uniquefiers + final Map uniqueLetters ) throws WrappedTargetException, IllegalArgumentException, @@ -1757,15 +1742,17 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne FindCitedEntriesResult fce = findCitedEntries(databases, - findCitedKeys(documentConnection) + findCitedKeys(documentConnection) + // TODO: why are we scanning the document + // if we already hev the referenceMarkNames? ); - // fce.entries are now in same order as returned by findCitedKeys + // fce.entries are in same order as returned by findCitedKeys // citMarkers[i] = what goes in the text at referenceMark[i] - String[] citMarkers = new String[nRefMarks]; + String[] citMarkers; // fill citMarkers - uniquefiers.clear(); /* ModifiesParameter */ + uniqueLetters.clear(); /* ModifiesParameter */ if (style.isCitationKeyCiteMarkers()) { citMarkers = rcmCitationMarkersForIsCitationKeyCiteMarkers(referenceMarkNames, @@ -1790,17 +1777,16 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne } } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { - RcmCitationMarkersForNormalStyleResult nsr = + citMarkers = rcmCitationMarkersForNormalStyle(referenceMarkNames, bibtexKeys, fce.citeKeyToBibEntry, types, fce.entries, - uniquefiers, + uniqueLetters, style ); - citMarkers = nsr.citMarkers; - bibtexKeys = nsr.bibtexKeys; + } // Refresh all reference marks with the citation markers we computed: @@ -1937,7 +1923,7 @@ public void rebuildBibTextSection(List databases, entries = sortEntriesByComparator(fce.entries, entryComparator); } clearBibTextSectionContent2(documentConnection); - populateBibTextSection(documentConnection, entries, style, this.xUniquefiers); + populateBibTextSection(documentConnection, entries, style, this.xUniqueLetters); } SortedMap @@ -1952,7 +1938,7 @@ public void rebuildBibTextSection(List databases, } /** - * @param referenceMarkNames + * @param referenceMarkNames Names of reference marks. * @param citeKeyToBibEntry Helps to find the entries * @return LinkedHashMap from BibEntry to BibDatabase with * iteration order as first appearance in referenceMarkNames. @@ -1969,7 +1955,7 @@ public void rebuildBibTextSection(List databases, for (String name : referenceMarkNames) { Optional op = parseRefMarkName(name); - if (!op.isPresent()) { + if (op.isEmpty()) { continue; } @@ -2000,7 +1986,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, Map entries, OOBibStyle style, String parFormat, - final Map uniquefiers) + final Map uniqueLetters) throws UndefinedParagraphFormatException, IllegalArgumentException, UnknownPropertyException, @@ -2023,7 +2009,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // formatting a single entry. // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); int minGroupingCount = 2; - String marker = style.getNumCitationMarker(Collections.singletonList(number++), + List numbers = Collections.singletonList(number++); + String marker = style.getNumCitationMarker(numbers, minGroupingCount, true); @@ -2044,7 +2031,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, parFormat, entry.getKey(), entry.getValue(), - uniquefiers.get(entry.getKey().getCitationKey().orElse(null)) + uniqueLetters.get(entry.getKey().getCitationKey().orElse(null)) ); } } @@ -2057,9 +2044,11 @@ private void createBibTextSection2(DocumentConnection documentConnection, XTextCursor textCursor = documentConnection.xText.createTextCursor(); if (end) { textCursor.gotoEnd(false); - } else { - // where does textCursor point to in this branch? } + // where does textCursor point to if end is false? + // TODO: are we using this.atEnd == false? + // If we do, what happens (or expected to happen) here? + OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); // Create a new TextSection from the document factory and access it's XNamed interface XNamed xChildNamed; @@ -2079,8 +2068,7 @@ private void createBibTextSection2(DocumentConnection documentConnection, } private void clearBibTextSectionContent2(DocumentConnection documentConnection) - throws NoSuchElementException, - WrappedTargetException, + throws WrappedTargetException, IllegalArgumentException, CreationException { @@ -2090,29 +2078,29 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) com.sun.star.container.XNameAccess ts = supplier.getTextSections(); - if (ts.hasByName(OOBibBase.BIB_SECTION_NAME)) { - try { - Any a = ((Any) ts.getByName(OOBibBase.BIB_SECTION_NAME)); - XTextSection section = (XTextSection) a.getObject(); - // Clear it: - XTextCursor cursor = - documentConnection.xText.createTextCursorByRange(section.getAnchor()); - cursor.gotoRange(section.getAnchor(), false); - cursor.setString(""); - return; - } catch (NoSuchElementException ex) { - // NoSuchElementException: is thrown by child access - // methods of collections, if the addressed child does - // not exist. - - // We got this exception from ts.getByName() despite - // the ts.hasByName() check just above. + if (!ts.hasByName(OOBibBase.BIB_SECTION_NAME)) { + createBibTextSection2(documentConnection, this.atEnd); + return; + } - // Try to create. - LOGGER.warn("Could not get section '" + OOBibBase.BIB_SECTION_NAME + "'", ex); - createBibTextSection2(documentConnection, this.atEnd); - } - } else { + try { + Any a = ((Any) ts.getByName(OOBibBase.BIB_SECTION_NAME)); + XTextSection section = (XTextSection) a.getObject(); + // Clear it: + XTextCursor cursor = + documentConnection.xText.createTextCursorByRange(section.getAnchor()); + cursor.gotoRange(section.getAnchor(), false); + cursor.setString(""); + } catch (NoSuchElementException ex) { + // NoSuchElementException: is thrown by child access + // methods of collections, if the addressed child does + // not exist. + + // We got this exception from ts.getByName() despite + // the ts.hasByName() check just above. + + // Try to create. + LOGGER.warn("Could not get section '" + OOBibBase.BIB_SECTION_NAME + "'", ex); createBibTextSection2(documentConnection, this.atEnd); } } @@ -2123,7 +2111,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) private void populateBibTextSection(DocumentConnection documentConnection, Map entries, OOBibStyle style, - final Map uniquefiers) + final Map uniqueLetters) throws NoSuchElementException, WrappedTargetException, PropertyVetoException, @@ -2162,15 +2150,15 @@ private void populateBibTextSection(DocumentConnection documentConnection, entries, style, refParaFormat, - uniquefiers + uniqueLetters ); insertBookMark(documentConnection, OOBibBase.BIB_SECTION_END_NAME, cursor); } - private XTextContent insertBookMark(DocumentConnection documentConnection, - String name, - XTextCursor position) + private void insertBookMark(DocumentConnection documentConnection, + String name, + XTextCursor position) throws IllegalArgumentException, CreationException { Object bookmark; @@ -2191,9 +2179,32 @@ private XTextContent insertBookMark(DocumentConnection documentConnection, // insert bookmark at position documentConnection.xText.insertTextContent(position, xTextContent, true); position.collapseToEnd(); - return xTextContent; } + /** + * @param documentConnection Connection to a document. + * @param name Name of the custom property to query. + * @return "" for missing or empty pageInfo + */ + private static String + getPageInfoForReferenceMarkName(DocumentConnection documentConnection, + String name) + throws WrappedTargetException, + UnknownPropertyException { + Optional pageInfo = documentConnection.getCustomProperty(name); + if (pageInfo.isEmpty() || pageInfo.get().isEmpty()) { + return ""; + } + return pageInfo.get(); + } + + /** + * Insert a reference mark. + * + * @param documentConnection Connection to a document. + * @param name Name of the reference mark to be created and also + * the name of the custom property holding the pageInfo part. + */ private void insertReferenceMark(DocumentConnection documentConnection, String name, String citationText, @@ -2206,16 +2217,17 @@ private void insertReferenceMark(DocumentConnection documentConnection, IllegalArgumentException, UndefinedCharacterFormatException, CreationException { - - // Check if there is "page info" stored for this citation. If so, insert it into + // TODO: last minute editing is hacky. Move pageInfo stuff to + // citation marker generation. + // If there is "page info" for this citation, insert it into // the citation text before inserting the citation: - Optional pageInfo = documentConnection.getCustomProperty(name); String citText; - if ((pageInfo.isPresent()) && !pageInfo.get().isEmpty()) { - citText = style.insertPageInfo(citationText, pageInfo.get()); - } else { - citText = citationText; - } + String pageInfo = + getPageInfoForReferenceMarkName(documentConnection, name); + citText = + pageInfo.isEmpty() + ? citationText + : style.insertPageInfo(citationText, pageInfo); Object bookmark; try { @@ -2255,75 +2267,35 @@ private void insertReferenceMark(DocumentConnection documentConnection, position.getText().insertTextContent(position, xTextContent, true); + // Are we sure that OOBibStyle.ET_AL_STRING cannot be part of author names + // in any language? + // TODO: could we move italicizing "et al." to a more proper place? // Check if we should italicize the "et al." string in citations: boolean italicize = style.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); if (italicize) { String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); int index = citText.indexOf(etAlString); if (index >= 0) { - italicizeOrBold(position, true, index, index + etAlString.length()); + italicizeRangeFromPosition(position, index, index + etAlString.length()); } } position.collapseToEnd(); } - private void removeReferenceMark(DocumentConnection documentConnection, String name) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException { - XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); - if (xReferenceMarks.hasByName(name)) { - Object referenceMark = xReferenceMarks.getByName(name); - XTextContent bookmark = unoQI(XTextContent.class, referenceMark); - documentConnection.xText.removeTextContent(bookmark); - } - } - - /** - * Get the XTextRange corresponding to the named bookmark. - * - * @param name The name of the bookmark to find. - * @return The XTextRange for the bookmark. - * @throws WrappedTargetException - * @throws NoSuchElementException - */ - private XTextRange getBookmarkRange(DocumentConnection documentConnection, - String name) - throws NoSuchElementException, - WrappedTargetException { - XNameAccess xNamedBookmarks = getBookmarks(documentConnection); - - // retrieve bookmark by name - if (!xNamedBookmarks.hasByName(name)) { - return null; - } - Object foundBookmark = xNamedBookmarks.getByName(name); - XTextContent xFoundBookmark = unoQI(XTextContent.class, foundBookmark); - return xFoundBookmark.getAnchor(); - } - - private XNameAccess getBookmarks(DocumentConnection documentConnection) { - // query XBookmarksSupplier from document model - // and get bookmarks collection - XBookmarksSupplier xBookmarksSupplier = - unoQI(XBookmarksSupplier.class, - documentConnection.xCurrentComponent - ); - XNameAccess xNamedBookmarks = - xBookmarksSupplier.getBookmarks(); - return xNamedBookmarks; - } - /** * Taking ref=position.getStart(), italicize the range (ref+start,ref+end) * * @param position : position.getStart() is out reference point. - * @param italicize : if false, applies Bold, not Italic - * @param start - * @param end + * @param start : start of range to italicize w.r.t position.getStart(). + * @param end : end of range to italicize w.r.t position.getStart(). + * + * TODO: this is a strange API. Why? Answer: used after finding + * "et al." string in a citation marker. */ - private void italicizeOrBold(XTextCursor position, boolean italicize, int start, int end) + private void italicizeRangeFromPosition(XTextCursor position, + int start, + int end) throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, @@ -2332,24 +2304,44 @@ private void italicizeOrBold(XTextCursor position, boolean italicize, int start, XTextCursor cursor = position.getText().createTextCursorByRange(range); cursor.goRight((short) start, false); cursor.goRight((short) (end - start), true); + XPropertySet xcp = unoQI(XPropertySet.class, cursor); - if (italicize) { - xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); - } else { - xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD); + xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); + // xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD); + } + + /** + * Look up a single citation key in a list of databases. + * + * @param key Citation key to look up. + * @param databases Key is looked up in these, in this order. + * @return The BibEntry at the first match, or Optional.empty(). + */ + Optional lookupEntryInDatabases(String key, List databases) { + for (BibDatabase database : databases) { + Optional entry = database.getEntryByCitationKey(key); + if (entry.isPresent()) { + return entry; + } } + return Optional.empty(); } - List lookupEntriesInDatabases(List keys, List databases) { + /** + * @param keys Citation keys to look up. + * @param databases Keys are looked up in these, in this order. + * @return The BibEntry objects found. + * + * The order of keys is kept in the result, but unresolved keys + * have no representation in the result, so result.get(i) does not + * necessarily belong to keys.get(i) + * + */ + List lookupEntriesInDatabasesSkipMissing(List keys, + List databases) { List entries = new ArrayList<>(); for (String key : keys) { - for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(key); - if (entry.isPresent()) { - entries.add(entry.get()); - break; - } - } + lookupEntryInDatabases(key, databases).ifPresent(entries::add); } return entries; } @@ -2413,7 +2405,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) if (range1.getText() != range2.getText()) { /* pivot and (pivot+1) belong to different XText entities? * Maybe to different footnotes? - * Cannot combine accross boundaries skip. + * Cannot combine across boundaries skip. */ pivot++; continue; @@ -2450,15 +2442,41 @@ public void combineCiteMarkers(List databases, OOBibStyle style) testFormatCitations(textCursor, style); } + /* + * This only gets the keys: itcType is discarded. + * + * AUTHORYEAR_PAR: "(X and Y 2000)" + * AUTHORYEAR_INTEXT: "X and Y (2000)" + * INVISIBLE_CIT: "" + * + * TODO: We probably only want to collect citations with + * AUTHORYEAR_PAR itcType. + * + * No, "X and Y (2000,2001)" appears a meaningful + * case as well. + * + * Proposed rules: + * (1) Do not combine citations with different itcType + * (2) INVISIBLE_CIT: leave it alone + * (3) AUTHORYEAR_PAR: combine, present as AUTHORYEAR_PAR + * + * (4) AUTHORYEAR_INTEXT: Same list of authors with + * same or different years, possibly with + * uniqueLetters could be done. + * But with different list of authors? + * "(X, Y et al 2000) (X, Y et al 2001)" + * will depend on authors not shown here. + * + */ List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); - removeReferenceMark(documentConnection, names.get(pivot)); - removeReferenceMark(documentConnection, names.get(pivot + 1)); + documentConnection.removeReferenceMark(names.get(pivot)); + documentConnection.removeReferenceMark(names.get(pivot + 1)); - List entries = lookupEntriesInDatabases(keys, databases); - Collections.sort(entries, new FieldComparator(StandardField.YEAR)); + List entries = lookupEntriesInDatabasesSkipMissing(keys, databases); + entries.sort(new FieldComparator(StandardField.YEAR)); String keyString = entries.stream() @@ -2470,7 +2488,14 @@ public void combineCiteMarkers(List databases, OOBibStyle style) keyString, OOBibBase.AUTHORYEAR_PAR ); - insertReferenceMark(documentConnection, newName, "tmp", textCursor, true, style); + + insertReferenceMark( + documentConnection, + newName, + "tmp", + textCursor, + true, // withText + style); names.set(pivot + 1, newName); // <- put in the next-to-be-processed position madeModifications = true; @@ -2484,7 +2509,9 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } /** - * GUI action. Do the opposite of combineCiteMarkers. Combined markers are split, with a space inserted between. + * GUI action. + * Do the opposite of combineCiteMarkers. + * Combined markers are split, with a space inserted between. */ public void unCombineCiteMarkers(List databases, OOBibStyle style) throws IOException, @@ -2502,9 +2529,6 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) List names = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - documentConnection.xText); - int pivot = 0; boolean madeModifications = false; XNameAccess nameAccess = documentConnection.getReferenceMarks(); @@ -2533,7 +2557,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) continue; } - removeReferenceMark(documentConnection, names.get(pivot)); + documentConnection.removeReferenceMark(names.get(pivot)); // Insert bookmark for each key int last = keys.size() - 1; @@ -2543,7 +2567,15 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) key, OOBibBase.AUTHORYEAR_PAR ); - insertReferenceMark(documentConnection, newName, "tmp", textCursor, true, style); + + insertReferenceMark( + documentConnection, + newName, + "tmp", + textCursor, + /* TODO: withText should be itcType != OOBibBase.INVISIBLE_CIT */ + true, + style); textCursor.collapseToEnd(); if (i != last) { textCursor.setString(" "); @@ -2579,25 +2611,42 @@ public BibDatabase generateDatabase(List databases) // Loop through the available databases for (BibDatabase loopDatabase : databases) { Optional entry = loopDatabase.getEntryByCitationKey(key); + if (entry.isEmpty()) { + continue; + } // If entry found - if (entry.isPresent()) { - BibEntry clonedEntry = (BibEntry) entry.get().clone(); - // Insert a copy of the entry - entriesToInsert.add(clonedEntry); - // Check if the cloned entry has a crossref field - clonedEntry.getField(StandardField.CROSSREF).ifPresent(crossref -> { - // If the crossref entry is not already in the database - if (!resultDatabase.getEntryByCitationKey(crossref).isPresent()) { - // Add it if it is in the current library - loopDatabase.getEntryByCitationKey(crossref).ifPresent(entriesToInsert::add); - } - }); + BibEntry clonedEntry = (BibEntry) entry.get().clone(); + // Insert a copy of the entry + entriesToInsert.add(clonedEntry); + + // Check if the cloned entry has a cross-reference field + clonedEntry + .getField(StandardField.CROSSREF) + .ifPresent(crossReference -> { + // If the crossReference entry is not already in the database + + // TODO: broken logic here: we just created resultDatabase, + // and added nothing yet. Question: why do we use + // entriesToInsert instead of directly adding to resultDatabase? + // And why do we not look for it in entriesToInsert? + // With the present code we are always adding it. + // How does BibDatabase handle this situation? + boolean isNew = (resultDatabase + .getEntryByCitationKey(crossReference) + .isEmpty()); + if (isNew) { + // Add it if it is in the current library + loopDatabase + .getEntryByCitationKey(crossReference) + .ifPresent(entriesToInsert::add); + } + }); // Be happy with the first found BibEntry and move on to next key break; - } } } + resultDatabase.insertEntries(entriesToInsert); return resultDatabase; } @@ -2629,8 +2678,9 @@ public boolean equals(Object o) { if (o instanceof ComparableMark) { ComparableMark other = (ComparableMark) o; - return (this.position.X == other.position.X) && (this.position.Y == other.position.Y) - && Objects.equals(this.name, other.name); + return ((this.position.X == other.position.X) + && (this.position.Y == other.position.Y) + && Objects.equals(this.name, other.name)); } return false; } From 2f2d7171315b5746258e9a005d213749e2e891f3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Feb 2021 15:46:16 +0100 Subject: [PATCH 0344/1068] check connection before starting ManageCitationsDialogView --- .../java/org/jabref/gui/openoffice/OpenOfficePanel.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index e30b02649a2..6d7b3b3f6c6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -270,7 +270,11 @@ private void initPanel() { settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { - dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); + if ( ooBase.documentConnectionMissing() ){ + showNoDocumentErrorMessage(); + } else { + dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); + } }); exportCitations.setMaxWidth(Double.MAX_VALUE); From 515105090a1ae7f9db433b2bcb9520866fedd628 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 08:43:17 +0100 Subject: [PATCH 0345/1068] refactor: revise code format, comments (partial) --- .../org/jabref/gui/openoffice/OOBibBase.java | 1001 +++++++++++------ 1 file changed, 644 insertions(+), 357 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6d7d80806e4..671e647eaa9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -112,7 +112,7 @@ class OOBibBase { private static final int INVISIBLE_CIT = 3; private static final Logger LOGGER = - LoggerFactory.getLogger(OOBibBase.class); + LoggerFactory.getLogger(OOBibBase.class); /* variables */ private final DialogService dialogService; @@ -134,15 +134,16 @@ private static class DocumentConnection { public XPropertyContainer userProperties; private final Logger LOGGER; - DocumentConnection(XMultiServiceFactory mxDocFactory, - XTextDocument mxDoc, - XText xText, - XTextViewCursorSupplier xViewCursorSupplier, - XComponent xCurrentComponent, - XPropertySet propertySet, - XPropertyContainer userProperties, - Logger LOGGER - ) { + DocumentConnection( + XMultiServiceFactory mxDocFactory, + XTextDocument mxDoc, + XText xText, + XTextViewCursorSupplier xViewCursorSupplier, + XComponent xCurrentComponent, + XPropertySet propertySet, + XPropertyContainer userProperties, + Logger LOGGER + ) { this.mxDocFactory = mxDocFactory; this.mxDoc = mxDoc; this.xText = xText; @@ -302,7 +303,7 @@ public String getCitationContext(String refMarkName, // If we are close to charBefore and see a space, // then cut here. Might avoid cutting a word in half. if ((i >= (charBefore - flex)) - && Character.isWhitespace(cursor.getString().charAt(0))) { + && Character.isWhitespace(cursor.getString().charAt(0))) { break; } } catch (IndexOutOfBoundsException ex) { @@ -331,9 +332,9 @@ public String getCitationContext(String refMarkName, String result = cursor.getString(); if (htmlMarkup) { result = - result.substring(0, addedBefore) - + "" + citPart + "" - + result.substring(lengthWithBefore); + result.substring(0, addedBefore) + + "" + citPart + "" + + result.substring(lengthWithBefore); } return result.trim(); } @@ -342,17 +343,21 @@ public String getCitationContext(String refMarkName, * Get the cursor positioned by the user. * */ - public XTextViewCursor getViewCursor() { + public XTextViewCursor + getViewCursor() { return this.xViewCursorSupplier.getViewCursor(); } - public XNameAccess getBookmarks() { + /** + * Provides access to bookmarks by name. + */ + public XNameAccess + getBookmarks() { // query XBookmarksSupplier from document model // and get bookmarks collection XBookmarksSupplier xBookmarksSupplier = unoQI(XBookmarksSupplier.class, - this.xCurrentComponent - ); + this.xCurrentComponent); return xBookmarksSupplier.getBookmarks(); } @@ -385,14 +390,18 @@ public XTextRange getBookmarkRange(String name) */ private DocumentConnection xDocumentConnection; - /* - * xUniqueLetters : maps bibtexkeys to letters ("a", "b") that + /** + * Map citation keys to letters ("a", "b") that * make the citation markers unique. + * + * Used directly (apart from passing around as `uniqueLetters`): + * refreshCiteMarkers, rebuildBibTextSection. */ private final Map xUniqueLetters = new HashMap<>(); /** - * + * Names of reference marks belonging to JabRef sorted by visual + * position. * */ private List jabRefReferenceMarkNamesSortedByPosition; @@ -400,36 +409,42 @@ public XTextRange getBookmarkRange(String name) /* * Constructor */ - public OOBibBase(Path loPath, - boolean atEnd, - DialogService dialogService - ) throws BootstrapException, - CreationException { + public + OOBibBase(Path loPath, + boolean atEnd, + DialogService dialogService) + throws + BootstrapException, + CreationException { + this.dialogService = dialogService; - FieldComparator a = new FieldComparator(StandardField.AUTHOR); - FieldComparator y = new FieldComparator(StandardField.YEAR); - FieldComparator t = new FieldComparator(StandardField.TITLE); + FieldComparator a = new FieldComparator(StandardField.AUTHOR); + FieldComparator y = new FieldComparator(StandardField.YEAR); + FieldComparator t = new FieldComparator(StandardField.TITLE); - List> ayt = new ArrayList<>(3); - ayt.add(a); - ayt.add(y); - ayt.add(t); - this.entryComparator = new FieldComparatorStack<>(ayt); + List> ayt = new ArrayList<>(3); + ayt.add(a); + ayt.add(y); + ayt.add(t); + this.entryComparator = new FieldComparatorStack<>(ayt); - List> yat = new ArrayList<>(3); - yat.add(y); - yat.add(a); - yat.add(t); - this.yearAuthorTitleComparator = new FieldComparatorStack<>(yat); + List> yat = new ArrayList<>(3); + yat.add(y); + yat.add(a); + yat.add(t); + this.yearAuthorTitleComparator = new FieldComparatorStack<>(yat); this.atEnd = atEnd; this.xDesktop = simpleBootstrap(loPath); } - private XDesktop simpleBootstrap(Path loPath) - throws CreationException, - BootstrapException { + private XDesktop + simpleBootstrap(Path loPath) + throws + CreationException, + BootstrapException { + // Get the office component context: XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); XMultiComponentFactory sem = context.getServiceManager(); @@ -455,18 +470,22 @@ private XDesktop simpleBootstrap(Path loPath) * @return A reference to the requested UNO interface type if available, * otherwise null */ - private static T unoQI(Class zInterface, - Object object) { + private static T + unoQI( + Class zInterface, + Object object) { return UnoRuntime.queryInterface(zInterface, object); } - /* - * section: selectDocument() + /** + * Used by selectDocument */ + private static List + getTextDocuments(XDesktop desktop) + throws + NoSuchElementException, + WrappedTargetException { - private static List getTextDocuments(XDesktop desktop) - throws NoSuchElementException, - WrappedTargetException { List result = new ArrayList<>(); XEnumerationAccess enumAccess = desktop.getComponents(); @@ -483,24 +502,40 @@ private static List getTextDocuments(XDesktop desktop) return result; } - private static Optional getDocumentTitle(XTextDocument doc) { + /** + * @param doc The XTextDocument we want the title for. Null allowed. + * @return The title or Optional.empty() + */ + private static Optional + getDocumentTitle(XTextDocument doc) { + if (doc == null) { return Optional.empty(); } try { XFrame frame = doc.getCurrentController().getFrame(); - Object frame_title_obj = OOUtil.getProperty(frame, "Title"); - String frame_title_str = String.valueOf(frame_title_obj); - return Optional.of(frame_title_str); + Object frameTitleObj = OOUtil.getProperty(frame, "Title"); + String frameTitleString = String.valueOf(frameTitleObj); + return Optional.of(frameTitleString); } catch (UnknownPropertyException | WrappedTargetException e) { LOGGER.warn("Could not get document title", e); return Optional.empty(); } } - private static XTextDocument selectDocumentDialog(List list, - DialogService dialogService) { + /** + * Run a dialog allowing the user to choose among the documents in `list`. + * + * @return Null if no document was selected. Otherwise the + * document selected. + * + */ + private static XTextDocument + selectDocumentDialog( + List list, + DialogService dialogService) { + class DocumentTitleViewModel { private final XTextDocument xTextDocument; @@ -522,54 +557,73 @@ public String toString() { } List viewModel = - list.stream() - .map(DocumentTitleViewModel::new) - .collect(Collectors.toList()); + list.stream() + .map(DocumentTitleViewModel::new) + .collect(Collectors.toList()); // This whole method is part of a background task when // auto-detecting instances, so we need to show dialog in FX // thread Optional selectedDocument = - dialogService - .showChoiceDialogAndWait( - Localization.lang("Select document"), - Localization.lang("Found documents:"), - Localization.lang("Use selected document"), - viewModel - ); + dialogService + .showChoiceDialogAndWait( + Localization.lang("Select document"), + Localization.lang("Found documents:"), + Localization.lang("Use selected document"), + viewModel + ); + return - selectedDocument - .map(DocumentTitleViewModel::getXtextDocument) - .orElse(null); + selectedDocument + .map(DocumentTitleViewModel::getXtextDocument) + .orElse(null); } /** * Choose a document to work with. + * + * Assumes we have already connected to Libroffice or OpenOffice. + * + * If there is a single document to choose from, selects that. + * If there are more than one, shows selection dialog. + * If there are none, throws NoDocumentException + * + * After successful selection connects to the selected document + * and extracts some frequently used parts (starting points for + * managing its content). + * + * Finally initializes this.xDocumentConnection with the selected + * document and parts extracted. + * */ - public void selectDocument() - throws NoDocumentException, - NoSuchElementException, - WrappedTargetException { + public void + selectDocument() + throws + NoDocumentException, + NoSuchElementException, + WrappedTargetException { + XTextDocument mxDoc; - XTextDocument selected; - List textDocumentList = getTextDocuments(this.xDesktop); - if (textDocumentList.isEmpty()) { - throw new NoDocumentException("No Writer documents found"); - } else if (textDocumentList.size() == 1) { - // Get the only one - selected = textDocumentList.get(0); - } else { - // Bring up a dialog - selected = - OOBibBase.selectDocumentDialog(textDocumentList, - this.dialogService); - } + XTextDocument selected; + List textDocumentList = getTextDocuments(this.xDesktop); + if (textDocumentList.isEmpty()) { + throw new NoDocumentException("No Writer documents found"); + } else if (textDocumentList.size() == 1) { + // Get the only one + selected = textDocumentList.get(0); + } else { + // Bring up a dialog + selected = + OOBibBase.selectDocumentDialog( + textDocumentList, + this.dialogService); + } - if (selected == null) { - return; - } - mxDoc = selected; + if (selected == null) { + return; + } + mxDoc = selected; XComponent component = unoQI(XComponent.class, mxDoc); @@ -577,9 +631,9 @@ public void selectDocument() XTextViewCursorSupplier viewCursorSupplier; - XModel mo = unoQI(XModel.class, component); - XController co = mo.getCurrentController(); - viewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); + XModel mo = unoQI(XModel.class, component); + XController co = mo.getCurrentController(); + viewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); // get a reference to the body text of the document XText text = mxDoc.getText(); @@ -589,21 +643,21 @@ public void selectDocument() XPropertyContainer userProperties; - XDocumentPropertiesSupplier supp = - unoQI(XDocumentPropertiesSupplier.class, mxDoc); - userProperties = supp.getDocumentProperties().getUserDefinedProperties(); + XDocumentPropertiesSupplier supp = + unoQI(XDocumentPropertiesSupplier.class, mxDoc); + userProperties = supp.getDocumentProperties().getUserDefinedProperties(); XPropertySet propertySet = unoQI(XPropertySet.class, userProperties); this.xDocumentConnection = new DocumentConnection( - mxDocFactory, - mxDoc, - text, - viewCursorSupplier, - component, - propertySet, - userProperties, - LOGGER + mxDocFactory, + mxDoc, + text, + viewCursorSupplier, + component, + propertySet, + userProperties, + LOGGER ); // TODO: maybe we should install an event handler for document @@ -613,13 +667,23 @@ public void selectDocument() // util/XCloseBroadcaster.html#addCloseListener } - /* + /** + * Mark the current document as missing. + * * TODO: GUI should be notified */ - private void forgetDocument() { + private void + forgetDocument() { this.xDocumentConnection = null; } + /** + * A simple test for document availability. + * + * See also `documentConnectionMissing` for a test + * actually attempting to use teh connection. + * + */ public boolean isConnectedToDocument() { return this.xDocumentConnection != null; } @@ -638,19 +702,24 @@ public boolean documentConnectionMissing() { return res; } - private DocumentConnection getDocumentConnectionOrThrow() - throws NoDocumentException { + /** + * Either return a valid DocumentConnection or throw + * NoDocumentException. + */ + private DocumentConnection + getDocumentConnectionOrThrow() + throws NoDocumentException { if (documentConnectionMissing()) { throw new NoDocumentException("Not connected to document"); } return this.xDocumentConnection; } - /* - * Getters useful after selectDocument() + /** + * The title of the current document, or Optional.empty() */ - - public Optional getCurrentDocumentTitle() { + public Optional + getCurrentDocumentTitle() { if (documentConnectionMissing()) { return Optional.empty(); } else { @@ -658,11 +727,15 @@ public Optional getCurrentDocumentTitle() { } } - /* - * insertEntry + /** + * The comparator used to sort within a group of merged + * citations. + * + * The term used here is "multicite". The option controlling the + * order is "MultiCiteChronological" in style files. */ - - private Comparator comparatorForMulticite(OOBibStyle style) { + private Comparator + comparatorForMulticite(OOBibStyle style) { if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { return this.yearAuthorTitleComparator; } else { @@ -670,15 +743,30 @@ private Comparator comparatorForMulticite(OOBibStyle style) { } } - private void sortBibEntryListForMulticite(List entries, - OOBibStyle style) { + /** + * Sort entries within a group of merged citations. + * + * Note: the sort is inplace, modifies the argument. + */ + private void + sortBibEntryListForMulticite(List entries, + OOBibStyle style) { if (entries.size() <= 1) { return; } entries.sort(comparatorForMulticite(style)); } - private static int citationTypeFromOptions(boolean withText, boolean inParenthesis) { + /** + * Given the withText and inParenthesis options, + * return the corresponding itcType. + * + * @param withText False means invisible citation (no text). + * @param inParenthesis True means "(Au and Thor 2000)". + * False means "Au and Thor (2000)". + */ + private static int + citationTypeFromOptions(boolean withText, boolean inParenthesis) { if (!withText) { return OOBibBase.INVISIBLE_CIT; } @@ -687,11 +775,22 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes : OOBibBase.AUTHORYEAR_INTEXT); } - private static boolean isJabRefReferenceMarkName(String name) { + /** + * @return true if name matches the pattern used for JabRef + * reference mark names. + */ + private static boolean + isJabRefReferenceMarkName(String name) { return (CITE_PATTERN.matcher(name).find()); } - private static List filterIsJabRefReferenceMarkName(List names) { + /** + * Filter a list of reference mark names by `isJabRefReferenceMarkName` + * + * @param names The list to be filtered. + */ + private static List + filterIsJabRefReferenceMarkName(List names) { return (names .stream() .filter(OOBibBase::isJabRefReferenceMarkName) @@ -699,38 +798,57 @@ private static List filterIsJabRefReferenceMarkName(List names) ); } - /* - * called from getCitationEntries(...) + /** + * Get reference mark naems from the document matching the pattern + * used for JabRef reference mark names. + * + * Note: the names returned are in arbitrary order. + * + * See also: `getJabRefReferenceMarkNamesSortedByPosition` + * */ - private List getJabRefReferenceMarkNames(DocumentConnection documentConnection) - throws NoDocumentException { - return filterIsJabRefReferenceMarkName(documentConnection.getReferenceMarknames()); + private List + getJabRefReferenceMarkNames(DocumentConnection documentConnection) + throws NoDocumentException { + List allNames = documentConnection.getReferenceMarkNames(); + return filterIsJabRefReferenceMarkName(allNames); } /** + * Get a list of CitationEntry objects corresponding to citations + * in the document. + * + * @return A list with entries corresponding to citations in the + * text, in arbitrary order (same order as from + * getJabRefReferenceMarkNames). + * + * TODO: Note: visual or alphabetic order could be more + * managable for the user. We could provide these + * here, but switching between them needs change on + * GUI (adding a toggle or selector). * + * Wish: selecting an entry in the GUI cold move cursor in + * the document. */ - public List getCitationEntries() - throws NoSuchElementException, - UnknownPropertyException, - WrappedTargetException, - NoDocumentException { - return this.getCitationEntriesImpl(this.getDocumentConnectionOrThrow()); - } + public List + getCitationEntries() + throws + NoSuchElementException, + UnknownPropertyException, + WrappedTargetException, + NoDocumentException { + + DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - private List getCitationEntriesImpl(DocumentConnection documentConnection) - throws NoSuchElementException, - UnknownPropertyException, - WrappedTargetException, - NoDocumentException { List names = this.getJabRefReferenceMarkNames(documentConnection); List citations = new ArrayList<>(names.size()); for (String name : names) { CitationEntry entry = - new CitationEntry(name, - documentConnection.getCitationContext(name, 30, 30, true), - documentConnection.getCustomProperty(name) + new CitationEntry( + name, + documentConnection.getCitationContext(name, 30, 30, true), + documentConnection.getCustomProperty(name) ); citations.add(entry); } @@ -739,40 +857,37 @@ private List getCitationEntriesImpl(DocumentConnection documentCo /** * Apply editable parts of citationEntries to the document. - * - * - Currently the only editable part is pageInfo. - * + *

+ * Currently the only editable part is pageInfo. + *

* Since the only call to applyCitationEntries() only changes * pageInfo w.r.t those returned by getCitationEntries(), we can * do with the following restrictions: - * - * - Missing pageInfo means no action. - * - * - Missing CitationEntry means no action (no attempt to remove - citation from the text). - * - * - Reference to citation not present in the text evokes no - error, and setCustomProperty() is called. + *

    + *
  • Missing pageInfo means no action.
  • + *
  • Missing CitationEntry means no action (no attempt to remove + * citation from the text).
  • + *
*/ - public void applyCitationEntries(List citationEntries) - throws UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException, - NoDocumentException { - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - // Leave exceptions to the caller. + public void + applyCitationEntries( + List citationEntries) + throws + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException, + NoDocumentException { - // Note: not catching exceptions here means nothing is applied - // after the first problematic entry. We might catch and - // collect messages here. + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - // try { for (CitationEntry entry : citationEntries) { Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { - documentConnection.setCustomProperty(entry.getRefMarkName(), pageInfo.get()); + documentConnection.setCustomProperty( + entry.getRefMarkName(), + pageInfo.get()); } // TODO: if pageInfo is not present, or is empty: // maybe we should remove it from the document. @@ -780,15 +895,26 @@ public void applyCitationEntries(List citationEntries) } /** + * Produce a reference mark name for JabRef for the given citation + * key and itcType that does not yet appear among the reference + * marks of the document. + * + * @param bibtexKey The citation key. + * @param itcType Encodes the effect of withText and + * inParenthesis options. + * * The first occurrence of bibtexKey gets no serial number, the * second gets 0, the third 1 ... * * Or the first unused in this series, after removals. */ - private String getUniqueReferenceMarkName(DocumentConnection documentConnection, - String bibtexKey, - int itcType) - throws NoDocumentException { + private String + getUniqueReferenceMarkName( + DocumentConnection documentConnection, + String bibtexKey, + int itcType) + throws NoDocumentException { + XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); int i = 0; String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; @@ -806,8 +932,11 @@ private String getUniqueReferenceMarkName(DocumentConnection documentConnection, * number of itcType values. */ private static class ParsedRefMark { - public String i; // "", "0", "1" ... - public int itcType; // in-text-citation type + /** "", "0", "1" ... */ + public String i; + /** in-text-citation type */ + public int itcType; + /** Citation keys embedded in the reference mark. */ public List citedKeys; ParsedRefMark(String i, int itcType, List citedKeys) { @@ -818,13 +947,19 @@ private static class ParsedRefMark { } /** - * Parse a refMarkName. + * Parse a JabRef reference mark name. + * + * @return Optional.empty() on failure. + * */ - private static Optional parseRefMarkName(String refMarkName) { + private static Optional + parseRefMarkName(String refMarkName) { + Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); if (!citeMatcher.find()) { return Optional.empty(); } + List keys = Arrays.asList(citeMatcher.group(3).split(",")); String i = citeMatcher.group(1); int itcType = Integer.parseInt(citeMatcher.group(2)); @@ -832,47 +967,70 @@ private static Optional parseRefMarkName(String refMarkName) { } /** - * This method inserts a cite marker in the text (at the cursor) - * for the given BibEntry, and may refresh the bibliography. + * This method inserts a reference mark in the text (at the cursor) + * citing the entries, and may refresh the bibliography. * * @param entries The entries to cite. - * @param database The database the entry belongs to. + * + * @param database The database the entries belong to (all of them). + * Used when creating the citation mark. + * + * @param allBases Used if sync is true. The list of all databases + * we may need to refresh the document. + * * @param style The bibliography style we are using. * @param inParenthesis Indicates whether it is an in-text - * citation or a citation in parenthesis. This is not relevant if - * numbered citations are used. - * @param withText Indicates whether this should be a normal - * citation (true) or an empty (invisible) citation (false). - * @param sync Indicates whether the reference list should be - * refreshed. + * citation or a citation in parenthesis. + * This is not relevant if + * numbered citations are used. + * @param withText Indicates whether this should be a visible + * citation (true) or an empty (invisible) citation (false). + * + * @param pageInfo A single pageinfo for these entries. Stored in custom property + * with the same name as the reference mark. + * + * Related https://latex.org/forum/viewtopic.php?t=14331 + * + * Q: What I would like is something like this: + * (Jones, 2010, p. 12; Smith, 2003, pp. 21 - 23) + * A: Not in a single \citep, no. + * Use \citetext{\citealp[p.~12]{jones2010}; + * \citealp[pp.~21--23]{smith2003}} + * + * @param sync Indicates whether the reference list and in-text citations + * should be refreshed in the document. * * TODO: * https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html * Group changes into a single Undo context. */ - public void insertEntry(List entries, - BibDatabase database, - List allBases, - OOBibStyle style, - boolean inParenthesis, - boolean withText, - String pageInfo, - boolean sync - ) - throws IllegalArgumentException, - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - UndefinedCharacterFormatException, - WrappedTargetException, - NoSuchElementException, - PropertyVetoException, - IOException, - CreationException, - BibEntryNotFoundException, - UndefinedParagraphFormatException, - NoDocumentException { + public void + insertEntry( + List entries, + BibDatabase database, + List allBases, + OOBibStyle style, + boolean inParenthesis, + boolean withText, + String pageInfo, + boolean sync + ) + throws + IllegalArgumentException, + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + UndefinedCharacterFormatException, + WrappedTargetException, + NoSuchElementException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException, + UndefinedParagraphFormatException, + NoDocumentException { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { @@ -882,14 +1040,15 @@ public void insertEntry(List entries, sortBibEntryListForMulticite(entries, style); String keyString = - entries.stream() - .map(entry -> entry.getCitationKey().orElse("")) - .collect(Collectors.joining(",")); + entries.stream() + .map(entry -> entry.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); // Generate unique bookmark-name int citationType = citationTypeFromOptions(withText, inParenthesis); - String newName = getUniqueReferenceMarkName(documentConnection, - keyString, - citationType); + String newName = getUniqueReferenceMarkName( + documentConnection, + keyString, + citationType); // If we should store metadata for page info, do that now: if (pageInfo != null) { @@ -899,10 +1058,11 @@ public void insertEntry(List entries, // insert space cursor - .getText() - .insertString(cursor, " ", false); + .getText() + .insertString(cursor, " ", false); // format the space inserted + // TOOD: extract applyCharacterStyle() if (style.isFormatCitations()) { XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); String charStyle = style.getCitationCharacterFormat(); @@ -927,25 +1087,30 @@ public void insertEntry(List entries, // go back to before the space cursor.goLeft((short) 1, false); - // Insert bookmark and text - + // Insert rerefence mark and text + //{ // Create a BibEntry to BibDatabase map (to make // style.getCitationMarker happy?) Map databaseMap = new HashMap<>(); for (BibEntry entry : entries) { + // Using the same database for each entry. + // Probably the GUI limits selection to a single database. databaseMap.put(entry, database); } - // the text we insert? + + // The text we insert String citeText = - style.isNumberEntries() - ? "-" // A dash only. Presumably we expect a refresh later. - : style.getCitationMarker(entries, - databaseMap, - inParenthesis, - null, - null - ); - insertReferenceMark(documentConnection, newName, citeText, cursor, withText, style); + style.isNumberEntries() + ? "-" // A dash only. Presumably we expect a refresh later. + : style.getCitationMarker( + entries, + databaseMap, + inParenthesis, + null, + null); + insertReferenceMark(documentConnection, newName, citeText, + cursor, withText, style); + //} // end of scope for databaseMap, citeText // Move to the right of the space and remember this // position: we will come back here in the end. @@ -971,6 +1136,9 @@ public void insertEntry(List entries, * at org.jabref@100.0.0/org.jabref.gui.openoffice * .OOBibBase.insertEntry(OOBibBase.java:609) * + * Maybe we should refuse to insert in places to be + * overwritten: bibliography, reference marks. + * */ // Go back to the relevant position: try { @@ -992,17 +1160,26 @@ public void insertEntry(List entries, * Extract the list of citation keys from a reference mark name. * * @param name The reference mark name. - * @return The list of citation keys encoded in the name. In case of duplicated citation keys, - * only the first occurrence. Otherwise their order is preserved. - * If name does not match CITE_PATTERN, an empty list of strings is returned. - * */ - private List parseRefMarkNameToUniqueCitationKeys(String name) { + * @return The list of citation keys encoded in the name. + * + * In case of duplicated citation keys, + * only the first occurrence. + * Otherwise their order is preserved. + * + * If name does not match CITE_PATTERN, + * an empty list of strings is returned. + */ + private List + parseRefMarkNameToUniqueCitationKeys(String name) { Optional op = parseRefMarkName(name); - return op.map(parsedRefMark -> + return + op.map( + parsedRefMark -> parsedRefMark.citedKeys.stream() - .distinct() - .collect(Collectors.toList())) - .orElseGet(ArrayList::new); + .distinct() + .collect(Collectors.toList()) + ) + .orElseGet(ArrayList::new); } /** @@ -1012,10 +1189,12 @@ private List parseRefMarkNameToUniqueCitationKeys(String name) { * * doc.referenceMarks.names.map(parse).flatten.unique */ - private List findCitedKeys(DocumentConnection documentConnection) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException { + private List + findCitedKeys(DocumentConnection documentConnection) + throws + NoSuchElementException, + WrappedTargetException, + NoDocumentException { List names = getJabRefReferenceMarkNames(documentConnection); @@ -1026,7 +1205,7 @@ private List findCitedKeys(DocumentConnection documentConnection) assert (null != unoQI(XTextContent.class, bookmark)); } - // + // Collect to a flat list while keep only the first appearance. List keys = new ArrayList<>(); for (String name1 : names) { List newKeys = parseRefMarkNameToUniqueCitationKeys(name1); @@ -1040,19 +1219,25 @@ private List findCitedKeys(DocumentConnection documentConnection) return keys; } + /** + * The collection of data returned by findCitedKeys. + */ private static class FindCitedEntriesResult { /* * entries : LinkedHashMap with iteration order as the * citedKeys parameter of findCitedEntries */ Map entries; + /* * citeKeyToBibEntry : HashMap (no order) */ Map citeKeyToBibEntry; - FindCitedEntriesResult(Map entries, - Map citeKeyToBibEntry) { + FindCitedEntriesResult( + Map entries, + Map citeKeyToBibEntry + ) { this.entries = entries; this.citeKeyToBibEntry = citeKeyToBibEntry; } @@ -1075,8 +1260,9 @@ private static class FindCitedEntriesResult { * citedKey in the entry is the same as the original citedKey */ private FindCitedEntriesResult - findCitedEntries(List databases, - List citedKeys + findCitedEntries( + List citedKeys, + List databases ) { Map citeKeyToBibEntry = new HashMap<>(); @@ -1110,21 +1296,28 @@ private static class FindCitedEntriesResult { * @param style The bibliography style to use. * @return A list of those referenced citation keys that could not be resolved. */ - public List refreshCiteMarkers(List databases, - OOBibStyle style) - throws WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - IOException, - CreationException, - BibEntryNotFoundException, - NoDocumentException { + public List + refreshCiteMarkers( + List databases, + OOBibStyle style) + throws + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + try { - return refreshCiteMarkersInternal(documentConnection, + return + refreshCiteMarkersInternal( + documentConnection, databases, style, this.xUniqueLetters); @@ -1136,108 +1329,166 @@ public List refreshCiteMarkers(List databases, } } - private static BibEntry undefinedBibentryToNull(BibEntry cEntry) { + /** + * @return Null if cEntry is an UndefinedBibtexEntry, + * otherwise return cEntry itself. + */ + private static BibEntry + undefinedBibentryToNull(BibEntry cEntry) { if (cEntry instanceof UndefinedBibtexEntry) { return null; } return cEntry; } - private static BibEntry[] mapUndefinedBibentriesToNull(BibEntry[] cEntries) { + /** + * @return A copy of the input with UndefinedBibtexEntry + * instances repalced by null. + */ + private static BibEntry[] + mapUndefinedBibEntriesToNull(BibEntry[] cEntries) { return - Arrays.stream(cEntries) - .map(OOBibBase::undefinedBibentryToNull) - .toArray(BibEntry[]::new); + Arrays.stream(cEntries) + .map(OOBibBase::undefinedBibentryToNull) + .toArray(BibEntry[]::new); } + /** + * Checks that keys do appear in citeKeys as keys. Collects the + * missing keys, and if there is any, throws BibEntryNotFoundException + * (currently mentioning only the first missing key). + * + * @param keys An array of citation keys, we expect to appear as + * keys in citeKeyToBibEntry. + * + * @param citeKeyToBibEntry Should map each key in keys to a BibEntry. + * @param referenceMarkName The reference mark these keys belong to. + * Mentioned in the exception. + */ private static void - assertKeysInCiteKeyToBibEntry(String[] keys, // citeKeys - Map citeKeyToBibEntry, - String referenceMarkName // for reporting + assertKeysInCiteKeyToBibEntry( + String[] keys, // citeKeys + Map citeKeyToBibEntry, + String referenceMarkName // for reporting ) - throws BibEntryNotFoundException { + throws BibEntryNotFoundException { + // check keys List unresolvedKeys = - Arrays.stream(keys) - .filter(key -> null == citeKeyToBibEntry.get(key)) - .collect(Collectors.toList()); + Arrays.stream(keys) + .filter(key -> null == citeKeyToBibEntry.get(key)) + .collect(Collectors.toList()); for (String key : unresolvedKeys) { LOGGER.info("Citation key not found: '" + key + '\''); LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); - String msg = Localization.lang("Could not resolve BibTeX entry" - + " for citation marker '%0'.", - referenceMarkName - ); + String msg = + Localization.lang( + "Could not resolve BibTeX entry" + + " for citation marker '%0'.", + referenceMarkName ); throw new BibEntryNotFoundException(referenceMarkName, msg); } } - // TODO: is mapCiteKeysToBibEntryArray is still needed? - private static BibEntry[] - mapCiteKeysToBibEntryArray(String[] keys, // citeKeys - Map citeKeyToBibEntry, - String referenceMarkName // for reporting - // boolean undefinedToNull // for undefined entries insert NULL - ) - throws BibEntryNotFoundException { - assertKeysInCiteKeyToBibEntry(keys, citeKeyToBibEntry, referenceMarkName); - - // process keys - return - Arrays.stream(keys) - .map(citeKeyToBibEntry::get) - .toArray(BibEntry[]::new); - } - + /** + * For each reference mark name check the corresponding part of + * bibtexKeys with assertKeysInCiteKeyToBibEntry. + */ private static void - assertAllKeysInCiteKeyToBibEntry(List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry) - throws BibEntryNotFoundException { + assertAllKeysInCiteKeyToBibEntry( + List referenceMarkNames, + String[][] bibtexKeys, + Map citeKeyToBibEntry + ) + throws BibEntryNotFoundException { + final int nRefMarks = referenceMarkNames.size(); assert (nRefMarks == bibtexKeys.length); for (int i = 0; i < nRefMarks; i++) { - final String referenceMarkName = referenceMarkNames.get(i); - assertKeysInCiteKeyToBibEntry(bibtexKeys[i], - citeKeyToBibEntry, - referenceMarkName); + assertKeysInCiteKeyToBibEntry( + bibtexKeys[i], + citeKeyToBibEntry, + referenceMarkNames.get(i)); } } + // TODO: is mapCiteKeysToBibEntryArray is still needed? + // We still have a call site, followed by mapUndefinedBibEntriesToNull + /** + * Map an array of citation keys to the corresponding BibEntry + * objects using citeKeyToBibEntry. + * + * @param citeKeys + * @param citeKeyToBibEntry + * @param referenceMarkName For reporting keys missing from citeKeyToBibEntry. + */ + private static BibEntry[] + mapCiteKeysToBibEntryArray( + String[] citeKeys, + Map citeKeyToBibEntry, + String referenceMarkName + ) + throws BibEntryNotFoundException { + + assertKeysInCiteKeyToBibEntry(citeKeys, citeKeyToBibEntry, referenceMarkName); + + return + Arrays.stream(citeKeys) + .map(citeKeyToBibEntry::get) + .toArray(BibEntry[]::new); + } + + /** + * Produce citation markers for the case when the citation + * markers are the citation keys themselves, separated by commas. + */ private static String[] - rcmCitationMarkersForIsCitationKeyCiteMarkers(List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry, - OOBibStyle style) - throws BibEntryNotFoundException { + produceCitationMarkersForIsCitationKeyCiteMarkers( + List referenceMarkNames, + String[][] bibtexKeys, + Map citeKeyToBibEntry, + OOBibStyle style + ) + throws BibEntryNotFoundException { + assert style.isCitationKeyCiteMarkers(); final int nRefMarks = referenceMarkNames.size(); + assert nRefMarks == bibtexKeys.length; assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { citMarkers[i] = - Arrays.stream(bibtexKeys[i]) - .map(citeKeyToBibEntry::get) - .map((c) -> c.getCitationKey().orElse("")) - .collect(Collectors.joining(",")); + Arrays.stream(bibtexKeys[i]) + .map(citeKeyToBibEntry::get) + .map(c -> c.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); } return citMarkers; } /** * Number source for (1-based) numbering of citations. + * + * For numbered citation style with first appearance order. */ private static class CitationNumberingState { - public Map numbers; - public int lastNum; + /** + * numbers : Remembers keys we have seen + * and what number did they receive. + */ + private Map numbers; + + /** + * The highest number we ever allocated. + */ + private int lastNum; CitationNumberingState() { - // For numbered citation style. Map(citedKey, number ) this.numbers = new HashMap<>(); this.lastNum = 0; } @@ -1336,21 +1587,23 @@ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, assert (nRefMarks == bibtexKeys.length); String[] citMarkers = new String[nRefMarks]; - // sort entries to order in bibliography - Map sortedEntries = sortEntriesByComparator(entries, entryComparator); + // Sort entries to order in bibliography + Map sortedEntries = + sortEntriesByComparator(entries, entryComparator); - // adjust order of cited to match + // Adjust order of cited to match sortedEntries List sortedCited = new ArrayList<>(entries.size()); for (BibEntry entry : sortedEntries.keySet()) { sortedCited.add(entry.getCitationKey().orElse(null)); } final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + for (int i = 0; i < referenceMarkNames.size(); i++) { - List num = - findCitedEntryIndices(Arrays.asList(bibtexKeys[i]), sortedCited); - citMarkers[i] = style.getNumCitationMarker(num, minGroupingCount, false); + List numbers = + findCitedEntryIndices(Arrays.asList(bibtexKeys[i]), sortedCited); + citMarkers[i] = style.getNumCitationMarker(numbers, minGroupingCount, false); } return citMarkers; } @@ -1361,17 +1614,24 @@ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, * * @param keysCitedHere The citation keys needing indices. * @param orderedCiteKeys A List of citation keys representing the - * entries in the bibliography. - * @return the (1-based) indices of the cited keys, -1 if a key is - * not found. Returns Collections.emptyList() if the ref name - * could not be resolved as a citation. + * entries in the bibliography. + * + * @return The (1-based) indices of the cited keys, + * or (-1) if a key is not found. */ - private static List findCitedEntryIndices(List keysCitedHere, - List orderedCiteKeys) { + private static List + findCitedEntryIndices( + List keysCitedHere, + List orderedCiteKeys + ) { List result = new ArrayList<>(keysCitedHere.size()); for (String key : keysCitedHere) { int ind = orderedCiteKeys.indexOf(key); - result.add(ind == -1 ? -1 : 1 + ind); + result.add( + ind == -1 + ? -1 + : 1 + ind // 1-based + ); } return result; } @@ -1802,7 +2062,8 @@ private List refreshCiteMarkersInternal(DocumentConnection documentConne // Position as in a document on the screen. // Probably to get the correct order with // referenceMarks in footnotes - private static Point findPositionOfTextRange(XTextViewCursor cursor, XTextRange range) { + private static Point + findPositionOfTextRange(XTextViewCursor cursor, XTextRange range) { cursor.gotoRange(range, false); return cursor.getPosition(); // the cursor's coordinates relative to the top left position @@ -1813,37 +2074,40 @@ private static Point findPositionOfTextRange(XTextViewCursor cursor, XTextRange * */ private List - getJabRefReferenceMarkNamesSortedByPosition(DocumentConnection documentConnection) - throws WrappedTargetException, - NoSuchElementException, - NoDocumentException { + getJabRefReferenceMarkNamesSortedByPosition( + DocumentConnection documentConnection) + throws + WrappedTargetException, + NoSuchElementException, + NoDocumentException { List names = getJabRefReferenceMarkNames(documentConnection); // find coordinates List positions = new ArrayList<>(names.size()); - XNameAccess nameAccess = documentConnection.getReferenceMarks(); - XTextViewCursor viewCursor = documentConnection.getViewCursor(); - // initialPos: to be restored before return - XTextRange initialPos = viewCursor.getStart(); - for (String name : names) { - - XTextContent textContent = - unoQI(XTextContent.class, nameAccess.getByName(name)); - XTextRange range = textContent.getAnchor(); - - // Adjust range if we are inside a footnote: - if (unoQI(XFootnote.class, range.getText()) != null) { - // Find the linking footnote marker: - XFootnote footer = unoQI(XFootnote.class, range.getText()); - // The footnote's anchor gives the correct position in the text: - range = footer.getAnchor(); - } - positions.add(findPositionOfTextRange(viewCursor, range)); + XNameAccess nameAccess = documentConnection.getReferenceMarks(); + XTextViewCursor viewCursor = documentConnection.getViewCursor(); + // initialPos: to be restored before return + XTextRange initialPos = viewCursor.getStart(); + for (String name : names) { + + XTextContent textContent = + //documentConnection.nameAccessGetTextContentByName( nameAccess, name ); + unoQI(XTextContent.class, nameAccess.getByName(name)); + XTextRange range = textContent.getAnchor(); + + // Adjust range if we are inside a footnote: + if (unoQI(XFootnote.class, range.getText()) != null) { + // Find the linking footnote marker: + XFootnote footer = unoQI(XFootnote.class, range.getText()); + // The footnote's anchor gives the correct position in the text: + range = footer.getAnchor(); } - // restore cursor position - viewCursor.gotoRange(initialPos, false); + positions.add(findPositionOfTextRange(viewCursor, range)); + } + // restore cursor position + viewCursor.gotoRange(initialPos, false); // order by position Set set = new TreeSet<>(); @@ -2089,6 +2353,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) // Clear it: XTextCursor cursor = documentConnection.xText.createTextCursorByRange(section.getAnchor()); + cursor.gotoRange(section.getAnchor(), false); cursor.setString(""); } catch (NoSuchElementException ex) { @@ -2364,6 +2629,26 @@ private void testFormatCitations(XTextCursor textCursor, OOBibStyle style) /** * GUI action + * + * combineCiteMarkers does not work with citations in footnotes. + * + * Note: citations can be inserted in footnotes and they appear in + * the bibliography. They are also updated on style change+refresh + * + * The same (insertable, appears in bibliography, update on + * style change) is true for citations in tables. + * + * Merge (combineCiteMarkers) and Separate (unCombineCiteMarkers) + * seem to work in a cell of a table. + * + * In footnotes: "Separate" (on merged citations inserted by + * selecting multiple entries then "Cite") leaves first of + * two citation marks with text "tmp", which can be + * corrected by a few repetions of pressing the "refresh" + * button. + * With 3 citations, "Separate" left the 2nd and 3rd as "tmp". + * Three refresh corrected the 2nd. The 4th refresh corrected the 3rd citation. + * */ public void combineCiteMarkers(List databases, OOBibStyle style) throws IOException, @@ -2390,6 +2675,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) XNameAccess nameAccess = documentConnection.getReferenceMarks(); while (pivot < (names.size() - 1)) { + XTextRange range1 = unoQI(XTextContent.class, nameAccess.getByName(names.get(pivot))) @@ -2479,9 +2765,9 @@ public void combineCiteMarkers(List databases, OOBibStyle style) entries.sort(new FieldComparator(StandardField.YEAR)); String keyString = - entries.stream() - .map(c -> c.getCitationKey().orElse("")) - .collect(Collectors.joining(",")); + entries.stream() + .map(c -> c.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); // Insert reference mark: String newName = getUniqueReferenceMarkName(documentConnection, @@ -2490,12 +2776,12 @@ public void combineCiteMarkers(List databases, OOBibStyle style) ); insertReferenceMark( - documentConnection, - newName, - "tmp", - textCursor, - true, // withText - style); + documentConnection, + newName, + "tmp", + textCursor, + true, // withText + style); names.set(pivot + 1, newName); // <- put in the next-to-be-processed position madeModifications = true; @@ -2524,6 +2810,7 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) CreationException, BibEntryNotFoundException, NoDocumentException { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); List names = From 008f5cc44883ef72e53916fa022229cd6b9ad85f Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:04:06 +0100 Subject: [PATCH 0346/1068] refactor: revise code format, comments (partial) --- .../org/jabref/gui/openoffice/OOBibBase.java | 302 +++++++++++------- 1 file changed, 189 insertions(+), 113 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 671e647eaa9..ccb40a08307 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -158,59 +158,90 @@ public Optional getDocumentTitle() { return OOBibBase.getDocumentTitle(this.mxDoc); } - private Optional getCustomProperty(String property) - throws UnknownPropertyException, - WrappedTargetException { + /** + * @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. + * + */ + private Optional + getCustomProperty(String property) + throws + UnknownPropertyException, + WrappedTargetException { + assert (this.propertySet != null); - XPropertySetInfo psi = - this.propertySet - .getPropertySetInfo(); + XPropertySetInfo psi = (this.propertySet + .getPropertySetInfo()); if (psi.hasPropertyByName(property)) { String v = - this.propertySet - .getPropertyValue(property) - .toString(); + this.propertySet + .getPropertyValue(property) + .toString(); return Optional.ofNullable(v); } return Optional.empty(); } - private void setCustomProperty(String property, String value) - throws UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException { - XPropertySetInfo psi = - this.propertySet - .getPropertySetInfo(); + /** + * @param property Name of a custom document property in the + * current document. + * + * @param value The value to be stored. + * + * @return The value of the property or Optional.empty() + */ + private void + setCustomProperty(String property, String value) + throws + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException { + + XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + if (psi.hasPropertyByName(property)) { this.userProperties.removeProperty(property); } + if (value != null) { this.userProperties - .addProperty(property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value) - ); + .addProperty( + property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value)); } } /** * @throws NoDocumentException If cannot get reference marks + * + * Note: also used by `documentConnectionMissing` to test if + * we have a working connecion. + * */ - private XNameAccess getReferenceMarks() - throws NoDocumentException { + private XNameAccess + getReferenceMarks() + throws NoDocumentException { + XReferenceMarksSupplier supplier = - unoQI(XReferenceMarksSupplier.class, - this.xCurrentComponent); + unoQI( + XReferenceMarksSupplier.class, + this.xCurrentComponent + ); try { return supplier.getReferenceMarks(); - } catch (Exception ex) { - LOGGER.warn("getReferenceMarks caught: ", ex); - throw new NoDocumentException("getReferenceMarks failed"); + } catch (DisposedException ex) { + // LOGGER.warn("getReferenceMarks caught: ", ex); + throw new NoDocumentException("getReferenceMarks failed with" + ex); } } @@ -235,9 +266,15 @@ public boolean documentConnectionMissing() { } return false; } + /** + * Names of all reference marks. + * + * Empty list for nothing. + */ + List + getReferenceMarkNames() + throws NoDocumentException { - List getReferenceMarknames() - throws NoDocumentException { XNameAccess nameAccess = getReferenceMarks(); String[] names = nameAccess.getElementNames(); if (names == null) { @@ -248,10 +285,16 @@ List getReferenceMarknames() /** * Remove the named reference mark. + * + * Removes both the text and the mark itself. */ - public void removeReferenceMark(String name) - throws WrappedTargetException, - NoDocumentException { + public void + removeReferenceMark(String name) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException { + XNameAccess xReferenceMarks = this.getReferenceMarks(); if (xReferenceMarks.hasByName(name)) { try { @@ -367,8 +410,9 @@ public String getCitationContext(String refMarkName, * @param name The name of the bookmark to find. * @return The XTextRange for the bookmark, or null. */ - public XTextRange getBookmarkRange(String name) - throws NoSuchElementException, + public XTextRange + getBookmarkRange(String name) + throws WrappedTargetException { XNameAccess xNamedBookmarks = this.getBookmarks(); @@ -1512,31 +1556,44 @@ public int getOrAllocateNumber(String key) { } /** - * Get number for a BibEntry. (-1) for UndefinedBibtexEntry + * Gets number for a BibEntry. (-1) for UndefinedBibtexEntry * * BibEntry.getCitationKey() must not be Optional.empty(). + * */ - private static int numberPossiblyUndefinedBibEntry(BibEntry ce, - CitationNumberingState cns) { + private static int + numberPossiblyUndefinedBibEntry( + BibEntry ce, + CitationNumberingState cns + ) { + if (ce instanceof UndefinedBibtexEntry) { return (-1); } - String key = ce.getCitationKey() - .orElseThrow(IllegalArgumentException::new); + String key = (ce.getCitationKey() + .orElseThrow(IllegalArgumentException::new)); return cns.getOrAllocateNumber(key); } /** + * Produce citation markers for the case of numbered citations + * with bibliography sorted by first appearance in the text. + * * @param referenceMarkNames Names of reference marks. + * * @param bibtexKeys Expects bibtexKeys[i] to correspond to - * referenceMarkNames.get(i) - * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. Must - * contain all bibtexKeys, but may map to UndefinedBibtexEntry. - * @return Numbered citation markers for bibtexKeys. Numbering is - * according to first encounter in bibtexKeys[i][j] - * (for(i){for(j){}} ) + * referenceMarkNames.get(i) + * + * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. + * Must contain all bibtexKeys, + * but may map to UndefinedBibtexEntry. + * + * @return Numbered citation markers for bibtexKeys. + * Numbering is according to first encounter + * in bibtexKeys[i][j] + * */ private static String[] rcmCitationMarkersForIsNumberEntriesIsSortByPosition(List referenceMarkNames, @@ -1556,24 +1613,26 @@ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, CitationNumberingState cns = new CitationNumberingState(); final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); for (int i = 0; i < referenceMarkNames.size(); i++) { - // numbers: Numbers for cEntries, (-1) for none. + // numbers: Numbers for cited sources. (-1) for UndefinedBibtexEntry. List numbers = - Arrays.stream(bibtexKeys[i]) - .map(citeKeyToBibEntry::get) - .map(ce -> numberPossiblyUndefinedBibEntry(ce, cns)) - .collect(Collectors.toList()); + Arrays.stream(bibtexKeys[i]) + .map(citeKeyToBibEntry::get) + .map(ce -> numberPossiblyUndefinedBibEntry(ce, cns)) + .collect(Collectors.toList()); - citMarkers[i] = style.getNumCitationMarker(numbers, minGroupingCount, false); - } // for + citMarkers[i] = + style.getNumCitationMarker(numbers, minGroupingCount, false); + } return citMarkers; } /** - * Produce citation markers for the case of `numbered entries` that are not sorted by position. + * Produce citation markers for the case of numbered citations + * when the bibliography is not sorted by position. */ private String[] rcmCitationMarkersForIsNumberEntriesNotSortByPosition(List referenceMarkNames, @@ -1644,9 +1703,12 @@ private static int numberPossiblyUndefinedBibEntry(BibEntry ce, * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. * * @param referenceMarkNames Reference mark names + * * @param citMarkers Corresponding text for each reference mark, - * that replaces the old text. + * that replaces the old text. + * * @param types itcType codes for each reference mark. + * * @param style Bibliography style to use. */ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, @@ -1666,9 +1728,11 @@ private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, assert (citMarkers.length == nRefMarks); assert (types.length == nRefMarks); - XNameAccess xReferenceMarks = documentConnection.getReferenceMarks(); + XNameAccess nameAccess = + documentConnection.getReferenceMarks(); + final boolean hadBibSection = - (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); + (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); // If we are supposed to set character format for citations, // must run a test before we delete old citation @@ -1971,20 +2035,21 @@ private static List unresolvedKeysFromEntries(Map return citMarkers; } - private List refreshCiteMarkersInternal(DocumentConnection documentConnection, - List databases, - OOBibStyle style, - final Map uniqueLetters - ) - throws WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException { + private List + refreshCiteMarkersInternal(DocumentConnection documentConnection, + List databases, + OOBibStyle style, + final Map uniqueLetters) + throws + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { // Normally we sort the reference marks according to their // order of appearance: @@ -2138,35 +2203,39 @@ public void updateSortedReferenceMarks() * * @return unresolvedKeys */ - public List updateDocumentActionHelper(List databases, - OOBibStyle style) - throws NoSuchElementException, - WrappedTargetException, - IllegalArgumentException, - CreationException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - NoDocumentException, - UndefinedCharacterFormatException, - BibEntryNotFoundException, - IOException { + public List updateDocumentActionHelper( + List databases, + OOBibStyle style) + throws + NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException, + NoDocumentException, + UndefinedCharacterFormatException, + BibEntryNotFoundException, + IOException { updateSortedReferenceMarks(); List unresolvedKeys = refreshCiteMarkers(databases, style); rebuildBibTextSection(databases, style); return unresolvedKeys; } - public void rebuildBibTextSection(List databases, - OOBibStyle style) - throws NoSuchElementException, - WrappedTargetException, - IllegalArgumentException, - CreationException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - NoDocumentException { + public void rebuildBibTextSection( + List databases, + OOBibStyle style) + throws + NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException, + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); FindCitedEntriesResult fce = @@ -2372,6 +2441,8 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) /** * Only called from: rebuildBibTextSection + * + * Assumes the section named `OOBibBase.BIB_SECTION_NAME` exists. */ private void populateBibTextSection(DocumentConnection documentConnection, Map entries, @@ -2398,14 +2469,14 @@ private void populateBibTextSection(DocumentConnection documentConnection, ); XTextCursor cursor = - documentConnection.xText - .createTextCursorByRange(section.getAnchor()); + documentConnection.xText + .createTextCursorByRange(section.getAnchor()); OOUtil.insertTextAtCurrentLocation( - documentConnection.xText, - cursor, - (String) style.getProperty(OOBibStyle.TITLE), - (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT) + documentConnection.xText, + cursor, + (String) style.getProperty(OOBibStyle.TITLE), + (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT) ); String refParaFormat = @@ -2447,15 +2518,20 @@ private void insertBookMark(DocumentConnection documentConnection, } /** + * Given the name of a reference mark, get the corresponding + * pageInfo text. + * * @param documentConnection Connection to a document. * @param name Name of the custom property to query. * @return "" for missing or empty pageInfo */ private static String - getPageInfoForReferenceMarkName(DocumentConnection documentConnection, - String name) - throws WrappedTargetException, - UnknownPropertyException { + getPageInfoForReferenceMarkName( + DocumentConnection documentConnection, + String name) + throws WrappedTargetException, + UnknownPropertyException { + Optional pageInfo = documentConnection.getCustomProperty(name); if (pageInfo.isEmpty() || pageInfo.get().isEmpty()) { return ""; @@ -2555,16 +2631,17 @@ private void insertReferenceMark(DocumentConnection documentConnection, * @param start : start of range to italicize w.r.t position.getStart(). * @param end : end of range to italicize w.r.t position.getStart(). * - * TODO: this is a strange API. Why? Answer: used after finding - * "et al." string in a citation marker. + * Why this API? This is used after finding "et al." string in a + * citation marker. */ private void italicizeRangeFromPosition(XTextCursor position, int start, int end) - throws UnknownPropertyException, - PropertyVetoException, - IllegalArgumentException, - WrappedTargetException { + throws + UnknownPropertyException, + PropertyVetoException, + IllegalArgumentException, + WrappedTargetException { XTextRange range = position.getStart(); XTextCursor cursor = position.getText().createTextCursorByRange(range); cursor.goRight((short) start, false); @@ -2663,7 +2740,6 @@ public void combineCiteMarkers(List databases, OOBibStyle style) NoDocumentException { DocumentConnection documentConnection = this.xDocumentConnection; - // TODO: doesn't work for citations in footnotes/tables List names = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); From aa17579ebdc7a5713efba508c2c635916773be91 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:08:48 +0100 Subject: [PATCH 0347/1068] add getTextCursorOfTextContent --- .../org/jabref/gui/openoffice/OOBibBase.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ccb40a08307..f6f773723c3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -283,6 +283,22 @@ public boolean documentConnectionMissing() { return Arrays.asList(names); } + /** + * Create a textcursor for a textContent. + * + * @return null if makr is null, otherwise cursor. + */ + static XTextCursor + getTextCursorOfTextContent(XTextContent mark) { + if ( mark == null ){ + return null; + } + XTextRange markAnchor = mark.getAnchor(); + XTextCursor cursor = + markAnchor.getText() + .createTextCursorByRange(markAnchor); + return cursor; + } /** * Remove the named reference mark. * From 7603a45e1192a55bb5904e5ecfa68e12dc86ccd2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:10:21 +0100 Subject: [PATCH 0348/1068] move documentConnectionMissing --- .../org/jabref/gui/openoffice/OOBibBase.java | 53 +++++++++++-------- 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f6f773723c3..ab1fc5233ac 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -155,6 +155,38 @@ private static class DocumentConnection { } public Optional getDocumentTitle() { + /** + * @return True if we cannot reach the current document. + */ + public boolean + documentConnectionMissing() { + + // These are set by selectDocument, via DocumentConnection + // constructor. + if (null == this.xCurrentComponent + || null == this.mxDoc + || null == this.xViewCursorSupplier + || null == this.xText + || null == this.mxDocFactory + || null == this.userProperties + || null == this.propertySet) { + return true; + } + + // Attempt to check document is really available + try { + getReferenceMarks(); + } catch (NoDocumentException ex) { + return true; + } + return false; + } + + /** + * Get the title of the connected document. + */ + public Optional + getDocumentTitle() { return OOBibBase.getDocumentTitle(this.mxDoc); } @@ -245,27 +277,6 @@ public Optional getDocumentTitle() { } } - public boolean documentConnectionMissing() { - - // These are set by selectDocument: - if (null == this.xCurrentComponent - || null == this.mxDoc - || null == this.xViewCursorSupplier - || null == this.xText - || null == this.mxDocFactory - || null == this.userProperties - || null == this.propertySet) { - return true; - } - - // Attempt to check document is really available - try { - getReferenceMarks(); - } catch (NoDocumentException ex) { - return true; - } - return false; - } /** * Names of all reference marks. * From d29c6aa048def4cb89fa98fc8fd203d68abf8024 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:11:05 +0100 Subject: [PATCH 0349/1068] add nameAccessGetTextContentByName --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ab1fc5233ac..5526221b7c9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -310,6 +310,26 @@ public Optional getDocumentTitle() { .createTextCursorByRange(markAnchor); return cursor; } + + XTextContent + nameAccessGetTextContentByName(XNameAccess nameAccess, String name) + throws WrappedTargetException { + + if (!nameAccess.hasByName(name)) { + return null; + } + try { + Object referenceMark = nameAccess.getByName(name); + XTextContent mark = unoQI(XTextContent.class, referenceMark); + return mark; + } catch (NoSuchElementException ex) { + LOGGER.warn(String.format( + "nameAccessGetTextContentByName got NoSuchElementException" + + " for '%s'", name)); + return null; + } + } + /** * Remove the named reference mark. * From c119ffab66dcbdcbd259bfeb6e4b672eca5d05f4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:12:04 +0100 Subject: [PATCH 0350/1068] use nameAccessGetTextContentByName --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5526221b7c9..7454091922c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -343,15 +343,13 @@ public Optional getDocumentTitle() { NoSuchElementException { XNameAccess xReferenceMarks = this.getReferenceMarks(); + if (xReferenceMarks.hasByName(name)) { - try { - Object referenceMark = xReferenceMarks.getByName(name); - XTextContent bookmark = unoQI(XTextContent.class, referenceMark); - this.xText.removeTextContent(bookmark); - } catch (NoSuchElementException ex) { - LOGGER.warn(String.format("referenceMark got NoSuchElementException" - + " for '%s'", name)); + XTextContent mark = nameAccessGetTextContentByName( xReferenceMarks, name ); + if ( mark == null ){ + return; } + this.xText.removeTextContent(mark); } } From 945b82777fcc5eb7d96aae8e3468e181abcd77d4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:12:57 +0100 Subject: [PATCH 0351/1068] use nameAccessGetTextContentByName, getTextCursorOfTextContent --- .../org/jabref/gui/openoffice/OOBibBase.java | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7454091922c..15c261f4f77 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -365,21 +365,20 @@ public Optional getDocumentTitle() { * @param htmlMarkup If true, the text belonging to the * reference mark is surrounded by bold html tag. */ - public String getCitationContext(String refMarkName, - int charBefore, - int charAfter, - boolean htmlMarkup) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException { - XNameAccess nameAccess = getReferenceMarks(); - Object referenceMark = nameAccess.getByName(refMarkName); - XTextContent bookmark = unoQI(XTextContent.class, referenceMark); + public String + getCitationContext( + String refMarkName, + int charBefore, + int charAfter, + boolean htmlMarkup) + throws + NoSuchElementException, + WrappedTargetException, + NoDocumentException { - XTextCursor cursor = - bookmark.getAnchor() // the text range to which the content is attached. - .getText() - .createTextCursorByRange(bookmark.getAnchor()); + XNameAccess nameAccess = getReferenceMarks(); + XTextContent mark = nameAccessGetTextContentByName(nameAccess, refMarkName); + XTextCursor cursor = getTextCursorOfTextContent(mark); String citPart = cursor.getString(); From 330eabeb2daaea4939d851d4f9f590db42df2d14 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:14:32 +0100 Subject: [PATCH 0352/1068] use nameAccessGetTextContentByName --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 15c261f4f77..adb27b5ba1c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -458,14 +458,13 @@ public Optional getDocumentTitle() { getBookmarkRange(String name) throws WrappedTargetException { - XNameAccess xNamedBookmarks = this.getBookmarks(); - // retrieve bookmark by name - if (!xNamedBookmarks.hasByName(name)) { + XNameAccess xNamedBookmarks = this.getBookmarks(); + XTextContent xFoundBookmark = + nameAccessGetTextContentByName( xNamedBookmarks, name ); + if (xFoundBookmark == null){ return null; } - Object foundBookmark = xNamedBookmarks.getByName(name); - XTextContent xFoundBookmark = unoQI(XTextContent.class, foundBookmark); return xFoundBookmark.getAnchor(); } From 5c9cbb300eff1a3b894bfc1142902748d1b25553 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:15:23 +0100 Subject: [PATCH 0353/1068] add getTextSectionByName --- .../org/jabref/gui/openoffice/OOBibBase.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index adb27b5ba1c..5d1db1daa08 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -468,6 +468,23 @@ public Optional getDocumentTitle() { return xFoundBookmark.getAnchor(); } + /** + * Get an XTextSection by name. + */ + public XTextSection + getTextSectionByName(String name) + throws + NoSuchElementException, + WrappedTargetException { + + XTextSectionsSupplier supplier = + unoQI(XTextSectionsSupplier.class, + this.mxDoc); + + return ((XTextSection) + ((Any) supplier.getTextSections().getByName(name)) + .getObject()); + } } // end DocumentConnection /** From 29bbf48a082047eb0b8ec7cfbabd14c47d873af7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:16:32 +0100 Subject: [PATCH 0354/1068] correct missed negation from documentConnectionMissing --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5d1db1daa08..8a8594f4154 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -797,7 +797,7 @@ public boolean isConnectedToDocument() { */ public boolean documentConnectionMissing() { if (this.xDocumentConnection == null) { - return false; + return true; } boolean res = this.xDocumentConnection.documentConnectionMissing(); if (res) { From a1e876f82508e3497946b3f17223b90238a7b79d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:17:56 +0100 Subject: [PATCH 0355/1068] correct forgotten null pointer check --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8a8594f4154..49109c107f6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2798,7 +2798,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) CreationException, BibEntryNotFoundException, NoDocumentException { - DocumentConnection documentConnection = this.xDocumentConnection; + DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); List names = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); From 2c711efdc38770de152c5037d5206733c4719e45 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:20:03 +0100 Subject: [PATCH 0356/1068] rename rcmCitationMarkers... to produceCitationMarkers... --- .../org/jabref/gui/openoffice/OOBibBase.java | 70 ++++++++++--------- 1 file changed, 38 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 49109c107f6..10129d714b2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1656,11 +1656,14 @@ public int getOrAllocateNumber(String key) { * */ private static String[] - rcmCitationMarkersForIsNumberEntriesIsSortByPosition(List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry, - OOBibStyle style) - throws BibEntryNotFoundException { + produceCitationMarkersForIsNumberEntriesIsSortByPosition( + List referenceMarkNames, + String[][] bibtexKeys, + Map citeKeyToBibEntry, + OOBibStyle style + ) + throws BibEntryNotFoundException { + assert style.isNumberEntries(); assert style.isSortByPosition(); @@ -1695,10 +1698,12 @@ public int getOrAllocateNumber(String key) { * when the bibliography is not sorted by position. */ private String[] - rcmCitationMarkersForIsNumberEntriesNotSortByPosition(List referenceMarkNames, - String[][] bibtexKeys, - Map entries, - OOBibStyle style) { + produceCitationMarkersForIsNumberEntriesNotSortByPosition( + List referenceMarkNames, + String[][] bibtexKeys, + Map entries, + OOBibStyle style + ) { assert style.isNumberEntries(); assert !style.isSortByPosition(); @@ -1897,7 +1902,7 @@ private static List unresolvedKeysFromEntries(Map * @param style Bibliography style. */ String[] - rcmCitationMarkersForNormalStyle(List referenceMarkNames, + produceCitationMarkersForNormalStyle(List referenceMarkNames, String[][] bibtexKeysIn, Map citeKeyToBibEntry, int[] itcTypes, @@ -2140,37 +2145,38 @@ private static List unresolvedKeysFromEntries(Map uniqueLetters.clear(); /* ModifiesParameter */ if (style.isCitationKeyCiteMarkers()) { citMarkers = - rcmCitationMarkersForIsCitationKeyCiteMarkers(referenceMarkNames, - bibtexKeys, - fce.citeKeyToBibEntry, - style - ); + produceCitationMarkersForIsCitationKeyCiteMarkers( + referenceMarkNames, + bibtexKeys, + fce.citeKeyToBibEntry, + style); } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { citMarkers = - rcmCitationMarkersForIsNumberEntriesIsSortByPosition(referenceMarkNames, - bibtexKeys, - fce.citeKeyToBibEntry, - style); + produceCitationMarkersForIsNumberEntriesIsSortByPosition( + referenceMarkNames, + bibtexKeys, + fce.citeKeyToBibEntry, + style); } else { citMarkers = - rcmCitationMarkersForIsNumberEntriesNotSortByPosition(referenceMarkNames, - bibtexKeys, - fce.entries, - style - ); + produceCitationMarkersForIsNumberEntriesNotSortByPosition( + referenceMarkNames, + bibtexKeys, + fce.entries, + style); } } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { citMarkers = - rcmCitationMarkersForNormalStyle(referenceMarkNames, - bibtexKeys, - fce.citeKeyToBibEntry, - types, - fce.entries, - uniqueLetters, - style - ); + produceCitationMarkersForNormalStyle( + referenceMarkNames, + bibtexKeys, + fce.citeKeyToBibEntry, + types, + fce.entries, + uniqueLetters, + style); } From 98504025913a8cea3ed036281fad95ea0748e06d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:21:28 +0100 Subject: [PATCH 0357/1068] rename rcmApplyNewCitationMarkers to applyNewCitationMarkers --- .../org/jabref/gui/openoffice/OOBibBase.java | 41 +++++++++++-------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 10129d714b2..6c0b321fb0a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1776,19 +1776,23 @@ public int getOrAllocateNumber(String key) { * * @param style Bibliography style to use. */ - private void rcmApplyNewCitationMarkers(DocumentConnection documentConnection, - List referenceMarkNames, - String[] citMarkers, - int[] types, - OOBibStyle style - ) - throws NoDocumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - CreationException, - WrappedTargetException, - PropertyVetoException { + private void + applyNewCitationMarkers( + DocumentConnection documentConnection, + List referenceMarkNames, + String[] citMarkers, + int[] types, + OOBibStyle style + ) + throws + NoDocumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + CreationException, + WrappedTargetException, + PropertyVetoException { + final int nRefMarks = referenceMarkNames.size(); assert (citMarkers.length == nRefMarks); assert (types.length == nRefMarks); @@ -2181,11 +2185,12 @@ private static List unresolvedKeysFromEntries(Map } // Refresh all reference marks with the citation markers we computed: - rcmApplyNewCitationMarkers(documentConnection, - referenceMarkNames, - citMarkers, - types, - style); + applyNewCitationMarkers( + documentConnection, + referenceMarkNames, + citMarkers, + types, + style); return unresolvedKeysFromEntries(fce.entries); } From e0023a06a66882f50de8acb8eecf69681802eb12 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:23:02 +0100 Subject: [PATCH 0358/1068] use nameAccessGetTextContentByName, getTextCursorOfTextContent and also - introduce name - rename bookmark to mark --- .../org/jabref/gui/openoffice/OOBibBase.java | 27 +++++++++---------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6c0b321fb0a..d72b33dcba0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1812,29 +1812,26 @@ public int getOrAllocateNumber(String key) { boolean mustTestCharFormat = style.isFormatCitations(); for (int i = 0; i < nRefMarks; i++) { - Object referenceMark = xReferenceMarks.getByName(referenceMarkNames.get(i)); - XTextContent bookmark = unoQI(XTextContent.class, referenceMark); + final String name = referenceMarkNames.get(i); - XTextCursor cursor = - bookmark - .getAnchor() - .getText() - .createTextCursorByRange(bookmark.getAnchor()); + XTextContent mark = documentConnection.nameAccessGetTextContentByName(nameAccess, name); + XTextCursor cursor = documentConnection.getTextCursorOfTextContent(mark); if (mustTestCharFormat) { mustTestCharFormat = false; // need to do this only once testFormatCitations(cursor, style); } - documentConnection.xText.removeTextContent(bookmark); + documentConnection.xText.removeTextContent(mark); - insertReferenceMark(documentConnection, - referenceMarkNames.get(i), - citMarkers[i], - cursor, - types[i] != OOBibBase.INVISIBLE_CIT, - style - ); + insertReferenceMark( + documentConnection, + name, + citMarkers[i], + cursor, + types[i] != OOBibBase.INVISIBLE_CIT, + style + ); if (hadBibSection && (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { From 69e23575bfbe55fffa12669ca278486ebe650bd8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:25:45 +0100 Subject: [PATCH 0359/1068] findCitedEntries argument order changed --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d72b33dcba0..1dd1f3411a3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2132,10 +2132,11 @@ private static List unresolvedKeysFromEntries(Map parseRefMarkNamesToArrays(referenceMarkNames, types, bibtexKeys); FindCitedEntriesResult fce = - findCitedEntries(databases, - findCitedKeys(documentConnection) - // TODO: why are we scanning the document - // if we already hev the referenceMarkNames? + findCitedEntries( + findCitedKeys(documentConnection), + databases + // TODO: why are we scanning the document + // if we already hev the referenceMarkNames? ); // fce.entries are in same order as returned by findCitedKeys @@ -2307,8 +2308,9 @@ public void rebuildBibTextSection( DocumentConnection documentConnection = getDocumentConnectionOrThrow(); FindCitedEntriesResult fce = - findCitedEntries(databases, - findCitedKeys(documentConnection) + findCitedEntries( + findCitedKeys(documentConnection), + databases ); Map entries; From ee2d9937e468adceb1d7493de74194053db9094a Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:29:37 +0100 Subject: [PATCH 0360/1068] camelCase find-the-difference puzzle --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1dd1f3411a3..b30028ae804 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2052,7 +2052,7 @@ private static List unresolvedKeysFromEntries(Map mapCiteKeysToBibEntryArray(bibtexKeys[i], citeKeyToBibEntry, referenceMarkName); - cEntries = mapUndefinedBibentriesToNull(cEntries); + cEntries = mapUndefinedBibEntriesToNull(cEntries); for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; From 92625b725a3017b4ffadecea481b1f6a623685f8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:32:32 +0100 Subject: [PATCH 0361/1068] indent --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b30028ae804..264c487090a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2550,7 +2550,6 @@ private void populateBibTextSection(DocumentConnection documentConnection, ); String refParaFormat = - (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); insertFullReferenceAtCursor(documentConnection, cursor, entries, @@ -2558,6 +2557,7 @@ private void populateBibTextSection(DocumentConnection documentConnection, refParaFormat, uniqueLetters ); + (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); insertBookMark(documentConnection, OOBibBase.BIB_SECTION_END_NAME, cursor); } From 18147c572c4f3b3169f84e9b568deb11a7cb4f45 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:34:08 +0100 Subject: [PATCH 0362/1068] insertBookMark in DocumentConnection --- .../org/jabref/gui/openoffice/OOBibBase.java | 79 +++++++++++-------- 1 file changed, 46 insertions(+), 33 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 264c487090a..8c26da94be7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -468,6 +468,40 @@ public Optional getDocumentTitle() { return xFoundBookmark.getAnchor(); } + /** + * Insert a bookmark with the given name at the cursor provided. + * + * @param name For the bookmark. + * @param position Cursor marking the location or range for + * the bookmark. If it is a range, its content will be replaced. + */ + public void + insertBookMark( + String name, + XTextCursor position) + throws + IllegalArgumentException, + CreationException { + + Object bookmark; + try { + bookmark = (this.mxDocFactory + .createInstance("com.sun.star.text.Bookmark")); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + + // name the bookmark + XNamed xNamed = unoQI(XNamed.class, bookmark); + xNamed.setName(name); + + // get XTextContent interface + XTextContent xTextContent = unoQI(XTextContent.class, bookmark); + + // insert bookmark at position, overwrite text in position + this.xText.insertTextContent(position, xTextContent, true); + } + /** * Get an XTextSection by name. */ @@ -1839,7 +1873,8 @@ public int getOrAllocateNumber(String key) { // We need to add it again. cursor.collapseToEnd(); OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - insertBookMark(documentConnection, OOBibBase.BIB_SECTION_NAME, cursor); + documentConnection.insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); + cursor.collapseToEnd(); } } } @@ -2550,41 +2585,19 @@ private void populateBibTextSection(DocumentConnection documentConnection, ); String refParaFormat = - insertFullReferenceAtCursor(documentConnection, - cursor, - entries, - style, - refParaFormat, - uniqueLetters - ); (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); - insertBookMark(documentConnection, OOBibBase.BIB_SECTION_END_NAME, cursor); - } - - private void insertBookMark(DocumentConnection documentConnection, - String name, - XTextCursor position) - throws IllegalArgumentException, - CreationException { - Object bookmark; - try { - bookmark = (documentConnection.mxDocFactory - .createInstance("com.sun.star.text.Bookmark")); - } catch (Exception e) { - throw new CreationException(e.getMessage()); - } - - // name the bookmark - XNamed xNamed = unoQI(XNamed.class, bookmark); - xNamed.setName(name); - - // get XTextContent interface - XTextContent xTextContent = unoQI(XTextContent.class, bookmark); + insertFullReferenceAtCursor( + documentConnection, + cursor, + entries, + style, + refParaFormat, + uniqueLetters + ); - // insert bookmark at position - documentConnection.xText.insertTextContent(position, xTextContent, true); - position.collapseToEnd(); + documentConnection.insertBookMark(OOBibBase.BIB_SECTION_END_NAME, cursor); + cursor.collapseToEnd(); } /** From 359743b76166a926e449c0ef7ccd801732a58f62 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:36:04 +0100 Subject: [PATCH 0363/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8c26da94be7..4a821145772 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2549,20 +2549,23 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) * * Assumes the section named `OOBibBase.BIB_SECTION_NAME` exists. */ - private void populateBibTextSection(DocumentConnection documentConnection, - Map entries, - OOBibStyle style, - final Map uniqueLetters) - throws NoSuchElementException, - WrappedTargetException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - IllegalArgumentException, - CreationException { XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); + private void + populateBibTextSection( + DocumentConnection documentConnection, + Map entries, + OOBibStyle style, + final Map uniqueLetters) + throws + NoSuchElementException, + WrappedTargetException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException, + IllegalArgumentException, + CreationException { XTextSection section = ((XTextSection) From fde0001ee745ee6bda3351ad8c4a43b7c4c92da6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 09:39:33 +0100 Subject: [PATCH 0364/1068] getTextSections drop unused variable (ts) --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4a821145772..a01cb3b60f5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2510,11 +2510,18 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) IllegalArgumentException, CreationException { + private XNameAccess + getTextSections(DocumentConnection documentConnection) + throws + WrappedTargetException, + IllegalArgumentException, + CreationException { // Check if the section exists: XTextSectionsSupplier supplier = - unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); + unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); - com.sun.star.container.XNameAccess ts = supplier.getTextSections(); + return supplier.getTextSections(); + } if (!ts.hasByName(OOBibBase.BIB_SECTION_NAME)) { createBibTextSection2(documentConnection, this.atEnd); From 2117850c56b1be28db270ca2e7f4e5b08a5408a6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 10:11:33 +0100 Subject: [PATCH 0365/1068] extract createAndInsertSection --- .../org/jabref/gui/openoffice/OOBibBase.java | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a01cb3b60f5..2cb835af93a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2486,20 +2486,29 @@ private void createBibTextSection2(DocumentConnection documentConnection, // where does textCursor point to if end is false? // TODO: are we using this.atEnd == false? // If we do, what happens (or expected to happen) here? + private void + createAndInsertSection( + DocumentConnection documentConnection, + String sectionName, + XTextCursor textCursor + ) + throws + IllegalArgumentException, + CreationException { - OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); - // Create a new TextSection from the document factory and access it's XNamed interface + // Create a new TextSection from the document factory + // and access it's XNamed interface XNamed xChildNamed; try { - xChildNamed = unoQI(XNamed.class, - (documentConnection.mxDocFactory - .createInstance("com.sun.star.text.TextSection")) - ); + xChildNamed = + unoQI(XNamed.class, + (documentConnection.mxDocFactory + .createInstance("com.sun.star.text.TextSection"))); } catch (Exception e) { throw new CreationException(e.getMessage()); } // Set the new sections name to 'Child_Section' - xChildNamed.setName(OOBibBase.BIB_SECTION_NAME); + xChildNamed.setName(sectionName); // Access the Child_Section's XTextContent interface and insert it into the document XTextContent xChildSection = unoQI(XTextContent.class, xChildNamed); documentConnection.xText.insertTextContent(textCursor, xChildSection, false); From dbe29c14037aa687cf842b3e04123f577ee998a3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 10:17:51 +0100 Subject: [PATCH 0366/1068] ust getTextSections, getTextSectionByName --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2cb835af93a..78ff4c12ec4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2532,6 +2532,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) return supplier.getTextSections(); } + XNameAccess ts = getTextSections( documentConnection ); if (!ts.hasByName(OOBibBase.BIB_SECTION_NAME)) { createBibTextSection2(documentConnection, this.atEnd); return; @@ -2565,9 +2566,6 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) * * Assumes the section named `OOBibBase.BIB_SECTION_NAME` exists. */ - XTextSectionsSupplier supplier = - unoQI(XTextSectionsSupplier.class, - documentConnection.mxDoc); private void populateBibTextSection( DocumentConnection documentConnection, @@ -2584,13 +2582,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) CreationException { XTextSection section = - ((XTextSection) - ((Any) supplier - .getTextSections() - .getByName(OOBibBase.BIB_SECTION_NAME) - ) - .getObject() - ); + documentConnection.getTextSectionByName(OOBibBase.BIB_SECTION_NAME); XTextCursor cursor = documentConnection.xText From 0877fcf11abed2cec0e31333590299190e7febb4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 10:19:44 +0100 Subject: [PATCH 0367/1068] clearBibTextSectionContent2 createBibTextSection2 --- .../org/jabref/gui/openoffice/OOBibBase.java | 40 ++++++++++++------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 78ff4c12ec4..f77236348d4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2474,18 +2474,6 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, } } - private void createBibTextSection2(DocumentConnection documentConnection, - boolean end) - throws IllegalArgumentException, - CreationException { - - XTextCursor textCursor = documentConnection.xText.createTextCursor(); - if (end) { - textCursor.gotoEnd(false); - } - // where does textCursor point to if end is false? - // TODO: are we using this.atEnd == false? - // If we do, what happens (or expected to happen) here? private void createAndInsertSection( DocumentConnection documentConnection, @@ -2514,11 +2502,27 @@ private void createBibTextSection2(DocumentConnection documentConnection, documentConnection.xText.insertTextContent(textCursor, xChildSection, false); } - private void clearBibTextSectionContent2(DocumentConnection documentConnection) - throws WrappedTargetException, - IllegalArgumentException, + private void createBibTextSection2(DocumentConnection documentConnection, + boolean end) + throws IllegalArgumentException, CreationException { + XTextCursor textCursor = documentConnection.xText.createTextCursor(); + if (end) { + textCursor.gotoEnd(false); + } + // where does textCursor point to if end is false? + // TODO: are we using this.atEnd == false? + // If we do, what happens (or expected to happen) here? + + OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); + createAndInsertSection( + documentConnection, + OOBibBase.BIB_SECTION_NAME, + textCursor + ); + } + private XNameAccess getTextSections(DocumentConnection documentConnection) throws @@ -2532,6 +2536,12 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) return supplier.getTextSections(); } + private void clearBibTextSectionContent2(DocumentConnection documentConnection) + throws + WrappedTargetException, + IllegalArgumentException, + CreationException { + XNameAccess ts = getTextSections( documentConnection ); if (!ts.hasByName(OOBibBase.BIB_SECTION_NAME)) { createBibTextSection2(documentConnection, this.atEnd); From e1f29beecbfee6ed21dbdda1dd1cd213b4adc87c Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 10:20:15 +0100 Subject: [PATCH 0368/1068] fragment from an earlier diff --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f77236348d4..29c6ff6b2e2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -154,7 +154,6 @@ private static class DocumentConnection { this.LOGGER = LOGGER; } - public Optional getDocumentTitle() { /** * @return True if we cannot reach the current document. */ From d08a2040ea64bd2139d144cb2b170e0687197870 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 11:36:49 +0100 Subject: [PATCH 0369/1068] describe findCitedEntries --- .../org/jabref/gui/openoffice/OOBibBase.java | 39 ++++++++++++------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 29c6ff6b2e2..d44ca963cff 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1360,13 +1360,13 @@ private static class ParsedRefMark { * The collection of data returned by findCitedKeys. */ private static class FindCitedEntriesResult { - /* + /** * entries : LinkedHashMap with iteration order as the - * citedKeys parameter of findCitedEntries + * citedKeys parameter of findCitedEntries */ Map entries; - /* + /** * citeKeyToBibEntry : HashMap (no order) */ Map citeKeyToBibEntry; @@ -1381,20 +1381,31 @@ private static class FindCitedEntriesResult { } /** - * @return LinkedHashMap, from BibEntry to BibDatabase. - * Side effect: adds citedKeys to citeKeyToBibEntry, - * using UndefinedBibtexEntry if not found. + * @return A FindCitedEntriesResult containing + * + * entries: A LinkedHashMap, from BibEntry to BibDatabase with + * iteration order as the citedKeys parameter. + * + * Stores: in which database was the entry found. + * + * citeKeyToBibEntry: + * A HashMap from citation key to BibEntry. + * Stores: result of lookup. + * + * For citation keys not found, a new + * UndefinedBibtexEntry(citedKey) is created and added to both + * maps, with a null BibDatabase. + * + * How is the result used? + * + * entries : Allows to recover the list of keys in original + * order, and finding the corresponding databases. * - * If a citedKey is not found, then - * BibEntry is new UndefinedBibtexEntry(citedKey), - * and BibDatabase is null. - * If citedKey is found, then BibEntry is what we found, - * BibDatabase is the database we found it in. + * citeKeyToBibEntry: * - * So: result has an entry for each citedKey, - * in the same order as in citedKeys + * Caches the result of lookup performed here, with "not + * found" encoded as an instance of UndefinedBibtexEntry. * - * citedKey in the entry is the same as the original citedKey */ private FindCitedEntriesResult findCitedEntries( From 57281433ae19b1a982eeac3e2d37819ceae3fad4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 11:47:31 +0100 Subject: [PATCH 0370/1068] comments --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d44ca963cff..1ccc1ef260d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1438,7 +1438,7 @@ private static class FindCitedEntriesResult { } /** - * Refresh all cite markers in the document. + * Refresh all citation markers in the document. * * @param databases The databases to get entries from. * @param style The bibliography style to use. @@ -1491,7 +1491,7 @@ private static class FindCitedEntriesResult { /** * @return A copy of the input with UndefinedBibtexEntry - * instances repalced by null. + * instances replaced with null. */ private static BibEntry[] mapUndefinedBibEntriesToNull(BibEntry[] cEntries) { @@ -1502,9 +1502,11 @@ private static class FindCitedEntriesResult { } /** - * Checks that keys do appear in citeKeys as keys. Collects the - * missing keys, and if there is any, throws BibEntryNotFoundException - * (currently mentioning only the first missing key). + * Checks that every element of `keys` can be found in `citeKeyToBibEntry`. + * + * Collects the missing keys, and if there is any, throws + * BibEntryNotFoundException (currently mentioning only the first + * missing key). * * @param keys An array of citation keys, we expect to appear as * keys in citeKeyToBibEntry. @@ -1540,7 +1542,7 @@ private static class FindCitedEntriesResult { } /** - * For each reference mark name check the corresponding part of + * For each reference mark name: check the corresponding element of * bibtexKeys with assertKeysInCiteKeyToBibEntry. */ private static void From 44c97263f42ddbefc8194795a99d1e3f8e278170 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 11:48:25 +0100 Subject: [PATCH 0371/1068] mention assertKeysInCiteKeyToBibEntry in LOGGER output --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1ccc1ef260d..0ecd441377a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1530,7 +1530,7 @@ private static class FindCitedEntriesResult { .collect(Collectors.toList()); for (String key : unresolvedKeys) { - LOGGER.info("Citation key not found: '" + key + '\''); + LOGGER.info("assertKeysInCiteKeyToBibEntry: Citation key not found: '" + key + '\''); LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); String msg = Localization.lang( From 993603ad0b52e7f392423d4fffd47d5f1a6feea8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 11:53:12 +0100 Subject: [PATCH 0372/1068] inline mapCiteKeysToBibEntryArray and mapUndefinedBibEntriesToNull --- .../org/jabref/gui/openoffice/OOBibBase.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0ecd441377a..8bc8916f84f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2089,17 +2089,25 @@ private static List unresolvedKeysFromEntries(Map // those referring to entries in our current list: final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); + for (int i = 0; i < nRefMarks; i++) { final String referenceMarkName = referenceMarkNames.get(i); final int nCitedEntries = bibtexKeys[i].length; boolean needsChange = false; int[] firstLimAuthors = new int[nCitedEntries]; String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; + + assertKeysInCiteKeyToBibEntry(bibtexKeys[i], citeKeyToBibEntry, referenceMarkName); BibEntry[] cEntries = - mapCiteKeysToBibEntryArray(bibtexKeys[i], - citeKeyToBibEntry, - referenceMarkName); - cEntries = mapUndefinedBibEntriesToNull(cEntries); + Arrays.stream(bibtexKeys[i]) + .map(citeKeyToBibEntry::get) + .toArray(BibEntry[]::new); + + cEntries = + Arrays.stream(cEntries) + .map(OOBibBase::undefinedBibentryToNull) + .toArray(BibEntry[]::new); + for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; From 33658ecf5c0487ffb0555969379e2f51d56b4942 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 11:55:10 +0100 Subject: [PATCH 0373/1068] join streams --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8bc8916f84f..c9d1329e97a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2101,10 +2101,6 @@ private static List unresolvedKeysFromEntries(Map BibEntry[] cEntries = Arrays.stream(bibtexKeys[i]) .map(citeKeyToBibEntry::get) - .toArray(BibEntry[]::new); - - cEntries = - Arrays.stream(cEntries) .map(OOBibBase::undefinedBibentryToNull) .toArray(BibEntry[]::new); From 90882cc46ae45d1b5eeffad18f1b43b67e5a30f0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 11:56:23 +0100 Subject: [PATCH 0374/1068] drop unused mapUndefinedBibEntriesToNull, mapCiteKeysToBibEntryArray --- .../org/jabref/gui/openoffice/OOBibBase.java | 37 ------------------- 1 file changed, 37 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c9d1329e97a..4e302d95078 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1489,17 +1489,6 @@ private static class FindCitedEntriesResult { return cEntry; } - /** - * @return A copy of the input with UndefinedBibtexEntry - * instances replaced with null. - */ - private static BibEntry[] - mapUndefinedBibEntriesToNull(BibEntry[] cEntries) { - return - Arrays.stream(cEntries) - .map(OOBibBase::undefinedBibentryToNull) - .toArray(BibEntry[]::new); - } /** * Checks that every element of `keys` can be found in `citeKeyToBibEntry`. @@ -1564,32 +1553,6 @@ private static class FindCitedEntriesResult { } } - // TODO: is mapCiteKeysToBibEntryArray is still needed? - // We still have a call site, followed by mapUndefinedBibEntriesToNull - /** - * Map an array of citation keys to the corresponding BibEntry - * objects using citeKeyToBibEntry. - * - * @param citeKeys - * @param citeKeyToBibEntry - * @param referenceMarkName For reporting keys missing from citeKeyToBibEntry. - */ - private static BibEntry[] - mapCiteKeysToBibEntryArray( - String[] citeKeys, - Map citeKeyToBibEntry, - String referenceMarkName - ) - throws BibEntryNotFoundException { - - assertKeysInCiteKeyToBibEntry(citeKeys, citeKeyToBibEntry, referenceMarkName); - - return - Arrays.stream(citeKeys) - .map(citeKeyToBibEntry::get) - .toArray(BibEntry[]::new); - } - /** * Produce citation markers for the case when the citation * markers are the citation keys themselves, separated by commas. From b23fbf0b34e5bff6e38a7801a88e3b8bf20f2924 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 12:08:52 +0100 Subject: [PATCH 0375/1068] throw IllegalArgumentException on (should be) impossible case --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4e302d95078..aa3fd760070 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1586,8 +1586,6 @@ private static class FindCitedEntriesResult { /** * Number source for (1-based) numbering of citations. - * - * For numbered citation style with first appearance order. */ private static class CitationNumberingState { /** @@ -1724,10 +1722,15 @@ public int getOrAllocateNumber(String key) { Map sortedEntries = sortEntriesByComparator(entries, entryComparator); - // Adjust order of cited to match sortedEntries + // Citation keys, in the same order as sortedEntries List sortedCited = new ArrayList<>(entries.size()); for (BibEntry entry : sortedEntries.keySet()) { - sortedCited.add(entry.getCitationKey().orElse(null)); + sortedCited.add( + entry.getCitationKey() + // entries should have been augmented with UndefinedBibtexEntry + // to cover all bibtexKeys + .orElseThrow(IllegalArgumentException::new) + ); } final int minGroupingCount = From 01fdd0395adae9d735513f978919a81b5576cf9f Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 12:29:30 +0100 Subject: [PATCH 0376/1068] extract citationKeysInBibliographyOrderFromEntries --- .../org/jabref/gui/openoffice/OOBibBase.java | 42 +++++++++++++------ 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index aa3fd760070..7cf4a000a1d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1700,6 +1700,33 @@ public int getOrAllocateNumber(String key) { return citMarkers; } + /** + * @return Citation keys from `entries`, ordered as in the bibliography. + */ + private List + citationKeysInBibliographyOrderFromEntries( + Map entries + ) { + + // Citation keys, in the same order as sortedEntries + List result = new ArrayList<>(entries.size()); + + // Sort entries to order in bibliography + Map sortedEntries = + sortEntriesByComparator(entries, entryComparator); + + return + sortedEntries.keySet().stream() + .map( + entry -> + entry.getCitationKey() + // entries should have been augmented with UndefinedBibtexEntry + // to cover all bibtexKeys + .orElseThrow(IllegalArgumentException::new) + ) + .collect(Collectors.toList()); + } + /** * Produce citation markers for the case of numbered citations * when the bibliography is not sorted by position. @@ -1718,20 +1745,9 @@ public int getOrAllocateNumber(String key) { assert (nRefMarks == bibtexKeys.length); String[] citMarkers = new String[nRefMarks]; - // Sort entries to order in bibliography - Map sortedEntries = - sortEntriesByComparator(entries, entryComparator); - // Citation keys, in the same order as sortedEntries - List sortedCited = new ArrayList<>(entries.size()); - for (BibEntry entry : sortedEntries.keySet()) { - sortedCited.add( - entry.getCitationKey() - // entries should have been augmented with UndefinedBibtexEntry - // to cover all bibtexKeys - .orElseThrow(IllegalArgumentException::new) - ); - } + List sortedCited = + citationKeysInBibliographyOrderFromEntries( entries ); final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); From 5150477dde17946874e2761708dd12b125cb9cc9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 12:32:10 +0100 Subject: [PATCH 0377/1068] change comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7cf4a000a1d..8f785d5453d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1720,8 +1720,8 @@ public int getOrAllocateNumber(String key) { .map( entry -> entry.getCitationKey() - // entries should have been augmented with UndefinedBibtexEntry - // to cover all bibtexKeys + // entries came from looking up by citation key, + // so Optional.empty() is not possible here. .orElseThrow(IllegalArgumentException::new) ) .collect(Collectors.toList()); From dd439aaa43e6bd6e015ec8fd419802e75ae99011 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 12:34:13 +0100 Subject: [PATCH 0378/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8f785d5453d..07f14763067 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1745,7 +1745,6 @@ public int getOrAllocateNumber(String key) { assert (nRefMarks == bibtexKeys.length); String[] citMarkers = new String[nRefMarks]; - // Citation keys, in the same order as sortedEntries List sortedCited = citationKeysInBibliographyOrderFromEntries( entries ); @@ -1754,7 +1753,10 @@ public int getOrAllocateNumber(String key) { for (int i = 0; i < referenceMarkNames.size(); i++) { List numbers = - findCitedEntryIndices(Arrays.asList(bibtexKeys[i]), sortedCited); + findCitedEntryIndices( + Arrays.asList(bibtexKeys[i]), + sortedCited + ); citMarkers[i] = style.getNumCitationMarker(numbers, minGroupingCount, false); } return citMarkers; From 1ee36679d5608b6f6416111b5a8eaab3944bbdd5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 13:00:20 +0100 Subject: [PATCH 0379/1068] add TODO: bibliography section vs bookmark --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 07f14763067..56fe7270660 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1842,10 +1842,14 @@ public int getOrAllocateNumber(String key) { boolean mustTestCharFormat = style.isFormatCitations(); for (int i = 0; i < nRefMarks; i++) { + final String name = referenceMarkNames.get(i); - XTextContent mark = documentConnection.nameAccessGetTextContentByName(nameAccess, name); - XTextCursor cursor = documentConnection.getTextCursorOfTextContent(mark); + XTextContent mark = + documentConnection.nameAccessGetTextContentByName(nameAccess, name); + + XTextCursor cursor = + documentConnection.getTextCursorOfTextContent(mark); if (mustTestCharFormat) { mustTestCharFormat = false; // need to do this only once @@ -1865,6 +1869,9 @@ public int getOrAllocateNumber(String key) { if (hadBibSection && (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { + // TODO: I think we used a *section* for the + // bibliography elsewhere. Here we use a *bookmark*. Relation? + // // We have overwritten the marker for the start of the reference list. // We need to add it again. cursor.collapseToEnd(); From cab66738cc94959fa0a03947151d5e3fbdd38aac Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 13:05:26 +0100 Subject: [PATCH 0380/1068] do not continue, throw --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 56fe7270660..f2c672dfefb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1890,9 +1890,12 @@ public int getOrAllocateNumber(String key) { * @param types OUT Must be same length as referenceMarkNames. * @param bibtexKeys OUT First level must be same length as referenceMarkNames. */ - private static void parseRefMarkNamesToArrays(List referenceMarkNames, - int[] types, - String[][] bibtexKeys) { + private static void + parseRefMarkNamesToArrays( + List referenceMarkNames, + int[] types, + String[][] bibtexKeys + ) { final int nRefMarks = referenceMarkNames.size(); assert (types.length == nRefMarks); assert (bibtexKeys.length == nRefMarks); @@ -1904,8 +1907,9 @@ private static void parseRefMarkNamesToArrays(List referenceMarkNames, // to correspond to referenceMarkNames.get(i). // And do not want null in bibtexKeys (or error code in types) // on return. - assert false : "parseRefMarkNamesToArrays expects parsable referenceMarkNames"; - continue; + throw new IllegalArgumentException( + "parseRefMarkNamesToArrays expects parsable referenceMarkNames" + ); } ParsedRefMark ov = op.get(); types[i] = ov.itcType; From 7e1969c685d1f69967459916f1013aaffd6954b2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 13:56:12 +0100 Subject: [PATCH 0381/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 225 ++++++++++-------- 1 file changed, 132 insertions(+), 93 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f2c672dfefb..e6c87c4e0d3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1917,9 +1917,14 @@ public int getOrAllocateNumber(String key) { } } - private static List unresolvedKeysFromEntries(Map entries) { - // Collect and return unresolved citation keys. - // uses: entries + /** + * @return The list of citation keys from `instanceof + * UndefinedBibtexEntry` elements of (keys of) `entries`. + * + * Intent: Get list of unresolved citation keys. + */ + private static List + unresolvedKeysFromEntries(Map entries) { List unresolvedKeys = new ArrayList<>(); for (BibEntry entry : entries.keySet()) { if (entry instanceof UndefinedBibtexEntry) { @@ -1932,28 +1937,111 @@ private static List unresolvedKeysFromEntries(Map return unresolvedKeys; } + /** + * Given bibtexKeys for each reference mark and the corresponding + * normalized citation markers for each, fills uniqueLetters. + * + * We expect to see data for all JabRef reference marks here, and + * clear uniqueLetters before filling. + * + * On return: uniqueLetters.get(bibtexkey) provides letter to be + * added after the year (null for none). + * + */ + void updateUniqueLetters( + String bibtexKeys[][], + String normCitMarkers[][], + final Map uniqueLetters ){ + + // See if there are duplicate citations marks referring to + // different entries. If so, we need to use uniqueLetters. + + // refKeys: (normCitMarker) to (list of bibtexkeys sharing it). + // The entries in the lists are ordered as in + // normCitMarkers[i][j] + Map> refKeys = new HashMap<>(); + + for (int i = 0; i < nRefMarks; i++) { + // Compare normalized markers, since the actual + // markers can be different. + String[] markers = normCitMarkers[i]; + for (int j = 0; j < markers.length; j++) { + String marker = markers[j]; + String currentKey = bibtexKeys[i][j]; + if (refKeys.containsKey(marker)) { + // Ok, we have seen this exact marker before. + if (!refKeys.get(marker).contains(currentKey)) { + // ... but not for this entry. + refKeys.get(marker).add(currentKey); + } + } else { + // add as new entry + List l = new ArrayList<>(1); + l.add(currentKey); + refKeys.put(marker, l); + } + } + } + + uniqueLetters.clear(); + + // Go through the collected lists and see where we need to + // add unique letters to the year. + for (Map.Entry> stringListEntry : refKeys.entrySet()) { + List clashingKeys = stringListEntry.getValue(); + if (clashingKeys.size() > 1) { + // This marker appears for more than one unique entry: + int nextUniqueLetter = 'a'; + for (String key : clashingKeys) { + // Update the map of uniqueLetters for the + // benefit of both the following generation of + // new citation markers, and for the method + // that builds the bibliography: + uniqueLetters.put(key, String.valueOf((char) nextUniqueLetter)); + nextUniqueLetter++; + } + } + } + } + + private BibEntry[][] + getBibEntriesSortedWithinReferenceMarks( String[][] bibtexKeysIn, Map citeKeyToBibEntry, OOBibStyle style ) { + return + Arrays.stream(bibtexKeysIn) + .map(bibtexKeysOfAReferenceMark -> + Arrays.stream(bibtexKeysOfAReferenceMark) + .map(citeKeyToBibEntry::get) + .sorted(comparatorForMulticite(style)) // sort within referenceMark + .toArray(BibEntry[]::new) + ) + .toArray(BibEntry[][]::new); + } + /** - * Produce citMarkers for normal (!isCitationKeyCiteMarkers && ! isNumberEntries) styles. + * Produce citation markers for normal + * (!isCitationKeyCiteMarkers && ! isNumberEntries) styles. * * @param referenceMarkNames Names of reference marks. * @param bibtexKeysIn Bibtex citation keys. - * @param citeKeyToBibEntry Maps citation keys to BibEntry. + * @param citeKeyToBibEntry Maps citation key to BibEntry. * @param itcTypes Citation types. * @param entries Map BibEntry to BibDatabase. * @param uniqueLetters Filled with new values here. * @param style Bibliography style. */ String[] - produceCitationMarkersForNormalStyle(List referenceMarkNames, - String[][] bibtexKeysIn, - Map citeKeyToBibEntry, - int[] itcTypes, - Map entries, - final Map uniqueLetters, - OOBibStyle style - ) - throws BibEntryNotFoundException { + produceCitationMarkersForNormalStyle( + List referenceMarkNames, + String[][] bibtexKeysIn, + Map citeKeyToBibEntry, + int[] itcTypes, + Map entries, + final Map uniqueLetters, + OOBibStyle style + ) + throws BibEntryNotFoundException { + uniqueLetters.clear(); assert !style.isCitationKeyCiteMarkers(); @@ -1965,39 +2053,22 @@ private static List unresolvedKeysFromEntries(Map assert (itcTypes.length == nRefMarks); assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); + // BibEntry for each bibtexKeysIn[i][j], sorted within bibtexKeysIn[i] BibEntry[][] cEntriesForAll = - Arrays.stream(bibtexKeysIn) - .map(bibtexKeysOfAReferenceMark -> - Arrays.stream(bibtexKeysOfAReferenceMark) - .map(citeKeyToBibEntry::get) - .sorted(comparatorForMulticite(style)) // sort within referenceMark - .toArray(BibEntry[]::new) - ) - .toArray(BibEntry[][]::new); - - // Update bibtexKeys to match the new sorting (within each referenceMark) - String[][] bibtexKeys = - Arrays.stream(cEntriesForAll) - .map(cEntries -> - Arrays.stream(cEntries) - .map(ce -> ce.getCitationKey().orElse(null)) - .toArray(String[]::new) - ) - .toArray(String[][]::new); - - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); - assert (bibtexKeys.length == nRefMarks); + getBibEntriesSortedWithinReferenceMarks(bibtexKeysIn, citeKeyToBibEntry, style); String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { BibEntry[] cEntries = cEntriesForAll[i]; int type = itcTypes[i]; - citMarkers[i] = style.getCitationMarker(Arrays.asList(cEntries), // entries + citMarkers[i] = + style.getCitationMarker( + Arrays.asList(cEntries), // entries entries, // database type == OOBibBase.AUTHORYEAR_PAR, null, null - ); + ); } // normCitMarkers[i][j] = for unification @@ -2007,17 +2078,17 @@ private static List unresolvedKeysFromEntries(Map // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: normCitMarkers[i] = - Arrays.stream(cEntries) - .map(ce -> - style.getCitationMarker( - Collections.singletonList(ce), - entries, - true, - null, - new int[] {-1} // no limit on authors - ) - ) - .toArray(String[]::new); + Arrays.stream(cEntries) + .map(ce -> + style.getCitationMarker( + Collections.singletonList(ce), + entries, + true, + null, + new int[] {-1} // no limit on authors + ) + ) + .toArray(String[]::new); } uniqueLetters.clear(); @@ -2026,59 +2097,27 @@ private static List unresolvedKeysFromEntries(Map // changes: citMarkers[i], uniqueLetters // uses: nRefMarks, normCitMarkers, bibtexKeys, // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) - // citeKeyToBibEntry, entries, types + // citeKeyToBibEntry, entries, itcTypes if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { // Only for normal citations. Numbered citations and // citeKeys are already unique. - // See if there are duplicate citations marks referring to - // different entries. If so, we need to use uniqueLetters: + // Reconstruct bibtexKeys, now sorted within each referenceMark + String[][] bibtexKeys = + Arrays.stream(cEntriesForAll) + .map(cEntries -> + Arrays.stream(cEntries) + .map(ce -> ce.getCitationKey().orElseThrow(IllegalArgumentException::new)) + .toArray(String[]::new) + ) + .toArray(String[][]::new); - // refKeys: normCitMarker to list of bibtexkeys sharing it. - // The entries in the lists are ordered as in - // normCitMarkers[i][j] - Map> refKeys = new HashMap<>(); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); + assert (bibtexKeys.length == nRefMarks); - for (int i = 0; i < nRefMarks; i++) { - // Compare normalized markers, since the actual - // markers can be different. - String[] markers = normCitMarkers[i]; - for (int j = 0; j < markers.length; j++) { - String marker = markers[j]; - String currentKey = bibtexKeys[i][j]; - if (refKeys.containsKey(marker)) { - // Ok, we have seen this exact marker before. - if (!refKeys.get(marker).contains(currentKey)) { - // ... but not for this entry. - refKeys.get(marker).add(currentKey); - } - } else { - // add as new entry - List l = new ArrayList<>(1); - l.add(currentKey); - refKeys.put(marker, l); - } - } - } + updateUniqueLetters( bibtexKeys, normCitMarkers, uniqueLetters ); - // Go through the collected lists and see where we need to - // add unique letters to the year. - for (Map.Entry> stringListEntry : refKeys.entrySet()) { - List clashingKeys = stringListEntry.getValue(); - if (clashingKeys.size() > 1) { - // This marker appears for more than one unique entry: - int nextUniqueLetter = 'a'; - for (String key : clashingKeys) { - // Update the map of uniqueLetters for the - // benefit of both the following generation of - // new citation markers, and for the method - // that builds the bibliography: - uniqueLetters.put(key, String.valueOf((char) nextUniqueLetter)); - nextUniqueLetter++; - } - } - } // Finally, go through all citation markers, and update // those referring to entries in our current list: From 65a993d3fdf1948095f12abaf7807cd82e104131 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 13:56:53 +0100 Subject: [PATCH 0382/1068] Revert "format" This reverts commit 87f0d86f574c2ff97bba2902b10c1867d82e8e01. --- .../org/jabref/gui/openoffice/OOBibBase.java | 225 ++++++++---------- 1 file changed, 93 insertions(+), 132 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e6c87c4e0d3..f2c672dfefb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1917,14 +1917,9 @@ public int getOrAllocateNumber(String key) { } } - /** - * @return The list of citation keys from `instanceof - * UndefinedBibtexEntry` elements of (keys of) `entries`. - * - * Intent: Get list of unresolved citation keys. - */ - private static List - unresolvedKeysFromEntries(Map entries) { + private static List unresolvedKeysFromEntries(Map entries) { + // Collect and return unresolved citation keys. + // uses: entries List unresolvedKeys = new ArrayList<>(); for (BibEntry entry : entries.keySet()) { if (entry instanceof UndefinedBibtexEntry) { @@ -1937,111 +1932,28 @@ public int getOrAllocateNumber(String key) { return unresolvedKeys; } - /** - * Given bibtexKeys for each reference mark and the corresponding - * normalized citation markers for each, fills uniqueLetters. - * - * We expect to see data for all JabRef reference marks here, and - * clear uniqueLetters before filling. - * - * On return: uniqueLetters.get(bibtexkey) provides letter to be - * added after the year (null for none). - * - */ - void updateUniqueLetters( - String bibtexKeys[][], - String normCitMarkers[][], - final Map uniqueLetters ){ - - // See if there are duplicate citations marks referring to - // different entries. If so, we need to use uniqueLetters. - - // refKeys: (normCitMarker) to (list of bibtexkeys sharing it). - // The entries in the lists are ordered as in - // normCitMarkers[i][j] - Map> refKeys = new HashMap<>(); - - for (int i = 0; i < nRefMarks; i++) { - // Compare normalized markers, since the actual - // markers can be different. - String[] markers = normCitMarkers[i]; - for (int j = 0; j < markers.length; j++) { - String marker = markers[j]; - String currentKey = bibtexKeys[i][j]; - if (refKeys.containsKey(marker)) { - // Ok, we have seen this exact marker before. - if (!refKeys.get(marker).contains(currentKey)) { - // ... but not for this entry. - refKeys.get(marker).add(currentKey); - } - } else { - // add as new entry - List l = new ArrayList<>(1); - l.add(currentKey); - refKeys.put(marker, l); - } - } - } - - uniqueLetters.clear(); - - // Go through the collected lists and see where we need to - // add unique letters to the year. - for (Map.Entry> stringListEntry : refKeys.entrySet()) { - List clashingKeys = stringListEntry.getValue(); - if (clashingKeys.size() > 1) { - // This marker appears for more than one unique entry: - int nextUniqueLetter = 'a'; - for (String key : clashingKeys) { - // Update the map of uniqueLetters for the - // benefit of both the following generation of - // new citation markers, and for the method - // that builds the bibliography: - uniqueLetters.put(key, String.valueOf((char) nextUniqueLetter)); - nextUniqueLetter++; - } - } - } - } - - private BibEntry[][] - getBibEntriesSortedWithinReferenceMarks( String[][] bibtexKeysIn, Map citeKeyToBibEntry, OOBibStyle style ) { - return - Arrays.stream(bibtexKeysIn) - .map(bibtexKeysOfAReferenceMark -> - Arrays.stream(bibtexKeysOfAReferenceMark) - .map(citeKeyToBibEntry::get) - .sorted(comparatorForMulticite(style)) // sort within referenceMark - .toArray(BibEntry[]::new) - ) - .toArray(BibEntry[][]::new); - } - /** - * Produce citation markers for normal - * (!isCitationKeyCiteMarkers && ! isNumberEntries) styles. + * Produce citMarkers for normal (!isCitationKeyCiteMarkers && ! isNumberEntries) styles. * * @param referenceMarkNames Names of reference marks. * @param bibtexKeysIn Bibtex citation keys. - * @param citeKeyToBibEntry Maps citation key to BibEntry. + * @param citeKeyToBibEntry Maps citation keys to BibEntry. * @param itcTypes Citation types. * @param entries Map BibEntry to BibDatabase. * @param uniqueLetters Filled with new values here. * @param style Bibliography style. */ String[] - produceCitationMarkersForNormalStyle( - List referenceMarkNames, - String[][] bibtexKeysIn, - Map citeKeyToBibEntry, - int[] itcTypes, - Map entries, - final Map uniqueLetters, - OOBibStyle style - ) - throws BibEntryNotFoundException { - + produceCitationMarkersForNormalStyle(List referenceMarkNames, + String[][] bibtexKeysIn, + Map citeKeyToBibEntry, + int[] itcTypes, + Map entries, + final Map uniqueLetters, + OOBibStyle style + ) + throws BibEntryNotFoundException { uniqueLetters.clear(); assert !style.isCitationKeyCiteMarkers(); @@ -2053,22 +1965,39 @@ void updateUniqueLetters( assert (itcTypes.length == nRefMarks); assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); - // BibEntry for each bibtexKeysIn[i][j], sorted within bibtexKeysIn[i] BibEntry[][] cEntriesForAll = - getBibEntriesSortedWithinReferenceMarks(bibtexKeysIn, citeKeyToBibEntry, style); + Arrays.stream(bibtexKeysIn) + .map(bibtexKeysOfAReferenceMark -> + Arrays.stream(bibtexKeysOfAReferenceMark) + .map(citeKeyToBibEntry::get) + .sorted(comparatorForMulticite(style)) // sort within referenceMark + .toArray(BibEntry[]::new) + ) + .toArray(BibEntry[][]::new); + + // Update bibtexKeys to match the new sorting (within each referenceMark) + String[][] bibtexKeys = + Arrays.stream(cEntriesForAll) + .map(cEntries -> + Arrays.stream(cEntries) + .map(ce -> ce.getCitationKey().orElse(null)) + .toArray(String[]::new) + ) + .toArray(String[][]::new); + + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); + assert (bibtexKeys.length == nRefMarks); String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { BibEntry[] cEntries = cEntriesForAll[i]; int type = itcTypes[i]; - citMarkers[i] = - style.getCitationMarker( - Arrays.asList(cEntries), // entries + citMarkers[i] = style.getCitationMarker(Arrays.asList(cEntries), // entries entries, // database type == OOBibBase.AUTHORYEAR_PAR, null, null - ); + ); } // normCitMarkers[i][j] = for unification @@ -2078,17 +2007,17 @@ void updateUniqueLetters( // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: normCitMarkers[i] = - Arrays.stream(cEntries) - .map(ce -> - style.getCitationMarker( - Collections.singletonList(ce), - entries, - true, - null, - new int[] {-1} // no limit on authors - ) - ) - .toArray(String[]::new); + Arrays.stream(cEntries) + .map(ce -> + style.getCitationMarker( + Collections.singletonList(ce), + entries, + true, + null, + new int[] {-1} // no limit on authors + ) + ) + .toArray(String[]::new); } uniqueLetters.clear(); @@ -2097,27 +2026,59 @@ void updateUniqueLetters( // changes: citMarkers[i], uniqueLetters // uses: nRefMarks, normCitMarkers, bibtexKeys, // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) - // citeKeyToBibEntry, entries, itcTypes + // citeKeyToBibEntry, entries, types if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { // Only for normal citations. Numbered citations and // citeKeys are already unique. - // Reconstruct bibtexKeys, now sorted within each referenceMark - String[][] bibtexKeys = - Arrays.stream(cEntriesForAll) - .map(cEntries -> - Arrays.stream(cEntries) - .map(ce -> ce.getCitationKey().orElseThrow(IllegalArgumentException::new)) - .toArray(String[]::new) - ) - .toArray(String[][]::new); + // See if there are duplicate citations marks referring to + // different entries. If so, we need to use uniqueLetters: - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); - assert (bibtexKeys.length == nRefMarks); + // refKeys: normCitMarker to list of bibtexkeys sharing it. + // The entries in the lists are ordered as in + // normCitMarkers[i][j] + Map> refKeys = new HashMap<>(); - updateUniqueLetters( bibtexKeys, normCitMarkers, uniqueLetters ); + for (int i = 0; i < nRefMarks; i++) { + // Compare normalized markers, since the actual + // markers can be different. + String[] markers = normCitMarkers[i]; + for (int j = 0; j < markers.length; j++) { + String marker = markers[j]; + String currentKey = bibtexKeys[i][j]; + if (refKeys.containsKey(marker)) { + // Ok, we have seen this exact marker before. + if (!refKeys.get(marker).contains(currentKey)) { + // ... but not for this entry. + refKeys.get(marker).add(currentKey); + } + } else { + // add as new entry + List l = new ArrayList<>(1); + l.add(currentKey); + refKeys.put(marker, l); + } + } + } + // Go through the collected lists and see where we need to + // add unique letters to the year. + for (Map.Entry> stringListEntry : refKeys.entrySet()) { + List clashingKeys = stringListEntry.getValue(); + if (clashingKeys.size() > 1) { + // This marker appears for more than one unique entry: + int nextUniqueLetter = 'a'; + for (String key : clashingKeys) { + // Update the map of uniqueLetters for the + // benefit of both the following generation of + // new citation markers, and for the method + // that builds the bibliography: + uniqueLetters.put(key, String.valueOf((char) nextUniqueLetter)); + nextUniqueLetter++; + } + } + } // Finally, go through all citation markers, and update // those referring to entries in our current list: From 2546e7be3def5cd63378658f2e4cc145139f2471 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 13:59:47 +0100 Subject: [PATCH 0383/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f2c672dfefb..ecdc1639cde 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1917,9 +1917,15 @@ public int getOrAllocateNumber(String key) { } } - private static List unresolvedKeysFromEntries(Map entries) { + /** + * @return The list of citation keys from `instanceof + * UndefinedBibtexEntry` elements of (keys of) `entries`. + * + * Intent: Get list of unresolved citation keys. + */ + private static List + unresolvedKeysFromEntries(Map entries) { // Collect and return unresolved citation keys. - // uses: entries List unresolvedKeys = new ArrayList<>(); for (BibEntry entry : entries.keySet()) { if (entry instanceof UndefinedBibtexEntry) { From b1033da24cec718a0796125fe97dfd7df33ae5c2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 14:05:04 +0100 Subject: [PATCH 0384/1068] extract updateUniqueLetters --- .../org/jabref/gui/openoffice/OOBibBase.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ecdc1639cde..bdb1f089b51 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1938,6 +1938,70 @@ public int getOrAllocateNumber(String key) { return unresolvedKeys; } + + /** + * Given bibtexKeys for each reference mark and the corresponding + * normalized citation markers for each, fills uniqueLetters. + * + * We expect to see data for all JabRef reference marks here, and + * clear uniqueLetters before filling. + * + * On return: uniqueLetters.get(bibtexkey) provides letter to be + * added after the year (null for none). + * + */ + void updateUniqueLetters( + String bibtexKeys[][], + String normCitMarkers[][], + final Map uniqueLetters ) { + + // refKeys: (normCitMarker) to (list of bibtexkeys sharing it). + // The entries in the lists are ordered as in + // normCitMarkers[i][j] + Map> refKeys = new HashMap<>(); + + for (int i = 0; i < nRefMarks; i++) { + // Compare normalized markers, since the actual + // markers can be different. + String[] markers = normCitMarkers[i]; + for (int j = 0; j < markers.length; j++) { + String marker = markers[j]; + String currentKey = bibtexKeys[i][j]; + if (refKeys.containsKey(marker)) { + // Ok, we have seen this exact marker before. + if (!refKeys.get(marker).contains(currentKey)) { + // ... but not for this entry. + refKeys.get(marker).add(currentKey); + } + } else { + // add as new entry + List l = new ArrayList<>(1); + l.add(currentKey); + refKeys.put(marker, l); + } + } + } + + uniqueLetters.clear(); + + // Go through the collected lists and see where we need to + // add unique letters to the year. + for (Map.Entry> stringListEntry : refKeys.entrySet()) { + List clashingKeys = stringListEntry.getValue(); + if (clashingKeys.size() > 1) { + // This marker appears for more than one unique entry: + int nextUniqueLetter = 'a'; + for (String key : clashingKeys) { + // Update the map of uniqueLetters for the + // benefit of both the following generation of + // new citation markers, and for the method + // that builds the bibliography: + uniqueLetters.put(key, String.valueOf((char) nextUniqueLetter)); + nextUniqueLetter++; + } + } + } + } /** * Produce citMarkers for normal (!isCitationKeyCiteMarkers && ! isNumberEntries) styles. @@ -2038,6 +2102,7 @@ public int getOrAllocateNumber(String key) { // Only for normal citations. Numbered citations and // citeKeys are already unique. + updateUniqueLetters( bibtexKeys, normCitMarkers, uniqueLetters ); // See if there are duplicate citations marks referring to // different entries. If so, we need to use uniqueLetters: From 1e85a5d25fd5364e936ac8004ca7968e28120196 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 14:09:45 +0100 Subject: [PATCH 0385/1068] extract getBibEntriesSortedWithinReferenceMarks --- .../org/jabref/gui/openoffice/OOBibBase.java | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index bdb1f089b51..0ac80c424d8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1938,7 +1938,27 @@ public int getOrAllocateNumber(String key) { return unresolvedKeys; } - + /** + * Look up `bibtexkeys` in `citeKeyToBibEntry`, sort result within + * each reference mark. + */ + private BibEntry[][] + getBibEntriesSortedWithinReferenceMarks( + String[][] bibtexKeys, + Map citeKeyToBibEntry, + OOBibStyle style + ) { + return + Arrays.stream(bibtexKeys) + .map(bibtexKeysOfAReferenceMark -> + Arrays.stream(bibtexKeysOfAReferenceMark) + .map(citeKeyToBibEntry::get) + .sorted(comparatorForMulticite(style)) // sort within referenceMark + .toArray(BibEntry[]::new) + ) + .toArray(BibEntry[][]::new); + } + /** * Given bibtexKeys for each reference mark and the corresponding * normalized citation markers for each, fills uniqueLetters. @@ -2036,14 +2056,7 @@ void updateUniqueLetters( assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); BibEntry[][] cEntriesForAll = - Arrays.stream(bibtexKeysIn) - .map(bibtexKeysOfAReferenceMark -> - Arrays.stream(bibtexKeysOfAReferenceMark) - .map(citeKeyToBibEntry::get) - .sorted(comparatorForMulticite(style)) // sort within referenceMark - .toArray(BibEntry[]::new) - ) - .toArray(BibEntry[][]::new); + getBibEntriesSortedWithinReferenceMarks( bibtexKeysIn, citeKeyToBibEntry, style ); // Update bibtexKeys to match the new sorting (within each referenceMark) String[][] bibtexKeys = From 666a2c587fd5df07cbc381daed3f76e415f0e10d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 14:19:57 +0100 Subject: [PATCH 0386/1068] extract mapBibEntriesToCitationKeysForall --- .../org/jabref/gui/openoffice/OOBibBase.java | 33 +++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0ac80c424d8..8d25e2573f3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1959,6 +1959,21 @@ public int getOrAllocateNumber(String key) { .toArray(BibEntry[][]::new); } + /** + * result[i][j] = cEntriesForAll[i][j].getCitationKey() + */ + private String[][] + mapBibEntriesToCitationKeysForall( BibEntry[][] cEntriesForAll ) { + return + Arrays.stream(cEntriesForAll) + .map(cEntries -> + Arrays.stream(cEntries) + .map(ce -> ce.getCitationKey().orElseThrow(IllegalArgumentException::new)) + .toArray(String[]::new) + ) + .toArray(String[][]::new); + } + /** * Given bibtexKeys for each reference mark and the corresponding * normalized citation markers for each, fills uniqueLetters. @@ -2058,19 +2073,6 @@ void updateUniqueLetters( BibEntry[][] cEntriesForAll = getBibEntriesSortedWithinReferenceMarks( bibtexKeysIn, citeKeyToBibEntry, style ); - // Update bibtexKeys to match the new sorting (within each referenceMark) - String[][] bibtexKeys = - Arrays.stream(cEntriesForAll) - .map(cEntries -> - Arrays.stream(cEntries) - .map(ce -> ce.getCitationKey().orElse(null)) - .toArray(String[]::new) - ) - .toArray(String[][]::new); - - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); - assert (bibtexKeys.length == nRefMarks); - String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { BibEntry[] cEntries = cEntriesForAll[i]; @@ -2115,6 +2117,11 @@ void updateUniqueLetters( // Only for normal citations. Numbered citations and // citeKeys are already unique. + // Update bibtexKeys to match the new sorting (within each referenceMark) + String[][] bibtexKeys = mapBibEntriesToCitationKeysForall( cEntriesForAll ); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); + assert (bibtexKeys.length == nRefMarks); + updateUniqueLetters( bibtexKeys, normCitMarkers, uniqueLetters ); // See if there are duplicate citations marks referring to // different entries. If so, we need to use uniqueLetters: From becf7d24c373b6726f6b2116c9139f4dbfb794c8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 14:21:32 +0100 Subject: [PATCH 0387/1068] remove body of updateUniqueLetters from original location --- .../org/jabref/gui/openoffice/OOBibBase.java | 47 ------------------- 1 file changed, 47 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8d25e2573f3..9c776aa1582 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2123,53 +2123,6 @@ void updateUniqueLetters( assert (bibtexKeys.length == nRefMarks); updateUniqueLetters( bibtexKeys, normCitMarkers, uniqueLetters ); - // See if there are duplicate citations marks referring to - // different entries. If so, we need to use uniqueLetters: - - // refKeys: normCitMarker to list of bibtexkeys sharing it. - // The entries in the lists are ordered as in - // normCitMarkers[i][j] - Map> refKeys = new HashMap<>(); - - for (int i = 0; i < nRefMarks; i++) { - // Compare normalized markers, since the actual - // markers can be different. - String[] markers = normCitMarkers[i]; - for (int j = 0; j < markers.length; j++) { - String marker = markers[j]; - String currentKey = bibtexKeys[i][j]; - if (refKeys.containsKey(marker)) { - // Ok, we have seen this exact marker before. - if (!refKeys.get(marker).contains(currentKey)) { - // ... but not for this entry. - refKeys.get(marker).add(currentKey); - } - } else { - // add as new entry - List l = new ArrayList<>(1); - l.add(currentKey); - refKeys.put(marker, l); - } - } - } - - // Go through the collected lists and see where we need to - // add unique letters to the year. - for (Map.Entry> stringListEntry : refKeys.entrySet()) { - List clashingKeys = stringListEntry.getValue(); - if (clashingKeys.size() > 1) { - // This marker appears for more than one unique entry: - int nextUniqueLetter = 'a'; - for (String key : clashingKeys) { - // Update the map of uniqueLetters for the - // benefit of both the following generation of - // new citation markers, and for the method - // that builds the bibliography: - uniqueLetters.put(key, String.valueOf((char) nextUniqueLetter)); - nextUniqueLetter++; - } - } - } // Finally, go through all citation markers, and update // those referring to entries in our current list: From ebc1b1984d87a1e0a1a610121a5a7cfcf42a32ed Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 14:31:12 +0100 Subject: [PATCH 0388/1068] extract normalizedCitationMarkersForNormalStyle --- .../org/jabref/gui/openoffice/OOBibBase.java | 75 +++++++++++-------- 1 file changed, 44 insertions(+), 31 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9c776aa1582..32c96075d4c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1988,7 +1988,11 @@ public int getOrAllocateNumber(String key) { void updateUniqueLetters( String bibtexKeys[][], String normCitMarkers[][], - final Map uniqueLetters ) { + final Map uniqueLetters + ) { + + final int nRefMarks = bibtexKeys.length; + assert nRefMarks == normCitMarkers.length; // refKeys: (normCitMarker) to (list of bibtexkeys sharing it). // The entries in the lists are ordered as in @@ -2038,6 +2042,36 @@ void updateUniqueLetters( } } + private String[][] + normalizedCitationMarkersForNormalStyle( + BibEntry[][] cEntriesForAll, + Map entries, + OOBibStyle style + ) { + + final int nRefMarks = cEntriesForAll.length; + + String[][] normCitMarkers = new String[nRefMarks][]; + for (int i = 0; i < nRefMarks; i++) { + BibEntry[] cEntries = cEntriesForAll[i]; + // We need "normalized" (in parenthesis) markers + // for uniqueness checking purposes: + normCitMarkers[i] = + Arrays.stream(cEntries) + .map(ce -> + style.getCitationMarker( + Collections.singletonList(ce), + entries, + true, + null, + new int[] {-1} // no limit on authors + ) + ) + .toArray(String[]::new); + } + return normCitMarkers; + } + /** * Produce citMarkers for normal (!isCitationKeyCiteMarkers && ! isNumberEntries) styles. * @@ -2054,7 +2088,7 @@ void updateUniqueLetters( String[][] bibtexKeysIn, Map citeKeyToBibEntry, int[] itcTypes, - Map entries, + Map entries, final Map uniqueLetters, OOBibStyle style ) @@ -2086,26 +2120,8 @@ void updateUniqueLetters( } // normCitMarkers[i][j] = for unification - String[][] normCitMarkers = new String[nRefMarks][]; - for (int i = 0; i < nRefMarks; i++) { - BibEntry[] cEntries = cEntriesForAll[i]; - // We need "normalized" (in parenthesis) markers - // for uniqueness checking purposes: - normCitMarkers[i] = - Arrays.stream(cEntries) - .map(ce -> - style.getCitationMarker( - Collections.singletonList(ce), - entries, - true, - null, - new int[] {-1} // no limit on authors - ) - ) - .toArray(String[]::new); - } - - uniqueLetters.clear(); + String[][] normCitMarkers = + normalizedCitationMarkersForNormalStyle( cEntriesForAll, entries, style ); // The following block // changes: citMarkers[i], uniqueLetters @@ -2113,16 +2129,13 @@ void updateUniqueLetters( // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) // citeKeyToBibEntry, entries, types - if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { - // Only for normal citations. Numbered citations and - // citeKeys are already unique. - // Update bibtexKeys to match the new sorting (within each referenceMark) - String[][] bibtexKeys = mapBibEntriesToCitationKeysForall( cEntriesForAll ); - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); - assert (bibtexKeys.length == nRefMarks); + // Update bibtexKeys to match the new sorting (within each referenceMark) + String[][] bibtexKeys = mapBibEntriesToCitationKeysForall( cEntriesForAll ); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); + assert (bibtexKeys.length == nRefMarks); - updateUniqueLetters( bibtexKeys, normCitMarkers, uniqueLetters ); + updateUniqueLetters( bibtexKeys, normCitMarkers, uniqueLetters ); // Finally, go through all citation markers, and update // those referring to entries in our current list: @@ -2187,7 +2200,7 @@ void updateUniqueLetters( ); } } // for i - } // if normalStyle + return citMarkers; } From 7dd192ff822057ba43bf5a46104f58474c2149fc Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 14:41:42 +0100 Subject: [PATCH 0389/1068] move normCitMarkers to its use --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 32c96075d4c..c12e1dfdd64 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2119,22 +2119,14 @@ void updateUniqueLetters( ); } - // normCitMarkers[i][j] = for unification - String[][] normCitMarkers = - normalizedCitationMarkersForNormalStyle( cEntriesForAll, entries, style ); - - // The following block - // changes: citMarkers[i], uniqueLetters - // uses: nRefMarks, normCitMarkers, bibtexKeys, - // style (style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST)) - // citeKeyToBibEntry, entries, types - - // Update bibtexKeys to match the new sorting (within each referenceMark) String[][] bibtexKeys = mapBibEntriesToCitationKeysForall( cEntriesForAll ); assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); assert (bibtexKeys.length == nRefMarks); + String[][] normCitMarkers = + normalizedCitationMarkersForNormalStyle( cEntriesForAll, entries, style ); + updateUniqueLetters( bibtexKeys, normCitMarkers, uniqueLetters ); // Finally, go through all citation markers, and update From ec71fca79e55a8fb9740015d526c79565528cb98 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 14:55:26 +0100 Subject: [PATCH 0390/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 131 +++++++++--------- 1 file changed, 66 insertions(+), 65 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c12e1dfdd64..1e301e9a7d1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2110,12 +2110,12 @@ void updateUniqueLetters( String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { BibEntry[] cEntries = cEntriesForAll[i]; - int type = itcTypes[i]; - citMarkers[i] = style.getCitationMarker(Arrays.asList(cEntries), // entries - entries, // database - type == OOBibBase.AUTHORYEAR_PAR, - null, - null + citMarkers[i] = style.getCitationMarker( + Arrays.asList(cEntries), // entries + entries, // database + itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, + null, + null ); } @@ -2129,69 +2129,70 @@ void updateUniqueLetters( updateUniqueLetters( bibtexKeys, normCitMarkers, uniqueLetters ); - // Finally, go through all citation markers, and update - // those referring to entries in our current list: - final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); - Set seenBefore = new HashSet<>(); - - for (int i = 0; i < nRefMarks; i++) { - final String referenceMarkName = referenceMarkNames.get(i); - final int nCitedEntries = bibtexKeys[i].length; - boolean needsChange = false; - int[] firstLimAuthors = new int[nCitedEntries]; - String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; - - assertKeysInCiteKeyToBibEntry(bibtexKeys[i], citeKeyToBibEntry, referenceMarkName); - BibEntry[] cEntries = - Arrays.stream(bibtexKeys[i]) - .map(citeKeyToBibEntry::get) - .map(OOBibBase::undefinedBibentryToNull) - .toArray(BibEntry[]::new); - - - for (int j = 0; j < nCitedEntries; j++) { - String currentKey = bibtexKeys[i][j]; - - // firstLimAuthors will be (-1) except at the first - // refMark it appears at, where a positive maxAuthorsFirst - // may override. This is why: - // https://discourse.jabref.org/t/ - // number-of-authors-in-citations-style-libreoffice/747/3 - // "Some citation styles require to list the full - // names of the first 4 authors for the first - // time. Later it is sufficient to have only maybe - // (Author A and Author B 2019 et al.)" - firstLimAuthors[j] = -1; - if (maxAuthorsFirst > 0) { - if (!seenBefore.contains(currentKey)) { - firstLimAuthors[j] = maxAuthorsFirst; - } - seenBefore.add(currentKey); - } + // Finally, go through all citation markers, and update + // those referring to entries in our current list: + final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); + Set seenBefore = new HashSet<>(); - String uniqueLetterForKey = uniqueLetters.get(currentKey); - if (uniqueLetterForKey == null) { - uniqueLetterForCitedEntry[j] = ""; - } else { - uniqueLetterForCitedEntry[j] = uniqueLetterForKey; - needsChange = true; - } + for (int i = 0; i < nRefMarks; i++) { + + final String referenceMarkName = referenceMarkNames.get(i); + final int nCitedEntries = bibtexKeys[i].length; + boolean needsChange = false; + int[] firstLimAuthors = new int[nCitedEntries]; + String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; + + assertKeysInCiteKeyToBibEntry(bibtexKeys[i], citeKeyToBibEntry, referenceMarkName); + BibEntry[] cEntries = + Arrays.stream(bibtexKeys[i]) + .map(citeKeyToBibEntry::get) + .map(OOBibBase::undefinedBibentryToNull) + .toArray(BibEntry[]::new); + + for (int j = 0; j < nCitedEntries; j++) { + String currentKey = bibtexKeys[i][j]; - if (firstLimAuthors[j] > 0) { - needsChange = true; + // firstLimAuthors will be (-1) except at the first + // refMark it appears at, where a positive maxAuthorsFirst + // may override. This is why: + // https://discourse.jabref.org/t/ + // number-of-authors-in-citations-style-libreoffice/747/3 + // "Some citation styles require to list the full + // names of the first 4 authors for the first + // time. Later it is sufficient to have only maybe + // (Author A and Author B 2019 et al.)" + firstLimAuthors[j] = -1; + if (maxAuthorsFirst > 0) { + if (!seenBefore.contains(currentKey)) { + firstLimAuthors[j] = maxAuthorsFirst; } - } // for j - - if (needsChange) { - citMarkers[i] = - style.getCitationMarker(Arrays.asList(cEntries), - entries, - itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, - uniqueLetterForCitedEntry, - firstLimAuthors - ); + seenBefore.add(currentKey); } - } // for i + + String uniqueLetterForKey = uniqueLetters.get(currentKey); + if (uniqueLetterForKey == null) { + uniqueLetterForCitedEntry[j] = ""; + } else { + uniqueLetterForCitedEntry[j] = uniqueLetterForKey; + needsChange = true; + } + + if (firstLimAuthors[j] > 0) { + needsChange = true; + } + } // for j + + if (needsChange) { + citMarkers[i] = + style.getCitationMarker( + Arrays.asList(cEntries), + entries, + itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, + uniqueLetterForCitedEntry, + firstLimAuthors + ); + } + } // for i return citMarkers; } From fb3d309fe28d49903c818c817f52941b0d03c01a Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 15:01:52 +0100 Subject: [PATCH 0391/1068] only fill citMarkers when we updated UniqueLetters --- .../org/jabref/gui/openoffice/OOBibBase.java | 39 ++++++------------- 1 file changed, 12 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1e301e9a7d1..30955a61f89 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2107,18 +2107,6 @@ void updateUniqueLetters( BibEntry[][] cEntriesForAll = getBibEntriesSortedWithinReferenceMarks( bibtexKeysIn, citeKeyToBibEntry, style ); - String[] citMarkers = new String[nRefMarks]; - for (int i = 0; i < nRefMarks; i++) { - BibEntry[] cEntries = cEntriesForAll[i]; - citMarkers[i] = style.getCitationMarker( - Arrays.asList(cEntries), // entries - entries, // database - itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, - null, - null - ); - } - // Update bibtexKeys to match the new sorting (within each referenceMark) String[][] bibtexKeys = mapBibEntriesToCitationKeysForall( cEntriesForAll ); assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); @@ -2134,11 +2122,12 @@ void updateUniqueLetters( final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); + String[] citMarkers = new String[nRefMarks]; + for (int i = 0; i < nRefMarks; i++) { final String referenceMarkName = referenceMarkNames.get(i); final int nCitedEntries = bibtexKeys[i].length; - boolean needsChange = false; int[] firstLimAuthors = new int[nCitedEntries]; String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; @@ -2148,6 +2137,8 @@ void updateUniqueLetters( .map(citeKeyToBibEntry::get) .map(OOBibBase::undefinedBibentryToNull) .toArray(BibEntry[]::new); + // ^^^ Note: pregenerated citMarkers used + // BibEntry[] cEntries = cEntriesForAll[i]; for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; @@ -2174,24 +2165,18 @@ void updateUniqueLetters( uniqueLetterForCitedEntry[j] = ""; } else { uniqueLetterForCitedEntry[j] = uniqueLetterForKey; - needsChange = true; } - if (firstLimAuthors[j] > 0) { - needsChange = true; - } } // for j - if (needsChange) { - citMarkers[i] = - style.getCitationMarker( - Arrays.asList(cEntries), - entries, - itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, - uniqueLetterForCitedEntry, - firstLimAuthors - ); - } + citMarkers[i] = + style.getCitationMarker( + Arrays.asList(cEntries), + entries, + itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, + uniqueLetterForCitedEntry, + firstLimAuthors + ); } // for i return citMarkers; From dd95200be42ab207287d16a3c339361a41df9edf Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 16:03:09 +0100 Subject: [PATCH 0392/1068] reverting to map empty to null Was thrown when clicking on "Export" with no bib file open. --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 30955a61f89..0f46e503e9a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1963,12 +1963,12 @@ public int getOrAllocateNumber(String key) { * result[i][j] = cEntriesForAll[i][j].getCitationKey() */ private String[][] - mapBibEntriesToCitationKeysForall( BibEntry[][] cEntriesForAll ) { + mapBibEntriesToCitationKeysOrNullForall( BibEntry[][] cEntriesForAll ) { return Arrays.stream(cEntriesForAll) .map(cEntries -> Arrays.stream(cEntries) - .map(ce -> ce.getCitationKey().orElseThrow(IllegalArgumentException::new)) + .map(ce -> ce.getCitationKey().orElse(null)) .toArray(String[]::new) ) .toArray(String[][]::new); From dbc863634014638e4ff02c3a4ea4fe51d2a860c3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 16:12:10 +0100 Subject: [PATCH 0393/1068] use mapBibEntriesToCitationKeysOrNullForall --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0f46e503e9a..e1c6d54e806 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2108,7 +2108,7 @@ void updateUniqueLetters( getBibEntriesSortedWithinReferenceMarks( bibtexKeysIn, citeKeyToBibEntry, style ); // Update bibtexKeys to match the new sorting (within each referenceMark) - String[][] bibtexKeys = mapBibEntriesToCitationKeysForall( cEntriesForAll ); + String[][] bibtexKeys = mapBibEntriesToCitationKeysOrNullForall( cEntriesForAll ); assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); assert (bibtexKeys.length == nRefMarks); From ee9b46172ce1f246b7e666f6b092337fbc632a9e Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 17:37:59 +0100 Subject: [PATCH 0394/1068] reinstate getCitationKey().orElse(null) --- .../org/jabref/gui/openoffice/OOBibBase.java | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e1c6d54e806..d8acbe4f57d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1401,6 +1401,15 @@ private static class FindCitedEntriesResult { * entries : Allows to recover the list of keys in original * order, and finding the corresponding databases. * + * Well, it does, but not by a simple + * entry.getCitationKey(), because + * UndefinedBibtexEntry.getCitationKey() returns + * Optional.empty(). + * + * For UndefinedBibtexEntry, + * UndefinedBibtexEntry.getKey() returns the + * original key we stored. + * * citeKeyToBibEntry: * * Caches the result of lookup performed here, with "not @@ -1625,7 +1634,8 @@ public int getOrAllocateNumber(String key) { /** * Gets number for a BibEntry. (-1) for UndefinedBibtexEntry * - * BibEntry.getCitationKey() must not be Optional.empty(). + * BibEntry.getCitationKey() must not be Optional.empty(), except + * for UndefinedBibtexEntry. * */ private static int @@ -1704,7 +1714,7 @@ public int getOrAllocateNumber(String key) { * @return Citation keys from `entries`, ordered as in the bibliography. */ private List - citationKeysInBibliographyOrderFromEntries( + citationKeysOrNullInBibliographyOrderFromEntries( Map entries ) { @@ -1722,7 +1732,7 @@ public int getOrAllocateNumber(String key) { entry.getCitationKey() // entries came from looking up by citation key, // so Optional.empty() is not possible here. - .orElseThrow(IllegalArgumentException::new) + .orElse(null) ) .collect(Collectors.toList()); } @@ -1746,7 +1756,7 @@ public int getOrAllocateNumber(String key) { String[] citMarkers = new String[nRefMarks]; List sortedCited = - citationKeysInBibliographyOrderFromEntries( entries ); + citationKeysOrNullInBibliographyOrderFromEntries( entries ); final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); @@ -1984,6 +1994,7 @@ public int getOrAllocateNumber(String key) { * On return: uniqueLetters.get(bibtexkey) provides letter to be * added after the year (null for none). * + * Note: bibtexKeys[i][j] may be null (from UndefinedBibtexEntry) */ void updateUniqueLetters( String bibtexKeys[][], @@ -2006,6 +2017,7 @@ void updateUniqueLetters( for (int j = 0; j < markers.length; j++) { String marker = markers[j]; String currentKey = bibtexKeys[i][j]; + // containsKey(null) is OK, contains(null) is OK. if (refKeys.containsKey(marker)) { // Ok, we have seen this exact marker before. if (!refKeys.get(marker).contains(currentKey)) { @@ -2109,7 +2121,11 @@ void updateUniqueLetters( // Update bibtexKeys to match the new sorting (within each referenceMark) String[][] bibtexKeys = mapBibEntriesToCitationKeysOrNullForall( cEntriesForAll ); - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); + // Note: bibtexKeys[i][j] may be null, for UndefinedBibtexEntry + + // String[][] bibtexKeys = mapBibEntriesToCitationKeysOrThrowForall( cEntriesForAll ); + // assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); + assert (bibtexKeys.length == nRefMarks); String[][] normCitMarkers = @@ -2217,7 +2233,7 @@ void updateUniqueLetters( findCitedKeys(documentConnection), databases // TODO: why are we scanning the document - // if we already hev the referenceMarkNames? + // if we already have the referenceMarkNames? ); // fce.entries are in same order as returned by findCitedKeys From 51cb545f157b43182945f617a8c33d96c76b23b3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 18:42:54 +0100 Subject: [PATCH 0395/1068] assertKeysInCiteKeyToBibEntry has extr arg "where" --- .../org/jabref/gui/openoffice/OOBibBase.java | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d8acbe4f57d..dddd04a9f0d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1517,7 +1517,8 @@ private static class FindCitedEntriesResult { assertKeysInCiteKeyToBibEntry( String[] keys, // citeKeys Map citeKeyToBibEntry, - String referenceMarkName // for reporting + String referenceMarkName, // for reporting + String where ) throws BibEntryNotFoundException { @@ -1529,7 +1530,7 @@ private static class FindCitedEntriesResult { for (String key : unresolvedKeys) { LOGGER.info("assertKeysInCiteKeyToBibEntry: Citation key not found: '" + key + '\''); - LOGGER.info("Problem with reference mark: '" + referenceMarkName + '\''); + LOGGER.info("Problem with reference mark: '" + referenceMarkName + "' "+ where); String msg = Localization.lang( "Could not resolve BibTeX entry" @@ -1547,7 +1548,8 @@ private static class FindCitedEntriesResult { assertAllKeysInCiteKeyToBibEntry( List referenceMarkNames, String[][] bibtexKeys, - Map citeKeyToBibEntry + Map citeKeyToBibEntry, + String where ) throws BibEntryNotFoundException { @@ -1558,7 +1560,9 @@ private static class FindCitedEntriesResult { assertKeysInCiteKeyToBibEntry( bibtexKeys[i], citeKeyToBibEntry, - referenceMarkNames.get(i)); + referenceMarkNames.get(i), + where + ); } } @@ -1580,7 +1584,7 @@ private static class FindCitedEntriesResult { final int nRefMarks = referenceMarkNames.size(); assert nRefMarks == bibtexKeys.length; - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, "produceCitationMarkersForIsCitationKeyCiteMarkers"); String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { @@ -1686,7 +1690,7 @@ public int getOrAllocateNumber(String key) { final int nRefMarks = referenceMarkNames.size(); assert (nRefMarks == bibtexKeys.length); - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, "produceCitationMarkersForIsNumberEntriesIsSortByPosition"); String[] citMarkers = new String[nRefMarks]; @@ -2114,7 +2118,7 @@ void updateUniqueLetters( final int nRefMarks = referenceMarkNames.size(); assert (bibtexKeysIn.length == nRefMarks); assert (itcTypes.length == nRefMarks); - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry, "produceCitationMarkersForNormalStyle"); BibEntry[][] cEntriesForAll = getBibEntriesSortedWithinReferenceMarks( bibtexKeysIn, citeKeyToBibEntry, style ); @@ -2147,7 +2151,8 @@ void updateUniqueLetters( int[] firstLimAuthors = new int[nCitedEntries]; String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; - assertKeysInCiteKeyToBibEntry(bibtexKeys[i], citeKeyToBibEntry, referenceMarkName); + // Not valid here, bibtexKeys may contain null: + // assertKeysInCiteKeyToBibEntry(bibtexKeys[i], citeKeyToBibEntry, referenceMarkName); BibEntry[] cEntries = Arrays.stream(bibtexKeys[i]) .map(citeKeyToBibEntry::get) @@ -2892,6 +2897,9 @@ private void testFormatCitations(XTextCursor textCursor, OOBibStyle style) * With 3 citations, "Separate" left the 2nd and 3rd as "tmp". * Three refresh corrected the 2nd. The 4th refresh corrected the 3rd citation. * + * TODO: if the corresponding bib file is not open, this leaves a + * mess: (1) reference marks with "tmp" i the text (2) with + * reference mark name "JR_cite_1_", i.e. without citation key. */ public void combineCiteMarkers(List databases, OOBibStyle style) throws IOException, From 959ba9738899d70b712a27c5358b5b4f0b4f0aea Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 18:43:52 +0100 Subject: [PATCH 0396/1068] getCitationMarker chokes on entries with null as associated database --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index dddd04a9f0d..95bd9008062 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2076,7 +2076,7 @@ void updateUniqueLetters( Arrays.stream(cEntries) .map(ce -> style.getCitationMarker( - Collections.singletonList(ce), + Collections.singletonList(undefinedBibentryToNull(ce)), entries, true, null, From 2355944a3da185adb961caee2bc73f3f3bdaf768 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 18:45:16 +0100 Subject: [PATCH 0397/1068] It appears we must map to null before getCitationMarker --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 95bd9008062..b27f029b24a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2153,9 +2153,9 @@ void updateUniqueLetters( // Not valid here, bibtexKeys may contain null: // assertKeysInCiteKeyToBibEntry(bibtexKeys[i], citeKeyToBibEntry, referenceMarkName); + BibEntry[] cEntries = - Arrays.stream(bibtexKeys[i]) - .map(citeKeyToBibEntry::get) + Arrays.stream(cEntriesForAll[i]) .map(OOBibBase::undefinedBibentryToNull) .toArray(BibEntry[]::new); // ^^^ Note: pregenerated citMarkers used From 6d761c8b2cefd77593f0f57a369343174ee205ec Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 19:00:11 +0100 Subject: [PATCH 0398/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 41 ++++++++++--------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b27f029b24a..4686f3d95d3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1584,7 +1584,8 @@ private static class FindCitedEntriesResult { final int nRefMarks = referenceMarkNames.size(); assert nRefMarks == bibtexKeys.length; - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, "produceCitationMarkersForIsCitationKeyCiteMarkers"); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, + "produceCitationMarkersForIsCitationKeyCiteMarkers"); String[] citMarkers = new String[nRefMarks]; for (int i = 0; i < nRefMarks; i++) { @@ -1690,7 +1691,8 @@ public int getOrAllocateNumber(String key) { final int nRefMarks = referenceMarkNames.size(); assert (nRefMarks == bibtexKeys.length); - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, "produceCitationMarkersForIsNumberEntriesIsSortByPosition"); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, + "produceCitationMarkersForIsNumberEntriesIsSortByPosition"); String[] citMarkers = new String[nRefMarks]; @@ -2100,15 +2102,16 @@ void updateUniqueLetters( * @param style Bibliography style. */ String[] - produceCitationMarkersForNormalStyle(List referenceMarkNames, - String[][] bibtexKeysIn, - Map citeKeyToBibEntry, - int[] itcTypes, - Map entries, - final Map uniqueLetters, - OOBibStyle style - ) - throws BibEntryNotFoundException { + produceCitationMarkersForNormalStyle( + List referenceMarkNames, + String[][] bibtexKeysIn, + Map citeKeyToBibEntry, + int[] itcTypes, + Map entries, + final Map uniqueLetters, + OOBibStyle style + ) + throws BibEntryNotFoundException { uniqueLetters.clear(); assert !style.isCitationKeyCiteMarkers(); @@ -2118,7 +2121,8 @@ void updateUniqueLetters( final int nRefMarks = referenceMarkNames.size(); assert (bibtexKeysIn.length == nRefMarks); assert (itcTypes.length == nRefMarks); - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry, "produceCitationMarkersForNormalStyle"); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry, + "produceCitationMarkersForNormalStyle"); BibEntry[][] cEntriesForAll = getBibEntriesSortedWithinReferenceMarks( bibtexKeysIn, citeKeyToBibEntry, style ); @@ -2127,9 +2131,6 @@ void updateUniqueLetters( String[][] bibtexKeys = mapBibEntriesToCitationKeysOrNullForall( cEntriesForAll ); // Note: bibtexKeys[i][j] may be null, for UndefinedBibtexEntry - // String[][] bibtexKeys = mapBibEntriesToCitationKeysOrThrowForall( cEntriesForAll ); - // assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry); - assert (bibtexKeys.length == nRefMarks); String[][] normCitMarkers = @@ -2162,13 +2163,13 @@ void updateUniqueLetters( // BibEntry[] cEntries = cEntriesForAll[i]; for (int j = 0; j < nCitedEntries; j++) { - String currentKey = bibtexKeys[i][j]; + String currentKey = bibtexKeys[i][j]; // nullable // firstLimAuthors will be (-1) except at the first - // refMark it appears at, where a positive maxAuthorsFirst - // may override. This is why: + // refMark it appears at, where a positive + // maxAuthorsFirst may override. This is why: // https://discourse.jabref.org/t/ - // number-of-authors-in-citations-style-libreoffice/747/3 + // number-of-authors-in-citations-style-libreoffice/747/3 // "Some citation styles require to list the full // names of the first 4 authors for the first // time. Later it is sufficient to have only maybe @@ -2187,8 +2188,8 @@ void updateUniqueLetters( } else { uniqueLetterForCitedEntry[j] = uniqueLetterForKey; } + } - } // for j citMarkers[i] = style.getCitationMarker( From c100f3dab5b63f29482b0ffff84f8319284eb71d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 19:00:27 +0100 Subject: [PATCH 0399/1068] move cEntries to use, collect to List --- .../org/jabref/gui/openoffice/OOBibBase.java | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4686f3d95d3..adef3e2d10f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2152,16 +2152,6 @@ void updateUniqueLetters( int[] firstLimAuthors = new int[nCitedEntries]; String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; - // Not valid here, bibtexKeys may contain null: - // assertKeysInCiteKeyToBibEntry(bibtexKeys[i], citeKeyToBibEntry, referenceMarkName); - - BibEntry[] cEntries = - Arrays.stream(cEntriesForAll[i]) - .map(OOBibBase::undefinedBibentryToNull) - .toArray(BibEntry[]::new); - // ^^^ Note: pregenerated citMarkers used - // BibEntry[] cEntries = cEntriesForAll[i]; - for (int j = 0; j < nCitedEntries; j++) { String currentKey = bibtexKeys[i][j]; // nullable @@ -2190,16 +2180,20 @@ void updateUniqueLetters( } } + List cEntries = + Arrays.stream(cEntriesForAll[i]) + .map(OOBibBase::undefinedBibentryToNull) + .collect(Collectors.toList()); citMarkers[i] = style.getCitationMarker( - Arrays.asList(cEntries), + cEntries, entries, itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, uniqueLetterForCitedEntry, firstLimAuthors ); - } // for i + } return citMarkers; } From 5483e6191a3709e2551d1f8bd3988e21102f4038 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 19:37:29 +0100 Subject: [PATCH 0400/1068] In "Export" check we have a database before touching the document. --- .../org/jabref/gui/openoffice/OpenOfficePanel.java | 10 +++++++++- src/main/resources/l10n/JabRef_en.properties | 4 ++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 6d7b3b3f6c6..0df250ad55f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -316,9 +316,17 @@ private void exportEntries() { style.ensureUpToDate(); } - ooBase.updateSortedReferenceMarks(); // NoDocumentException List databases = getBaseList(); + if ( databases.isEmpty() ){ + dialogService.showErrorDialogAndWait( + Localization.lang("No database is open"), + Localization.lang("We need a database to export from. Open one.") + ); + return; + } + + ooBase.updateSortedReferenceMarks(); // NoDocumentException List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style); BibDatabase newDatabase = ooBase.generateDatabase(databases); if (!unresolvedKeys.isEmpty()) { diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 4b0423e4e60..787ee746e93 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -506,6 +506,10 @@ Moved\ group\ "%0".=Moved group "%0". Mr.\ DLib\ Privacy\ settings=Mr. DLib Privacy settings +No\ database\ is\ open=No database is open + +We\ need\ a\ database\ to\ export\ from.\ Open\ one.=We need a database to export from. Open one. + No\ recommendations\ received\ from\ Mr.\ DLib\ for\ this\ entry.=No recommendations received from Mr. DLib for this entry. Error\ while\ fetching\ recommendations\ from\ Mr.DLib.=Error while fetching recommendations from Mr.DLib. From 46f7d02156e3e50cff303de52f8956ed1cf78335 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 19:55:47 +0100 Subject: [PATCH 0401/1068] comments on updateSortedReferenceMarks --- .../org/jabref/gui/openoffice/OOBibBase.java | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index adef3e2d10f..73af610c3a0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2229,11 +2229,12 @@ void updateUniqueLetters( parseRefMarkNamesToArrays(referenceMarkNames, types, bibtexKeys); FindCitedEntriesResult fce = - findCitedEntries( - findCitedKeys(documentConnection), - databases - // TODO: why are we scanning the document - // if we already have the referenceMarkNames? + findCitedEntries( + findCitedKeys(documentConnection), + databases + // TODO: Pass jabRefReferenceMarkNamesSortedByPosition around, and + // also add as a parameter to findCitedKeys, + // to make calls to updateSortedReferenceMarks more visible. ); // fce.entries are in same order as returned by findCitedKeys @@ -2355,6 +2356,14 @@ void updateUniqueLetters( return result; } + /** + * Refresh list of JabRef reference marks (sorts by position). + * + * Probably should be called at the start of actions from the GUI, + * that rely on jabRefReferenceMarkNamesSortedByPosition to be up-to-date. + * + * TODO: maybe we should pass around a fresh copy? + */ public void updateSortedReferenceMarks() throws WrappedTargetException, NoSuchElementException, From b7760d129e6b2915c3bb255763ccbbbba59d7176 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 19:56:59 +0100 Subject: [PATCH 0402/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 73af610c3a0..5d0ae0ab173 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2198,11 +2198,23 @@ void updateUniqueLetters( return citMarkers; } + /** + * Refresh citation markers according to `style`. + * + * - Requires an uptodate jabRefReferenceMarkNamesSortedByPosition + * + * @param documentConnection + * @param databases For look up by citation key. Must have at least one. + * @param style + * @param uniqueLetters Will be cleared and potentially filled with new values. + */ private List - refreshCiteMarkersInternal(DocumentConnection documentConnection, - List databases, - OOBibStyle style, - final Map uniqueLetters) + refreshCiteMarkersInternal( + DocumentConnection documentConnection, + List databases, + OOBibStyle style, + final Map uniqueLetters + ) throws WrappedTargetException, IllegalArgumentException, @@ -2218,12 +2230,8 @@ void updateUniqueLetters( // order of appearance: List referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; - // Compute citation markers for all citations: final int nRefMarks = referenceMarkNames.size(); - // fill: - // types[i] = ov.itcType - // bibtexKeys[i] = ov.citedKeys.toArray() int[] types = new int[nRefMarks]; String[][] bibtexKeys = new String[nRefMarks][]; parseRefMarkNamesToArrays(referenceMarkNames, types, bibtexKeys); @@ -2267,7 +2275,6 @@ void updateUniqueLetters( style); } } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { - citMarkers = produceCitationMarkersForNormalStyle( referenceMarkNames, @@ -2277,7 +2284,6 @@ void updateUniqueLetters( fce.entries, uniqueLetters, style); - } // Refresh all reference marks with the citation markers we computed: From 3403785ad437611b81dd97ad485b54736f3ac318 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 19:57:19 +0100 Subject: [PATCH 0403/1068] rename types to itcTypes --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5d0ae0ab173..887798e3edf 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2232,9 +2232,9 @@ void updateUniqueLetters( final int nRefMarks = referenceMarkNames.size(); - int[] types = new int[nRefMarks]; + int[] itcTypes = new int[nRefMarks]; String[][] bibtexKeys = new String[nRefMarks][]; - parseRefMarkNamesToArrays(referenceMarkNames, types, bibtexKeys); + parseRefMarkNamesToArrays(referenceMarkNames, itcTypes, bibtexKeys); FindCitedEntriesResult fce = findCitedEntries( @@ -2280,7 +2280,7 @@ void updateUniqueLetters( referenceMarkNames, bibtexKeys, fce.citeKeyToBibEntry, - types, + itcTypes, fce.entries, uniqueLetters, style); @@ -2291,7 +2291,7 @@ void updateUniqueLetters( documentConnection, referenceMarkNames, citMarkers, - types, + itcTypes, style); return unresolvedKeysFromEntries(fce.entries); From 7a05aefdf1e9c458818549247a848ff789557354 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 20:03:04 +0100 Subject: [PATCH 0404/1068] Argument order of findPositionOfTextRange changed --- .../org/jabref/gui/openoffice/OOBibBase.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 887798e3edf..c6e4b7cf1e7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2297,15 +2297,19 @@ void updateUniqueLetters( return unresolvedKeysFromEntries(fce.entries); } - // Position as in a document on the screen. - // Probably to get the correct order with - // referenceMarks in footnotes + /** + * Given an XTextRange, return its position: + * coordinates relative to the top left position + * of the first page of the document. + * + * @param range + * @param cursor To get the position, we need az XTextViewCursor. + * It will be moved to the range. + */ private static Point - findPositionOfTextRange(XTextViewCursor cursor, XTextRange range) { + findPositionOfTextRange(XTextRange range, XTextViewCursor cursor) { cursor.gotoRange(range, false); return cursor.getPosition(); - // the cursor's coordinates relative to the top left position - // of the first page of the document. } /** @@ -2342,7 +2346,7 @@ void updateUniqueLetters( // The footnote's anchor gives the correct position in the text: range = footer.getAnchor(); } - positions.add(findPositionOfTextRange(viewCursor, range)); + positions.add(findPositionOfTextRange(range,viewCursor)); } // restore cursor position viewCursor.gotoRange(initialPos, false); From dc0312a4a2fafdb2bad6068f4f5eae79ba19a7b3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 1 Mar 2021 20:13:06 +0100 Subject: [PATCH 0405/1068] comments, use nameAccessGetTextContentByName --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c6e4b7cf1e7..59baa1128b0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -310,6 +310,9 @@ private static class DocumentConnection { return cursor; } + /** + * (this could be static, except for the LOGGER) + */ XTextContent nameAccessGetTextContentByName(XNameAccess nameAccess, String name) throws WrappedTargetException { @@ -2313,7 +2316,10 @@ void updateUniqueLetters( } /** + * Read reference mark names from the document, keep only those + * with JabRef naming convention, get their visual positions, * + * @return JabRef reference mark names sorted by these positions. */ private List getJabRefReferenceMarkNamesSortedByPosition( @@ -2335,8 +2341,9 @@ void updateUniqueLetters( for (String name : names) { XTextContent textContent = - //documentConnection.nameAccessGetTextContentByName( nameAccess, name ); - unoQI(XTextContent.class, nameAccess.getByName(name)); + documentConnection.nameAccessGetTextContentByName( nameAccess, name ); + // unoQI(XTextContent.class, nameAccess.getByName(name)); + XTextRange range = textContent.getAnchor(); // Adjust range if we are inside a footnote: From f2371c496ae1f71ae34206645a26c2e1b60d46f2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 08:57:11 +0100 Subject: [PATCH 0406/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 208 +++++++++++++----- 1 file changed, 151 insertions(+), 57 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 59baa1128b0..3cde72c8ab8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1325,7 +1325,8 @@ private static class ParsedRefMark { /** * Extract citation keys from names of referenceMarks in the document. * - * Each citation key is listed only once, in the order of first appearance. + * Each citation key is listed only once, in the order of first appearance + * (in `names`, which itself is in arbitrary order) * * doc.referenceMarks.names.map(parse).flatten.unique */ @@ -2320,6 +2321,11 @@ void updateUniqueLetters( * with JabRef naming convention, get their visual positions, * * @return JabRef reference mark names sorted by these positions. + * + * Limitation: for two column layout visual (top-down, + * left-right) order does not match the expected (textual) + * order. + * */ private List getJabRefReferenceMarkNamesSortedByPosition( @@ -2381,21 +2387,30 @@ void updateUniqueLetters( * * TODO: maybe we should pass around a fresh copy? */ - public void updateSortedReferenceMarks() - throws WrappedTargetException, - NoSuchElementException, - NoDocumentException { + public void + updateSortedReferenceMarks() + throws + WrappedTargetException, + NoSuchElementException, + NoDocumentException { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + this.jabRefReferenceMarkNamesSortedByPosition = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); } /** - * GUI action + * GUI action, refreshes citation markers and bibliography. + * + * @param databases Must have at least one. + * @param style + * @return List of unresolved citation keys. * - * @return unresolvedKeys + * Note: calls updateSortedReferenceMarks(); */ - public List updateDocumentActionHelper( + public List + updateDocumentActionHelper( List databases, OOBibStyle style) throws @@ -2410,13 +2425,23 @@ public List updateDocumentActionHelper( UndefinedCharacterFormatException, BibEntryNotFoundException, IOException { + updateSortedReferenceMarks(); List unresolvedKeys = refreshCiteMarkers(databases, style); rebuildBibTextSection(databases, style); return unresolvedKeys; } - public void rebuildBibTextSection( + /** + * Rebuilds the bibliography. + * + * @param databases Must have at least one. + * + * Note: assumes fresh `jabRefReferenceMarkNamesSortedByPosition` + * if `style.isSortByPosition()` + */ + public void + rebuildBibTextSection( List databases, OOBibStyle style) throws @@ -2428,53 +2453,79 @@ public void rebuildBibTextSection( UnknownPropertyException, UndefinedParagraphFormatException, NoDocumentException { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); FindCitedEntriesResult fce = - findCitedEntries( - findCitedKeys(documentConnection), - databases + findCitedEntries( + findCitedKeys(documentConnection), + databases ); Map entries; if (style.isSortByPosition()) { // We need to sort the entries according to their order of appearance: - entries = sortEntriesByRefMarkNames( + entries = + sortEntriesByRefMarkNames( jabRefReferenceMarkNamesSortedByPosition, fce.citeKeyToBibEntry, fce.entries - ); + ); } else { entries = sortEntriesByComparator(fce.entries, entryComparator); } + clearBibTextSectionContent2(documentConnection); - populateBibTextSection(documentConnection, entries, style, this.xUniqueLetters); + + populateBibTextSection( + documentConnection, + entries, + style, + this.xUniqueLetters); } + /** + * Return a TreeMap(entryComparator) copy of entries. + * + * For sorting the bibliography. + */ SortedMap - sortEntriesByComparator(Map entries, - Comparator entryComparator) { + sortEntriesByComparator( + Map entries, + Comparator entryComparator + ) { SortedMap newMap = new TreeMap<>(entryComparator); for (Map.Entry kv : entries.entrySet()) { - newMap.put(kv.getKey(), - kv.getValue()); + newMap.put( + kv.getKey(), + kv.getValue()); } return newMap; } /** + * Return bibliography entries sorted according to the order of + * first appearance in referenceMarkNames. + * * @param referenceMarkNames Names of reference marks. * @param citeKeyToBibEntry Helps to find the entries * @return LinkedHashMap from BibEntry to BibDatabase with - * iteration order as first appearance in referenceMarkNames. + * iteration order as first appearance in referenceMarkNames. + * + * Note: Within citation group (a reference mark) the order is + * as appears there. + * + * TODO: The order within a reference mark name is decided on + * construction. Is it updated after a style change? + * */ private Map - sortEntriesByRefMarkNames(List referenceMarkNames, - Map citeKeyToBibEntry, - Map entries - ) { - + sortEntriesByRefMarkNames( + List referenceMarkNames, + Map citeKeyToBibEntry, + Map entries + ) { // LinkedHashMap: iteration order is insertion-order, not // affected if a key is re-inserted. Map newList = new LinkedHashMap<>(); @@ -2505,19 +2556,32 @@ public void rebuildBibTextSection( } /** + * Insert body of bibliography at `cursor`. + * + * @param documentConnection + * @param cursor Where to + * @param entries Its iteration order defines order in bibliography. + * @param style + * @param parFormat + * @param uniqueLetters + * * Only called from populateBibTextSection (and that from rebuildBibTextSection) */ - private void insertFullReferenceAtCursor(DocumentConnection documentConnection, - XTextCursor cursor, - Map entries, - OOBibStyle style, - String parFormat, - final Map uniqueLetters) - throws UndefinedParagraphFormatException, - IllegalArgumentException, - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { + private void + insertFullReferenceAtCursor( + DocumentConnection documentConnection, + XTextCursor cursor, + Map entries, + OOBibStyle style, + String parFormat, + final Map uniqueLetters + ) + throws + UndefinedParagraphFormatException, + IllegalArgumentException, + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { int number = 1; for (Map.Entry entry : entries.entrySet()) { @@ -2531,37 +2595,51 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // insert marker if (style.isNumberEntries()) { - // NOte: minGroupingCount is pointless here, we are + // Note: minGroupingCount is pointless here, we are // formatting a single entry. // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); int minGroupingCount = 2; List numbers = Collections.singletonList(number++); - String marker = style.getNumCitationMarker(numbers, + String marker = + style.getNumCitationMarker( + numbers, minGroupingCount, true); - OOUtil.insertTextAtCurrentLocation(documentConnection.xText, - cursor, - marker, - Collections.emptyList() - ); + OOUtil.insertTextAtCurrentLocation( + documentConnection.xText, + cursor, + marker, + Collections.emptyList() + ); } // insert the actual details. Layout layout = style.getReferenceFormat(entry.getKey().getType()); layout.setPostFormatter(POSTFORMATTER); OOUtil.insertFullReferenceAtCurrentLocation( - documentConnection.xText, - cursor, - layout, - parFormat, - entry.getKey(), - entry.getValue(), - uniqueLetters.get(entry.getKey().getCitationKey().orElse(null)) - ); + documentConnection.xText, + cursor, + layout, + parFormat, + entry.getKey(), + entry.getValue(), + uniqueLetters.get(entry.getKey() + .getCitationKey() + .orElse(null)) + ); } } + /** + * Create a text section with the provided name and insert it at + * the provided cursor. + * + * @param sectionName The desired name for the section. + * @param textCursor The location to insert at. + * + * (This could move to DocumentConnection) + */ private void createAndInsertSection( DocumentConnection documentConnection, @@ -2590,10 +2668,19 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, documentConnection.xText.insertTextContent(textCursor, xChildSection, false); } - private void createBibTextSection2(DocumentConnection documentConnection, - boolean end) - throws IllegalArgumentException, - CreationException { + /** + * Insert a paragraph break and creates a text section for the bibliography. + * + * @param end If true, insert at the end of the document. + * + */ + private void + createBibTextSection2( + DocumentConnection documentConnection, + boolean end) + throws + IllegalArgumentException, + CreationException { XTextCursor textCursor = documentConnection.xText.createTextCursor(); if (end) { @@ -2604,6 +2691,7 @@ private void createBibTextSection2(DocumentConnection documentConnection, // If we do, what happens (or expected to happen) here? OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); + createAndInsertSection( documentConnection, OOBibBase.BIB_SECTION_NAME, @@ -2624,7 +2712,12 @@ private void createBibTextSection2(DocumentConnection documentConnection, return supplier.getTextSections(); } - private void clearBibTextSectionContent2(DocumentConnection documentConnection) + /** + * Find and clear the text section OOBibBase.BIB_SECTION_NAME to "", + * or create it. + */ + private void + clearBibTextSectionContent2(DocumentConnection documentConnection) throws WrappedTargetException, IllegalArgumentException, @@ -2640,6 +2733,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) Any a = ((Any) ts.getByName(OOBibBase.BIB_SECTION_NAME)); XTextSection section = (XTextSection) a.getObject(); // Clear it: + XTextCursor cursor = documentConnection.xText.createTextCursorByRange(section.getAnchor()); From fcb21dd3afec3cb9fb72540276ff3cd574b41f5f Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 08:58:35 +0100 Subject: [PATCH 0407/1068] rename locals xChild.. to section.. --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3cde72c8ab8..ae773226823 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2652,9 +2652,9 @@ void updateUniqueLetters( // Create a new TextSection from the document factory // and access it's XNamed interface - XNamed xChildNamed; + XNamed sectionNamed; try { - xChildNamed = + sectionNamed = unoQI(XNamed.class, (documentConnection.mxDocFactory .createInstance("com.sun.star.text.TextSection"))); @@ -2662,10 +2662,12 @@ void updateUniqueLetters( throw new CreationException(e.getMessage()); } // Set the new sections name to 'Child_Section' - xChildNamed.setName(sectionName); + sectionNamed.setName(sectionName); // Access the Child_Section's XTextContent interface and insert it into the document - XTextContent xChildSection = unoQI(XTextContent.class, xChildNamed); - documentConnection.xText.insertTextContent(textCursor, xChildSection, false); + XTextContent sectionTextContent = unoQI(XTextContent.class, sectionNamed); + documentConnection.xText.insertTextContent(textCursor, sectionTextContent, false); + } + } /** From ed3ecc96d56bb37626caecfac8ec216dcc7a9005 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 08:59:49 +0100 Subject: [PATCH 0408/1068] getTextSections moved up --- .../org/jabref/gui/openoffice/OOBibBase.java | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ae773226823..e2d43933143 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2668,6 +2668,20 @@ void updateUniqueLetters( documentConnection.xText.insertTextContent(textCursor, sectionTextContent, false); } + /** + * @return An XNameAccess to find sections by name. + */ + private XNameAccess + getTextSections(DocumentConnection documentConnection) + throws + WrappedTargetException, + IllegalArgumentException, + CreationException { + + XTextSectionsSupplier supplier = + unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); + + return supplier.getTextSections(); } /** @@ -2701,19 +2715,6 @@ void updateUniqueLetters( ); } - private XNameAccess - getTextSections(DocumentConnection documentConnection) - throws - WrappedTargetException, - IllegalArgumentException, - CreationException { - // Check if the section exists: - XTextSectionsSupplier supplier = - unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); - - return supplier.getTextSections(); - } - /** * Find and clear the text section OOBibBase.BIB_SECTION_NAME to "", * or create it. From 90beba79eeee94531ee8d6154b761f9413dcdf9e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 09:00:19 +0100 Subject: [PATCH 0409/1068] rname local ts to nameAccess --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e2d43933143..a8a848689f1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2726,14 +2726,14 @@ void updateUniqueLetters( IllegalArgumentException, CreationException { - XNameAccess ts = getTextSections( documentConnection ); - if (!ts.hasByName(OOBibBase.BIB_SECTION_NAME)) { + XNameAccess nameAccess = getTextSections( documentConnection ); + if (!nameAccess.hasByName(OOBibBase.BIB_SECTION_NAME)) { createBibTextSection2(documentConnection, this.atEnd); return; } try { - Any a = ((Any) ts.getByName(OOBibBase.BIB_SECTION_NAME)); + Any a = ((Any) nameAccess.getByName(OOBibBase.BIB_SECTION_NAME)); XTextSection section = (XTextSection) a.getObject(); // Clear it: @@ -2747,8 +2747,8 @@ void updateUniqueLetters( // methods of collections, if the addressed child does // not exist. - // We got this exception from ts.getByName() despite - // the ts.hasByName() check just above. + // We got this exception from nameAccess.getByName() despite + // the nameAccess.hasByName() check just above. // Try to create. LOGGER.warn("Could not get section '" + OOBibBase.BIB_SECTION_NAME + "'", ex); From fb807768298b3e3430ecdc161a97171628f4f593 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 09:28:52 +0100 Subject: [PATCH 0410/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 55 +++++++++++-------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a8a848689f1..9c6a6f66255 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2689,6 +2689,7 @@ void updateUniqueLetters( * * @param end If true, insert at the end of the document. * + * Only called from `clearBibTextSectionContent2` */ private void createBibTextSection2( @@ -2718,6 +2719,9 @@ void updateUniqueLetters( /** * Find and clear the text section OOBibBase.BIB_SECTION_NAME to "", * or create it. + * + * Only called from: `rebuildBibTextSection` + * */ private void clearBibTextSectionContent2(DocumentConnection documentConnection) @@ -2757,7 +2761,7 @@ void updateUniqueLetters( } /** - * Only called from: rebuildBibTextSection + * Only called from: `rebuildBibTextSection` * * Assumes the section named `OOBibBase.BIB_SECTION_NAME` exists. */ @@ -2832,28 +2836,35 @@ void updateUniqueLetters( * Insert a reference mark. * * @param documentConnection Connection to a document. + * * @param name Name of the reference mark to be created and also - * the name of the custom property holding the pageInfo part. - */ - private void insertReferenceMark(DocumentConnection documentConnection, - String name, - String citationText, - XTextCursor position, - boolean withText, - OOBibStyle style) - throws UnknownPropertyException, - WrappedTargetException, - PropertyVetoException, - IllegalArgumentException, - UndefinedCharacterFormatException, - CreationException { - // TODO: last minute editing is hacky. Move pageInfo stuff to - // citation marker generation. - // If there is "page info" for this citation, insert it into - // the citation text before inserting the citation: + * the name of the custom property holding the pageInfo part. + */ + private void insertReferenceMark( + DocumentConnection documentConnection, + String name, + String citationText, + XTextCursor position, + boolean withText, + OOBibStyle style + ) + throws + UnknownPropertyException, + WrappedTargetException, + PropertyVetoException, + IllegalArgumentException, + UndefinedCharacterFormatException, + CreationException { + + // Last minute editing: If there is "page info" for this + // citation mark, inject it into the citation marker before + // inserting. + + // TODO: Consider moving pageInfo stuff to citation marker + // generation. String citText; String pageInfo = - getPageInfoForReferenceMarkName(documentConnection, name); + getPageInfoForReferenceMarkName(documentConnection, name); citText = pageInfo.isEmpty() ? citationText @@ -2862,8 +2873,8 @@ private void insertReferenceMark(DocumentConnection documentConnection, Object bookmark; try { bookmark = - documentConnection.mxDocFactory - .createInstance("com.sun.star.text.ReferenceMark"); + documentConnection.mxDocFactory + .createInstance("com.sun.star.text.ReferenceMark"); } catch (Exception e) { throw new CreationException(e.getMessage()); } From e75d98be0335e61434fbbea6cc7e14b547f1d781 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 10:39:43 +0100 Subject: [PATCH 0411/1068] extract DocumentConnection.insertReferenceMark (from OOBibBase.insertReferenceMark) --- .../org/jabref/gui/openoffice/OOBibBase.java | 72 ++++++++++++++----- 1 file changed, 54 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9c6a6f66255..7322e50b0fc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -470,12 +470,59 @@ private static class DocumentConnection { return xFoundBookmark.getAnchor(); } + /** + * Insert a new reference mark at the provided cursor + * position. + * + * The text in the cursor range will be the text with gray + * background. + * + * @param name For the reference mark. + * @param position Cursor marking the location or range for + * the reference mark. + * + * Note: Almost identical to insertBookMark + */ + public void + insertReferenceMark( + String name, + XTextCursor position + ) + throws + CreationException { + + Object bookmark; + try { + bookmark = + this.mxDocFactory + .createInstance("com.sun.star.text.ReferenceMark"); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + // Name the reference + XNamed xNamed = unoQI(XNamed.class, bookmark); + xNamed.setName(name); + + // get XTextContent interface + XTextContent xTextContent = unoQI(XTextContent.class, bookmark); + + position.getText().insertTextContent(position, xTextContent, true); + } + /** * Insert a bookmark with the given name at the cursor provided. * - * @param name For the bookmark. + * @param name For the bookmark. * @param position Cursor marking the location or range for - * the bookmark. If it is a range, its content will be replaced. + * the bookmark. + * + * If it is a range, its content will be + * replaced. + * TODO: I thought from insertTextContent doc, + * https://www.openoffice.org/api/docs/common/ref/ + * com/sun/star/text/XText.html#insertTextContent + * that it will be. But it might depend on the + * type of textContent. */ public void insertBookMark( @@ -2639,6 +2686,8 @@ void updateUniqueLetters( * @param textCursor The location to insert at. * * (This could move to DocumentConnection) + * + * TODO: c.f. DocumentConnection.insertBookMark and DocumentConnection.insertReferenceMark */ private void createAndInsertSection( @@ -2670,6 +2719,8 @@ void updateUniqueLetters( /** * @return An XNameAccess to find sections by name. + * + * TODO: c.f. DocumentConnection.getReferenceMarks and DocumentConnection.getBookmarks */ private XNameAccess getTextSections(DocumentConnection documentConnection) @@ -2870,18 +2921,6 @@ private void insertReferenceMark( ? citationText : style.insertPageInfo(citationText, pageInfo); - Object bookmark; - try { - bookmark = - documentConnection.mxDocFactory - .createInstance("com.sun.star.text.ReferenceMark"); - } catch (Exception e) { - throw new CreationException(e.getMessage()); - } - // Name the reference - XNamed xNamed = unoQI(XNamed.class, bookmark); - xNamed.setName(name); - if (withText) { position.setString(citText); XPropertySet xCursorProps = unoQI(XPropertySet.class, position); @@ -2903,10 +2942,7 @@ private void insertReferenceMark( position.setString(""); } - // get XTextContent interface - XTextContent xTextContent = unoQI(XTextContent.class, bookmark); - - position.getText().insertTextContent(position, xTextContent, true); + documentConnection.insertReferenceMark(name, position); // Are we sure that OOBibStyle.ET_AL_STRING cannot be part of author names // in any language? From 54f593f181b8488dc707188aa335128937d5135c Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 11:07:05 +0100 Subject: [PATCH 0412/1068] extract setCharStyle into DocumentConnection --- .../org/jabref/gui/openoffice/OOBibBase.java | 66 +++++++++++-------- 1 file changed, 39 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7322e50b0fc..2a226019120 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -102,8 +102,6 @@ class OOBibBase { private static final Pattern CITE_PATTERN = Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); - private static final String CHAR_STYLE_NAME = "CharStyleName"; - /* Types of in-text citation. (itcType) * Their numeric values are used in reference mark names. */ @@ -125,6 +123,11 @@ class OOBibBase { * Document-connection related variables. */ private static class DocumentConnection { + /** https://wiki.openoffice.org/wiki/Documentation/BASIC_Guide/Structure_of_Text_Documents#Character_Properties + * "CharStyleName" is an OpenOffice Property name. + */ + private static final String CHAR_STYLE_NAME = "CharStyleName"; + public XMultiServiceFactory mxDocFactory; public XTextDocument mxDoc; public XText xText; @@ -568,6 +571,35 @@ private static class DocumentConnection { ((Any) supplier.getTextSections().getByName(name)) .getObject()); } + + /** + * Apply a character style to a range of text selected by a + * cursor. + * + * @param position The range to apply to. + * @param charStyle Name of the character style as known by Openoffice. + */ + private static void + setCharStyle( + XTextCursor position, + String charStyle + ) + throws UndefinedCharacterFormatException { + + XPropertySet xCursorProps = unoQI(XPropertySet.class, position); + + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + throw new UndefinedCharacterFormatException(charStyle); + // Setting the character format failed, so we throw an exception that + // will result in an error message for the user: + } + } + } // end DocumentConnection /** @@ -1254,12 +1286,8 @@ private static class ParsedRefMark { XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); String charStyle = style.getCitationCharacterFormat(); try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex - ) { + DocumentConnection.setCharStyle(cursor, charStyle); + } catch (UndefinedCharacterFormatException ex ) { // Setting the character format failed, so we // throw an exception that will result in an // error message for the user. @@ -2929,14 +2957,7 @@ private void insertReferenceMark( xCursorProps.setPropertyValue("CharLocale", new Locale("zxx", "", "")); if (style.isFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - throw new UndefinedCharacterFormatException(charStyle); - } + DocumentConnection.setCharStyle( position, charStyle ); } } else { position.setString(""); @@ -3026,20 +3047,11 @@ List lookupEntriesInDatabasesSkipMissing(List keys, private void testFormatCitations(XTextCursor textCursor, OOBibStyle style) throws UndefinedCharacterFormatException { - XPropertySet xCursorProps = unoQI(XPropertySet.class, textCursor); String charStyle = style.getCitationCharacterFormat(); - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - // Setting the character format failed, so we throw an exception that - // will result in an error message for the user: - throw new UndefinedCharacterFormatException(charStyle); - } + DocumentConnection.setCharStyle( textCursor, charStyle ); } + /** * GUI action * From 2ed3bb42b1fd335bf2f421d33f67666bc0a82945 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 11:58:52 +0100 Subject: [PATCH 0413/1068] apply IDEA and checkstyle suggestions --- .../org/jabref/gui/openoffice/OOBibBase.java | 108 ++++++++---------- 1 file changed, 46 insertions(+), 62 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2a226019120..0289922bc0d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -228,8 +228,6 @@ private static class DocumentConnection { * current document. * * @param value The value to be stored. - * - * @return The value of the property or Optional.empty() */ private void setCustomProperty(String property, String value) @@ -299,18 +297,17 @@ private static class DocumentConnection { /** * Create a textcursor for a textContent. * - * @return null if makr is null, otherwise cursor. + * @return null if mark is null, otherwise cursor. */ static XTextCursor getTextCursorOfTextContent(XTextContent mark) { - if ( mark == null ){ + if (mark == null) { return null; } XTextRange markAnchor = mark.getAnchor(); - XTextCursor cursor = + return markAnchor.getText() .createTextCursorByRange(markAnchor); - return cursor; } /** @@ -325,8 +322,7 @@ private static class DocumentConnection { } try { Object referenceMark = nameAccess.getByName(name); - XTextContent mark = unoQI(XTextContent.class, referenceMark); - return mark; + return unoQI(XTextContent.class, referenceMark); } catch (NoSuchElementException ex) { LOGGER.warn(String.format( "nameAccessGetTextContentByName got NoSuchElementException" @@ -350,8 +346,9 @@ private static class DocumentConnection { XNameAccess xReferenceMarks = this.getReferenceMarks(); if (xReferenceMarks.hasByName(name)) { - XTextContent mark = nameAccessGetTextContentByName( xReferenceMarks, name ); - if ( mark == null ){ + XTextContent mark = + nameAccessGetTextContentByName(xReferenceMarks, name); + if (mark == null) { return; } this.xText.removeTextContent(mark); @@ -377,7 +374,6 @@ private static class DocumentConnection { int charAfter, boolean htmlMarkup) throws - NoSuchElementException, WrappedTargetException, NoDocumentException { @@ -466,8 +462,8 @@ private static class DocumentConnection { XNameAccess xNamedBookmarks = this.getBookmarks(); XTextContent xFoundBookmark = - nameAccessGetTextContentByName( xNamedBookmarks, name ); - if (xFoundBookmark == null){ + nameAccessGetTextContentByName(xNamedBookmarks, name); + if (xFoundBookmark == null) { return null; } return xFoundBookmark.getAnchor(); @@ -1052,7 +1048,6 @@ public boolean documentConnectionMissing() { public List getCitationEntries() throws - NoSuchElementException, UnknownPropertyException, WrappedTargetException, NoDocumentException { @@ -1281,13 +1276,11 @@ private static class ParsedRefMark { .insertString(cursor, " ", false); // format the space inserted - // TOOD: extract applyCharacterStyle() if (style.isFormatCitations()) { - XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); String charStyle = style.getCitationCharacterFormat(); try { DocumentConnection.setCharStyle(cursor, charStyle); - } catch (UndefinedCharacterFormatException ex ) { + } catch (UndefinedCharacterFormatException ex) { // Setting the character format failed, so we // throw an exception that will result in an // error message for the user. @@ -1302,8 +1295,8 @@ private static class ParsedRefMark { // go back to before the space cursor.goLeft((short) 1, false); - // Insert rerefence mark and text - //{ + // Insert reference mark and text + // { // Create a BibEntry to BibDatabase map (to make // style.getCitationMarker happy?) Map databaseMap = new HashMap<>(); @@ -1325,7 +1318,7 @@ private static class ParsedRefMark { null); insertReferenceMark(documentConnection, newName, citeText, cursor, withText, style); - //} // end of scope for databaseMap, citeText + // } // end of scope for databaseMap, citeText // Move to the right of the space and remember this // position: we will come back here in the end. @@ -1577,7 +1570,6 @@ private static class FindCitedEntriesResult { return cEntry; } - /** * Checks that every element of `keys` can be found in `citeKeyToBibEntry`. * @@ -1609,12 +1601,12 @@ private static class FindCitedEntriesResult { for (String key : unresolvedKeys) { LOGGER.info("assertKeysInCiteKeyToBibEntry: Citation key not found: '" + key + '\''); - LOGGER.info("Problem with reference mark: '" + referenceMarkName + "' "+ where); + LOGGER.info("Problem with reference mark: '" + referenceMarkName + "' " + where); String msg = Localization.lang( "Could not resolve BibTeX entry" + " for citation marker '%0'.", - referenceMarkName ); + referenceMarkName); throw new BibEntryNotFoundException(referenceMarkName, msg); } } @@ -1685,7 +1677,7 @@ private static class CitationNumberingState { * numbers : Remembers keys we have seen * and what number did they receive. */ - private Map numbers; + private final Map numbers; /** * The highest number we ever allocated. @@ -1803,20 +1795,18 @@ public int getOrAllocateNumber(String key) { Map entries ) { - // Citation keys, in the same order as sortedEntries - List result = new ArrayList<>(entries.size()); - // Sort entries to order in bibliography Map sortedEntries = sortEntriesByComparator(entries, entryComparator); + // Citation keys, in the same order as sortedEntries return sortedEntries.keySet().stream() .map( entry -> entry.getCitationKey() // entries came from looking up by citation key, - // so Optional.empty() is not possible here. + // so Optional.empty() is only possible here for UndefinedBibtexEntry. .orElse(null) ) .collect(Collectors.toList()); @@ -1841,7 +1831,7 @@ public int getOrAllocateNumber(String key) { String[] citMarkers = new String[nRefMarks]; List sortedCited = - citationKeysOrNullInBibliographyOrderFromEntries( entries ); + citationKeysOrNullInBibliographyOrderFromEntries(entries); final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); @@ -1944,7 +1934,7 @@ public int getOrAllocateNumber(String key) { documentConnection.nameAccessGetTextContentByName(nameAccess, name); XTextCursor cursor = - documentConnection.getTextCursorOfTextContent(mark); + DocumentConnection.getTextCursorOfTextContent(mark); if (mustTestCharFormat) { mustTestCharFormat = false; // need to do this only once @@ -2058,7 +2048,7 @@ public int getOrAllocateNumber(String key) { * result[i][j] = cEntriesForAll[i][j].getCitationKey() */ private String[][] - mapBibEntriesToCitationKeysOrNullForall( BibEntry[][] cEntriesForAll ) { + mapBibEntriesToCitationKeysOrNullForall(BibEntry[][] cEntriesForAll) { return Arrays.stream(cEntriesForAll) .map(cEntries -> @@ -2082,8 +2072,8 @@ public int getOrAllocateNumber(String key) { * Note: bibtexKeys[i][j] may be null (from UndefinedBibtexEntry) */ void updateUniqueLetters( - String bibtexKeys[][], - String normCitMarkers[][], + String[][] bibtexKeys, + String[][] normCitMarkers, final Map uniqueLetters ) { @@ -2204,18 +2194,18 @@ void updateUniqueLetters( "produceCitationMarkersForNormalStyle"); BibEntry[][] cEntriesForAll = - getBibEntriesSortedWithinReferenceMarks( bibtexKeysIn, citeKeyToBibEntry, style ); + getBibEntriesSortedWithinReferenceMarks(bibtexKeysIn, citeKeyToBibEntry, style); // Update bibtexKeys to match the new sorting (within each referenceMark) - String[][] bibtexKeys = mapBibEntriesToCitationKeysOrNullForall( cEntriesForAll ); + String[][] bibtexKeys = mapBibEntriesToCitationKeysOrNullForall(cEntriesForAll); // Note: bibtexKeys[i][j] may be null, for UndefinedBibtexEntry assert (bibtexKeys.length == nRefMarks); String[][] normCitMarkers = - normalizedCitationMarkersForNormalStyle( cEntriesForAll, entries, style ); + normalizedCitationMarkersForNormalStyle(cEntriesForAll, entries, style); - updateUniqueLetters( bibtexKeys, normCitMarkers, uniqueLetters ); + updateUniqueLetters(bibtexKeys, normCitMarkers, uniqueLetters); // Finally, go through all citation markers, and update // those referring to entries in our current list: @@ -2226,7 +2216,6 @@ void updateUniqueLetters( for (int i = 0; i < nRefMarks; i++) { - final String referenceMarkName = referenceMarkNames.get(i); final int nCitedEntries = bibtexKeys[i].length; int[] firstLimAuthors = new int[nCitedEntries]; String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; @@ -2252,11 +2241,10 @@ void updateUniqueLetters( } String uniqueLetterForKey = uniqueLetters.get(currentKey); - if (uniqueLetterForKey == null) { - uniqueLetterForCitedEntry[j] = ""; - } else { - uniqueLetterForCitedEntry[j] = uniqueLetterForKey; - } + uniqueLetterForCitedEntry[j] = + (uniqueLetterForKey == null + ? "" + : uniqueLetterForKey); } List cEntries = @@ -2280,11 +2268,11 @@ void updateUniqueLetters( /** * Refresh citation markers according to `style`. * - * - Requires an uptodate jabRefReferenceMarkNamesSortedByPosition + * - Requires an up-to-date jabRefReferenceMarkNamesSortedByPosition * - * @param documentConnection + * @param documentConnection Connection. * @param databases For look up by citation key. Must have at least one. - * @param style + * @param style Style. * @param uniqueLetters Will be cleared and potentially filled with new values. */ private List @@ -2377,11 +2365,11 @@ void updateUniqueLetters( } /** - * Given an XTextRange, return its position: + * Given a location, return its position: * coordinates relative to the top left position * of the first page of the document. * - * @param range + * @param range Location. * @param cursor To get the position, we need az XTextViewCursor. * It will be moved to the range. */ @@ -2407,7 +2395,6 @@ void updateUniqueLetters( DocumentConnection documentConnection) throws WrappedTargetException, - NoSuchElementException, NoDocumentException { List names = getJabRefReferenceMarkNames(documentConnection); @@ -2422,7 +2409,7 @@ void updateUniqueLetters( for (String name : names) { XTextContent textContent = - documentConnection.nameAccessGetTextContentByName( nameAccess, name ); + documentConnection.nameAccessGetTextContentByName(nameAccess, name); // unoQI(XTextContent.class, nameAccess.getByName(name)); XTextRange range = textContent.getAnchor(); @@ -2434,7 +2421,7 @@ void updateUniqueLetters( // The footnote's anchor gives the correct position in the text: range = footer.getAnchor(); } - positions.add(findPositionOfTextRange(range,viewCursor)); + positions.add(findPositionOfTextRange(range, viewCursor)); } // restore cursor position viewCursor.gotoRange(initialPos, false); @@ -2479,7 +2466,7 @@ void updateUniqueLetters( * GUI action, refreshes citation markers and bibliography. * * @param databases Must have at least one. - * @param style + * @param style Style. * @return List of unresolved citation keys. * * Note: calls updateSortedReferenceMarks(); @@ -2633,11 +2620,11 @@ void updateUniqueLetters( /** * Insert body of bibliography at `cursor`. * - * @param documentConnection + * @param documentConnection Connection. * @param cursor Where to * @param entries Its iteration order defines order in bibliography. - * @param style - * @param parFormat + * @param style Style. + * @param parFormat Passed to OOUtil.insertFullReferenceAtCurrentLocation * @param uniqueLetters * * Only called from populateBibTextSection (and that from rebuildBibTextSection) @@ -2753,9 +2740,7 @@ void updateUniqueLetters( private XNameAccess getTextSections(DocumentConnection documentConnection) throws - WrappedTargetException, - IllegalArgumentException, - CreationException { + IllegalArgumentException { XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); @@ -2809,7 +2794,7 @@ void updateUniqueLetters( IllegalArgumentException, CreationException { - XNameAccess nameAccess = getTextSections( documentConnection ); + XNameAccess nameAccess = getTextSections(documentConnection); if (!nameAccess.hasByName(OOBibBase.BIB_SECTION_NAME)) { createBibTextSection2(documentConnection, this.atEnd); return; @@ -2957,7 +2942,7 @@ private void insertReferenceMark( xCursorProps.setPropertyValue("CharLocale", new Locale("zxx", "", "")); if (style.isFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle( position, charStyle ); + DocumentConnection.setCharStyle(position, charStyle); } } else { position.setString(""); @@ -3048,10 +3033,9 @@ List lookupEntriesInDatabasesSkipMissing(List keys, private void testFormatCitations(XTextCursor textCursor, OOBibStyle style) throws UndefinedCharacterFormatException { String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle( textCursor, charStyle ); + DocumentConnection.setCharStyle(textCursor, charStyle); } - /** * GUI action * From ccbab3dd16ea2472e4d9429c97e613f31fd792c5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 12:24:06 +0100 Subject: [PATCH 0414/1068] comments --- .../org/jabref/gui/openoffice/OOBibBase.java | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0289922bc0d..d5409f4a7b7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2904,7 +2904,8 @@ void updateUniqueLetters( * @param name Name of the reference mark to be created and also * the name of the custom property holding the pageInfo part. */ - private void insertReferenceMark( + private void + insertReferenceMark( DocumentConnection documentConnection, String name, String citationText, @@ -2950,9 +2951,21 @@ private void insertReferenceMark( documentConnection.insertReferenceMark(name, position); - // Are we sure that OOBibStyle.ET_AL_STRING cannot be part of author names - // in any language? - // TODO: could we move italicizing "et al." to a more proper place? + // Last minute editing: find "et al." (OOBibStyle.ET_AL_STRING) and + // format it as italic. + + // Q: Are we sure that OOBibStyle.ET_AL_STRING cannot be part of author names + // in any language? + // A: No, but have no examples either. + + // Q: Are we sure, citText does not contain multiple "et al." strings? + // A: It *can* contain more than one. + + // TODO: Could we move italicizing "et al." to a more proper place? + // Maybe we could use POSTFORMATTER with "..." + // That might make OOBibStyle.ITALIC_ET_AL superfluous. + // TODO: Handle multiple "et al." strings. + // Check if we should italicize the "et al." string in citations: boolean italicize = style.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); if (italicize) { From accc356a4b6b177bd25bf54d68a73d79745bd4a5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 22:51:53 +0100 Subject: [PATCH 0415/1068] exract direct character formatting expressions --- .../org/jabref/gui/openoffice/OOBibBase.java | 54 ++++++++++++++++--- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d5409f4a7b7..7c7087a1d1a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -596,6 +596,50 @@ private static class DocumentConnection { } } + /** + * Apply direct character format "Italic" to a range of text. + * + * Ref: https://www.openoffice.org/api/docs/common/ref/com/sun/star/style/CharacterProperties.html + */ + private static void + setCharFormatItalic(XTextRange textRange) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + XPropertySet xcp = unoQI(XPropertySet.class, textRange); + xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); + } + + /** + * Apply direct character format "Bold" to a range of text. + */ + private static void + setCharFormatBold(XTextRange textRange) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + XPropertySet xcp = unoQI(XPropertySet.class, textRange); + xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD); + } + + /** + * Set language to [None] + * + * Note: "zxx" is an https://en.wikipedia.org/wiki/ISO_639 code for + * "No linguistic information at all" + */ + private static void + setCharLocaleNone(XTextRange textRange) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + XPropertySet xcp = unoQI(XPropertySet.class, textRange); + xcp.setPropertyValue("CharLocale", new Locale("zxx", "", "")); + } + } // end DocumentConnection /** @@ -2937,10 +2981,7 @@ void updateUniqueLetters( if (withText) { position.setString(citText); - XPropertySet xCursorProps = unoQI(XPropertySet.class, position); - - // Set language to [None]: - xCursorProps.setPropertyValue("CharLocale", new Locale("zxx", "", "")); + DocumentConnection.setCharLocaleNone(position); if (style.isFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); DocumentConnection.setCharStyle(position, charStyle); @@ -3002,8 +3043,9 @@ private void italicizeRangeFromPosition(XTextCursor position, cursor.goRight((short) start, false); cursor.goRight((short) (end - start), true); - XPropertySet xcp = unoQI(XPropertySet.class, cursor); - xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); + DocumentConnection.setCharFormatItalic( cursor ); + // XPropertySet xcp = unoQI(XPropertySet.class, cursor); + // xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); // xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD); } From c5e7f3d271ec677887ea5be636aed744f1954c69 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 2 Mar 2021 23:07:44 +0100 Subject: [PATCH 0416/1068] inline and remove testFormatCitations --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7c7087a1d1a..2d8913a5bfd 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1982,7 +1982,8 @@ public int getOrAllocateNumber(String key) { if (mustTestCharFormat) { mustTestCharFormat = false; // need to do this only once - testFormatCitations(cursor, style); + String charStyle = style.getCitationCharacterFormat(); + DocumentConnection.setCharStyle(cursor, charStyle); } documentConnection.xText.removeTextContent(mark); @@ -3085,12 +3086,6 @@ List lookupEntriesInDatabasesSkipMissing(List keys, return entries; } - private void testFormatCitations(XTextCursor textCursor, OOBibStyle style) - throws UndefinedCharacterFormatException { - String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(textCursor, charStyle); - } - /** * GUI action * @@ -3191,7 +3186,8 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // marks are removed, preventing damage to the user's // document: if (style.isFormatCitations()) { - testFormatCitations(textCursor, style); + String charStyle = style.getCitationCharacterFormat(); + DocumentConnection.setCharStyle(textCursor, charStyle); } /* @@ -3301,7 +3297,8 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) // marks are removed, preventing damage to the user's // document: if (style.isFormatCitations()) { - testFormatCitations(textCursor, style); + String charStyle = style.getCitationCharacterFormat(); + DocumentConnection.setCharStyle(textCursor, charStyle); } List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); From 509f7e437d7c6d6125c65169a0df5e00fc5d845b Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 3 Mar 2021 17:43:08 +0100 Subject: [PATCH 0417/1068] refactor: format, comments --- .../org/jabref/gui/openoffice/OOBibBase.java | 195 +++++++++++------- 1 file changed, 119 insertions(+), 76 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2d8913a5bfd..d116e437029 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3031,23 +3031,24 @@ void updateUniqueLetters( * Why this API? This is used after finding "et al." string in a * citation marker. */ - private void italicizeRangeFromPosition(XTextCursor position, - int start, - int end) + private void + italicizeRangeFromPosition( + XTextCursor position, + int start, + int end + ) throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException { + XTextRange range = position.getStart(); XTextCursor cursor = position.getText().createTextCursorByRange(range); cursor.goRight((short) start, false); cursor.goRight((short) (end - start), true); DocumentConnection.setCharFormatItalic( cursor ); - // XPropertySet xcp = unoQI(XPropertySet.class, cursor); - // xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); - // xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD); } /** @@ -3057,7 +3058,8 @@ private void italicizeRangeFromPosition(XTextCursor position, * @param databases Key is looked up in these, in this order. * @return The BibEntry at the first match, or Optional.empty(). */ - Optional lookupEntryInDatabases(String key, List databases) { + Optional + lookupEntryInDatabases(String key, List databases) { for (BibDatabase database : databases) { Optional entry = database.getEntryByCitationKey(key); if (entry.isPresent()) { @@ -3068,6 +3070,8 @@ Optional lookupEntryInDatabases(String key, List database } /** + * Look up a list of citation keys in a list of databases. + * * @param keys Citation keys to look up. * @param databases Keys are looked up in these, in this order. * @return The BibEntry objects found. @@ -3077,8 +3081,11 @@ Optional lookupEntryInDatabases(String key, List database * necessarily belong to keys.get(i) * */ - List lookupEntriesInDatabasesSkipMissing(List keys, - List databases) { + List + lookupEntriesInDatabasesSkipMissing( + List keys, + List databases + ) { List entries = new ArrayList<>(); for (String key : keys) { lookupEntryInDatabases(key, databases).ifPresent(entries::add); @@ -3087,72 +3094,94 @@ List lookupEntriesInDatabasesSkipMissing(List keys, } /** - * GUI action - * - * combineCiteMarkers does not work with citations in footnotes. + * GUI action "Merge citations" * - * Note: citations can be inserted in footnotes and they appear in - * the bibliography. They are also updated on style change+refresh + * Earlier note: "combineCiteMarkers does not work with citations in footnotes" * - * The same (insertable, appears in bibliography, update on - * style change) is true for citations in tables. + * Note: + * - citations in footnotes + * - [X] can be inserted and + * - [X] they appear in the bibliography. + * - [X] They are also updated on style change+refresh + * - [ ] Merge fails (does not merge). + * - [ ] "Separate" (on merged citations inserted by + * selecting multiple entries then "Cite") + * May leave some of the two citation marks with text "tmp". + * This can be corrected by a few repetions of pressing the "refresh" + * button. * - * Merge (combineCiteMarkers) and Separate (unCombineCiteMarkers) - * seem to work in a cell of a table. + * - citations in tables (text tables) + * - [X] can be inserted + * - [X] they appear in bibliography + * - [X] they are updated on style change+refresh + * - [X} Merge (combineCiteMarkers) works + * - [X} Separate (unCombineCiteMarkers) works * - * In footnotes: "Separate" (on merged citations inserted by - * selecting multiple entries then "Cite") leaves first of - * two citation marks with text "tmp", which can be - * corrected by a few repetions of pressing the "refresh" - * button. - * With 3 citations, "Separate" left the 2nd and 3rd as "tmp". - * Three refresh corrected the 2nd. The 4th refresh corrected the 3rd citation. - * - * TODO: if the corresponding bib file is not open, this leaves a - * mess: (1) reference marks with "tmp" i the text (2) with + * TODO: if the corresponding bib file is not open, Separate (unCombineCiteMarkers) (or Merge?) + * leaves a mess: (1) reference marks with "tmp" in the text (2) with * reference mark name "JR_cite_1_", i.e. without citation key. + * */ - public void combineCiteMarkers(List databases, OOBibStyle style) - throws IOException, - WrappedTargetException, - NoSuchElementException, - IllegalArgumentException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException { + public void + combineCiteMarkers( + List databases, + OOBibStyle style + ) + throws + IOException, + WrappedTargetException, + NoSuchElementException, + IllegalArgumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { + DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + // The testing for whitespace-only between (pivot) and (pivot+1) assumes that + // names are in textual order: textually consecutive pairs + // must appear as neighbours (and in textual order). + // We have a bit of a clash here: names is sorted by visual position, + // but we are testing if they are textually neighbours. + // In a two-coloumn layout + // | a | c | + // | b | d | + // abcd is the textual order, but the visual order is acbd. + // So we will not find out that a and b are only separated by white space. List names = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + // XTextRangeCompare: compares the positions of two TextRanges within a Text. + // Only TextRange instances within the same Text can be compared. final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - documentConnection.xText); + documentConnection.xText); int pivot = 0; boolean madeModifications = false; + boolean setCharStyleTested = false; XNameAccess nameAccess = documentConnection.getReferenceMarks(); while (pivot < (names.size() - 1)) { XTextRange range1 = - unoQI(XTextContent.class, - nameAccess.getByName(names.get(pivot))) - .getAnchor() - .getEnd(); + unoQI(XTextContent.class, + nameAccess.getByName(names.get(pivot))) + .getAnchor() + .getEnd(); XTextRange range2 = - unoQI(XTextContent.class, - nameAccess.getByName(names.get(pivot + 1))) - .getAnchor() - .getStart(); + unoQI(XTextContent.class, + nameAccess.getByName(names.get(pivot + 1))) + .getAnchor() + .getStart(); // end of range2 is the start of (pivot + 1) if (range1.getText() != range2.getText()) { - /* pivot and (pivot+1) belong to different XText entities? + /* pivot and (pivot+1) belong to different Text instances. * Maybe to different footnotes? - * Cannot combine across boundaries skip. + * Cannot combine across boundaries, skip. */ pivot++; continue; @@ -3160,11 +3189,16 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // Start from end of text for pivot. XTextCursor textCursor = - range1.getText().createTextCursorByRange(range1); + range1.getText().createTextCursorByRange(range1); + + // Select next character (if possible), and more, as long as we can and + // do not reach start of (pivot+1), which we now know to be + // in the same Text instance. - // Select next character, and more, as long as we can and - // do not reach stat of (pivot+1), which we now know to be - // under the same XText entity. + // TODO: If there is no space between the two reference marks, + // the next line moves INTO the next. And probably will + // cover a non-whitespace character, inhibiting the merge. + // Empirically: does not merge. Probably a bug. textCursor.goRight((short) 1, true); boolean couldExpand = true; while (couldExpand && (compare.compareRegionEnds(textCursor, range2) > 0)) { @@ -3186,6 +3220,8 @@ public void combineCiteMarkers(List databases, OOBibStyle style) // marks are removed, preventing damage to the user's // document: if (style.isFormatCitations()) { + // Q: we may have zero characters selected. Is this a valied test + // in this case? String charStyle = style.getCitationCharacterFormat(); DocumentConnection.setCharStyle(textCursor, charStyle); } @@ -3217,7 +3253,7 @@ public void combineCiteMarkers(List databases, OOBibStyle style) * */ List keys = - parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); + parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); documentConnection.removeReferenceMark(names.get(pivot)); @@ -3232,10 +3268,11 @@ public void combineCiteMarkers(List databases, OOBibStyle style) .collect(Collectors.joining(",")); // Insert reference mark: - String newName = getUniqueReferenceMarkName(documentConnection, + String newName = + getUniqueReferenceMarkName( + documentConnection, keyString, - OOBibBase.AUTHORYEAR_PAR - ); + OOBibBase.AUTHORYEAR_PAR ); insertReferenceMark( documentConnection, @@ -3257,26 +3294,32 @@ public void combineCiteMarkers(List databases, OOBibStyle style) } /** - * GUI action. + * GUI action "Separate citations". + * * Do the opposite of combineCiteMarkers. * Combined markers are split, with a space inserted between. */ - public void unCombineCiteMarkers(List databases, OOBibStyle style) - throws IOException, - WrappedTargetException, - NoSuchElementException, - IllegalArgumentException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, - BibEntryNotFoundException, - NoDocumentException { + public void + unCombineCiteMarkers( + List databases, + OOBibStyle style + ) + throws + IOException, + WrappedTargetException, + NoSuchElementException, + IllegalArgumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); List names = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); int pivot = 0; boolean madeModifications = false; @@ -3284,12 +3327,12 @@ public void unCombineCiteMarkers(List databases, OOBibStyle style) while (pivot < (names.size())) { XTextRange range1 = - unoQI(XTextContent.class, - nameAccess.getByName(names.get(pivot))) - .getAnchor(); + unoQI(XTextContent.class, + nameAccess.getByName(names.get(pivot))) + .getAnchor(); XTextCursor textCursor = - range1.getText().createTextCursorByRange(range1); + range1.getText().createTextCursorByRange(range1); // If we are supposed to set character format for // citations, test this before making any changes. This From 22c1b44d7807bed64826a933506b4ea20a40900d Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 3 Mar 2021 17:52:23 +0100 Subject: [PATCH 0418/1068] refactor: setCharStyle test only once in combineCiteMarkers, unCombineCiteMarkers --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d116e437029..17b2fee6386 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3219,11 +3219,12 @@ void updateUniqueLetters( // way we can throw an exception before any reference // marks are removed, preventing damage to the user's // document: - if (style.isFormatCitations()) { // Q: we may have zero characters selected. Is this a valied test // in this case? + if (style.isFormatCitations() && !setCharStyleTested) { String charStyle = style.getCitationCharacterFormat(); DocumentConnection.setCharStyle(textCursor, charStyle); + setCharStyleTested = true; } /* @@ -3323,6 +3324,7 @@ void updateUniqueLetters( int pivot = 0; boolean madeModifications = false; + boolean setCharStyleTested = false; XNameAccess nameAccess = documentConnection.getReferenceMarks(); while (pivot < (names.size())) { @@ -3339,9 +3341,10 @@ void updateUniqueLetters( // way we can throw an exception before any reference // marks are removed, preventing damage to the user's // document: - if (style.isFormatCitations()) { + if (style.isFormatCitations() && ! setCharStyleTested ) { String charStyle = style.getCitationCharacterFormat(); DocumentConnection.setCharStyle(textCursor, charStyle); + setCharStyleTested = true; } List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); From 8598a0e04fce064050b27e5ff44ee2c515eb6c22 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 3 Mar 2021 19:06:19 +0100 Subject: [PATCH 0419/1068] format --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 17b2fee6386..46fc3d44a62 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3219,7 +3219,7 @@ void updateUniqueLetters( // way we can throw an exception before any reference // marks are removed, preventing damage to the user's // document: - // Q: we may have zero characters selected. Is this a valied test + // Q: we may have zero characters selected. Is this a valid test // in this case? if (style.isFormatCitations() && !setCharStyleTested) { String charStyle = style.getCitationCharacterFormat(); @@ -3341,7 +3341,7 @@ void updateUniqueLetters( // way we can throw an exception before any reference // marks are removed, preventing damage to the user's // document: - if (style.isFormatCitations() && ! setCharStyleTested ) { + if (style.isFormatCitations() && !setCharStyleTested ) { String charStyle = style.getCitationCharacterFormat(); DocumentConnection.setCharStyle(textCursor, charStyle); setCharStyleTested = true; @@ -3359,10 +3359,10 @@ void updateUniqueLetters( int last = keys.size() - 1; int i = 0; for (String key : keys) { - String newName = getUniqueReferenceMarkName(documentConnection, - key, - OOBibBase.AUTHORYEAR_PAR - ); + String newName = getUniqueReferenceMarkName( + documentConnection, + key, + OOBibBase.AUTHORYEAR_PAR); insertReferenceMark( documentConnection, From b2d949ec4bae318257d3346d4abcae5704a9d70b Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 3 Mar 2021 19:06:55 +0100 Subject: [PATCH 0420/1068] question: in "Separate citations" what style for inserted spaces? --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 46fc3d44a62..992ea7fa762 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3374,6 +3374,8 @@ void updateUniqueLetters( style); textCursor.collapseToEnd(); if (i != last) { + // TODO: space between citation markers: what style? + // DocumentConnection.setCharStyle(textCursor, "Standard"); textCursor.setString(" "); textCursor.collapseToEnd(); } From 99f4178888ba183963a7604bc0f7ae6e015f3592 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 3 Mar 2021 19:24:25 +0100 Subject: [PATCH 0421/1068] refactor: format, comments (reached end of file) --- .../org/jabref/gui/openoffice/OOBibBase.java | 31 ++++++++++++++++--- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 992ea7fa762..10472489f4f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3392,12 +3392,24 @@ void updateUniqueLetters( } /** - * Used from GUI. + * Used from GUI: "Export cited" + * + * @param databases The databases to look up the citation keys in the document from. + * @result A new database, with cloned entries. + * + * If a key is not found, it is silently ignored. + * + * Cross references (in StandardField.CROSSREF) are followed (not recursively): + * if the referenced entry is found, it is included in the result. + * If it is not found, it is silently ignored. */ - public BibDatabase generateDatabase(List databases) - throws NoSuchElementException, - WrappedTargetException, - NoDocumentException { + public BibDatabase + generateDatabase(List databases) + throws + NoSuchElementException, + WrappedTargetException, + NoDocumentException { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); BibDatabase resultDatabase = new BibDatabase(); @@ -3443,12 +3455,21 @@ public BibDatabase generateDatabase(List databases) // Be happy with the first found BibEntry and move on to next key break; } + // key not found here. No action. } resultDatabase.insertEntries(entriesToInsert); return resultDatabase; } + /** + * A reference mark name paired with its visual position. + * + * Comparison is based on (Y,X): vertical compared first, horizontal second. + * + * Used for sorting reference marks by their visual positions. + * + */ private static class ComparableMark implements Comparable { private final String name; From 17b9a6ecdaabd93b2691fa42a25dce2a61cde5e5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 3 Mar 2021 20:20:58 +0100 Subject: [PATCH 0422/1068] refactor: IDEA and style checker --- .../org/jabref/gui/openoffice/OOBibBase.java | 54 ++++++++++--------- 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 10472489f4f..be2e2e7c679 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -123,7 +123,8 @@ class OOBibBase { * Document-connection related variables. */ private static class DocumentConnection { - /** https://wiki.openoffice.org/wiki/Documentation/BASIC_Guide/Structure_of_Text_Documents#Character_Properties + /** https://wiki.openoffice.org/wiki/Documentation/BASIC_Guide/ + * Structure_of_Text_Documents#Character_Properties * "CharStyleName" is an OpenOffice Property name. */ private static final String CHAR_STYLE_NAME = "CharStyleName"; @@ -257,7 +258,7 @@ private static class DocumentConnection { * @throws NoDocumentException If cannot get reference marks * * Note: also used by `documentConnectionMissing` to test if - * we have a working connecion. + * we have a working connection. * */ private XNameAccess @@ -295,7 +296,7 @@ private static class DocumentConnection { } /** - * Create a textcursor for a textContent. + * Create a text cursor for a textContent. * * @return null if mark is null, otherwise cursor. */ @@ -611,9 +612,10 @@ private static class DocumentConnection { xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); } - /** + /* * Apply direct character format "Bold" to a range of text. */ + /* unused: private static void setCharFormatBold(XTextRange textRange) throws @@ -623,6 +625,7 @@ private static class DocumentConnection { XPropertySet xcp = unoQI(XPropertySet.class, textRange); xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD); } + */ /** * Set language to [None] @@ -841,7 +844,7 @@ public String toString() { /** * Choose a document to work with. * - * Assumes we have already connected to Libroffice or OpenOffice. + * Assumes we have already connected to LibreOffice or OpenOffice. * * If there is a single document to choose from, selects that. * If there are more than one, shows selection dialog. @@ -1005,7 +1008,7 @@ public boolean documentConnectionMissing() { /** * Sort entries within a group of merged citations. * - * Note: the sort is inplace, modifies the argument. + * Note: the sort is in-place, modifies the argument. */ private void sortBibEntryListForMulticite(List entries, @@ -1058,7 +1061,7 @@ public boolean documentConnectionMissing() { } /** - * Get reference mark naems from the document matching the pattern + * Get reference mark names from the document matching the pattern * used for JabRef reference mark names. * * Note: the names returned are in arbitrary order. @@ -1082,7 +1085,7 @@ public boolean documentConnectionMissing() { * getJabRefReferenceMarkNames). * * TODO: Note: visual or alphabetic order could be more - * managable for the user. We could provide these + * manageable for the user. We could provide these * here, but switching between them needs change on * GUI (adding a toggle or selector). * @@ -1158,8 +1161,8 @@ public boolean documentConnectionMissing() { * marks of the document. * * @param bibtexKey The citation key. - * @param itcType Encodes the effect of withText and - * inParenthesis options. + * @param itcType Encodes the effect of withText and + * inParenthesis options. * * The first occurrence of bibtexKey gets no serial number, the * second gets 0, the third 1 ... @@ -1244,7 +1247,7 @@ private static class ParsedRefMark { * @param withText Indicates whether this should be a visible * citation (true) or an empty (invisible) citation (false). * - * @param pageInfo A single pageinfo for these entries. Stored in custom property + * @param pageInfo A single page-info for these entries. Stored in custom property * with the same name as the reference mark. * * Related https://latex.org/forum/viewtopic.php?t=14331 @@ -1607,7 +1610,7 @@ private static class FindCitedEntriesResult { * otherwise return cEntry itself. */ private static BibEntry - undefinedBibentryToNull(BibEntry cEntry) { + undefinedBibEntryToNull(BibEntry cEntry) { if (cEntry instanceof UndefinedBibtexEntry) { return null; } @@ -2069,8 +2072,11 @@ public int getOrAllocateNumber(String key) { } /** - * Look up `bibtexkeys` in `citeKeyToBibEntry`, sort result within + * Look up citation keys from a map caching earlier look up, sort result within * each reference mark. + * + * @param bibtexKeys Citation keys, bibtexKeys[i][j] is for the ith reference mark. + * @param citeKeyToBibEntry Cached lookup from keys to entries. */ private BibEntry[][] getBibEntriesSortedWithinReferenceMarks( @@ -2093,7 +2099,7 @@ public int getOrAllocateNumber(String key) { * result[i][j] = cEntriesForAll[i][j].getCitationKey() */ private String[][] - mapBibEntriesToCitationKeysOrNullForall(BibEntry[][] cEntriesForAll) { + mapBibEntriesToCitationKeysOrNullForAll(BibEntry[][] cEntriesForAll) { return Arrays.stream(cEntriesForAll) .map(cEntries -> @@ -2125,7 +2131,7 @@ void updateUniqueLetters( final int nRefMarks = bibtexKeys.length; assert nRefMarks == normCitMarkers.length; - // refKeys: (normCitMarker) to (list of bibtexkeys sharing it). + // refKeys: (normCitMarker) to (list of citation keys sharing it). // The entries in the lists are ordered as in // normCitMarkers[i][j] Map> refKeys = new HashMap<>(); @@ -2192,7 +2198,7 @@ void updateUniqueLetters( Arrays.stream(cEntries) .map(ce -> style.getCitationMarker( - Collections.singletonList(undefinedBibentryToNull(ce)), + Collections.singletonList(undefinedBibEntryToNull(ce)), entries, true, null, @@ -2242,7 +2248,7 @@ void updateUniqueLetters( getBibEntriesSortedWithinReferenceMarks(bibtexKeysIn, citeKeyToBibEntry, style); // Update bibtexKeys to match the new sorting (within each referenceMark) - String[][] bibtexKeys = mapBibEntriesToCitationKeysOrNullForall(cEntriesForAll); + String[][] bibtexKeys = mapBibEntriesToCitationKeysOrNullForAll(cEntriesForAll); // Note: bibtexKeys[i][j] may be null, for UndefinedBibtexEntry assert (bibtexKeys.length == nRefMarks); @@ -2294,7 +2300,7 @@ void updateUniqueLetters( List cEntries = Arrays.stream(cEntriesForAll[i]) - .map(OOBibBase::undefinedBibentryToNull) + .map(OOBibBase::undefinedBibEntryToNull) .collect(Collectors.toList()); citMarkers[i] = @@ -3048,7 +3054,7 @@ void updateUniqueLetters( cursor.goRight((short) start, false); cursor.goRight((short) (end - start), true); - DocumentConnection.setCharFormatItalic( cursor ); + DocumentConnection.setCharFormatItalic(cursor); } /** @@ -3107,7 +3113,7 @@ void updateUniqueLetters( * - [ ] "Separate" (on merged citations inserted by * selecting multiple entries then "Cite") * May leave some of the two citation marks with text "tmp". - * This can be corrected by a few repetions of pressing the "refresh" + * This can be corrected by a few repetitions of pressing the "refresh" * button. * * - citations in tables (text tables) @@ -3146,7 +3152,7 @@ void updateUniqueLetters( // must appear as neighbours (and in textual order). // We have a bit of a clash here: names is sorted by visual position, // but we are testing if they are textually neighbours. - // In a two-coloumn layout + // In a two-column layout // | a | c | // | b | d | // abcd is the textual order, but the visual order is acbd. @@ -3273,7 +3279,7 @@ void updateUniqueLetters( getUniqueReferenceMarkName( documentConnection, keyString, - OOBibBase.AUTHORYEAR_PAR ); + OOBibBase.AUTHORYEAR_PAR); insertReferenceMark( documentConnection, @@ -3341,7 +3347,7 @@ void updateUniqueLetters( // way we can throw an exception before any reference // marks are removed, preventing damage to the user's // document: - if (style.isFormatCitations() && !setCharStyleTested ) { + if (style.isFormatCitations() && !setCharStyleTested) { String charStyle = style.getCitationCharacterFormat(); DocumentConnection.setCharStyle(textCursor, charStyle); setCharStyleTested = true; @@ -3395,7 +3401,7 @@ void updateUniqueLetters( * Used from GUI: "Export cited" * * @param databases The databases to look up the citation keys in the document from. - * @result A new database, with cloned entries. + * @return A new database, with cloned entries. * * If a key is not found, it is silently ignored. * From 05afee823d2a787d3960364052a6c339547a928d Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 3 Mar 2021 20:45:00 +0100 Subject: [PATCH 0423/1068] resolved question on insertimng bookmark to a range --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index be2e2e7c679..2760093a9eb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -516,13 +516,8 @@ private static class DocumentConnection { * @param position Cursor marking the location or range for * the bookmark. * - * If it is a range, its content will be - * replaced. - * TODO: I thought from insertTextContent doc, - * https://www.openoffice.org/api/docs/common/ref/ - * com/sun/star/text/XText.html#insertTextContent - * that it will be. But it might depend on the - * type of textContent. + * If it is a range, the bookmark will point + * to the whole range. */ public void insertBookMark( @@ -547,7 +542,8 @@ private static class DocumentConnection { // get XTextContent interface XTextContent xTextContent = unoQI(XTextContent.class, bookmark); - // insert bookmark at position, overwrite text in position + // insert bookmark at position. The range of position + // becomes the range of the bookmark. this.xText.insertTextContent(position, xTextContent, true); } From 34f6be0fb5bc67e45912cf8343ef2604535ad324 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 4 Mar 2021 14:20:33 +0100 Subject: [PATCH 0424/1068] refactor: comments --- .../org/jabref/gui/openoffice/OOBibBase.java | 95 ++++++++++++++++--- 1 file changed, 84 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2760093a9eb..c19acc21550 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1183,7 +1183,7 @@ public boolean documentConnectionMissing() { } /** - * This is what we get back from parsing a refMarkName + * This is what we get back from parsing a refMarkName. * * TODO: We have one itcType per refMarkName. Merge reduces the * number of itcType values. @@ -1224,8 +1224,13 @@ private static class ParsedRefMark { } /** - * This method inserts a reference mark in the text (at the cursor) - * citing the entries, and may refresh the bibliography. + * Called from: OpenOfficePanel.pushEntries, a GUI action for + * "Cite", "Cite in-text", "Cite special" and "Insert empty + * citation". + * + * This method inserts a reference mark in the text (at the + * cursor) citing the entries, and (if sync is true) refreshes the + * citation markers and the bibliography. * * @param entries The entries to cite. * @@ -1257,9 +1262,11 @@ private static class ParsedRefMark { * @param sync Indicates whether the reference list and in-text citations * should be refreshed in the document. * - * TODO: + * TODO: Group changes into a single Undo context. * https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html - * Group changes into a single Undo context. + * + * TODO: centralize inserting a citation group in a way that is + * also suitable for combineCiteMarkers, unCombineCiteMarkers (Is there any other to consider?) */ public void insertEntry( @@ -1294,13 +1301,24 @@ private static class ParsedRefMark { // Get the cursor positioned by the user. XTextCursor cursor = documentConnection.getViewCursor(); + // TODO: (style-dependent) sorting entries for presentation + // affects the storage order of citation keys. + // - (1) presentation order shoudl be decided + // when generating the presentation + // - (2) storage order should keep the order + // provided by the user. sortBibEntryListForMulticite(entries, style); + // TODO: consistent handling of citation groups (merged citations). + // keyString generation differs from the one in combineCiteMarkers + // Here we get A,,C for (A,B,C) where could not look up B + // There we get A,C String keyString = entries.stream() .map(entry -> entry.getCitationKey().orElse("")) .collect(Collectors.joining(",")); // Generate unique bookmark-name + // TODO: citationType is itcType elsewhere int citationType = citationTypeFromOptions(withText, inParenthesis); String newName = getUniqueReferenceMarkName( documentConnection, @@ -1312,6 +1330,11 @@ private static class ParsedRefMark { LOGGER.info("Storing page info: " + pageInfo); documentConnection.setCustomProperty(newName, pageInfo); } + // else: branch ??? + // TODO: if (pageInfo is null), we might inadvertently + // pick up a pageInfo from an earlier citation. The user + // may have removed the citation, thus the reference mark, + // but pageInfo stored separately stays there. // insert space cursor @@ -1387,8 +1410,13 @@ private static class ParsedRefMark { * at org.jabref@100.0.0/org.jabref.gui.openoffice * .OOBibBase.insertEntry(OOBibBase.java:609) * - * Maybe we should refuse to insert in places to be - * overwritten: bibliography, reference marks. + * Idea: Maybe we should refuse to insert in places to be + * overwritten: bibliography, reference marks. + * + * Needs: (preferably accurate) knowledge of the forbidden ranges. + * Limitation: the user can still Cut and Paste to these parts. + * Q: Can we make them readonly inside, while allowing + * to move them around as a unit? * */ // Go back to the relevant position: @@ -2000,7 +2028,19 @@ public int getOrAllocateNumber(String key) { && (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { // TODO: I think we used a *section* for the // bibliography elsewhere. Here we use a *bookmark*. Relation? - // + // applyNewCitationMarkers: + // looks for: Bookmark + // creates: paragraph + Bookmark + // createBibTextSection2: + // creates: paragraph + Section + // clearBibTextSectionContent2: + // looks for: Section, calls createBibTextSection2 + // sets to "": Section + // populateBibTextSection: + // looks for: Section + // insert Bookmark BIB_SECTION_END_NAME + // after the body. + // We have overwritten the marker for the start of the reference list. // We need to add it again. cursor.collapseToEnd(); @@ -2626,7 +2666,7 @@ void updateUniqueLetters( * as appears there. * * TODO: The order within a reference mark name is decided on - * construction. Is it updated after a style change? + * construction (in insertEntry). Is it updated after a style change? * */ private Map @@ -2817,6 +2857,9 @@ void updateUniqueLetters( // where does textCursor point to if end is false? // TODO: are we using this.atEnd == false? // If we do, what happens (or expected to happen) here? + // OpenOfficePanel.createBibBase calls + // new OOBibBase(loPath, true, dialogService); + // So probably no. OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); @@ -2898,6 +2941,15 @@ void updateUniqueLetters( documentConnection.xText .createTextCursorByRange(section.getAnchor()); + // TODO: I think creating a Section, inserting TITLE and formatting + // it without question, is an overreach. + // These could be left to the user's discretion. + // - Section has problems with docx conversion (?) + // - Do we need a different style to replace "References" with "Bibliography"? + // - Do we want to edit the style to change "Heading 1" to "Heading 2" + // To do (the important part of) our job, it is sufficient to get + // a range marker for the body of the bibliography. + // Maybe an "Insert bibliogrgaphy at the cursor"? OOUtil.insertTextAtCurrentLocation( documentConnection.xText, cursor, @@ -2917,6 +2969,11 @@ void updateUniqueLetters( uniqueLetters ); + // TODO: Do not insert Bookmark without testing if it already + // exists. LibreOffice creates "JR_bib_end1" instead of "JR_bib_end", + // or rather "JR_bib_endN" where N may increase. + // Repeatedly pressing "Refresh" leaves "JR_bib_end" at the start + // of the bibliography. documentConnection.insertBookMark(OOBibBase.BIB_SECTION_END_NAME, cursor); cursor.collapseToEnd(); } @@ -2973,7 +3030,9 @@ void updateUniqueLetters( // inserting. // TODO: Consider moving pageInfo stuff to citation marker - // generation. + // generation. May need to modify getCitationMarker, + // at ./jabref/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java492: + // to emit html code. String citText; String pageInfo = getPageInfoForReferenceMarkName(documentConnection, name); @@ -3008,6 +3067,11 @@ void updateUniqueLetters( // TODO: Could we move italicizing "et al." to a more proper place? // Maybe we could use POSTFORMATTER with "..." // That might make OOBibStyle.ITALIC_ET_AL superfluous. + // Maybe + // insertOOFormattedTextAtCurrentLocation could be used + // to do the insert (if paragraph style manipulation + // is removed) + // TODO: Handle multiple "et al." strings. // Check if we should italicize the "et al." string in citations: @@ -3024,7 +3088,7 @@ void updateUniqueLetters( } /** - * Taking ref=position.getStart(), italicize the range (ref+start,ref+end) + * Taking position.getStart() as a reference point, italicize the range (ref+start,ref+end) * * @param position : position.getStart() is out reference point. * @param start : start of range to italicize w.r.t position.getStart(). @@ -3255,6 +3319,11 @@ void updateUniqueLetters( * will depend on authors not shown here. * */ + + // Note: silently drops duplicate keys. + // What if they have different pageInfo fields? + // TODO: combineCiteMarkers: merging for same citation keys, + // but different pageInfo looses information. List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); @@ -3262,6 +3331,8 @@ void updateUniqueLetters( documentConnection.removeReferenceMark(names.get(pivot)); documentConnection.removeReferenceMark(names.get(pivot + 1)); + // Note: citation keys not found are silently left out from the + // combined reference mark name. Loosing information. List entries = lookupEntriesInDatabasesSkipMissing(keys, databases); entries.sort(new FieldComparator(StandardField.YEAR)); @@ -3361,6 +3432,8 @@ void updateUniqueLetters( int last = keys.size() - 1; int i = 0; for (String key : keys) { + // Note: instead of generating a new name, we should explicitly + // recover the original. Otherwise ... String newName = getUniqueReferenceMarkName( documentConnection, key, From eeb7392f490667743bf340786e9fa083a02b7d93 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 4 Mar 2021 14:47:41 +0100 Subject: [PATCH 0425/1068] refactor: OOBibBase.atEnd removed (was always true) --- .../org/jabref/gui/openoffice/OOBibBase.java | 25 +++++-------------- .../gui/openoffice/OpenOfficePanel.java | 2 +- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c19acc21550..6ced8c963df 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -115,7 +115,6 @@ class OOBibBase { /* variables */ private final DialogService dialogService; private final XDesktop xDesktop; - private final boolean atEnd; private final Comparator entryComparator; private final Comparator yearAuthorTitleComparator; @@ -669,7 +668,6 @@ private static class DocumentConnection { */ public OOBibBase(Path loPath, - boolean atEnd, DialogService dialogService) throws BootstrapException, @@ -693,7 +691,6 @@ private static class DocumentConnection { yat.add(t); this.yearAuthorTitleComparator = new FieldComparatorStack<>(yat); - this.atEnd = atEnd; this.xDesktop = simpleBootstrap(loPath); } @@ -2838,28 +2835,18 @@ void updateUniqueLetters( /** * Insert a paragraph break and creates a text section for the bibliography. * - * @param end If true, insert at the end of the document. - * * Only called from `clearBibTextSectionContent2` */ private void - createBibTextSection2( - DocumentConnection documentConnection, - boolean end) + createBibTextSection2(DocumentConnection documentConnection) throws IllegalArgumentException, CreationException { + // Always creating at the end of documentConnection.xText + // Alternatively, we could receive a cursor. XTextCursor textCursor = documentConnection.xText.createTextCursor(); - if (end) { - textCursor.gotoEnd(false); - } - // where does textCursor point to if end is false? - // TODO: are we using this.atEnd == false? - // If we do, what happens (or expected to happen) here? - // OpenOfficePanel.createBibBase calls - // new OOBibBase(loPath, true, dialogService); - // So probably no. + textCursor.gotoEnd(false); OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); @@ -2886,7 +2873,7 @@ void updateUniqueLetters( XNameAccess nameAccess = getTextSections(documentConnection); if (!nameAccess.hasByName(OOBibBase.BIB_SECTION_NAME)) { - createBibTextSection2(documentConnection, this.atEnd); + createBibTextSection2(documentConnection); return; } @@ -2910,7 +2897,7 @@ void updateUniqueLetters( // Try to create. LOGGER.warn("Could not get section '" + OOBibBase.BIB_SECTION_NAME + "'", ex); - createBibTextSection2(documentConnection, this.atEnd); + createBibTextSection2(documentConnection); } } diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 0df250ad55f..f1b8ab96ce3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -493,7 +493,7 @@ protected OOBibBase call() throws Exception { private OOBibBase createBibBase(Path loPath) throws IOException, InvocationTargetException, IllegalAccessException, BootstrapException, CreationException, ClassNotFoundException { - return new OOBibBase(loPath, true, dialogService); + return new OOBibBase(loPath, dialogService); } private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addPageInfo) { From de1ac8d4c36115770972a05b5339be9da70cf86f Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 4 Mar 2021 17:33:13 +0100 Subject: [PATCH 0426/1068] rename createAndInsertSection to DocumentConnection.insertTextSection Also: extract common part: insertNamedTextContent --- .../org/jabref/gui/openoffice/OOBibBase.java | 191 ++++++++++-------- 1 file changed, 108 insertions(+), 83 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6ced8c963df..1524de13339 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -470,80 +470,141 @@ private static class DocumentConnection { } /** - * Insert a new reference mark at the provided cursor + * Insert a new instance of a service at the provided cursor * position. * - * The text in the cursor range will be the text with gray - * background. + * @param service For example + * "com.sun.star.text.ReferenceMark", + * "com.sun.star.text.Bookmark" or + * "com.sun.star.text.TextSection". * - * @param name For the reference mark. - * @param position Cursor marking the location or range for - * the reference mark. + * Passed to this.mxDocFactory.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. * - * Note: Almost identical to insertBookMark */ - public void - insertReferenceMark( + private XNamed + insertNamedTextContent( + String service, String name, - XTextCursor position + XTextRange range, + boolean absorb ) throws CreationException { - Object bookmark; + Object xObject; try { - bookmark = + xObject = this.mxDocFactory - .createInstance("com.sun.star.text.ReferenceMark"); + .createInstance(service); } catch (Exception e) { throw new CreationException(e.getMessage()); } - // Name the reference - XNamed xNamed = unoQI(XNamed.class, bookmark); + + XNamed xNamed = unoQI(XNamed.class, xObject); xNamed.setName(name); // get XTextContent interface - XTextContent xTextContent = unoQI(XTextContent.class, bookmark); + XTextContent xTextContent = unoQI(XTextContent.class, xObject); + range.getText().insertTextContent(range, xTextContent, absorb); + return xNamed; + } - position.getText().insertTextContent(position, xTextContent, true); + /** + * Insert a new reference mark at the provided cursor + * position. + * + * The text in the cursor range will be the text with gray + * background. + * + * @param name For the reference mark. + * @param range Cursor marking the location or range for + * the reference mark. + */ + public XNamed + insertReferenceMark( + String name, + XTextRange range, + boolean absorb + ) + throws + CreationException { + return + insertNamedTextContent( + "com.sun.star.text.ReferenceMark", + name, + range, + absorb // was true + ); } /** * Insert a bookmark with the given name at the cursor provided. * * @param name For the bookmark. - * @param position Cursor marking the location or range for + * @param range Cursor marking the location or range for * the bookmark. + * @param absorb Shall we incorporate range? * - * If it is a range, the bookmark will point - * to the whole range. */ - public void + public XNamed insertBookMark( String name, - XTextCursor position) + XTextRange range, + boolean absorb) throws IllegalArgumentException, CreationException { - Object bookmark; - try { - bookmark = (this.mxDocFactory - .createInstance("com.sun.star.text.Bookmark")); - } catch (Exception e) { - throw new CreationException(e.getMessage()); - } - - // name the bookmark - XNamed xNamed = unoQI(XNamed.class, bookmark); - xNamed.setName(name); + return + insertNamedTextContent( + "com.sun.star.text.Bookmark", + name, + range, + absorb // was true + ); + } - // get XTextContent interface - XTextContent xTextContent = unoQI(XTextContent.class, bookmark); + /** + * 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. + * + */ + private XNamed + insertTextSection( + String name, + XTextRange range, + boolean absorb) + throws + IllegalArgumentException, + CreationException { - // insert bookmark at position. The range of position - // becomes the range of the bookmark. - this.xText.insertTextContent(position, xTextContent, true); + return + insertNamedTextContent( + "com.sun.star.text.TextSection", + name, + range, + absorb // was false + ); } /** @@ -2042,7 +2103,7 @@ public int getOrAllocateNumber(String key) { // We need to add it again. cursor.collapseToEnd(); OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - documentConnection.insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); + documentConnection.insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor, true); cursor.collapseToEnd(); } } @@ -2777,45 +2838,6 @@ void updateUniqueLetters( } } - /** - * Create a text section with the provided name and insert it at - * the provided cursor. - * - * @param sectionName The desired name for the section. - * @param textCursor The location to insert at. - * - * (This could move to DocumentConnection) - * - * TODO: c.f. DocumentConnection.insertBookMark and DocumentConnection.insertReferenceMark - */ - private void - createAndInsertSection( - DocumentConnection documentConnection, - String sectionName, - XTextCursor textCursor - ) - throws - IllegalArgumentException, - CreationException { - - // Create a new TextSection from the document factory - // and access it's XNamed interface - XNamed sectionNamed; - try { - sectionNamed = - unoQI(XNamed.class, - (documentConnection.mxDocFactory - .createInstance("com.sun.star.text.TextSection"))); - } catch (Exception e) { - throw new CreationException(e.getMessage()); - } - // Set the new sections name to 'Child_Section' - sectionNamed.setName(sectionName); - // Access the Child_Section's XTextContent interface and insert it into the document - XTextContent sectionTextContent = unoQI(XTextContent.class, sectionNamed); - documentConnection.xText.insertTextContent(textCursor, sectionTextContent, false); - } - /** * @return An XNameAccess to find sections by name. * @@ -2850,10 +2872,10 @@ void updateUniqueLetters( OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); - createAndInsertSection( - documentConnection, + documentConnection.insertTextSection( OOBibBase.BIB_SECTION_NAME, - textCursor + textCursor, + false ); } @@ -2961,7 +2983,10 @@ void updateUniqueLetters( // or rather "JR_bib_endN" where N may increase. // Repeatedly pressing "Refresh" leaves "JR_bib_end" at the start // of the bibliography. - documentConnection.insertBookMark(OOBibBase.BIB_SECTION_END_NAME, cursor); + documentConnection.insertBookMark( + OOBibBase.BIB_SECTION_END_NAME, + cursor, + true); cursor.collapseToEnd(); } @@ -3039,7 +3064,7 @@ void updateUniqueLetters( position.setString(""); } - documentConnection.insertReferenceMark(name, position); + documentConnection.insertReferenceMark(name, position, true); // Last minute editing: find "et al." (OOBibStyle.ET_AL_STRING) and // format it as italic. From 94cce2b1092a9b3f294145abbdae599c4132bea2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 4 Mar 2021 17:35:11 +0100 Subject: [PATCH 0427/1068] insertBookMark renamed to insertBookmark to match service name --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1524de13339..00bc11694e9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -564,7 +564,7 @@ private static class DocumentConnection { * */ public XNamed - insertBookMark( + insertBookmark( String name, XTextRange range, boolean absorb) @@ -2103,7 +2103,7 @@ public int getOrAllocateNumber(String key) { // We need to add it again. cursor.collapseToEnd(); OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - documentConnection.insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor, true); + documentConnection.insertBookmark(OOBibBase.BIB_SECTION_NAME, cursor, true); cursor.collapseToEnd(); } } @@ -2983,7 +2983,7 @@ void updateUniqueLetters( // or rather "JR_bib_endN" where N may increase. // Repeatedly pressing "Refresh" leaves "JR_bib_end" at the start // of the bibliography. - documentConnection.insertBookMark( + documentConnection.insertBookmark( OOBibBase.BIB_SECTION_END_NAME, cursor, true); From daa5cb1393e4daaa06659853e0bfc79a92cfb32b Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 4 Mar 2021 18:37:51 +0100 Subject: [PATCH 0428/1068] refactor: moved getTextSections to DocumentConnection, collect similar together --- .../org/jabref/gui/openoffice/OOBibBase.java | 61 ++++++++++--------- 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 00bc11694e9..ac45faa40c4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -272,11 +272,40 @@ private static class DocumentConnection { try { return supplier.getReferenceMarks(); } catch (DisposedException ex) { - // LOGGER.warn("getReferenceMarks caught: ", ex); throw new NoDocumentException("getReferenceMarks failed with" + ex); } } + /** + * Provides access to bookmarks by name. + */ + private XNameAccess + getBookmarks() { + + XBookmarksSupplier supplier = + unoQI( + XBookmarksSupplier.class, + this.xCurrentComponent + ); + return supplier.getBookmarks(); + } + + /** + * @return An XNameAccess to find sections by name. + */ + private XNameAccess + getTextSections() + throws + IllegalArgumentException { + + XTextSectionsSupplier supplier = + unoQI( + XTextSectionsSupplier.class, + this.mxDoc + ); + return supplier.getTextSections(); + } + /** * Names of all reference marks. * @@ -436,18 +465,6 @@ private static class DocumentConnection { return this.xViewCursorSupplier.getViewCursor(); } - /** - * Provides access to bookmarks by name. - */ - public XNameAccess - getBookmarks() { - // query XBookmarksSupplier from document model - // and get bookmarks collection - XBookmarksSupplier xBookmarksSupplier = - unoQI(XBookmarksSupplier.class, - this.xCurrentComponent); - return xBookmarksSupplier.getBookmarks(); - } /** * Get the XTextRange corresponding to the named bookmark. @@ -2838,22 +2855,6 @@ void updateUniqueLetters( } } - /** - * @return An XNameAccess to find sections by name. - * - * TODO: c.f. DocumentConnection.getReferenceMarks and DocumentConnection.getBookmarks - */ - private XNameAccess - getTextSections(DocumentConnection documentConnection) - throws - IllegalArgumentException { - - XTextSectionsSupplier supplier = - unoQI(XTextSectionsSupplier.class, documentConnection.mxDoc); - - return supplier.getTextSections(); - } - /** * Insert a paragraph break and creates a text section for the bibliography. * @@ -2893,7 +2894,7 @@ void updateUniqueLetters( IllegalArgumentException, CreationException { - XNameAccess nameAccess = getTextSections(documentConnection); + XNameAccess nameAccess = documentConnection.getTextSections(); if (!nameAccess.hasByName(OOBibBase.BIB_SECTION_NAME)) { createBibTextSection2(documentConnection); return; From 7226f57a6d0d551e1e2e0e91c895692d0ae21e3a Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 4 Mar 2021 19:32:36 +0100 Subject: [PATCH 0429/1068] comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ac45faa40c4..1390468eef9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3557,6 +3557,8 @@ void updateUniqueLetters( * * Used for sorting reference marks by their visual positions. * + * Note: for text layouts with two or more columns, this gives the wrong order. + * */ private static class ComparableMark implements Comparable { From dd9847b87b20dd4bc1f48b713eb40bd22ccb83e9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 4 Mar 2021 21:21:02 +0100 Subject: [PATCH 0430/1068] extracting parts of mxDoc moved into DocumentConnection contructor --- .../org/jabref/gui/openoffice/OOBibBase.java | 107 ++++++++---------- 1 file changed, 47 insertions(+), 60 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1390468eef9..1a6631417c0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -128,32 +128,38 @@ private static class DocumentConnection { */ private static final String CHAR_STYLE_NAME = "CharStyleName"; - public XMultiServiceFactory mxDocFactory; public XTextDocument mxDoc; + public XComponent xCurrentComponent; + public XMultiServiceFactory mxDocFactory; public XText xText; public XTextViewCursorSupplier xViewCursorSupplier; - public XComponent xCurrentComponent; - public XPropertySet propertySet; public XPropertyContainer userProperties; + public XPropertySet propertySet; private final Logger LOGGER; DocumentConnection( - XMultiServiceFactory mxDocFactory, XTextDocument mxDoc, - XText xText, - XTextViewCursorSupplier xViewCursorSupplier, - XComponent xCurrentComponent, - XPropertySet propertySet, - XPropertyContainer userProperties, Logger LOGGER ) { - this.mxDocFactory = mxDocFactory; this.mxDoc = mxDoc; - this.xText = xText; - this.xViewCursorSupplier = xViewCursorSupplier; - this.xCurrentComponent = xCurrentComponent; - this.propertySet = propertySet; - this.userProperties = userProperties; + this.xCurrentComponent = unoQI(XComponent.class, mxDoc); + this.mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); + // unoQI(XDocumentIndexesSupplier.class, component); + + // get a reference to the body text of the document + this.xText = mxDoc.getText(); + + XModel mo = unoQI(XModel.class, this.xCurrentComponent); + XController co = mo.getCurrentController(); + this.xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); + + XDocumentPropertiesSupplier supp = + unoQI(XDocumentPropertiesSupplier.class, mxDoc); + this.userProperties = + supp.getDocumentProperties().getUserDefinedProperties(); + + this.propertySet = unoQI(XPropertySet.class, userProperties); + this.LOGGER = LOGGER; } @@ -163,25 +169,38 @@ private static class DocumentConnection { public boolean documentConnectionMissing() { - // These are set by selectDocument, via DocumentConnection - // constructor. - if (null == this.xCurrentComponent - || null == this.mxDoc - || null == this.xViewCursorSupplier - || null == this.xText + boolean missing = false; + // These are set by DocumentConnection constructor. + if (null == this.mxDoc + || null == this.xCurrentComponent || null == this.mxDocFactory + || null == this.xText + || null == this.xViewCursorSupplier || null == this.userProperties || null == this.propertySet) { - return true; + missing = true; } // Attempt to check document is really available - try { - getReferenceMarks(); - } catch (NoDocumentException ex) { - return true; + if ( !missing ){ + try { + getReferenceMarks(); + } catch (NoDocumentException ex) { + missing = true; + } } - return false; + + if ( missing ){ + // release it + this.mxDoc = null; + this.xCurrentComponent = null; + this.mxDocFactory = null; + this.xText = null; + this.xViewCursorSupplier = null; + this.userProperties = null; + this.propertySet = null; + } + return missing; } /** @@ -936,7 +955,6 @@ public String toString() { NoSuchElementException, WrappedTargetException { - XTextDocument mxDoc; XTextDocument selected; List textDocumentList = getTextDocuments(this.xDesktop); @@ -956,40 +974,9 @@ public String toString() { if (selected == null) { return; } - mxDoc = selected; - - XComponent component = unoQI(XComponent.class, mxDoc); - - unoQI(XDocumentIndexesSupplier.class, component); - - XTextViewCursorSupplier viewCursorSupplier; - - XModel mo = unoQI(XModel.class, component); - XController co = mo.getCurrentController(); - viewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); - - // get a reference to the body text of the document - XText text = mxDoc.getText(); - - // Access the text document's multi service factory: - XMultiServiceFactory mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); - - XPropertyContainer userProperties; - - XDocumentPropertiesSupplier supp = - unoQI(XDocumentPropertiesSupplier.class, mxDoc); - userProperties = supp.getDocumentProperties().getUserDefinedProperties(); - - XPropertySet propertySet = unoQI(XPropertySet.class, userProperties); this.xDocumentConnection = new DocumentConnection( - mxDocFactory, - mxDoc, - text, - viewCursorSupplier, - component, - propertySet, - userProperties, + selected, LOGGER ); From 159143cb62e9bf1e237df72b727e50643d5909f9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 4 Mar 2021 22:53:10 +0100 Subject: [PATCH 0431/1068] DocumentConnection.LOGGER final static, nameAccessGetTextContentByName is static --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1a6631417c0..40430d8e7d2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -135,7 +135,9 @@ private static class DocumentConnection { public XTextViewCursorSupplier xViewCursorSupplier; public XPropertyContainer userProperties; public XPropertySet propertySet; - private final Logger LOGGER; + + private static final Logger LOGGER = + LoggerFactory.getLogger(OOBibBase.DocumentConnection.class); DocumentConnection( XTextDocument mxDoc, @@ -159,8 +161,6 @@ private static class DocumentConnection { supp.getDocumentProperties().getUserDefinedProperties(); this.propertySet = unoQI(XPropertySet.class, userProperties); - - this.LOGGER = LOGGER; } /** @@ -359,9 +359,9 @@ private static class DocumentConnection { } /** - * (this could be static, except for the LOGGER) + * */ - XTextContent + static XTextContent nameAccessGetTextContentByName(XNameAccess nameAccess, String name) throws WrappedTargetException { From 2f68e62c930b9088100a9edc7ad314d2554657c4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 4 Mar 2021 22:54:24 +0100 Subject: [PATCH 0432/1068] getCitationContext back to OOBibBase --- .../org/jabref/gui/openoffice/OOBibBase.java | 151 +++++++++--------- 1 file changed, 77 insertions(+), 74 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 40430d8e7d2..71e704c3fbb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -403,77 +403,6 @@ private static class DocumentConnection { } } - /** - * Get the text belonging to refMarkName with up to - * charBefore and charAfter characters of context. - * - * The actual context may be smaller than requested. - * - * @param refMarkName Name of a reference mark. - * @param charBefore Number of characters requested. - * @param charAfter Number of characters requested. - * @param htmlMarkup If true, the text belonging to the - * reference mark is surrounded by bold html tag. - */ - public String - getCitationContext( - String refMarkName, - int charBefore, - int charAfter, - boolean htmlMarkup) - throws - WrappedTargetException, - NoDocumentException { - - XNameAccess nameAccess = getReferenceMarks(); - XTextContent mark = nameAccessGetTextContentByName(nameAccess, refMarkName); - XTextCursor cursor = getTextCursorOfTextContent(mark); - - String citPart = cursor.getString(); - - // extend cursor range left - int flex = 8; - for (int i = 0; i < charBefore; i++) { - try { - cursor.goLeft((short) 1, true); - // If we are close to charBefore and see a space, - // then cut here. Might avoid cutting a word in half. - if ((i >= (charBefore - flex)) - && Character.isWhitespace(cursor.getString().charAt(0))) { - break; - } - } catch (IndexOutOfBoundsException ex) { - LOGGER.warn("Problem going left", ex); - } - } - - int lengthWithBefore = cursor.getString().length(); - int addedBefore = lengthWithBefore - citPart.length(); - - cursor.collapseToStart(); - for (int i = 0; i < (charAfter + lengthWithBefore); i++) { - try { - cursor.goRight((short) 1, true); - if (i >= ((charAfter + lengthWithBefore) - flex)) { - String strNow = cursor.getString(); - if (Character.isWhitespace(strNow.charAt(strNow.length() - 1))) { - break; - } - } - } catch (IndexOutOfBoundsException ex) { - LOGGER.warn("Problem going right", ex); - } - } - - String result = cursor.getString(); - if (htmlMarkup) { - result = - result.substring(0, addedBefore) - + "" + citPart + "" - + result.substring(lengthWithBefore); - } - return result.trim(); - } /** * Get the cursor positioned by the user. @@ -1166,7 +1095,7 @@ public boolean documentConnectionMissing() { CitationEntry entry = new CitationEntry( name, - documentConnection.getCitationContext(name, 30, 30, true), + this.getCitationContext(documentConnection, name, 30, 30, true), documentConnection.getCustomProperty(name) ); citations.add(entry); @@ -1174,6 +1103,80 @@ public boolean documentConnectionMissing() { return citations; } + /** + * Get the text belonging to refMarkName with up to + * charBefore and charAfter characters of context. + * + * The actual context may be smaller than requested. + * + * @param refMarkName Name of a reference mark. + * @param charBefore Number of characters requested. + * @param charAfter Number of characters requested. + * @param htmlMarkup If true, the text belonging to the + * reference mark is surrounded by bold html tag. + */ + public String + getCitationContext( + DocumentConnection documentConnection, + String refMarkName, + int charBefore, + int charAfter, + boolean htmlMarkup + ) + throws + WrappedTargetException, + NoDocumentException { + + XNameAccess nameAccess = documentConnection.getReferenceMarks(); + XTextContent mark = DocumentConnection.nameAccessGetTextContentByName(nameAccess, refMarkName); + XTextCursor cursor = DocumentConnection.getTextCursorOfTextContent(mark); + + String citPart = cursor.getString(); + + // extend cursor range left + int flex = 8; + for (int i = 0; i < charBefore; i++) { + try { + cursor.goLeft((short) 1, true); + // If we are close to charBefore and see a space, + // then cut here. Might avoid cutting a word in half. + if ((i >= (charBefore - flex)) + && Character.isWhitespace(cursor.getString().charAt(0))) { + break; + } + } catch (IndexOutOfBoundsException ex) { + LOGGER.warn("Problem going left", ex); + } + } + + int lengthWithBefore = cursor.getString().length(); + int addedBefore = lengthWithBefore - citPart.length(); + + cursor.collapseToStart(); + for (int i = 0; i < (charAfter + lengthWithBefore); i++) { + try { + cursor.goRight((short) 1, true); + if (i >= ((charAfter + lengthWithBefore) - flex)) { + String strNow = cursor.getString(); + if (Character.isWhitespace(strNow.charAt(strNow.length() - 1))) { + break; + } + } + } catch (IndexOutOfBoundsException ex) { + LOGGER.warn("Problem going right", ex); + } + } + + String result = cursor.getString(); + if (htmlMarkup) { + result = + result.substring(0, addedBefore) + + "" + citPart + "" + + result.substring(lengthWithBefore); + } + return result.trim(); + } + /** * Apply editable parts of citationEntries to the document. *

@@ -2064,7 +2067,7 @@ public int getOrAllocateNumber(String key) { final String name = referenceMarkNames.get(i); XTextContent mark = - documentConnection.nameAccessGetTextContentByName(nameAccess, name); + DocumentConnection.nameAccessGetTextContentByName(nameAccess, name); XTextCursor cursor = DocumentConnection.getTextCursorOfTextContent(mark); @@ -2558,7 +2561,7 @@ void updateUniqueLetters( for (String name : names) { XTextContent textContent = - documentConnection.nameAccessGetTextContentByName(nameAccess, name); + DocumentConnection.nameAccessGetTextContentByName(nameAccess, name); // unoQI(XTextContent.class, nameAccess.getByName(name)); XTextRange range = textContent.getAnchor(); From 27674bc59ff6363cff1a7fbd8b890a1e390a2af6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 5 Mar 2021 13:35:07 +0100 Subject: [PATCH 0433/1068] refactor: group methods thematically --- .../org/jabref/gui/openoffice/OOBibBase.java | 3112 +++++++++-------- 1 file changed, 1642 insertions(+), 1470 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 71e704c3fbb..5dd18f7d490 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -343,23 +343,8 @@ private static class DocumentConnection { } /** - * Create a text cursor for a textContent. - * - * @return null if mark is null, otherwise cursor. - */ - static XTextCursor - getTextCursorOfTextContent(XTextContent mark) { - if (mark == null) { - return null; - } - XTextRange markAnchor = mark.getAnchor(); - return - markAnchor.getText() - .createTextCursorByRange(markAnchor); - } - - /** - * + * @return null if name not found, or if the result does not + * support the XTextContent interface. */ static XTextContent nameAccessGetTextContentByName(XNameAccess nameAccess, String name) @@ -379,6 +364,23 @@ private static class DocumentConnection { } } + /** + * Create a text cursor for a textContent. + * + * @return null if mark is null, otherwise cursor. + * + */ + static XTextCursor + getTextCursorOfTextContent(XTextContent mark) { + if (mark == null) { + return null; + } + XTextRange markAnchor = mark.getAnchor(); + return + markAnchor.getText() + .createTextCursorByRange(markAnchor); + } + /** * Remove the named reference mark. * @@ -679,6 +681,8 @@ private static class DocumentConnection { * * Used directly (apart from passing around as `uniqueLetters`): * refreshCiteMarkers, rebuildBibTextSection. + * + * Depends on: style, citations and their order. */ private final Map xUniqueLetters = new HashMap<>(); @@ -720,6 +724,12 @@ private static class DocumentConnection { this.xDesktop = simpleBootstrap(loPath); } + /* ***************************** + * + * Establish connection + * + * *****************************/ + private XDesktop simpleBootstrap(Path loPath) throws @@ -745,22 +755,6 @@ private static class DocumentConnection { return result; } - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if available, - * otherwise null - */ - private static T - unoQI( - Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - - /** - * Used by selectDocument - */ private static List getTextDocuments(XDesktop desktop) throws @@ -976,52 +970,168 @@ public boolean documentConnectionMissing() { } } + /* **************************** + * + * Misc + * + * ****************************/ + /** - * The comparator used to sort within a group of merged - * citations. + * unoQI : short for UnoRuntime.queryInterface * - * The term used here is "multicite". The option controlling the - * order is "MultiCiteChronological" in style files. + * @return A reference to the requested UNO interface type if available, + * otherwise null */ - private Comparator - comparatorForMulticite(OOBibStyle style) { - if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { - return this.yearAuthorTitleComparator; - } else { - return this.entryComparator; + private static T + unoQI( + Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + + + /* *************************************** + * + * Storage/retrieve of citations + * + * + * We store some information in the document about + * + * Citations : citation key, pageInfo, citation group. + * Each belongs to exactly one group. + * + * Citation groups (in case of multiple citation keys also + * known as "multicite", "merged citations"): + * + * Which citations belong to the group. + * Range of text owned (where the citation marks go). + * + * From these, the databases and the style we create and update + * the presentation (citation marks) + * + * How: + * database lookup yields: (BibEntry,whichDatabase) + * (UndefinedBibtexEntry,null) if not found + * + * Local order + * presentation order within groups from (style,BibEntry) + * + * Global order: + * visualPosition (for first appearance order) + * bibliography-order + * + * Make them unique + * numbering + * uniqueLetters from (Set, firstAppearanceOrder, style) + * + * + * Bibliography uses parts of the information above: + * citation keys, + * location of citation groups (if ordered and/or numbered by first appearance) + * + * and + * the range of text controlled (storage) + * + * And fills the bibliography (presentation) + * + * **************************************/ + + /** + * Produce a reference mark name for JabRef for the given citation + * key and itcType that does not yet appear among the reference + * marks of the document. + * + * @param bibtexKey The citation key. + * @param itcType Encodes the effect of withText and + * inParenthesis options. + * + * The first occurrence of bibtexKey gets no serial number, the + * second gets 0, the third 1 ... + * + * Or the first unused in this series, after removals. + */ + private String + getUniqueReferenceMarkName( + DocumentConnection documentConnection, + String bibtexKey, + int itcType) + throws NoDocumentException { + + XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); + int i = 0; + String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; + while (xNamedRefMarks.hasByName(name)) { + name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; + i++; } + return name; } /** - * Sort entries within a group of merged citations. + * This is what we get back from parsing a refMarkName. * - * Note: the sort is in-place, modifies the argument. + * TODO: We have one itcType per refMarkName. Merge reduces the + * number of itcType values. */ - private void - sortBibEntryListForMulticite(List entries, - OOBibStyle style) { - if (entries.size() <= 1) { - return; + private static class ParsedRefMark { + /** "", "0", "1" ... */ + public String i; + /** in-text-citation type */ + public int itcType; + /** Citation keys embedded in the reference mark. */ + public List citedKeys; + + ParsedRefMark(String i, int itcType, List citedKeys) { + this.i = i; + this.itcType = itcType; + this.citedKeys = citedKeys; } - entries.sort(comparatorForMulticite(style)); } /** - * Given the withText and inParenthesis options, - * return the corresponding itcType. + * Parse a JabRef reference mark name. + * + * @return Optional.empty() on failure. * - * @param withText False means invisible citation (no text). - * @param inParenthesis True means "(Au and Thor 2000)". - * False means "Au and Thor (2000)". */ - private static int - citationTypeFromOptions(boolean withText, boolean inParenthesis) { - if (!withText) { - return OOBibBase.INVISIBLE_CIT; + private static Optional + parseRefMarkName(String refMarkName) { + + Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); + if (!citeMatcher.find()) { + return Optional.empty(); } - return (inParenthesis - ? OOBibBase.AUTHORYEAR_PAR - : OOBibBase.AUTHORYEAR_INTEXT); + + List keys = Arrays.asList(citeMatcher.group(3).split(",")); + String i = citeMatcher.group(1); + int itcType = Integer.parseInt(citeMatcher.group(2)); + return (Optional.of(new OOBibBase.ParsedRefMark(i, itcType, keys))); + } + + /** + * Extract the list of citation keys from a reference mark name. + * + * @param name The reference mark name. + * @return The list of citation keys encoded in the name. + * + * In case of duplicated citation keys, + * only the first occurrence. + * Otherwise their order is preserved. + * + * If name does not match CITE_PATTERN, + * an empty list of strings is returned. + */ + private List + parseRefMarkNameToUniqueCitationKeys(String name) { + Optional op = parseRefMarkName(name); + return + op.map( + parsedRefMark -> + parsedRefMark.citedKeys.stream() + .distinct() + .collect(Collectors.toList()) + ) + .orElseGet(ArrayList::new); } /** @@ -1064,35 +1174,152 @@ public boolean documentConnectionMissing() { } /** - * Get a list of CitationEntry objects corresponding to citations - * in the document. + * For each name in referenceMarkNames set types[i] and + * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) * - * @return A list with entries corresponding to citations in the - * text, in arbitrary order (same order as from - * getJabRefReferenceMarkNames). + * @param referenceMarkNames Should only contain parsable names. + * @param types OUT Must be same length as referenceMarkNames. + * @param bibtexKeys OUT First level must be same length as referenceMarkNames. + */ + private static void + parseRefMarkNamesToArrays( + List referenceMarkNames, + int[] types, + String[][] bibtexKeys + ) { + final int nRefMarks = referenceMarkNames.size(); + assert (types.length == nRefMarks); + assert (bibtexKeys.length == nRefMarks); + for (int i = 0; i < nRefMarks; i++) { + final String name = referenceMarkNames.get(i); + Optional op = parseRefMarkName(name); + if (op.isEmpty()) { + // We have a problem. We want types[i] and bibtexKeys[i] + // to correspond to referenceMarkNames.get(i). + // And do not want null in bibtexKeys (or error code in types) + // on return. + throw new IllegalArgumentException( + "parseRefMarkNamesToArrays expects parsable referenceMarkNames" + ); + } + ParsedRefMark ov = op.get(); + types[i] = ov.itcType; + bibtexKeys[i] = ov.citedKeys.toArray(String[]::new); + } + } + + /** + * Extract citation keys from names of referenceMarks in the document. * - * TODO: Note: visual or alphabetic order could be more - * manageable for the user. We could provide these - * here, but switching between them needs change on - * GUI (adding a toggle or selector). + * Each citation key is listed only once, in the order of first appearance + * (in `names`, which itself is in arbitrary order) * - * Wish: selecting an entry in the GUI cold move cursor in - * the document. + * doc.referenceMarks.names.map(parse).flatten.unique */ - public List - getCitationEntries() + private List + findCitedKeys(DocumentConnection documentConnection) throws - UnknownPropertyException, + NoSuchElementException, WrappedTargetException, NoDocumentException { - DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - - List names = this.getJabRefReferenceMarkNames(documentConnection); + List names = getJabRefReferenceMarkNames(documentConnection); - List citations = new ArrayList<>(names.size()); - for (String name : names) { - CitationEntry entry = + // assert it supports XTextContent + XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); + for (String name1 : names) { + Object bookmark = xNamedMarks.getByName(name1); + assert (null != unoQI(XTextContent.class, bookmark)); + } + + // Collect to a flat list while keep only the first appearance. + List keys = new ArrayList<>(); + for (String name1 : names) { + List newKeys = parseRefMarkNameToUniqueCitationKeys(name1); + for (String key : newKeys) { + if (!keys.contains(key)) { + keys.add(key); + } + } + } + + return keys; + } + + + /** + * Given the name of a reference mark, get the corresponding + * pageInfo text. + * + * @param documentConnection Connection to a document. + * @param name Name of the custom property to query. + * @return "" for missing or empty pageInfo + */ + private static String + getPageInfoForReferenceMarkName( + DocumentConnection documentConnection, + String name) + throws WrappedTargetException, + UnknownPropertyException { + + Optional pageInfo = documentConnection.getCustomProperty(name); + if (pageInfo.isEmpty() || pageInfo.get().isEmpty()) { + return ""; + } + return pageInfo.get(); + } + + /** + * GUI: Get a list of CitationEntry objects corresponding to citations + * in the document. + * + * Called from: ManageCitationsDialogViewModel constructor. + * + * @return A list with entries corresponding to citations in the + * text, in arbitrary order (same order as from + * getJabRefReferenceMarkNames). + * + * TODO: Note: visual or alphabetic order could be more + * manageable for the user. We could provide these + * here, but switching between them needs change on + * GUI (adding a toggle or selector). + * + * Note: CitationEntry implements Comparable, where + * compareTo() and equals() are based on refMarkName. + * The order used in the "Manage citations" dialog + * does not seem to use that. + * + * In the "Manage citations" dialog, there are 3 columns, + * the 3rd is empty, and has no title. + * + * The 1st is labeled "Citation" (show citation in bold, + * and some context around it). + * + * The columns can be sorted by clicking on the column title. + * For the "Citation" column, the sorting is based on the content, + * (the context before the citation), not on the citation itself. + * + * In the "Extra information ..." column some visual indication + * of the editable part could be helpful. + * + * Wish: selecting an entry (or a button in the line) in + * the GUI could move the cursor in the document to + * the entry. + */ + public List + getCitationEntries() + throws + UnknownPropertyException, + WrappedTargetException, + NoDocumentException { + + DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + + List names = this.getJabRefReferenceMarkNames(documentConnection); + + List citations = new ArrayList<>(names.size()); + for (String name : names) { + CitationEntry entry = new CitationEntry( name, this.getCitationContext(documentConnection, name, 30, 30, true), @@ -1178,7 +1405,14 @@ public boolean documentConnectionMissing() { } /** - * Apply editable parts of citationEntries to the document. + * Apply editable parts of citationEntries to the document: store + * pageInfo. + * + * Does not chaneg presentation. + * + * GUI: "Manage citations" dialog "OK" button. + * Called from: ManageCitationsDialogViewModel.storeSettings + * *

* Currently the only editable part is pageInfo. *

@@ -1216,771 +1450,650 @@ public boolean documentConnectionMissing() { } } - /** - * Produce a reference mark name for JabRef for the given citation - * key and itcType that does not yet appear among the reference - * marks of the document. - * - * @param bibtexKey The citation key. - * @param itcType Encodes the effect of withText and - * inParenthesis options. + /************************************** * - * The first occurrence of bibtexKey gets no serial number, the - * second gets 0, the third 1 ... + * Look up in databases * - * Or the first unused in this series, after removals. + * *************************************/ + + /** + * The collection of data returned by findCitedKeys. */ - private String - getUniqueReferenceMarkName( - DocumentConnection documentConnection, - String bibtexKey, - int itcType) - throws NoDocumentException { + private static class FindCitedEntriesResult { + /** + * entries : LinkedHashMap with iteration order as the + * citedKeys parameter of findCitedEntries + */ + Map entries; - XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); - int i = 0; - String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; - while (xNamedRefMarks.hasByName(name)) { - name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; - i++; + /** + * citeKeyToBibEntry : HashMap (no order) + */ + Map citeKeyToBibEntry; + + FindCitedEntriesResult( + Map entries, + Map citeKeyToBibEntry + ) { + this.entries = entries; + this.citeKeyToBibEntry = citeKeyToBibEntry; } - return name; } /** - * This is what we get back from parsing a refMarkName. + * Look up a single citation key in a list of databases. * - * TODO: We have one itcType per refMarkName. Merge reduces the - * number of itcType values. + * @param key Citation key to look up. + * @param databases Key is looked up in these, in this order. + * @return The BibEntry at the first match, or Optional.empty(). */ - private static class ParsedRefMark { - /** "", "0", "1" ... */ - public String i; - /** in-text-citation type */ - public int itcType; - /** Citation keys embedded in the reference mark. */ - public List citedKeys; - - ParsedRefMark(String i, int itcType, List citedKeys) { - this.i = i; - this.itcType = itcType; - this.citedKeys = citedKeys; + Optional + lookupEntryInDatabases(String key, List databases) { + for (BibDatabase database : databases) { + Optional entry = database.getEntryByCitationKey(key); + if (entry.isPresent()) { + return entry; + } } + return Optional.empty(); } /** - * Parse a JabRef reference mark name. + * Look up a list of citation keys in a list of databases. * - * @return Optional.empty() on failure. + * @param keys Citation keys to look up. + * @param databases Keys are looked up in these, in this order. + * @return The BibEntry objects found. + * + * The order of keys is kept in the result, but unresolved keys + * have no representation in the result, so result.get(i) does not + * necessarily belong to keys.get(i) * */ - private static Optional - parseRefMarkName(String refMarkName) { - - Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); - if (!citeMatcher.find()) { - return Optional.empty(); + List + lookupEntriesInDatabasesSkipMissing( + List keys, + List databases + ) { + List entries = new ArrayList<>(); + for (String key : keys) { + lookupEntryInDatabases(key, databases).ifPresent(entries::add); } - - List keys = Arrays.asList(citeMatcher.group(3).split(",")); - String i = citeMatcher.group(1); - int itcType = Integer.parseInt(citeMatcher.group(2)); - return (Optional.of(new OOBibBase.ParsedRefMark(i, itcType, keys))); + return entries; } /** - * Called from: OpenOfficePanel.pushEntries, a GUI action for - * "Cite", "Cite in-text", "Cite special" and "Insert empty - * citation". + * @return A FindCitedEntriesResult containing * - * This method inserts a reference mark in the text (at the - * cursor) citing the entries, and (if sync is true) refreshes the - * citation markers and the bibliography. + * entries: A LinkedHashMap, from BibEntry to BibDatabase with + * iteration order as the citedKeys parameter. * - * @param entries The entries to cite. + * Stores: in which database was the entry found. * - * @param database The database the entries belong to (all of them). - * Used when creating the citation mark. + * citeKeyToBibEntry: + * A HashMap from citation key to BibEntry. + * Stores: result of lookup. * - * @param allBases Used if sync is true. The list of all databases - * we may need to refresh the document. + * For citation keys not found, a new + * UndefinedBibtexEntry(citedKey) is created and added to both + * maps, with a null BibDatabase. * - * @param style The bibliography style we are using. - * @param inParenthesis Indicates whether it is an in-text - * citation or a citation in parenthesis. - * This is not relevant if - * numbered citations are used. - * @param withText Indicates whether this should be a visible - * citation (true) or an empty (invisible) citation (false). + * How is the result used? * - * @param pageInfo A single page-info for these entries. Stored in custom property - * with the same name as the reference mark. + * entries : Allows to recover the list of keys in original + * order, and finding the corresponding databases. * - * Related https://latex.org/forum/viewtopic.php?t=14331 + * Well, it does, but not by a simple + * entry.getCitationKey(), because + * UndefinedBibtexEntry.getCitationKey() returns + * Optional.empty(). * - * Q: What I would like is something like this: - * (Jones, 2010, p. 12; Smith, 2003, pp. 21 - 23) - * A: Not in a single \citep, no. - * Use \citetext{\citealp[p.~12]{jones2010}; - * \citealp[pp.~21--23]{smith2003}} + * For UndefinedBibtexEntry, + * UndefinedBibtexEntry.getKey() returns the + * original key we stored. * - * @param sync Indicates whether the reference list and in-text citations - * should be refreshed in the document. + * citeKeyToBibEntry: * - * TODO: Group changes into a single Undo context. - * https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html + * Caches the result of lookup performed here, with "not + * found" encoded as an instance of UndefinedBibtexEntry. * - * TODO: centralize inserting a citation group in a way that is - * also suitable for combineCiteMarkers, unCombineCiteMarkers (Is there any other to consider?) */ - public void - insertEntry( - List entries, - BibDatabase database, - List allBases, - OOBibStyle style, - boolean inParenthesis, - boolean withText, - String pageInfo, - boolean sync - ) - throws - IllegalArgumentException, - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - UndefinedCharacterFormatException, - WrappedTargetException, - NoSuchElementException, - PropertyVetoException, - IOException, - CreationException, - BibEntryNotFoundException, - UndefinedParagraphFormatException, - NoDocumentException { - - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - - try { - // Get the cursor positioned by the user. - XTextCursor cursor = documentConnection.getViewCursor(); - - // TODO: (style-dependent) sorting entries for presentation - // affects the storage order of citation keys. - // - (1) presentation order shoudl be decided - // when generating the presentation - // - (2) storage order should keep the order - // provided by the user. - sortBibEntryListForMulticite(entries, style); - - // TODO: consistent handling of citation groups (merged citations). - // keyString generation differs from the one in combineCiteMarkers - // Here we get A,,C for (A,B,C) where could not look up B - // There we get A,C - String keyString = - entries.stream() - .map(entry -> entry.getCitationKey().orElse("")) - .collect(Collectors.joining(",")); - // Generate unique bookmark-name - // TODO: citationType is itcType elsewhere - int citationType = citationTypeFromOptions(withText, inParenthesis); - String newName = getUniqueReferenceMarkName( - documentConnection, - keyString, - citationType); - - // If we should store metadata for page info, do that now: - if (pageInfo != null) { - LOGGER.info("Storing page info: " + pageInfo); - documentConnection.setCustomProperty(newName, pageInfo); - } - // else: branch ??? - // TODO: if (pageInfo is null), we might inadvertently - // pick up a pageInfo from an earlier citation. The user - // may have removed the citation, thus the reference mark, - // but pageInfo stored separately stays there. - - // insert space - cursor - .getText() - .insertString(cursor, " ", false); - - // format the space inserted - if (style.isFormatCitations()) { - String charStyle = style.getCitationCharacterFormat(); - try { - DocumentConnection.setCharStyle(cursor, charStyle); - } catch (UndefinedCharacterFormatException ex) { - // Setting the character format failed, so we - // throw an exception that will result in an - // error message for the user. + private FindCitedEntriesResult + findCitedEntries( + List citedKeys, + List databases + ) { + Map citeKeyToBibEntry = new HashMap<>(); - // Before that, delete the space we inserted: - cursor.goLeft((short) 1, true); - cursor.setString(""); - throw new UndefinedCharacterFormatException(charStyle); + // LinkedHashMap, iteration order as in citedKeys + Map entries = new LinkedHashMap<>(); + for (String citedKey : citedKeys) { + boolean found = false; + for (BibDatabase database : databases) { + Optional entry = database.getEntryByCitationKey(citedKey); + if (entry.isPresent()) { + entries.put(entry.get(), database); + citeKeyToBibEntry.put(citedKey, entry.get()); + found = true; + break; } } - // go back to before the space - cursor.goLeft((short) 1, false); - - // Insert reference mark and text - // { - // Create a BibEntry to BibDatabase map (to make - // style.getCitationMarker happy?) - Map databaseMap = new HashMap<>(); - for (BibEntry entry : entries) { - // Using the same database for each entry. - // Probably the GUI limits selection to a single database. - databaseMap.put(entry, database); - } - - // The text we insert - String citeText = - style.isNumberEntries() - ? "-" // A dash only. Presumably we expect a refresh later. - : style.getCitationMarker( - entries, - databaseMap, - inParenthesis, - null, - null); - insertReferenceMark(documentConnection, newName, citeText, - cursor, withText, style); - // } // end of scope for databaseMap, citeText - - // Move to the right of the space and remember this - // position: we will come back here in the end. - cursor.collapseToEnd(); - cursor.goRight((short) 1, false); - XTextRange position = cursor.getEnd(); - - if (sync) { - // To account for numbering and for uniqueLetters, we - // must refresh the cite markers: - updateSortedReferenceMarks(); - refreshCiteMarkers(allBases, style); - - // Insert it at the current position: - rebuildBibTextSection(allBases, style); + if (!found) { + BibEntry x = new UndefinedBibtexEntry(citedKey); + entries.put(x, null); + citeKeyToBibEntry.put(citedKey, x); + } + } + return new FindCitedEntriesResult(entries, citeKeyToBibEntry); + } - /* - * TODO: inserting a reference in the "References" section - * provokes an "Unknown Source" exception here, because - * position was deleted by rebuildBibTextSection() - * - * at com.sun.proxy.$Proxy44.gotoRange(Unknown Source) - * at org.jabref@100.0.0/org.jabref.gui.openoffice - * .OOBibBase.insertEntry(OOBibBase.java:609) - * - * Idea: Maybe we should refuse to insert in places to be - * overwritten: bibliography, reference marks. - * - * Needs: (preferably accurate) knowledge of the forbidden ranges. - * Limitation: the user can still Cut and Paste to these parts. - * Q: Can we make them readonly inside, while allowing - * to move them around as a unit? - * - */ - // Go back to the relevant position: - try { - cursor.gotoRange(position, false); - } catch (com.sun.star.uno.RuntimeException ex) { - LOGGER.warn("OOBibBase.insertEntry:" - + " Could not go back to end of in-text citation", ex); + /** + * @return The list of citation keys from `instanceof + * UndefinedBibtexEntry` elements of (keys of) `entries`. + * + * Intent: Get list of unresolved citation keys. + */ + private static List + unresolvedKeysFromEntries(Map entries) { + // Collect and return unresolved citation keys. + List unresolvedKeys = new ArrayList<>(); + for (BibEntry entry : entries.keySet()) { + if (entry instanceof UndefinedBibtexEntry) { + String key = ((UndefinedBibtexEntry) entry).getKey(); + if (!unresolvedKeys.contains(key)) { + unresolvedKeys.add(key); } } - } catch (DisposedException ex) { - // We need to catch this one here because the OpenOfficePanel class is - // loaded before connection, and therefore cannot directly reference - // or catch a DisposedException (which is in a OO JAR file). - throw new ConnectionLostException(ex.getMessage()); } + return unresolvedKeys; } - /** - * Extract the list of citation keys from a reference mark name. + /* *************************************** * - * @param name The reference mark name. - * @return The list of citation keys encoded in the name. + * Local order: Presentation order within citation groups * - * In case of duplicated citation keys, - * only the first occurrence. - * Otherwise their order is preserved. + * **************************************/ + + /** + * The comparator used to sort within a group of merged + * citations. * - * If name does not match CITE_PATTERN, - * an empty list of strings is returned. + * The term used here is "multicite". The option controlling the + * order is "MultiCiteChronological" in style files. */ - private List - parseRefMarkNameToUniqueCitationKeys(String name) { - Optional op = parseRefMarkName(name); - return - op.map( - parsedRefMark -> - parsedRefMark.citedKeys.stream() - .distinct() - .collect(Collectors.toList()) - ) - .orElseGet(ArrayList::new); + private Comparator + comparatorForMulticite(OOBibStyle style) { + if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { + return this.yearAuthorTitleComparator; + } else { + return this.entryComparator; + } } /** - * Extract citation keys from names of referenceMarks in the document. - * - * Each citation key is listed only once, in the order of first appearance - * (in `names`, which itself is in arbitrary order) + * Sort entries within a group of merged citations. * - * doc.referenceMarks.names.map(parse).flatten.unique + * Note: the sort is in-place, modifies the argument. */ - private List - findCitedKeys(DocumentConnection documentConnection) - throws - NoSuchElementException, - WrappedTargetException, - NoDocumentException { - - List names = getJabRefReferenceMarkNames(documentConnection); - - // assert it supports XTextContent - XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); - for (String name1 : names) { - Object bookmark = xNamedMarks.getByName(name1); - assert (null != unoQI(XTextContent.class, bookmark)); - } - - // Collect to a flat list while keep only the first appearance. - List keys = new ArrayList<>(); - for (String name1 : names) { - List newKeys = parseRefMarkNameToUniqueCitationKeys(name1); - for (String key : newKeys) { - if (!keys.contains(key)) { - keys.add(key); - } - } + private void + sortBibEntryListForMulticite(List entries, + OOBibStyle style) { + if (entries.size() <= 1) { + return; } - - return keys; + entries.sort(comparatorForMulticite(style)); } + /** - * The collection of data returned by findCitedKeys. + * Look up citation keys from a map caching earlier look up, sort result within + * each reference mark. + * + * @param bibtexKeys Citation keys, bibtexKeys[i][j] is for the ith reference mark. + * @param citeKeyToBibEntry Cached lookup from keys to entries. */ - private static class FindCitedEntriesResult { - /** - * entries : LinkedHashMap with iteration order as the - * citedKeys parameter of findCitedEntries - */ - Map entries; - - /** - * citeKeyToBibEntry : HashMap (no order) - */ - Map citeKeyToBibEntry; - - FindCitedEntriesResult( - Map entries, - Map citeKeyToBibEntry - ) { - this.entries = entries; - this.citeKeyToBibEntry = citeKeyToBibEntry; - } + private BibEntry[][] + getBibEntriesSortedWithinReferenceMarks( + String[][] bibtexKeys, + Map citeKeyToBibEntry, + OOBibStyle style + ) { + return + Arrays.stream(bibtexKeys) + .map(bibtexKeysOfAReferenceMark -> + Arrays.stream(bibtexKeysOfAReferenceMark) + .map(citeKeyToBibEntry::get) + .sorted(comparatorForMulticite(style)) // sort within referenceMark + .toArray(BibEntry[]::new) + ) + .toArray(BibEntry[][]::new); } - /** - * @return A FindCitedEntriesResult containing - * - * entries: A LinkedHashMap, from BibEntry to BibDatabase with - * iteration order as the citedKeys parameter. - * - * Stores: in which database was the entry found. - * - * citeKeyToBibEntry: - * A HashMap from citation key to BibEntry. - * Stores: result of lookup. - * - * For citation keys not found, a new - * UndefinedBibtexEntry(citedKey) is created and added to both - * maps, with a null BibDatabase. - * - * How is the result used? - * - * entries : Allows to recover the list of keys in original - * order, and finding the corresponding databases. - * - * Well, it does, but not by a simple - * entry.getCitationKey(), because - * UndefinedBibtexEntry.getCitationKey() returns - * Optional.empty(). - * - * For UndefinedBibtexEntry, - * UndefinedBibtexEntry.getKey() returns the - * original key we stored. - * - * citeKeyToBibEntry: + /* *************************************** * - * Caches the result of lookup performed here, with "not - * found" encoded as an instance of UndefinedBibtexEntry. + * Global order: by first appearance or by bibliography order * + * **************************************/ + + /* bibliography order */ + + /** + * @return Citation keys from `entries`, ordered as in the bibliography. */ - private FindCitedEntriesResult - findCitedEntries( - List citedKeys, - List databases - ) { - Map citeKeyToBibEntry = new HashMap<>(); + private List + citationKeysOrNullInBibliographyOrderFromEntries( + Map entries + ) { - // LinkedHashMap, iteration order as in citedKeys - Map entries = new LinkedHashMap<>(); - for (String citedKey : citedKeys) { - boolean found = false; - for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(citedKey); - if (entry.isPresent()) { - entries.put(entry.get(), database); - citeKeyToBibEntry.put(citedKey, entry.get()); - found = true; - break; - } - } + // Sort entries to order in bibliography + // Belongs to global order. + Map sortedEntries = + sortEntriesByComparator(entries, entryComparator); - if (!found) { - BibEntry x = new UndefinedBibtexEntry(citedKey); - entries.put(x, null); - citeKeyToBibEntry.put(citedKey, x); - } - } - return new FindCitedEntriesResult(entries, citeKeyToBibEntry); + // Citation keys, in the same order as sortedEntries + return + sortedEntries.keySet().stream() + .map( + entry -> + entry.getCitationKey() + // entries came from looking up by citation key, + // so Optional.empty() is only possible here for UndefinedBibtexEntry. + .orElse(null) + ) + .collect(Collectors.toList()); } /** - * Refresh all citation markers in the document. + * Return a TreeMap(entryComparator) copy of entries. * - * @param databases The databases to get entries from. - * @param style The bibliography style to use. - * @return A list of those referenced citation keys that could not be resolved. + * For sorting the bibliography. */ - public List - refreshCiteMarkers( - List databases, - OOBibStyle style) - throws - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - IOException, - CreationException, - BibEntryNotFoundException, - NoDocumentException { - - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - - try { - return - refreshCiteMarkersInternal( - documentConnection, - databases, - style, - this.xUniqueLetters); - } catch (DisposedException ex) { - // We need to catch this one here because the OpenOfficePanel class is - // loaded before connection, and therefore cannot directly reference - // or catch a DisposedException (which is in a OO JAR file). - throw new ConnectionLostException(ex.getMessage()); + SortedMap + sortEntriesByComparator( + Map entries, + Comparator entryComparator + ) { + SortedMap newMap = new TreeMap<>(entryComparator); + for (Map.Entry kv : entries.entrySet()) { + newMap.put( + kv.getKey(), + kv.getValue()); } + return newMap; } + + /* first appearance order, based on visual order */ + /** - * @return Null if cEntry is an UndefinedBibtexEntry, - * otherwise return cEntry itself. + * Given a location, return its position: + * coordinates relative to the top left position + * of the first page of the document. + * + * @param range Location. + * @param cursor To get the position, we need az XTextViewCursor. + * It will be moved to the range. */ - private static BibEntry - undefinedBibEntryToNull(BibEntry cEntry) { - if (cEntry instanceof UndefinedBibtexEntry) { - return null; - } - return cEntry; + private static Point + findPositionOfTextRange(XTextRange range, XTextViewCursor cursor) { + cursor.gotoRange(range, false); + return cursor.getPosition(); } /** - * Checks that every element of `keys` can be found in `citeKeyToBibEntry`. + * A reference mark name paired with its visual position. * - * Collects the missing keys, and if there is any, throws - * BibEntryNotFoundException (currently mentioning only the first - * missing key). + * Comparison is based on (Y,X): vertical compared first, horizontal second. * - * @param keys An array of citation keys, we expect to appear as - * keys in citeKeyToBibEntry. + * Used for sorting reference marks by their visual positions. + * + * Note: for text layouts with two or more columns, this gives the wrong order. * - * @param citeKeyToBibEntry Should map each key in keys to a BibEntry. - * @param referenceMarkName The reference mark these keys belong to. - * Mentioned in the exception. */ - private static void - assertKeysInCiteKeyToBibEntry( - String[] keys, // citeKeys - Map citeKeyToBibEntry, - String referenceMarkName, // for reporting - String where - ) - throws BibEntryNotFoundException { + private static class ComparableMark implements Comparable { - // check keys - List unresolvedKeys = - Arrays.stream(keys) - .filter(key -> null == citeKeyToBibEntry.get(key)) - .collect(Collectors.toList()); + private final String name; + private final Point position; - for (String key : unresolvedKeys) { - LOGGER.info("assertKeysInCiteKeyToBibEntry: Citation key not found: '" + key + '\''); - LOGGER.info("Problem with reference mark: '" + referenceMarkName + "' " + where); - String msg = - Localization.lang( - "Could not resolve BibTeX entry" - + " for citation marker '%0'.", - referenceMarkName); - throw new BibEntryNotFoundException(referenceMarkName, msg); + public ComparableMark(String name, Point position) { + this.name = name; + this.position = position; } - } - /** - * For each reference mark name: check the corresponding element of - * bibtexKeys with assertKeysInCiteKeyToBibEntry. - */ - private static void - assertAllKeysInCiteKeyToBibEntry( - List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry, - String where - ) - throws BibEntryNotFoundException { - - final int nRefMarks = referenceMarkNames.size(); - assert (nRefMarks == bibtexKeys.length); - - for (int i = 0; i < nRefMarks; i++) { - assertKeysInCiteKeyToBibEntry( - bibtexKeys[i], - citeKeyToBibEntry, - referenceMarkNames.get(i), - where - ); + @Override + public int compareTo(ComparableMark other) { + if (position.Y == other.position.Y) { + return position.X - other.position.X; + } else { + return position.Y - other.position.Y; + } } - } - /** - * Produce citation markers for the case when the citation - * markers are the citation keys themselves, separated by commas. - */ - private static String[] - produceCitationMarkersForIsCitationKeyCiteMarkers( - List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry, - OOBibStyle style - ) - throws BibEntryNotFoundException { - - assert style.isCitationKeyCiteMarkers(); + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } - final int nRefMarks = referenceMarkNames.size(); + if (o instanceof ComparableMark) { + ComparableMark other = (ComparableMark) o; + return ((this.position.X == other.position.X) + && (this.position.Y == other.position.Y) + && Objects.equals(this.name, other.name)); + } + return false; + } - assert nRefMarks == bibtexKeys.length; - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, - "produceCitationMarkersForIsCitationKeyCiteMarkers"); + public String getName() { + return name; + } - String[] citMarkers = new String[nRefMarks]; - for (int i = 0; i < nRefMarks; i++) { - citMarkers[i] = - Arrays.stream(bibtexKeys[i]) - .map(citeKeyToBibEntry::get) - .map(c -> c.getCitationKey().orElse("")) - .collect(Collectors.joining(",")); + @Override + public int hashCode() { + return Objects.hash(position, name); } - return citMarkers; } /** - * Number source for (1-based) numbering of citations. + * Read reference mark names from the document, keep only those + * with JabRef naming convention, get their visual positions, + * + * @return JabRef reference mark names sorted by these positions. + * + * Limitation: for two column layout visual (top-down, + * left-right) order does not match the expected (textual) + * order. + * */ - private static class CitationNumberingState { - /** - * numbers : Remembers keys we have seen - * and what number did they receive. - */ - private final Map numbers; + private List + getJabRefReferenceMarkNamesSortedByPosition( + DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException { - /** - * The highest number we ever allocated. - */ - private int lastNum; + List names = getJabRefReferenceMarkNames(documentConnection); - CitationNumberingState() { - this.numbers = new HashMap<>(); - this.lastNum = 0; - } + // find coordinates + List positions = new ArrayList<>(names.size()); - /** - * The first call returns 1. - */ - public int getOrAllocateNumber(String key) { - int result; - if (numbers.containsKey(key)) { - // Already seen - result = numbers.get(key); - } else { - // First time to see. Allocate number. - lastNum++; - numbers.put(key, lastNum); - result = lastNum; + XNameAccess nameAccess = documentConnection.getReferenceMarks(); + XTextViewCursor viewCursor = documentConnection.getViewCursor(); + // initialPos: to be restored before return + XTextRange initialPos = viewCursor.getStart(); + for (String name : names) { + + XTextContent textContent = + DocumentConnection.nameAccessGetTextContentByName(nameAccess, name); + // unoQI(XTextContent.class, nameAccess.getByName(name)); + + XTextRange range = textContent.getAnchor(); + + // Adjust range if we are inside a footnote: + if (unoQI(XFootnote.class, range.getText()) != null) { + // Find the linking footnote marker: + XFootnote footer = unoQI(XFootnote.class, range.getText()); + // The footnote's anchor gives the correct position in the text: + range = footer.getAnchor(); } - return result; + positions.add(findPositionOfTextRange(range, viewCursor)); + } + // restore cursor position + viewCursor.gotoRange(initialPos, false); + + // order by position + Set set = new TreeSet<>(); + for (int i = 0; i < positions.size(); i++) { + set.add(new ComparableMark(names.get(i), positions.get(i))); + } + + // collect referenceMarkNames in order + List result = new ArrayList<>(set.size()); + for (ComparableMark mark : set) { + result.add(mark.getName()); } + + return result; } /** - * Gets number for a BibEntry. (-1) for UndefinedBibtexEntry + * Refresh list of JabRef reference marks (sorts by position). * - * BibEntry.getCitationKey() must not be Optional.empty(), except - * for UndefinedBibtexEntry. + * Probably should be called at the start of actions from the GUI, + * that rely on jabRefReferenceMarkNamesSortedByPosition to be up-to-date. * + * TODO: maybe we should pass around a fresh copy? */ - private static int - numberPossiblyUndefinedBibEntry( - BibEntry ce, - CitationNumberingState cns - ) { - - if (ce instanceof UndefinedBibtexEntry) { - return (-1); - } + public void + updateSortedReferenceMarks() + throws + WrappedTargetException, + NoSuchElementException, + NoDocumentException { - String key = (ce.getCitationKey() - .orElseThrow(IllegalArgumentException::new)); + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - return cns.getOrAllocateNumber(key); + this.jabRefReferenceMarkNamesSortedByPosition = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); } /** - * Produce citation markers for the case of numbered citations - * with bibliography sorted by first appearance in the text. + * Return bibliography entries sorted according to the order of + * first appearance in referenceMarkNames. * * @param referenceMarkNames Names of reference marks. + * @param citeKeyToBibEntry Helps to find the entries + * @return LinkedHashMap from BibEntry to BibDatabase with + * iteration order as first appearance in referenceMarkNames. * - * @param bibtexKeys Expects bibtexKeys[i] to correspond to - * referenceMarkNames.get(i) - * - * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. - * Must contain all bibtexKeys, - * but may map to UndefinedBibtexEntry. + * Note: Within citation group (a reference mark) the order is + * as appears there. * - * @return Numbered citation markers for bibtexKeys. - * Numbering is according to first encounter - * in bibtexKeys[i][j] + * TODO: The order within a reference mark name is decided on + * construction (in insertEntry). Is it updated after a style change? * */ - private static String[] - produceCitationMarkersForIsNumberEntriesIsSortByPosition( + private Map + sortEntriesByRefMarkNames( List referenceMarkNames, - String[][] bibtexKeys, Map citeKeyToBibEntry, - OOBibStyle style - ) - throws BibEntryNotFoundException { - - assert style.isNumberEntries(); - assert style.isSortByPosition(); - - final int nRefMarks = referenceMarkNames.size(); - assert (nRefMarks == bibtexKeys.length); - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, - "produceCitationMarkersForIsNumberEntriesIsSortByPosition"); - - String[] citMarkers = new String[nRefMarks]; - - CitationNumberingState cns = new CitationNumberingState(); - - final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - - for (int i = 0; i < referenceMarkNames.size(); i++) { + Map entries + ) { + // LinkedHashMap: iteration order is insertion-order, not + // affected if a key is re-inserted. + Map newList = new LinkedHashMap<>(); - // numbers: Numbers for cited sources. (-1) for UndefinedBibtexEntry. - List numbers = - Arrays.stream(bibtexKeys[i]) - .map(citeKeyToBibEntry::get) - .map(ce -> numberPossiblyUndefinedBibEntry(ce, cns)) - .collect(Collectors.toList()); + for (String name : referenceMarkNames) { + Optional op = parseRefMarkName(name); + if (op.isEmpty()) { + continue; + } - citMarkers[i] = - style.getNumCitationMarker(numbers, minGroupingCount, false); + List keys = op.get().citedKeys; + // no need to look in the database again + for (String key : keys) { + BibEntry origEntry = citeKeyToBibEntry.get(key); + if (origEntry != null) { + if (!newList.containsKey(origEntry)) { + BibDatabase database = entries.get(origEntry); + newList.put(origEntry, database); + } + } else { + LOGGER.info("Citation key not found: '" + key + "'"); + LOGGER.info("Problem with reference mark: '" + name + "'"); + newList.put(new UndefinedBibtexEntry(key), null); + } + } } - return citMarkers; + return newList; } - /** - * @return Citation keys from `entries`, ordered as in the bibliography. - */ - private List - citationKeysOrNullInBibliographyOrderFromEntries( - Map entries + /* *************************************** + * + * Make them unique: uniqueLetters or numbers + * + * **************************************/ + + private String[][] + normalizedCitationMarkersForNormalStyle( + BibEntry[][] cEntriesForAll, + Map entries, + OOBibStyle style ) { - // Sort entries to order in bibliography - Map sortedEntries = - sortEntriesByComparator(entries, entryComparator); + final int nRefMarks = cEntriesForAll.length; - // Citation keys, in the same order as sortedEntries - return - sortedEntries.keySet().stream() - .map( - entry -> - entry.getCitationKey() - // entries came from looking up by citation key, - // so Optional.empty() is only possible here for UndefinedBibtexEntry. - .orElse(null) - ) - .collect(Collectors.toList()); + String[][] normCitMarkers = new String[nRefMarks][]; + for (int i = 0; i < nRefMarks; i++) { + BibEntry[] cEntries = cEntriesForAll[i]; + // We need "normalized" (in parenthesis) markers + // for uniqueness checking purposes: + normCitMarkers[i] = + Arrays.stream(cEntries) + .map(ce -> + style.getCitationMarker( + Collections.singletonList(undefinedBibEntryToNull(ce)), + entries, + true, + null, + new int[] {-1} // no limit on authors + ) + ) + .toArray(String[]::new); + } + return normCitMarkers; } /** - * Produce citation markers for the case of numbered citations - * when the bibliography is not sorted by position. + * Given bibtexKeys for each reference mark and the corresponding + * normalized citation markers for each, fills uniqueLetters. + * + * We expect to see data for all JabRef reference marks here, and + * clear uniqueLetters before filling. + * + * On return: uniqueLetters.get(bibtexkey) provides letter to be + * added after the year (null for none). + * + * Note: bibtexKeys[i][j] may be null (from UndefinedBibtexEntry) */ - private String[] - produceCitationMarkersForIsNumberEntriesNotSortByPosition( - List referenceMarkNames, + void updateUniqueLetters( String[][] bibtexKeys, - Map entries, - OOBibStyle style + String[][] normCitMarkers, + final Map uniqueLetters ) { - assert style.isNumberEntries(); - assert !style.isSortByPosition(); - final int nRefMarks = referenceMarkNames.size(); - assert (nRefMarks == bibtexKeys.length); - String[] citMarkers = new String[nRefMarks]; + final int nRefMarks = bibtexKeys.length; + assert nRefMarks == normCitMarkers.length; - List sortedCited = - citationKeysOrNullInBibliographyOrderFromEntries(entries); + // refKeys: (normCitMarker) to (list of citation keys sharing it). + // The entries in the lists are ordered as in + // normCitMarkers[i][j] + Map> refKeys = new HashMap<>(); - final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + for (int i = 0; i < nRefMarks; i++) { + // Compare normalized markers, since the actual + // markers can be different. + String[] markers = normCitMarkers[i]; + for (int j = 0; j < markers.length; j++) { + String marker = markers[j]; + String currentKey = bibtexKeys[i][j]; + // containsKey(null) is OK, contains(null) is OK. + if (refKeys.containsKey(marker)) { + // Ok, we have seen this exact marker before. + if (!refKeys.get(marker).contains(currentKey)) { + // ... but not for this entry. + refKeys.get(marker).add(currentKey); + } + } else { + // add as new entry + List l = new ArrayList<>(1); + l.add(currentKey); + refKeys.put(marker, l); + } + } + } - for (int i = 0; i < referenceMarkNames.size(); i++) { - List numbers = - findCitedEntryIndices( - Arrays.asList(bibtexKeys[i]), - sortedCited - ); - citMarkers[i] = style.getNumCitationMarker(numbers, minGroupingCount, false); + uniqueLetters.clear(); + + // Go through the collected lists and see where we need to + // add unique letters to the year. + for (Map.Entry> stringListEntry : refKeys.entrySet()) { + List clashingKeys = stringListEntry.getValue(); + if (clashingKeys.size() > 1) { + // This marker appears for more than one unique entry: + int nextUniqueLetter = 'a'; + for (String key : clashingKeys) { + // Update the map of uniqueLetters for the + // benefit of both the following generation of + // new citation markers, and for the method + // that builds the bibliography: + uniqueLetters.put(key, String.valueOf((char) nextUniqueLetter)); + nextUniqueLetter++; + } + } } - return citMarkers; + } + + /** + * Number source for (1-based) numbering of citations. + */ + private static class CitationNumberingState { + /** + * numbers : Remembers keys we have seen + * and what number did they receive. + */ + private final Map numbers; + + /** + * The highest number we ever allocated. + */ + private int lastNum; + + CitationNumberingState() { + this.numbers = new HashMap<>(); + this.lastNum = 0; + } + + /** + * The first call returns 1. + */ + public int getOrAllocateNumber(String key) { + int result; + if (numbers.containsKey(key)) { + // Already seen + result = numbers.get(key); + } else { + // First time to see. Allocate number. + lastNum++; + numbers.put(key, lastNum); + result = lastNum; + } + return result; + } + } + + /** + * Gets number for a BibEntry. (-1) for UndefinedBibtexEntry + * + * BibEntry.getCitationKey() must not be Optional.empty(), except + * for UndefinedBibtexEntry. + * + */ + private static int + numberPossiblyUndefinedBibEntry( + BibEntry ce, + CitationNumberingState cns + ) { + + if (ce instanceof UndefinedBibtexEntry) { + return (-1); + } + + String key = (ce.getCitationKey() + .orElseThrow(IllegalArgumentException::new)); + + return cns.getOrAllocateNumber(key); } /** @@ -2011,410 +2124,855 @@ public int getOrAllocateNumber(String key) { return result; } - /** - * Visit each reference mark in referenceMarkNames, remove its - * text content, call insertReferenceMark. - * - * After each insertReferenceMark call check if we lost the - * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. - * - * @param referenceMarkNames Reference mark names + + + /* *************************************** * - * @param citMarkers Corresponding text for each reference mark, - * that replaces the old text. + * Calculate presentation of citation groups + * (create citMarkers) * - * @param types itcType codes for each reference mark. + * **************************************/ + + /** + * Given the withText and inParenthesis options, + * return the corresponding itcType. * - * @param style Bibliography style to use. + * @param withText False means invisible citation (no text). + * @param inParenthesis True means "(Au and Thor 2000)". + * False means "Au and Thor (2000)". */ - private void - applyNewCitationMarkers( - DocumentConnection documentConnection, - List referenceMarkNames, - String[] citMarkers, - int[] types, - OOBibStyle style - ) - throws - NoDocumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - CreationException, - WrappedTargetException, - PropertyVetoException { - - final int nRefMarks = referenceMarkNames.size(); - assert (citMarkers.length == nRefMarks); - assert (types.length == nRefMarks); + private static int + citationTypeFromOptions(boolean withText, boolean inParenthesis) { + if (!withText) { + return OOBibBase.INVISIBLE_CIT; + } + return (inParenthesis + ? OOBibBase.AUTHORYEAR_PAR + : OOBibBase.AUTHORYEAR_INTEXT); + } - XNameAccess nameAccess = - documentConnection.getReferenceMarks(); + /** + * @return Null if cEntry is an UndefinedBibtexEntry, + * otherwise return cEntry itself. + */ + private static BibEntry + undefinedBibEntryToNull(BibEntry cEntry) { + if (cEntry instanceof UndefinedBibtexEntry) { + return null; + } + return cEntry; + } - final boolean hadBibSection = - (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); + /** + * result[i][j] = cEntriesForAll[i][j].getCitationKey() + */ + private String[][] + mapBibEntriesToCitationKeysOrNullForAll(BibEntry[][] cEntriesForAll) { + return + Arrays.stream(cEntriesForAll) + .map(cEntries -> + Arrays.stream(cEntries) + .map(ce -> ce.getCitationKey().orElse(null)) + .toArray(String[]::new) + ) + .toArray(String[][]::new); + } - // If we are supposed to set character format for citations, - // must run a test before we delete old citation - // markers. Otherwise, if the specified character format - // doesn't exist, we end up deleting the markers before the - // process crashes due to a the missing format, with - // catastrophic consequences for the user. - boolean mustTestCharFormat = style.isFormatCitations(); - - for (int i = 0; i < nRefMarks; i++) { - - final String name = referenceMarkNames.get(i); - - XTextContent mark = - DocumentConnection.nameAccessGetTextContentByName(nameAccess, name); - - XTextCursor cursor = - DocumentConnection.getTextCursorOfTextContent(mark); - - if (mustTestCharFormat) { - mustTestCharFormat = false; // need to do this only once - String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(cursor, charStyle); - } - - documentConnection.xText.removeTextContent(mark); - - insertReferenceMark( - documentConnection, - name, - citMarkers[i], - cursor, - types[i] != OOBibBase.INVISIBLE_CIT, - style - ); + /** + * Checks that every element of `keys` can be found in `citeKeyToBibEntry`. + * + * Collects the missing keys, and if there is any, throws + * BibEntryNotFoundException (currently mentioning only the first + * missing key). + * + * @param keys An array of citation keys, we expect to appear as + * keys in citeKeyToBibEntry. + * + * @param citeKeyToBibEntry Should map each key in keys to a BibEntry. + * @param referenceMarkName The reference mark these keys belong to. + * Mentioned in the exception. + */ + private static void + assertKeysInCiteKeyToBibEntry( + String[] keys, // citeKeys + Map citeKeyToBibEntry, + String referenceMarkName, // for reporting + String where + ) + throws BibEntryNotFoundException { - if (hadBibSection - && (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { - // TODO: I think we used a *section* for the - // bibliography elsewhere. Here we use a *bookmark*. Relation? - // applyNewCitationMarkers: - // looks for: Bookmark - // creates: paragraph + Bookmark - // createBibTextSection2: - // creates: paragraph + Section - // clearBibTextSectionContent2: - // looks for: Section, calls createBibTextSection2 - // sets to "": Section - // populateBibTextSection: - // looks for: Section - // insert Bookmark BIB_SECTION_END_NAME - // after the body. + // check keys + List unresolvedKeys = + Arrays.stream(keys) + .filter(key -> null == citeKeyToBibEntry.get(key)) + .collect(Collectors.toList()); - // We have overwritten the marker for the start of the reference list. - // We need to add it again. - cursor.collapseToEnd(); - OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - documentConnection.insertBookmark(OOBibBase.BIB_SECTION_NAME, cursor, true); - cursor.collapseToEnd(); - } + for (String key : unresolvedKeys) { + LOGGER.info("assertKeysInCiteKeyToBibEntry: Citation key not found: '" + key + '\''); + LOGGER.info("Problem with reference mark: '" + referenceMarkName + "' " + where); + String msg = + Localization.lang( + "Could not resolve BibTeX entry" + + " for citation marker '%0'.", + referenceMarkName); + throw new BibEntryNotFoundException(referenceMarkName, msg); } } /** - * For each name in referenceMarkNames set types[i] and - * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) - * - * @param referenceMarkNames Should only contain parsable names. - * @param types OUT Must be same length as referenceMarkNames. - * @param bibtexKeys OUT First level must be same length as referenceMarkNames. + * For each reference mark name: check the corresponding element of + * bibtexKeys with assertKeysInCiteKeyToBibEntry. */ private static void - parseRefMarkNamesToArrays( + assertAllKeysInCiteKeyToBibEntry( List referenceMarkNames, - int[] types, - String[][] bibtexKeys - ) { + String[][] bibtexKeys, + Map citeKeyToBibEntry, + String where + ) + throws BibEntryNotFoundException { + final int nRefMarks = referenceMarkNames.size(); - assert (types.length == nRefMarks); - assert (bibtexKeys.length == nRefMarks); - for (int i = 0; i < nRefMarks; i++) { - final String name = referenceMarkNames.get(i); - Optional op = parseRefMarkName(name); - if (op.isEmpty()) { - // We have a problem. We want types[i] and bibtexKeys[i] - // to correspond to referenceMarkNames.get(i). - // And do not want null in bibtexKeys (or error code in types) - // on return. - throw new IllegalArgumentException( - "parseRefMarkNamesToArrays expects parsable referenceMarkNames" - ); - } - ParsedRefMark ov = op.get(); - types[i] = ov.itcType; - bibtexKeys[i] = ov.citedKeys.toArray(String[]::new); - } - } + assert (nRefMarks == bibtexKeys.length); - /** - * @return The list of citation keys from `instanceof - * UndefinedBibtexEntry` elements of (keys of) `entries`. - * - * Intent: Get list of unresolved citation keys. - */ - private static List - unresolvedKeysFromEntries(Map entries) { - // Collect and return unresolved citation keys. - List unresolvedKeys = new ArrayList<>(); - for (BibEntry entry : entries.keySet()) { - if (entry instanceof UndefinedBibtexEntry) { - String key = ((UndefinedBibtexEntry) entry).getKey(); - if (!unresolvedKeys.contains(key)) { - unresolvedKeys.add(key); - } - } + for (int i = 0; i < nRefMarks; i++) { + assertKeysInCiteKeyToBibEntry( + bibtexKeys[i], + citeKeyToBibEntry, + referenceMarkNames.get(i), + where + ); } - return unresolvedKeys; } /** - * Look up citation keys from a map caching earlier look up, sort result within - * each reference mark. - * - * @param bibtexKeys Citation keys, bibtexKeys[i][j] is for the ith reference mark. - * @param citeKeyToBibEntry Cached lookup from keys to entries. + * Produce citation markers for the case when the citation + * markers are the citation keys themselves, separated by commas. */ - private BibEntry[][] - getBibEntriesSortedWithinReferenceMarks( + private static String[] + produceCitationMarkersForIsCitationKeyCiteMarkers( + List referenceMarkNames, String[][] bibtexKeys, Map citeKeyToBibEntry, OOBibStyle style - ) { - return - Arrays.stream(bibtexKeys) - .map(bibtexKeysOfAReferenceMark -> - Arrays.stream(bibtexKeysOfAReferenceMark) - .map(citeKeyToBibEntry::get) - .sorted(comparatorForMulticite(style)) // sort within referenceMark - .toArray(BibEntry[]::new) - ) - .toArray(BibEntry[][]::new); - } + ) + throws BibEntryNotFoundException { - /** - * result[i][j] = cEntriesForAll[i][j].getCitationKey() - */ - private String[][] - mapBibEntriesToCitationKeysOrNullForAll(BibEntry[][] cEntriesForAll) { - return - Arrays.stream(cEntriesForAll) - .map(cEntries -> - Arrays.stream(cEntries) - .map(ce -> ce.getCitationKey().orElse(null)) - .toArray(String[]::new) - ) - .toArray(String[][]::new); + assert style.isCitationKeyCiteMarkers(); + + final int nRefMarks = referenceMarkNames.size(); + + assert nRefMarks == bibtexKeys.length; + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, + "produceCitationMarkersForIsCitationKeyCiteMarkers"); + + String[] citMarkers = new String[nRefMarks]; + for (int i = 0; i < nRefMarks; i++) { + citMarkers[i] = + Arrays.stream(bibtexKeys[i]) + .map(citeKeyToBibEntry::get) + .map(c -> c.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); + } + return citMarkers; } + /** - * Given bibtexKeys for each reference mark and the corresponding - * normalized citation markers for each, fills uniqueLetters. + * Produce citation markers for the case of numbered citations + * with bibliography sorted by first appearance in the text. * - * We expect to see data for all JabRef reference marks here, and - * clear uniqueLetters before filling. + * @param referenceMarkNames Names of reference marks. * - * On return: uniqueLetters.get(bibtexkey) provides letter to be - * added after the year (null for none). + * @param bibtexKeys Expects bibtexKeys[i] to correspond to + * referenceMarkNames.get(i) + * + * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. + * Must contain all bibtexKeys, + * but may map to UndefinedBibtexEntry. + * + * @return Numbered citation markers for bibtexKeys. + * Numbering is according to first encounter + * in bibtexKeys[i][j] * - * Note: bibtexKeys[i][j] may be null (from UndefinedBibtexEntry) */ - void updateUniqueLetters( + private static String[] + produceCitationMarkersForIsNumberEntriesIsSortByPosition( + List referenceMarkNames, String[][] bibtexKeys, - String[][] normCitMarkers, - final Map uniqueLetters - ) { + Map citeKeyToBibEntry, + OOBibStyle style + ) + throws BibEntryNotFoundException { - final int nRefMarks = bibtexKeys.length; - assert nRefMarks == normCitMarkers.length; + assert style.isNumberEntries(); + assert style.isSortByPosition(); - // refKeys: (normCitMarker) to (list of citation keys sharing it). - // The entries in the lists are ordered as in - // normCitMarkers[i][j] - Map> refKeys = new HashMap<>(); + final int nRefMarks = referenceMarkNames.size(); + assert (nRefMarks == bibtexKeys.length); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, + "produceCitationMarkersForIsNumberEntriesIsSortByPosition"); - for (int i = 0; i < nRefMarks; i++) { - // Compare normalized markers, since the actual - // markers can be different. - String[] markers = normCitMarkers[i]; - for (int j = 0; j < markers.length; j++) { - String marker = markers[j]; - String currentKey = bibtexKeys[i][j]; - // containsKey(null) is OK, contains(null) is OK. - if (refKeys.containsKey(marker)) { - // Ok, we have seen this exact marker before. - if (!refKeys.get(marker).contains(currentKey)) { - // ... but not for this entry. - refKeys.get(marker).add(currentKey); + String[] citMarkers = new String[nRefMarks]; + + CitationNumberingState cns = new CitationNumberingState(); + + final int minGroupingCount = + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + + for (int i = 0; i < referenceMarkNames.size(); i++) { + + // numbers: Numbers for cited sources. (-1) for UndefinedBibtexEntry. + List numbers = + Arrays.stream(bibtexKeys[i]) + .map(citeKeyToBibEntry::get) + .map(ce -> numberPossiblyUndefinedBibEntry(ce, cns)) + .collect(Collectors.toList()); + + citMarkers[i] = + style.getNumCitationMarker(numbers, minGroupingCount, false); + } + return citMarkers; + } + + + /** + * Produce citation markers for the case of numbered citations + * when the bibliography is not sorted by position. + */ + private String[] + produceCitationMarkersForIsNumberEntriesNotSortByPosition( + List referenceMarkNames, + String[][] bibtexKeys, + Map entries, + OOBibStyle style + ) { + assert style.isNumberEntries(); + assert !style.isSortByPosition(); + + final int nRefMarks = referenceMarkNames.size(); + assert (nRefMarks == bibtexKeys.length); + String[] citMarkers = new String[nRefMarks]; + + List sortedCited = + citationKeysOrNullInBibliographyOrderFromEntries(entries); + + final int minGroupingCount = + style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + + for (int i = 0; i < referenceMarkNames.size(); i++) { + List numbers = + findCitedEntryIndices( + Arrays.asList(bibtexKeys[i]), + sortedCited + ); + citMarkers[i] = style.getNumCitationMarker(numbers, minGroupingCount, false); + } + return citMarkers; + } + + + /** + * Produce citMarkers for normal (!isCitationKeyCiteMarkers && ! isNumberEntries) styles. + * + * @param referenceMarkNames Names of reference marks. + * @param bibtexKeysIn Bibtex citation keys. + * @param citeKeyToBibEntry Maps citation keys to BibEntry. + * @param itcTypes Citation types. + * @param entries Map BibEntry to BibDatabase. + * @param uniqueLetters Filled with new values here. + * @param style Bibliography style. + */ + String[] + produceCitationMarkersForNormalStyle( + List referenceMarkNames, + String[][] bibtexKeysIn, + Map citeKeyToBibEntry, + int[] itcTypes, + Map entries, + final Map uniqueLetters, + OOBibStyle style + ) + throws BibEntryNotFoundException { + uniqueLetters.clear(); + + assert !style.isCitationKeyCiteMarkers(); + assert !style.isNumberEntries(); + // Citations in (Au1, Au2 2000) form + + final int nRefMarks = referenceMarkNames.size(); + assert (bibtexKeysIn.length == nRefMarks); + assert (itcTypes.length == nRefMarks); + assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry, + "produceCitationMarkersForNormalStyle"); + + BibEntry[][] cEntriesForAll = + getBibEntriesSortedWithinReferenceMarks(bibtexKeysIn, citeKeyToBibEntry, style); + + // Update bibtexKeys to match the new sorting (within each referenceMark) + String[][] bibtexKeys = mapBibEntriesToCitationKeysOrNullForAll(cEntriesForAll); + // Note: bibtexKeys[i][j] may be null, for UndefinedBibtexEntry + + assert (bibtexKeys.length == nRefMarks); + + String[][] normCitMarkers = + normalizedCitationMarkersForNormalStyle(cEntriesForAll, entries, style); + + updateUniqueLetters(bibtexKeys, normCitMarkers, uniqueLetters); + + // Finally, go through all citation markers, and update + // those referring to entries in our current list: + final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); + Set seenBefore = new HashSet<>(); + + String[] citMarkers = new String[nRefMarks]; + + for (int i = 0; i < nRefMarks; i++) { + + final int nCitedEntries = bibtexKeys[i].length; + int[] firstLimAuthors = new int[nCitedEntries]; + String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; + + for (int j = 0; j < nCitedEntries; j++) { + String currentKey = bibtexKeys[i][j]; // nullable + + // firstLimAuthors will be (-1) except at the first + // refMark it appears at, where a positive + // maxAuthorsFirst may override. This is why: + // https://discourse.jabref.org/t/ + // number-of-authors-in-citations-style-libreoffice/747/3 + // "Some citation styles require to list the full + // names of the first 4 authors for the first + // time. Later it is sufficient to have only maybe + // (Author A and Author B 2019 et al.)" + firstLimAuthors[j] = -1; + if (maxAuthorsFirst > 0) { + if (!seenBefore.contains(currentKey)) { + firstLimAuthors[j] = maxAuthorsFirst; } - } else { - // add as new entry - List l = new ArrayList<>(1); - l.add(currentKey); - refKeys.put(marker, l); + seenBefore.add(currentKey); + } + + String uniqueLetterForKey = uniqueLetters.get(currentKey); + uniqueLetterForCitedEntry[j] = + (uniqueLetterForKey == null + ? "" + : uniqueLetterForKey); + } + + List cEntries = + Arrays.stream(cEntriesForAll[i]) + .map(OOBibBase::undefinedBibEntryToNull) + .collect(Collectors.toList()); + + citMarkers[i] = + style.getCitationMarker( + cEntries, + entries, + itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, + uniqueLetterForCitedEntry, + firstLimAuthors + ); + } + + return citMarkers; + } + + + /* *********************************** + * + * modifies both storage and presentation + * + * ***********************************/ + + /** + * + * Insert a reference mark: creates and fills it. + * + * @param documentConnection Connection to a document. + * + * @param name Name of the reference mark to be created and also + * the name of the custom property holding the pageInfo part. + */ + private void + insertReferenceMark( + DocumentConnection documentConnection, + String name, + String citationText, + XTextCursor position, + boolean withText, + OOBibStyle style + ) + throws + UnknownPropertyException, + WrappedTargetException, + PropertyVetoException, + IllegalArgumentException, + UndefinedCharacterFormatException, + CreationException { + + // Last minute editing: If there is "page info" for this + // citation mark, inject it into the citation marker before + // inserting. + + // TODO: Consider moving pageInfo stuff to citation marker + // generation. May need to modify getCitationMarker, + // at ./jabref/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java492: + // to emit html code. + String citText; + String pageInfo = + getPageInfoForReferenceMarkName(documentConnection, name); + citText = + pageInfo.isEmpty() + ? citationText + : style.insertPageInfo(citationText, pageInfo); + + if (withText) { + position.setString(citText); + DocumentConnection.setCharLocaleNone(position); + if (style.isFormatCitations()) { + String charStyle = style.getCitationCharacterFormat(); + DocumentConnection.setCharStyle(position, charStyle); + } + } else { + position.setString(""); + } + + documentConnection.insertReferenceMark(name, position, true); + + // Last minute editing: find "et al." (OOBibStyle.ET_AL_STRING) and + // format it as italic. + + // Q: Are we sure that OOBibStyle.ET_AL_STRING cannot be part of author names + // in any language? + // A: No, but have no examples either. + + // Q: Are we sure, citText does not contain multiple "et al." strings? + // A: It *can* contain more than one. + + // TODO: Could we move italicizing "et al." to a more proper place? + // Maybe we could use POSTFORMATTER with "..." + // That might make OOBibStyle.ITALIC_ET_AL superfluous. + // Maybe + // insertOOFormattedTextAtCurrentLocation could be used + // to do the insert (if paragraph style manipulation + // is removed) + + // TODO: Handle multiple "et al." strings. + + // Check if we should italicize the "et al." string in citations: + boolean italicize = style.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); + if (italicize) { + String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); + int index = citText.indexOf(etAlString); + if (index >= 0) { + italicizeRangeFromPosition(position, index, index + etAlString.length()); + } + } + + position.collapseToEnd(); + } + + /** + * Taking position.getStart() as a reference point, italicize the range (ref+start,ref+end) + * + * @param position : position.getStart() is out reference point. + * @param start : start of range to italicize w.r.t position.getStart(). + * @param end : end of range to italicize w.r.t position.getStart(). + * + * Why this API? This is used after finding "et al." string in a + * citation marker. + */ + private void + italicizeRangeFromPosition( + XTextCursor position, + int start, + int end + ) + throws + UnknownPropertyException, + PropertyVetoException, + IllegalArgumentException, + WrappedTargetException { + + XTextRange range = position.getStart(); + XTextCursor cursor = position.getText().createTextCursorByRange(range); + cursor.goRight((short) start, false); + cursor.goRight((short) (end - start), true); + + DocumentConnection.setCharFormatItalic(cursor); + } + + /** + * Called from: OpenOfficePanel.pushEntries, a GUI action for + * "Cite", "Cite in-text", "Cite special" and "Insert empty + * citation". + * + * This method inserts a reference mark in the text (at the + * cursor) citing the entries, and (if sync is true) refreshes the + * citation markers and the bibliography. + * + * @param entries The entries to cite. + * + * @param database The database the entries belong to (all of them). + * Used when creating the citation mark. + * + * @param allBases Used if sync is true. The list of all databases + * we may need to refresh the document. + * + * @param style The bibliography style we are using. + * @param inParenthesis Indicates whether it is an in-text + * citation or a citation in parenthesis. + * This is not relevant if + * numbered citations are used. + * @param withText Indicates whether this should be a visible + * citation (true) or an empty (invisible) citation (false). + * + * @param pageInfo A single page-info for these entries. Stored in custom property + * with the same name as the reference mark. + * + * Related https://latex.org/forum/viewtopic.php?t=14331 + * + * Q: What I would like is something like this: + * (Jones, 2010, p. 12; Smith, 2003, pp. 21 - 23) + * A: Not in a single \citep, no. + * Use \citetext{\citealp[p.~12]{jones2010}; + * \citealp[pp.~21--23]{smith2003}} + * + * @param sync Indicates whether the reference list and in-text citations + * should be refreshed in the document. + * + * TODO: Group changes into a single Undo context. + * https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html + * + * TODO: centralize inserting a citation group in a way that is + * also suitable for combineCiteMarkers, unCombineCiteMarkers (Is there any other to consider?) + */ + public void + insertEntry( + List entries, + BibDatabase database, + List allBases, + OOBibStyle style, + boolean inParenthesis, + boolean withText, + String pageInfo, + boolean sync + ) + throws + IllegalArgumentException, + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + UndefinedCharacterFormatException, + WrappedTargetException, + NoSuchElementException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException, + UndefinedParagraphFormatException, + NoDocumentException { + + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + + try { + // Get the cursor positioned by the user. + XTextCursor cursor = documentConnection.getViewCursor(); + + // TODO: (style-dependent) sorting entries for presentation + // affects the storage order of citation keys. + // - (1) presentation order should be decided + // when generating the presentation + // - (2) storage order should keep the order + // provided by the user. + sortBibEntryListForMulticite(entries, style); + + // TODO: consistent handling of citation groups (merged citations). + // keyString generation differs from the one in combineCiteMarkers + // Here we get A,,C for (A,B,C) where could not look up B + // There we get A,C + String keyString = + entries.stream() + .map(entry -> entry.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); + // Generate unique bookmark-name + // TODO: citationType is itcType elsewhere + int citationType = citationTypeFromOptions(withText, inParenthesis); + String newName = + getUniqueReferenceMarkName( + documentConnection, + keyString, + citationType); + + // If we should store metadata for page info, do that now: + if (pageInfo != null) { + LOGGER.info("Storing page info: " + pageInfo); + documentConnection.setCustomProperty(newName, pageInfo); + } + // else: branch ??? + // TODO: if (pageInfo is null), we might inadvertently + // pick up a pageInfo from an earlier citation. The user + // may have removed the citation, thus the reference mark, + // but pageInfo stored separately stays there. + + // insert space + cursor + .getText() + .insertString(cursor, " ", false); + + // format the space inserted + if (style.isFormatCitations()) { + String charStyle = style.getCitationCharacterFormat(); + try { + DocumentConnection.setCharStyle(cursor, charStyle); + } catch (UndefinedCharacterFormatException ex) { + // Setting the character format failed, so we + // throw an exception that will result in an + // error message for the user. + + // Before that, delete the space we inserted: + cursor.goLeft((short) 1, true); + cursor.setString(""); + throw new UndefinedCharacterFormatException(charStyle); + } + } + + // go back to before the space + cursor.goLeft((short) 1, false); + + // Insert reference mark and text + // { + // Create a BibEntry to BibDatabase map (to make + // style.getCitationMarker happy?) + Map databaseMap = new HashMap<>(); + for (BibEntry entry : entries) { + // Using the same database for each entry. + // Probably the GUI limits selection to a single database. + databaseMap.put(entry, database); } - } - } - uniqueLetters.clear(); + // The text we insert + String citeText = + style.isNumberEntries() + ? "-" // A dash only. Presumably we expect a refresh later. + : style.getCitationMarker( + entries, + databaseMap, + inParenthesis, + null, + null); + insertReferenceMark(documentConnection, newName, citeText, + cursor, withText, style); + // } // end of scope for databaseMap, citeText - // Go through the collected lists and see where we need to - // add unique letters to the year. - for (Map.Entry> stringListEntry : refKeys.entrySet()) { - List clashingKeys = stringListEntry.getValue(); - if (clashingKeys.size() > 1) { - // This marker appears for more than one unique entry: - int nextUniqueLetter = 'a'; - for (String key : clashingKeys) { - // Update the map of uniqueLetters for the - // benefit of both the following generation of - // new citation markers, and for the method - // that builds the bibliography: - uniqueLetters.put(key, String.valueOf((char) nextUniqueLetter)); - nextUniqueLetter++; + // Move to the right of the space and remember this + // position: we will come back here in the end. + cursor.collapseToEnd(); + cursor.goRight((short) 1, false); + XTextRange position = cursor.getEnd(); + + if (sync) { + // To account for numbering and for uniqueLetters, we + // must refresh the cite markers: + updateSortedReferenceMarks(); + refreshCiteMarkers(allBases, style); + + // Insert it at the current position: + rebuildBibTextSection(allBases, style); + + /* + * TODO: inserting a reference in the "References" section + * provokes an "Unknown Source" exception here, because + * position was deleted by rebuildBibTextSection() + * + * at com.sun.proxy.$Proxy44.gotoRange(Unknown Source) + * at org.jabref@100.0.0/org.jabref.gui.openoffice + * .OOBibBase.insertEntry(OOBibBase.java:609) + * + * Idea: Maybe we should refuse to insert in places to be + * overwritten: bibliography, reference marks. + * + * Needs: (preferably accurate) knowledge of the forbidden ranges. + * Limitation: the user can still Cut and Paste to these parts. + * Q: Can we make them readonly inside, while allowing + * to move them around as a unit? + * + */ + // Go back to the relevant position: + try { + cursor.gotoRange(position, false); + } catch (com.sun.star.uno.RuntimeException ex) { + LOGGER.warn("OOBibBase.insertEntry:" + + " Could not go back to end of in-text citation", ex); } } + } catch (DisposedException ex) { + // We need to catch this one here because the OpenOfficePanel class is + // loaded before connection, and therefore cannot directly reference + // or catch a DisposedException (which is in a OO JAR file). + throw new ConnectionLostException(ex.getMessage()); } } - private String[][] - normalizedCitationMarkersForNormalStyle( - BibEntry[][] cEntriesForAll, - Map entries, - OOBibStyle style - ) { - final int nRefMarks = cEntriesForAll.length; + /* ************************************************** + * + * modifies both storage and presentation, but should only affect presentation + * + * **************************************************/ - String[][] normCitMarkers = new String[nRefMarks][]; - for (int i = 0; i < nRefMarks; i++) { - BibEntry[] cEntries = cEntriesForAll[i]; - // We need "normalized" (in parenthesis) markers - // for uniqueness checking purposes: - normCitMarkers[i] = - Arrays.stream(cEntries) - .map(ce -> - style.getCitationMarker( - Collections.singletonList(undefinedBibEntryToNull(ce)), - entries, - true, - null, - new int[] {-1} // no limit on authors - ) - ) - .toArray(String[]::new); + + /** + * Refresh all citation markers in the document. + * + * GUI: called as part of "Export cited" + * + * @param databases The databases to get entries from. + * @param style The bibliography style to use. + * @return A list of those referenced citation keys that could not be resolved. + */ + public List + refreshCiteMarkers( + List databases, + OOBibStyle style) + throws + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException, + NoDocumentException { + + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + + try { + return + refreshCiteMarkersInternal( + documentConnection, + databases, + style, + this.xUniqueLetters); + } catch (DisposedException ex) { + // We need to catch this one here because the OpenOfficePanel class is + // loaded before connection, and therefore cannot directly reference + // or catch a DisposedException (which is in a OO JAR file). + throw new ConnectionLostException(ex.getMessage()); } - return normCitMarkers; } + /** - * Produce citMarkers for normal (!isCitationKeyCiteMarkers && ! isNumberEntries) styles. + * Visit each reference mark in referenceMarkNames, remove its + * text content, call insertReferenceMark. * - * @param referenceMarkNames Names of reference marks. - * @param bibtexKeysIn Bibtex citation keys. - * @param citeKeyToBibEntry Maps citation keys to BibEntry. - * @param itcTypes Citation types. - * @param entries Map BibEntry to BibDatabase. - * @param uniqueLetters Filled with new values here. - * @param style Bibliography style. + * After each insertReferenceMark call check if we lost the + * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. + * + * @param referenceMarkNames Reference mark names + * + * @param citMarkers Corresponding text for each reference mark, + * that replaces the old text. + * + * @param types itcType codes for each reference mark. + * + * @param style Bibliography style to use. + * + * TODO: should not modify storage (i.e. call insertReferenceMark) + * TODO: do not mess with bibliography here */ - String[] - produceCitationMarkersForNormalStyle( + private void + applyNewCitationMarkers( + DocumentConnection documentConnection, List referenceMarkNames, - String[][] bibtexKeysIn, - Map citeKeyToBibEntry, - int[] itcTypes, - Map entries, - final Map uniqueLetters, + String[] citMarkers, + int[] types, OOBibStyle style ) - throws BibEntryNotFoundException { - uniqueLetters.clear(); - - assert !style.isCitationKeyCiteMarkers(); - assert !style.isNumberEntries(); - // Citations in (Au1, Au2 2000) form + throws + NoDocumentException, + NoSuchElementException, + UndefinedCharacterFormatException, + UnknownPropertyException, + CreationException, + WrappedTargetException, + PropertyVetoException { final int nRefMarks = referenceMarkNames.size(); - assert (bibtexKeysIn.length == nRefMarks); - assert (itcTypes.length == nRefMarks); - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry, - "produceCitationMarkersForNormalStyle"); - - BibEntry[][] cEntriesForAll = - getBibEntriesSortedWithinReferenceMarks(bibtexKeysIn, citeKeyToBibEntry, style); - - // Update bibtexKeys to match the new sorting (within each referenceMark) - String[][] bibtexKeys = mapBibEntriesToCitationKeysOrNullForAll(cEntriesForAll); - // Note: bibtexKeys[i][j] may be null, for UndefinedBibtexEntry - - assert (bibtexKeys.length == nRefMarks); - - String[][] normCitMarkers = - normalizedCitationMarkersForNormalStyle(cEntriesForAll, entries, style); + assert (citMarkers.length == nRefMarks); + assert (types.length == nRefMarks); - updateUniqueLetters(bibtexKeys, normCitMarkers, uniqueLetters); + XNameAccess nameAccess = + documentConnection.getReferenceMarks(); - // Finally, go through all citation markers, and update - // those referring to entries in our current list: - final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); - Set seenBefore = new HashSet<>(); + final boolean hadBibSection = + (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); - String[] citMarkers = new String[nRefMarks]; + // If we are supposed to set character format for citations, + // must run a test before we delete old citation + // markers. Otherwise, if the specified character format + // doesn't exist, we end up deleting the markers before the + // process crashes due to a the missing format, with + // catastrophic consequences for the user. + boolean mustTestCharFormat = style.isFormatCitations(); for (int i = 0; i < nRefMarks; i++) { - final int nCitedEntries = bibtexKeys[i].length; - int[] firstLimAuthors = new int[nCitedEntries]; - String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; + final String name = referenceMarkNames.get(i); - for (int j = 0; j < nCitedEntries; j++) { - String currentKey = bibtexKeys[i][j]; // nullable + XTextContent mark = + DocumentConnection.nameAccessGetTextContentByName(nameAccess, name); - // firstLimAuthors will be (-1) except at the first - // refMark it appears at, where a positive - // maxAuthorsFirst may override. This is why: - // https://discourse.jabref.org/t/ - // number-of-authors-in-citations-style-libreoffice/747/3 - // "Some citation styles require to list the full - // names of the first 4 authors for the first - // time. Later it is sufficient to have only maybe - // (Author A and Author B 2019 et al.)" - firstLimAuthors[j] = -1; - if (maxAuthorsFirst > 0) { - if (!seenBefore.contains(currentKey)) { - firstLimAuthors[j] = maxAuthorsFirst; - } - seenBefore.add(currentKey); - } + XTextCursor cursor = + DocumentConnection.getTextCursorOfTextContent(mark); - String uniqueLetterForKey = uniqueLetters.get(currentKey); - uniqueLetterForCitedEntry[j] = - (uniqueLetterForKey == null - ? "" - : uniqueLetterForKey); + if (mustTestCharFormat) { + mustTestCharFormat = false; // need to do this only once + String charStyle = style.getCitationCharacterFormat(); + DocumentConnection.setCharStyle(cursor, charStyle); } - List cEntries = - Arrays.stream(cEntriesForAll[i]) - .map(OOBibBase::undefinedBibEntryToNull) - .collect(Collectors.toList()); + documentConnection.xText.removeTextContent(mark); - citMarkers[i] = - style.getCitationMarker( - cEntries, - entries, - itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, - uniqueLetterForCitedEntry, - firstLimAuthors - ); - } + insertReferenceMark( + documentConnection, + name, + citMarkers[i], + cursor, + types[i] != OOBibBase.INVISIBLE_CIT, + style + ); - return citMarkers; + if (hadBibSection + && (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { + // TODO: I think we used a *section* for the + // bibliography elsewhere. Here we use a *bookmark*. Relation? + // applyNewCitationMarkers: + // looks for: Bookmark + // creates: paragraph + Bookmark + // createBibTextSection2: + // creates: paragraph + Section + // clearBibTextSectionContent2: + // looks for: Section, calls createBibTextSection2 + // sets to "": Section + // populateBibTextSection: + // looks for: Section + // insert Bookmark BIB_SECTION_END_NAME + // after the body. + + // We have overwritten the marker for the start of the reference list. + // We need to add it again. + cursor.collapseToEnd(); + OOUtil.insertParagraphBreak(documentConnection.xText, cursor); + documentConnection.insertBookmark(OOBibBase.BIB_SECTION_NAME, cursor, true); + cursor.collapseToEnd(); + } + } } /** @@ -2516,135 +3074,11 @@ void updateUniqueLetters( return unresolvedKeysFromEntries(fce.entries); } - /** - * Given a location, return its position: - * coordinates relative to the top left position - * of the first page of the document. - * - * @param range Location. - * @param cursor To get the position, we need az XTextViewCursor. - * It will be moved to the range. - */ - private static Point - findPositionOfTextRange(XTextRange range, XTextViewCursor cursor) { - cursor.gotoRange(range, false); - return cursor.getPosition(); - } - - /** - * Read reference mark names from the document, keep only those - * with JabRef naming convention, get their visual positions, - * - * @return JabRef reference mark names sorted by these positions. - * - * Limitation: for two column layout visual (top-down, - * left-right) order does not match the expected (textual) - * order. - * - */ - private List - getJabRefReferenceMarkNamesSortedByPosition( - DocumentConnection documentConnection) - throws - WrappedTargetException, - NoDocumentException { - - List names = getJabRefReferenceMarkNames(documentConnection); - - // find coordinates - List positions = new ArrayList<>(names.size()); - - XNameAccess nameAccess = documentConnection.getReferenceMarks(); - XTextViewCursor viewCursor = documentConnection.getViewCursor(); - // initialPos: to be restored before return - XTextRange initialPos = viewCursor.getStart(); - for (String name : names) { - - XTextContent textContent = - DocumentConnection.nameAccessGetTextContentByName(nameAccess, name); - // unoQI(XTextContent.class, nameAccess.getByName(name)); - - XTextRange range = textContent.getAnchor(); - - // Adjust range if we are inside a footnote: - if (unoQI(XFootnote.class, range.getText()) != null) { - // Find the linking footnote marker: - XFootnote footer = unoQI(XFootnote.class, range.getText()); - // The footnote's anchor gives the correct position in the text: - range = footer.getAnchor(); - } - positions.add(findPositionOfTextRange(range, viewCursor)); - } - // restore cursor position - viewCursor.gotoRange(initialPos, false); - - // order by position - Set set = new TreeSet<>(); - for (int i = 0; i < positions.size(); i++) { - set.add(new ComparableMark(names.get(i), positions.get(i))); - } - - // collect referenceMarkNames in order - List result = new ArrayList<>(set.size()); - for (ComparableMark mark : set) { - result.add(mark.getName()); - } - - return result; - } - - /** - * Refresh list of JabRef reference marks (sorts by position). - * - * Probably should be called at the start of actions from the GUI, - * that rely on jabRefReferenceMarkNamesSortedByPosition to be up-to-date. - * - * TODO: maybe we should pass around a fresh copy? - */ - public void - updateSortedReferenceMarks() - throws - WrappedTargetException, - NoSuchElementException, - NoDocumentException { - - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - - this.jabRefReferenceMarkNamesSortedByPosition = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - } - - /** - * GUI action, refreshes citation markers and bibliography. + /* ************************************************** * - * @param databases Must have at least one. - * @param style Style. - * @return List of unresolved citation keys. + * Bibliography: needs uniqueLetters or numbers * - * Note: calls updateSortedReferenceMarks(); - */ - public List - updateDocumentActionHelper( - List databases, - OOBibStyle style) - throws - NoSuchElementException, - WrappedTargetException, - IllegalArgumentException, - CreationException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - NoDocumentException, - UndefinedCharacterFormatException, - BibEntryNotFoundException, - IOException { - - updateSortedReferenceMarks(); - List unresolvedKeys = refreshCiteMarkers(databases, style); - rebuildBibTextSection(databases, style); - return unresolvedKeys; - } + * **************************************************/ /** * Rebuilds the bibliography. @@ -2690,83 +3124,13 @@ void updateUniqueLetters( entries = sortEntriesByComparator(fce.entries, entryComparator); } - clearBibTextSectionContent2(documentConnection); - - populateBibTextSection( - documentConnection, - entries, - style, - this.xUniqueLetters); - } - - /** - * Return a TreeMap(entryComparator) copy of entries. - * - * For sorting the bibliography. - */ - SortedMap - sortEntriesByComparator( - Map entries, - Comparator entryComparator - ) { - SortedMap newMap = new TreeMap<>(entryComparator); - for (Map.Entry kv : entries.entrySet()) { - newMap.put( - kv.getKey(), - kv.getValue()); - } - return newMap; - } - - /** - * Return bibliography entries sorted according to the order of - * first appearance in referenceMarkNames. - * - * @param referenceMarkNames Names of reference marks. - * @param citeKeyToBibEntry Helps to find the entries - * @return LinkedHashMap from BibEntry to BibDatabase with - * iteration order as first appearance in referenceMarkNames. - * - * Note: Within citation group (a reference mark) the order is - * as appears there. - * - * TODO: The order within a reference mark name is decided on - * construction (in insertEntry). Is it updated after a style change? - * - */ - private Map - sortEntriesByRefMarkNames( - List referenceMarkNames, - Map citeKeyToBibEntry, - Map entries - ) { - // LinkedHashMap: iteration order is insertion-order, not - // affected if a key is re-inserted. - Map newList = new LinkedHashMap<>(); - - for (String name : referenceMarkNames) { - Optional op = parseRefMarkName(name); - if (op.isEmpty()) { - continue; - } - - List keys = op.get().citedKeys; - // no need to look in the database again - for (String key : keys) { - BibEntry origEntry = citeKeyToBibEntry.get(key); - if (origEntry != null) { - if (!newList.containsKey(origEntry)) { - BibDatabase database = entries.get(origEntry); - newList.put(origEntry, database); - } - } else { - LOGGER.info("Citation key not found: '" + key + "'"); - LOGGER.info("Problem with reference mark: '" + name + "'"); - newList.put(new UndefinedBibtexEntry(key), null); - } - } - } - return newList; + clearBibTextSectionContent2(documentConnection); + + populateBibTextSection( + documentConnection, + entries, + style, + this.xUniqueLetters); } /** @@ -2981,186 +3345,14 @@ void updateUniqueLetters( cursor.collapseToEnd(); } - /** - * Given the name of a reference mark, get the corresponding - * pageInfo text. - * - * @param documentConnection Connection to a document. - * @param name Name of the custom property to query. - * @return "" for missing or empty pageInfo - */ - private static String - getPageInfoForReferenceMarkName( - DocumentConnection documentConnection, - String name) - throws WrappedTargetException, - UnknownPropertyException { - - Optional pageInfo = documentConnection.getCustomProperty(name); - if (pageInfo.isEmpty() || pageInfo.get().isEmpty()) { - return ""; - } - return pageInfo.get(); - } - - /** - * Insert a reference mark. - * - * @param documentConnection Connection to a document. - * - * @param name Name of the reference mark to be created and also - * the name of the custom property holding the pageInfo part. - */ - private void - insertReferenceMark( - DocumentConnection documentConnection, - String name, - String citationText, - XTextCursor position, - boolean withText, - OOBibStyle style - ) - throws - UnknownPropertyException, - WrappedTargetException, - PropertyVetoException, - IllegalArgumentException, - UndefinedCharacterFormatException, - CreationException { - - // Last minute editing: If there is "page info" for this - // citation mark, inject it into the citation marker before - // inserting. - - // TODO: Consider moving pageInfo stuff to citation marker - // generation. May need to modify getCitationMarker, - // at ./jabref/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java492: - // to emit html code. - String citText; - String pageInfo = - getPageInfoForReferenceMarkName(documentConnection, name); - citText = - pageInfo.isEmpty() - ? citationText - : style.insertPageInfo(citationText, pageInfo); - - if (withText) { - position.setString(citText); - DocumentConnection.setCharLocaleNone(position); - if (style.isFormatCitations()) { - String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(position, charStyle); - } - } else { - position.setString(""); - } - - documentConnection.insertReferenceMark(name, position, true); - - // Last minute editing: find "et al." (OOBibStyle.ET_AL_STRING) and - // format it as italic. - - // Q: Are we sure that OOBibStyle.ET_AL_STRING cannot be part of author names - // in any language? - // A: No, but have no examples either. - - // Q: Are we sure, citText does not contain multiple "et al." strings? - // A: It *can* contain more than one. - - // TODO: Could we move italicizing "et al." to a more proper place? - // Maybe we could use POSTFORMATTER with "..." - // That might make OOBibStyle.ITALIC_ET_AL superfluous. - // Maybe - // insertOOFormattedTextAtCurrentLocation could be used - // to do the insert (if paragraph style manipulation - // is removed) - - // TODO: Handle multiple "et al." strings. - - // Check if we should italicize the "et al." string in citations: - boolean italicize = style.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); - if (italicize) { - String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); - int index = citText.indexOf(etAlString); - if (index >= 0) { - italicizeRangeFromPosition(position, index, index + etAlString.length()); - } - } - - position.collapseToEnd(); - } - /** - * Taking position.getStart() as a reference point, italicize the range (ref+start,ref+end) - * - * @param position : position.getStart() is out reference point. - * @param start : start of range to italicize w.r.t position.getStart(). - * @param end : end of range to italicize w.r.t position.getStart(). + /************************** * - * Why this API? This is used after finding "et al." string in a - * citation marker. - */ - private void - italicizeRangeFromPosition( - XTextCursor position, - int start, - int end - ) - throws - UnknownPropertyException, - PropertyVetoException, - IllegalArgumentException, - WrappedTargetException { - - XTextRange range = position.getStart(); - XTextCursor cursor = position.getText().createTextCursorByRange(range); - cursor.goRight((short) start, false); - cursor.goRight((short) (end - start), true); - - DocumentConnection.setCharFormatItalic(cursor); - } - - /** - * Look up a single citation key in a list of databases. + * GUI level * - * @param key Citation key to look up. - * @param databases Key is looked up in these, in this order. - * @return The BibEntry at the first match, or Optional.empty(). - */ - Optional - lookupEntryInDatabases(String key, List databases) { - for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(key); - if (entry.isPresent()) { - return entry; - } - } - return Optional.empty(); - } + **************************/ - /** - * Look up a list of citation keys in a list of databases. - * - * @param keys Citation keys to look up. - * @param databases Keys are looked up in these, in this order. - * @return The BibEntry objects found. - * - * The order of keys is kept in the result, but unresolved keys - * have no representation in the result, so result.get(i) does not - * necessarily belong to keys.get(i) - * - */ - List - lookupEntriesInDatabasesSkipMissing( - List keys, - List databases - ) { - List entries = new ArrayList<>(); - for (String key : keys) { - lookupEntryInDatabases(key, databases).ifPresent(entries::add); - } - return entries; - } + /* GUI: Manage citations */ /** * GUI action "Merge citations" @@ -3540,57 +3732,37 @@ void updateUniqueLetters( return resultDatabase; } + /** - * A reference mark name paired with its visual position. - * - * Comparison is based on (Y,X): vertical compared first, horizontal second. - * - * Used for sorting reference marks by their visual positions. + * GUI action, refreshes citation markers and bibliography. * - * Note: for text layouts with two or more columns, this gives the wrong order. + * @param databases Must have at least one. + * @param style Style. + * @return List of unresolved citation keys. * + * Note: calls updateSortedReferenceMarks(); */ - private static class ComparableMark implements Comparable { - - private final String name; - private final Point position; - - public ComparableMark(String name, Point position) { - this.name = name; - this.position = position; - } - - @Override - public int compareTo(ComparableMark other) { - if (position.Y == other.position.Y) { - return position.X - other.position.X; - } else { - return position.Y - other.position.Y; - } - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (o instanceof ComparableMark) { - ComparableMark other = (ComparableMark) o; - return ((this.position.X == other.position.X) - && (this.position.Y == other.position.Y) - && Objects.equals(this.name, other.name)); - } - return false; - } - - public String getName() { - return name; - } + public List + updateDocumentActionHelper( + List databases, + OOBibStyle style) + throws + NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException, + PropertyVetoException, + UnknownPropertyException, + UndefinedParagraphFormatException, + NoDocumentException, + UndefinedCharacterFormatException, + BibEntryNotFoundException, + IOException { - @Override - public int hashCode() { - return Objects.hash(position, name); - } + updateSortedReferenceMarks(); + List unresolvedKeys = refreshCiteMarkers(databases, style); + rebuildBibTextSection(databases, style); + return unresolvedKeys; } -} + +} // end of OOBibBase From affc5643eb78e9812629f10e9bdbafa12878fc10 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 6 Mar 2021 15:48:21 +0100 Subject: [PATCH 0434/1068] Even with Settings/Automatically sync.. off, leave recognizabe marks Problem was: - Turn Settings/Automatically sync.. off on OO/LO panel - Select an article, Click Cite - The reference mark created was empty. It turned out, that in OOBibBase.insertReferenceMark position.setString(citText); failed to set the text. Solution was: create a new cursor and use that. --- .../org/jabref/gui/openoffice/OOBibBase.java | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5dd18f7d490..f9fafb20c03 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2527,18 +2527,23 @@ public int getOrAllocateNumber(String key) { ? citationText : style.insertPageInfo(citationText, pageInfo); + /* + * We had a problem here, position.setString() not inserting the text. + * The solution seems to be: create a new cursor (c2), and use that. + */ + XTextCursor c2 = position.getText().createTextCursorByRange(position); if (withText) { - position.setString(citText); - DocumentConnection.setCharLocaleNone(position); + c2.setString(citText); + DocumentConnection.setCharLocaleNone(c2); if (style.isFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(position, charStyle); + DocumentConnection.setCharStyle(c2, charStyle); } } else { - position.setString(""); + c2.setString(""); } - documentConnection.insertReferenceMark(name, position, true); + documentConnection.insertReferenceMark(name, c2, true); // Last minute editing: find "et al." (OOBibStyle.ET_AL_STRING) and // format it as italic. @@ -2566,7 +2571,7 @@ public int getOrAllocateNumber(String key) { String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); int index = citText.indexOf(etAlString); if (index >= 0) { - italicizeRangeFromPosition(position, index, index + etAlString.length()); + italicizeRangeFromPosition(c2, index, index + etAlString.length()); } } @@ -2717,7 +2722,7 @@ public int getOrAllocateNumber(String key) { // may have removed the citation, thus the reference mark, // but pageInfo stored separately stays there. - // insert space + // insert space: we will write our citation before this space. cursor .getText() .insertString(cursor, " ", false); @@ -2756,15 +2761,23 @@ public int getOrAllocateNumber(String key) { // The text we insert String citeText = style.isNumberEntries() - ? "-" // A dash only. Presumably we expect a refresh later. + ? "[-]" // A dash only. Presumably we expect a refresh later. : style.getCitationMarker( entries, databaseMap, inParenthesis, null, null); - insertReferenceMark(documentConnection, newName, citeText, - cursor, withText, style); + if ( citeText == "" ){ + citeText = "[?]"; + } + insertReferenceMark( + documentConnection, + newName, + citeText, + cursor, + withText, + style); // } // end of scope for databaseMap, citeText // Move to the right of the space and remember this From e66028cfa87b7b9da8c9be102d5eb44d3261f3f4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 6 Mar 2021 17:34:23 +0100 Subject: [PATCH 0435/1068] xxx-001 refactor: style check, IDEA suggestions --- .../org/jabref/gui/openoffice/OOBibBase.java | 120 ++++++++++-------- 1 file changed, 67 insertions(+), 53 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f9fafb20c03..dc91bc544ca 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -66,7 +66,6 @@ import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.text.XBookmarksSupplier; -import com.sun.star.text.XDocumentIndexesSupplier; import com.sun.star.text.XFootnote; import com.sun.star.text.XReferenceMarksSupplier; import com.sun.star.text.XText; @@ -92,7 +91,6 @@ */ @AllowedToUseAwt("Requires AWT for italics and bold") class OOBibBase { - private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); private static final String BIB_SECTION_NAME = "JR_bib"; @@ -127,6 +125,9 @@ private static class DocumentConnection { * "CharStyleName" is an OpenOffice Property name. */ private static final String CHAR_STYLE_NAME = "CharStyleName"; + private static final Logger LOGGER = + LoggerFactory.getLogger(OOBibBase.DocumentConnection.class); + public XTextDocument mxDoc; public XComponent xCurrentComponent; @@ -136,12 +137,8 @@ private static class DocumentConnection { public XPropertyContainer userProperties; public XPropertySet propertySet; - private static final Logger LOGGER = - LoggerFactory.getLogger(OOBibBase.DocumentConnection.class); - DocumentConnection( - XTextDocument mxDoc, - Logger LOGGER + XTextDocument mxDoc ) { this.mxDoc = mxDoc; this.xCurrentComponent = unoQI(XComponent.class, mxDoc); @@ -182,7 +179,7 @@ private static class DocumentConnection { } // Attempt to check document is really available - if ( !missing ){ + if (!missing) { try { getReferenceMarks(); } catch (NoDocumentException ex) { @@ -190,7 +187,7 @@ private static class DocumentConnection { } } - if ( missing ){ + if (missing) { // release it this.mxDoc = null; this.xCurrentComponent = null; @@ -347,7 +344,7 @@ private static class DocumentConnection { * support the XTextContent interface. */ static XTextContent - nameAccessGetTextContentByName(XNameAccess nameAccess, String name) + nameAccessGetTextContentByNameOrNull(XNameAccess nameAccess, String name) throws WrappedTargetException { if (!nameAccess.hasByName(name)) { @@ -358,7 +355,7 @@ private static class DocumentConnection { return unoQI(XTextContent.class, referenceMark); } catch (NoSuchElementException ex) { LOGGER.warn(String.format( - "nameAccessGetTextContentByName got NoSuchElementException" + "nameAccessGetTextContentByNameOrNull got NoSuchElementException" + " for '%s'", name)); return null; } @@ -397,7 +394,7 @@ private static class DocumentConnection { if (xReferenceMarks.hasByName(name)) { XTextContent mark = - nameAccessGetTextContentByName(xReferenceMarks, name); + nameAccessGetTextContentByNameOrNull(xReferenceMarks, name); if (mark == null) { return; } @@ -405,7 +402,6 @@ private static class DocumentConnection { } } - /** * Get the cursor positioned by the user. * @@ -415,7 +411,6 @@ private static class DocumentConnection { return this.xViewCursorSupplier.getViewCursor(); } - /** * Get the XTextRange corresponding to the named bookmark. * @@ -423,17 +418,32 @@ private static class DocumentConnection { * @return The XTextRange for the bookmark, or null. */ public XTextRange - getBookmarkRange(String name) + getBookmarkRangeOrNull(String name) + throws + WrappedTargetException { + + XNameAccess nameAccess = this.getBookmarks(); + XTextContent textContent = + nameAccessGetTextContentByNameOrNull(nameAccess, name); + if (textContent == null) { + return null; + } + return textContent.getAnchor(); + } + + public XTextRange + getReferenceMarkRangeOrNull(String name) throws + NoDocumentException, WrappedTargetException { - XNameAccess xNamedBookmarks = this.getBookmarks(); - XTextContent xFoundBookmark = - nameAccessGetTextContentByName(xNamedBookmarks, name); - if (xFoundBookmark == null) { + XNameAccess nameAccess = this.getReferenceMarks(); + XTextContent textContent = + nameAccessGetTextContentByNameOrNull(nameAccess, name); + if (textContent == null) { return null; } - return xFoundBookmark.getAnchor(); + return textContent.getAnchor(); } /** @@ -522,7 +532,8 @@ private static class DocumentConnection { } /** - * Insert a bookmark with the given name at the cursor provided. + * 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. * * @param name For the bookmark. * @param range Cursor marking the location or range for @@ -878,7 +889,6 @@ public String toString() { NoSuchElementException, WrappedTargetException { - XTextDocument selected; List textDocumentList = getTextDocuments(this.xDesktop); if (textDocumentList.isEmpty()) { @@ -898,16 +908,8 @@ public String toString() { return; } - this.xDocumentConnection = new DocumentConnection( - selected, - LOGGER - ); + this.xDocumentConnection = new DocumentConnection(selected); - // TODO: maybe we should install an event handler for document - // close: addCloseListener - // Reference: - // https://www.openoffice.org/api/docs/common/ref/com/sun/star/ - // util/XCloseBroadcaster.html#addCloseListener } /** @@ -989,7 +991,6 @@ public boolean documentConnectionMissing() { return UnoRuntime.queryInterface(zInterface, object); } - /* *************************************** * * Storage/retrieve of citations @@ -1246,7 +1247,6 @@ private static class ParsedRefMark { return keys; } - /** * Given the name of a reference mark, get the corresponding * pageInfo text. @@ -1355,7 +1355,16 @@ private static class ParsedRefMark { NoDocumentException { XNameAccess nameAccess = documentConnection.getReferenceMarks(); - XTextContent mark = DocumentConnection.nameAccessGetTextContentByName(nameAccess, refMarkName); + XTextContent mark = + DocumentConnection.nameAccessGetTextContentByNameOrNull(nameAccess, refMarkName); + if (null == mark) { + LOGGER.warn(String.format( + "OOBibBase.getCitationContext:" + + " lost reference mark: '%s'", + refMarkName + )); + return String.format("(Could not retrieve context for %s)", refMarkName); + } XTextCursor cursor = DocumentConnection.getTextCursorOfTextContent(mark); String citPart = cursor.getString(); @@ -1450,7 +1459,7 @@ private static class ParsedRefMark { } } - /************************************** + /* ************************************* * * Look up in databases * @@ -1645,7 +1654,6 @@ private static class FindCitedEntriesResult { entries.sort(comparatorForMulticite(style)); } - /** * Look up citation keys from a map caching earlier look up, sort result within * each reference mark. @@ -1723,7 +1731,6 @@ private static class FindCitedEntriesResult { return newMap; } - /* first appearance order, based on visual order */ /** @@ -1825,8 +1832,16 @@ public int hashCode() { for (String name : names) { XTextContent textContent = - DocumentConnection.nameAccessGetTextContentByName(nameAccess, name); + DocumentConnection.nameAccessGetTextContentByNameOrNull(nameAccess, name); // unoQI(XTextContent.class, nameAccess.getByName(name)); + if (null == textContent) { + LOGGER.warn(String.format( + "OOBibBase.getJabRefReferenceMarkNames:" + + " could not retrieve reference mark: '%s'", + name + )); + continue; // just skip it + } XTextRange range = textContent.getAnchor(); @@ -2124,8 +2139,6 @@ public int getOrAllocateNumber(String key) { return result; } - - /* *************************************** * * Calculate presentation of citation groups @@ -2277,7 +2290,6 @@ public int getOrAllocateNumber(String key) { return citMarkers; } - /** * Produce citation markers for the case of numbered citations * with bibliography sorted by first appearance in the text. @@ -2335,7 +2347,6 @@ public int getOrAllocateNumber(String key) { return citMarkers; } - /** * Produce citation markers for the case of numbered citations * when the bibliography is not sorted by position. @@ -2478,7 +2489,6 @@ public int getOrAllocateNumber(String key) { return citMarkers; } - /* *********************************** * * modifies both storage and presentation @@ -2768,7 +2778,7 @@ public int getOrAllocateNumber(String key) { inParenthesis, null, null); - if ( citeText == "" ){ + if (citeText.equals("")) { citeText = "[?]"; } insertReferenceMark( @@ -2829,14 +2839,12 @@ public int getOrAllocateNumber(String key) { } } - /* ************************************************** * * modifies both storage and presentation, but should only affect presentation * * **************************************************/ - /** * Refresh all citation markers in the document. * @@ -2879,7 +2887,6 @@ public int getOrAllocateNumber(String key) { } } - /** * Visit each reference mark in referenceMarkNames, remove its * text content, call insertReferenceMark. @@ -2924,7 +2931,7 @@ public int getOrAllocateNumber(String key) { documentConnection.getReferenceMarks(); final boolean hadBibSection = - (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null); + (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) != null); // If we are supposed to set character format for citations, // must run a test before we delete old citation @@ -2939,7 +2946,15 @@ public int getOrAllocateNumber(String key) { final String name = referenceMarkNames.get(i); XTextContent mark = - DocumentConnection.nameAccessGetTextContentByName(nameAccess, name); + DocumentConnection.nameAccessGetTextContentByNameOrNull(nameAccess, name); + if (null == mark) { + LOGGER.warn(String.format( + "OOBibBase.applyNewCitationMarkers:" + + " lost reference mark '%s'", + name + )); + continue; + } XTextCursor cursor = DocumentConnection.getTextCursorOfTextContent(mark); @@ -2962,7 +2977,7 @@ public int getOrAllocateNumber(String key) { ); if (hadBibSection - && (documentConnection.getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { + && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { // TODO: I think we used a *section* for the // bibliography elsewhere. Here we use a *bookmark*. Relation? // applyNewCitationMarkers: @@ -3358,8 +3373,7 @@ public int getOrAllocateNumber(String key) { cursor.collapseToEnd(); } - - /************************** + /* ************************* * * GUI level * @@ -3745,7 +3759,6 @@ public int getOrAllocateNumber(String key) { return resultDatabase; } - /** * GUI action, refreshes citation markers and bibliography. * @@ -3771,6 +3784,7 @@ public int getOrAllocateNumber(String key) { UndefinedCharacterFormatException, BibEntryNotFoundException, IOException { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); updateSortedReferenceMarks(); List unresolvedKeys = refreshCiteMarkers(databases, style); From a5f27cf4c76981efd66705c71f2f10c27771c0fa Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 6 Mar 2021 23:32:36 +0100 Subject: [PATCH 0436/1068] add getCustomPropertyNames --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index dc91bc544ca..20b44489b6c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -40,6 +40,7 @@ import com.sun.star.awt.Point; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.Property; import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; @@ -208,6 +209,20 @@ private static class DocumentConnection { return OOBibBase.getDocumentTitle(this.mxDoc); } + List + getCustomPropertyNames() { + assert (this.propertySet != null); + + XPropertySetInfo psi = (this.propertySet + .getPropertySetInfo()); + + List names = new ArrayList<>(); + for (Property p : psi.getProperties()) { + names.add(p.Name); + } + return names; + } + /** * @param property Name of a custom document property in the * current document. From 7f6d96017129d1e869c8e6ac6338dc7d00dddbe8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 6 Mar 2021 23:33:04 +0100 Subject: [PATCH 0437/1068] add getFootnoteMarkRangeOrNull --- .../org/jabref/gui/openoffice/OOBibBase.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 20b44489b6c..847a75b66fb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -618,6 +618,24 @@ private static class DocumentConnection { .getObject()); } + /** + * If original is in a footnote, return a range containing + * the corresponding footnote marker. + * + * Returns null if not in a footnote. + */ + static XTextRange + getFootnoteMarkRangeOrNull(XTextRange original) { + // If we are inside a footnote: + if (unoQI(XFootnote.class, original.getText()) != null) { + // Find the linking footnote marker: + XFootnote footer = unoQI(XFootnote.class, original.getText()); + // The footnote's anchor gives the correct position in the text: + return footer.getAnchor(); + } + return null; + } + /** * Apply a character style to a range of text selected by a * cursor. From ef433c33c089f67e7c91345c891687b95dd0a0e1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 6 Mar 2021 23:34:42 +0100 Subject: [PATCH 0438/1068] class CitationGroups, now has checkRangeOverlaps --- .../org/jabref/gui/openoffice/OOBibBase.java | 326 ++++++++++++++++++ 1 file changed, 326 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 847a75b66fb..17c197260af 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -23,6 +23,7 @@ import org.jabref.architecture.AllowedToUseAwt; import org.jabref.gui.DialogService; +import org.jabref.logic.JabRefException; import org.jabref.logic.bibtex.comparator.FieldComparator; import org.jabref.logic.bibtex.comparator.FieldComparatorStack; import org.jabref.logic.l10n.Localization; @@ -1302,6 +1303,331 @@ private static class ParsedRefMark { return pageInfo.get(); } + /* + * At the start of GUI actions we may want to check the state of the document. + */ + class CitationGroups { + private final Map indexByName; + private final String[] names; + // After parsing + private final int[] itcTypes; + private final String[][] citationKeys; + + // Probably wrong, but currently pageInfo belongs to the group + private final String[] pageInfo; + + // For custom properties belonging to us, but + // without a corresponding reference mark. + // These can be deleted. + private List pageInfoThrash; + + // After database lookup: + // private BibEntry[][] entries; + // private BibDatabase[][] entryDatabases; + + public CitationGroups(DocumentConnection documentConnection) + throws NoDocumentException { + // Get the names + this.names = + getJabRefReferenceMarkNames(documentConnection) + .toArray(String[]::new); + + // Fill indexByName + this.indexByName = new HashMap<>(); + for (int i = 0; i < this.names.length; i++) { + indexByName.put(names[i], i); + } + // collect pageInfo + this.pageInfo = new String[names.length]; + List jabrefPropertyNames = + documentConnection.getCustomPropertyNames() + .stream() + .filter(OOBibBase::isJabRefReferenceMarkName) + .collect(Collectors.toList()); + // For each name: either put into place or + // put into thrash collector. + this.pageInfoThrash = new ArrayList<>(); + for (String n : jabrefPropertyNames) { + if (indexByName.containsKey(n)) { + int i = indexByName.get(n); + pageInfo[i] = n; + } else { + pageInfoThrash.add(n); + } + } + // parse names + this.itcTypes = new int[names.length]; + this.citationKeys = new String[names.length][]; + for (int i = 0; i < names.length; i++) { + final String name = names[i]; + Optional op = parseRefMarkName(name); + if (op.isEmpty()) { + // We have a problem. We want types[i] and bibtexKeys[i] + // to correspond to referenceMarkNames.get(i). + // And do not want null in bibtexKeys (or error code in types) + // on return. + throw new IllegalArgumentException( + "citationGroups: found unparsable referenceMarkName" + ); + } + ParsedRefMark ov = op.get(); + itcTypes[i] = ov.itcType; + citationKeys[i] = ov.citedKeys.toArray(String[]::new); + } + // Now we have almost every information from the document about citations. + // What is left out: the ranges controlled by the reference marks. + // But (I guess) those change too easily, so we only ask when actually needed. + } + + /* + * ranges controlled by citation groups should not overlap with each other. + * + * + */ + public XTextRange + getReferenceMarkRangeOrNull(DocumentConnection documentConnection, int i) + throws + NoDocumentException, + WrappedTargetException { + return documentConnection.getReferenceMarkRangeOrNull(names[i]); + } + + class RangeForOverlapCheck { + final static int REFERENCE_MARK_KIND = 0; + final static int FOOTNOTE_MARK_KIND = 1; + + XTextRange range; + int i; + int kind; + String description; + + RangeForOverlapCheck(XTextRange range, int i, int kind, String description) { + this.range = range; + this.i = i; + this.kind = kind; + this.description = description; + } + + String format() { + return description; + // String[] prefixes = { "", "FootnoteMark for " } ; + // return prefixes[kind] + names[ this.i ]; + } + + } // class X + + /** + * Assumes a.getText() == b.getText(), and both belong to documentConnection.xText + */ + public int + compareRegionStarts(RangeForOverlapCheck a, + RangeForOverlapCheck b) { + // + // XTextRange cannot be compared, only == or != is available. + // + // XTextRangeCompare: compares the positions of two TextRanges within a Text. + // Only TextRange instances within the same Text can be compared. + // final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + // documentConnection.xText); + + XTextRange ra = a.range; + XTextRange rb = b.range; + if (ra.getText() != rb.getText()) { + throw new RuntimeException( + String.format( + "OOBibBase.CitationGroups.compareRegionStarts:" + + " incomparable regions: %s %s", + a.format(), + b.format()) + ); + } + + /* + * documentConnection.xText cannot compare two ranges in + * the same footnote. We must use XTextRangeCompare interface + * of the ranges themselves. + */ + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + ra.getText()); + + try { + return (-1) * compare.compareRegionStarts(ra, rb); + } catch (IllegalArgumentException ex) { + throw new RuntimeException( + String.format( + "OOBibBase.CitationGroups.compareRegionStarts:" + + " caught IllegalArgumentException: %s %s", + a.format(), + b.format() + ) + ); + } + } + + public int + compareRegionEndToStart(RangeForOverlapCheck a, + RangeForOverlapCheck b) { + + XTextRange ra = a.range.getEnd(); + XTextRange rb = b.range.getStart(); + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + ra.getText()); + return (-1) * compare.compareRegionStarts(ra, rb); + } + + /** + * @return A RangeForOverlapCheck for each citation group. + */ + List + citationRanges(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + List xs = new ArrayList<>(names.length); + for (int i = 0; i < names.length; i++) { + XTextRange r = this.getReferenceMarkRangeOrNull(documentConnection, i); + xs.add(new RangeForOverlapCheck( + r, i, + RangeForOverlapCheck.REFERENCE_MARK_KIND, + names[i] + )); + } + return xs; + } + + /** + * @return A range for each footnote mark where the footnote + * contains at least one citation group. + * + * Purpose: We do not want markers of footnotes containing + * reference marks to overlap with reference + * marks. Overwriting these footnote marks might kill our + * reference marks in the footnote. + * + */ + List + footnoteMarkRanges(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + // Avoid inserting the same mark twice. + List seen = new ArrayList<>(); + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + documentConnection.xText); + + List xs = new ArrayList<>(); + for (int i = 0; i < names.length; i++) { + XTextRange r = this.getReferenceMarkRangeOrNull(documentConnection, i); + XTextRange footnoteMarkRange = + DocumentConnection.getFootnoteMarkRangeOrNull(r); + + if (footnoteMarkRange != null) { + // Problem: quadratic complexity. Each new footnoteMarkRange + // is compared to all we have seen before. + boolean seenContains = false; + for (XTextRange s : seen) { + if (s.getText() == footnoteMarkRange.getText() && + compare.compareRegionStarts(s, footnoteMarkRange) == 0 && + compare.compareRegionEnds(s, footnoteMarkRange) == 0) { + seenContains = true; + break; + } + } + if (!seenContains) { + seen.add(footnoteMarkRange); + xs.add(new RangeForOverlapCheck( + footnoteMarkRange, + i, // index of citation group + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + names[i] + )); + } + } + } + return xs; + } + + private Map> + partitionByGetText(List xs) { + Map> xxs = new HashMap<>(); + for (RangeForOverlapCheck x : xs) { + XTextRange xr = x.range; + XText t = xr.getText(); + if (xxs.containsKey(t)) { + xxs.get(t).add(x); + } else { + xxs.put(t, new ArrayList<>(List.of(x))); + } + } + return xxs; + } + + private List + sortPartitionByRegionStart(List xs) { + return + xs.stream() + .sorted(this::compareRegionStarts) + .collect(Collectors.toList()); + } + + private void + checkSortedPartitionForOverlap(boolean requireSeparation, + List oxs) + throws JabRefException { + for (int i = 0; (i + 1) < oxs.size(); i++) { + RangeForOverlapCheck a = oxs.get(i); + RangeForOverlapCheck b = oxs.get(i + 1); + int cmp = compareRegionEndToStart(a, b); + if (cmp > 0) { + // found overlap + throw new JabRefException( + "Range overlap found", + Localization.lang( + "Ranges of '%0' and '%1' overlap", a.format(), b.format()) + ); + } + if (requireSeparation && cmp == 0) { + throw new JabRefException( + "Ranges with no gap found", + Localization.lang( + "Ranges of '%0' and '%1' are not separated", + a.format(), b.format()) + ); + } + } + } + + public void + checkRangeOverlaps(DocumentConnection documentConnection, + boolean requireSeparation) + throws + NoDocumentException, + WrappedTargetException, + JabRefException { + + List xs = citationRanges(documentConnection); + xs.addAll(footnoteMarkRanges(documentConnection)); + + // We can only compare ranges with equal .getText(), + // so partition the list. + Map> xxs = partitionByGetText(xs); + // Sort xs by x.getText() and x.getStart() + // Then, within each getText() value, we need x[i].getEnd() <= x[i+1].getStart() + // final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + // documentConnection.xText); + for (List partition : xxs.values()) { + List oxs = + sortPartitionByRegionStart(partition); + System.out.println("partition"); + for (RangeForOverlapCheck r : oxs) { + System.out.println(" " + r.format()); + } + checkSortedPartitionForOverlap(requireSeparation, oxs); + } + } + } // class citationGroups + /** * GUI: Get a list of CitationEntry objects corresponding to citations * in the document. From a7bb466878a743931c49eb22fb67476d962ae50f Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 6 Mar 2021 23:35:22 +0100 Subject: [PATCH 0439/1068] call checkRangeOverlaps in updateDocumentActionHelper, catch JabRefException in update.setOnAction --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 7 ++++++- .../java/org/jabref/gui/openoffice/OpenOfficePanel.java | 6 ++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 17c197260af..31b9cf7e0ec 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4142,8 +4142,13 @@ public int getOrAllocateNumber(String key) { NoDocumentException, UndefinedCharacterFormatException, BibEntryNotFoundException, - IOException { + IOException, + JabRefException { + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + boolean requireSeparation = false; // may loose citation without requireSeparation=true + CitationGroups cg = new CitationGroups(documentConnection); + cg.checkRangeOverlaps(this.xDocumentConnection, requireSeparation); updateSortedReferenceMarks(); List unresolvedKeys = refreshCiteMarkers(databases, style); diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index f1b8ab96ce3..2c3ace6ce53 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -40,6 +40,7 @@ import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.gui.util.TaskExecutor; +import org.jabref.logic.JabRefException; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.help.HelpFile; @@ -209,6 +210,11 @@ private void initPanel() { unresolvedKeys.get(0)) ); } + } catch (JabRefException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("JabRefException"), + ex.getLocalizedMessage() + ); } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); } catch (UndefinedParagraphFormatException ex) { From 76f4ed07c4e9f4da0ee2cbe0ea4019c9e19e538f Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 8 Mar 2021 10:04:34 +0100 Subject: [PATCH 0440/1068] refactor: cleanup notes --- .../org/jabref/gui/openoffice/OOBibBase.java | 161 +++--------------- 1 file changed, 22 insertions(+), 139 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 31b9cf7e0ec..20f3a06f223 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -949,7 +949,6 @@ public String toString() { /** * Mark the current document as missing. * - * TODO: GUI should be notified */ private void forgetDocument() { @@ -1105,8 +1104,6 @@ public boolean documentConnectionMissing() { /** * This is what we get back from parsing a refMarkName. * - * TODO: We have one itcType per refMarkName. Merge reduces the - * number of itcType values. */ private static class ParsedRefMark { /** "", "0", "1" ... */ @@ -1638,7 +1635,7 @@ String format() { * text, in arbitrary order (same order as from * getJabRefReferenceMarkNames). * - * TODO: Note: visual or alphabetic order could be more + * Note: visual or alphabetic order could be more * manageable for the user. We could provide these * here, but switching between them needs change on * GUI (adding a toggle or selector). @@ -1648,9 +1645,6 @@ String format() { * The order used in the "Manage citations" dialog * does not seem to use that. * - * In the "Manage citations" dialog, there are 3 columns, - * the 3rd is empty, and has no title. - * * The 1st is labeled "Citation" (show citation in bold, * and some context around it). * @@ -1813,8 +1807,6 @@ String format() { entry.getRefMarkName(), pageInfo.get()); } - // TODO: if pageInfo is not present, or is empty: - // maybe we should remove it from the document. } } @@ -2236,8 +2228,6 @@ public int hashCode() { * * Probably should be called at the start of actions from the GUI, * that rely on jabRefReferenceMarkNamesSortedByPosition to be up-to-date. - * - * TODO: maybe we should pass around a fresh copy? */ public void updateSortedReferenceMarks() @@ -2264,9 +2254,6 @@ public int hashCode() { * Note: Within citation group (a reference mark) the order is * as appears there. * - * TODO: The order within a reference mark name is decided on - * construction (in insertEntry). Is it updated after a style change? - * */ private Map sortEntriesByRefMarkNames( @@ -2884,10 +2871,6 @@ public int getOrAllocateNumber(String key) { // citation mark, inject it into the citation marker before // inserting. - // TODO: Consider moving pageInfo stuff to citation marker - // generation. May need to modify getCitationMarker, - // at ./jabref/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java492: - // to emit html code. String citText; String pageInfo = getPageInfoForReferenceMarkName(documentConnection, name); @@ -2917,23 +2900,6 @@ public int getOrAllocateNumber(String key) { // Last minute editing: find "et al." (OOBibStyle.ET_AL_STRING) and // format it as italic. - // Q: Are we sure that OOBibStyle.ET_AL_STRING cannot be part of author names - // in any language? - // A: No, but have no examples either. - - // Q: Are we sure, citText does not contain multiple "et al." strings? - // A: It *can* contain more than one. - - // TODO: Could we move italicizing "et al." to a more proper place? - // Maybe we could use POSTFORMATTER with "..." - // That might make OOBibStyle.ITALIC_ET_AL superfluous. - // Maybe - // insertOOFormattedTextAtCurrentLocation could be used - // to do the insert (if paragraph style manipulation - // is removed) - - // TODO: Handle multiple "et al." strings. - // Check if we should italicize the "et al." string in citations: boolean italicize = style.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); if (italicize) { @@ -3016,11 +2982,7 @@ public int getOrAllocateNumber(String key) { * @param sync Indicates whether the reference list and in-text citations * should be refreshed in the document. * - * TODO: Group changes into a single Undo context. - * https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html * - * TODO: centralize inserting a citation group in a way that is - * also suitable for combineCiteMarkers, unCombineCiteMarkers (Is there any other to consider?) */ public void insertEntry( @@ -3055,30 +3017,19 @@ public int getOrAllocateNumber(String key) { // Get the cursor positioned by the user. XTextCursor cursor = documentConnection.getViewCursor(); - // TODO: (style-dependent) sorting entries for presentation - // affects the storage order of citation keys. - // - (1) presentation order should be decided - // when generating the presentation - // - (2) storage order should keep the order - // provided by the user. sortBibEntryListForMulticite(entries, style); - // TODO: consistent handling of citation groups (merged citations). - // keyString generation differs from the one in combineCiteMarkers - // Here we get A,,C for (A,B,C) where could not look up B - // There we get A,C String keyString = entries.stream() .map(entry -> entry.getCitationKey().orElse("")) .collect(Collectors.joining(",")); // Generate unique bookmark-name - // TODO: citationType is itcType elsewhere - int citationType = citationTypeFromOptions(withText, inParenthesis); + int itcType = citationTypeFromOptions(withText, inParenthesis); String newName = getUniqueReferenceMarkName( documentConnection, keyString, - citationType); + itcType); // If we should store metadata for page info, do that now: if (pageInfo != null) { @@ -3086,7 +3037,7 @@ public int getOrAllocateNumber(String key) { documentConnection.setCustomProperty(newName, pageInfo); } // else: branch ??? - // TODO: if (pageInfo is null), we might inadvertently + // Note: if (pageInfo is null), we might inadvertently // pick up a pageInfo from an earlier citation. The user // may have removed the citation, thus the reference mark, // but pageInfo stored separately stays there. @@ -3165,22 +3116,8 @@ public int getOrAllocateNumber(String key) { rebuildBibTextSection(allBases, style); /* - * TODO: inserting a reference in the "References" section - * provokes an "Unknown Source" exception here, because - * position was deleted by rebuildBibTextSection() - * - * at com.sun.proxy.$Proxy44.gotoRange(Unknown Source) - * at org.jabref@100.0.0/org.jabref.gui.openoffice - * .OOBibBase.insertEntry(OOBibBase.java:609) - * - * Idea: Maybe we should refuse to insert in places to be - * overwritten: bibliography, reference marks. - * - * Needs: (preferably accurate) knowledge of the forbidden ranges. - * Limitation: the user can still Cut and Paste to these parts. - * Q: Can we make them readonly inside, while allowing - * to move them around as a unit? - * + * Problem: insertEntry in bibliography + * Reference is destroyed when we want to get there. */ // Go back to the relevant position: try { @@ -3262,8 +3199,6 @@ public int getOrAllocateNumber(String key) { * * @param style Bibliography style to use. * - * TODO: should not modify storage (i.e. call insertReferenceMark) - * TODO: do not mess with bibliography here */ private void applyNewCitationMarkers( @@ -3337,21 +3272,6 @@ public int getOrAllocateNumber(String key) { if (hadBibSection && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { - // TODO: I think we used a *section* for the - // bibliography elsewhere. Here we use a *bookmark*. Relation? - // applyNewCitationMarkers: - // looks for: Bookmark - // creates: paragraph + Bookmark - // createBibTextSection2: - // creates: paragraph + Section - // clearBibTextSectionContent2: - // looks for: Section, calls createBibTextSection2 - // sets to "": Section - // populateBibTextSection: - // looks for: Section - // insert Bookmark BIB_SECTION_END_NAME - // after the body. - // We have overwritten the marker for the start of the reference list. // We need to add it again. cursor.collapseToEnd(); @@ -3404,9 +3324,6 @@ public int getOrAllocateNumber(String key) { findCitedEntries( findCitedKeys(documentConnection), databases - // TODO: Pass jabRefReferenceMarkNamesSortedByPosition around, and - // also add as a parameter to findCitedKeys, - // to make calls to updateSortedReferenceMarks more visible. ); // fce.entries are in same order as returned by findCitedKeys @@ -3692,15 +3609,6 @@ public int getOrAllocateNumber(String key) { documentConnection.xText .createTextCursorByRange(section.getAnchor()); - // TODO: I think creating a Section, inserting TITLE and formatting - // it without question, is an overreach. - // These could be left to the user's discretion. - // - Section has problems with docx conversion (?) - // - Do we need a different style to replace "References" with "Bibliography"? - // - Do we want to edit the style to change "Heading 1" to "Heading 2" - // To do (the important part of) our job, it is sufficient to get - // a range marker for the body of the bibliography. - // Maybe an "Insert bibliogrgaphy at the cursor"? OOUtil.insertTextAtCurrentLocation( documentConnection.xText, cursor, @@ -3720,11 +3628,6 @@ public int getOrAllocateNumber(String key) { uniqueLetters ); - // TODO: Do not insert Bookmark without testing if it already - // exists. LibreOffice creates "JR_bib_end1" instead of "JR_bib_end", - // or rather "JR_bib_endN" where N may increase. - // Repeatedly pressing "Refresh" leaves "JR_bib_end" at the start - // of the bibliography. documentConnection.insertBookmark( OOBibBase.BIB_SECTION_END_NAME, cursor, @@ -3743,31 +3646,6 @@ public int getOrAllocateNumber(String key) { /** * GUI action "Merge citations" * - * Earlier note: "combineCiteMarkers does not work with citations in footnotes" - * - * Note: - * - citations in footnotes - * - [X] can be inserted and - * - [X] they appear in the bibliography. - * - [X] They are also updated on style change+refresh - * - [ ] Merge fails (does not merge). - * - [ ] "Separate" (on merged citations inserted by - * selecting multiple entries then "Cite") - * May leave some of the two citation marks with text "tmp". - * This can be corrected by a few repetitions of pressing the "refresh" - * button. - * - * - citations in tables (text tables) - * - [X] can be inserted - * - [X] they appear in bibliography - * - [X] they are updated on style change+refresh - * - [X} Merge (combineCiteMarkers) works - * - [X} Separate (unCombineCiteMarkers) works - * - * TODO: if the corresponding bib file is not open, Separate (unCombineCiteMarkers) (or Merge?) - * leaves a mess: (1) reference marks with "tmp" in the text (2) with - * reference mark name "JR_cite_1_", i.e. without citation key. - * */ public void combineCiteMarkers( @@ -3842,10 +3720,10 @@ public int getOrAllocateNumber(String key) { // do not reach start of (pivot+1), which we now know to be // in the same Text instance. - // TODO: If there is no space between the two reference marks, - // the next line moves INTO the next. And probably will - // cover a non-whitespace character, inhibiting the merge. - // Empirically: does not merge. Probably a bug. + // If there is no space between the two reference marks, + // the next line moves INTO the next. And probably will + // cover a non-whitespace character, inhibiting the merge. + // Empirically: does not merge. Probably a bug. textCursor.goRight((short) 1, true); boolean couldExpand = true; while (couldExpand && (compare.compareRegionEnds(textCursor, range2) > 0)) { @@ -3881,8 +3759,8 @@ public int getOrAllocateNumber(String key) { * AUTHORYEAR_INTEXT: "X and Y (2000)" * INVISIBLE_CIT: "" * - * TODO: We probably only want to collect citations with - * AUTHORYEAR_PAR itcType. + * We probably only want to collect citations with + * AUTHORYEAR_PAR itcType. * * No, "X and Y (2000,2001)" appears a meaningful * case as well. @@ -3903,7 +3781,8 @@ public int getOrAllocateNumber(String key) { // Note: silently drops duplicate keys. // What if they have different pageInfo fields? - // TODO: combineCiteMarkers: merging for same citation keys, + + // combineCiteMarkers: merging for same citation keys, // but different pageInfo looses information. List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); @@ -4025,12 +3904,12 @@ public int getOrAllocateNumber(String key) { newName, "tmp", textCursor, - /* TODO: withText should be itcType != OOBibBase.INVISIBLE_CIT */ + /* withText should be itcType != OOBibBase.INVISIBLE_CIT */ true, style); textCursor.collapseToEnd(); if (i != last) { - // TODO: space between citation markers: what style? + // space between citation markers: what style? // DocumentConnection.setCharStyle(textCursor, "Standard"); textCursor.setString(" "); textCursor.collapseToEnd(); @@ -4091,8 +3970,12 @@ public int getOrAllocateNumber(String key) { .ifPresent(crossReference -> { // If the crossReference entry is not already in the database - // TODO: broken logic here: we just created resultDatabase, - // and added nothing yet. Question: why do we use + // broken logic here: + + // we just created resultDatabase, and + // added nothing yet. + + // Question: why do we use // entriesToInsert instead of directly adding to resultDatabase? // And why do we not look for it in entriesToInsert? // With the present code we are always adding it. From 062da6baa1872b992e0fa66e9ddb2d689f91bfa3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 9 Mar 2021 19:25:51 +0100 Subject: [PATCH 0441/1068] throw JabRefException if could not get TextViewCursor --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 13 ++++++++++++- .../org/jabref/gui/openoffice/OpenOfficePanel.java | 5 +++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 20f3a06f223..99a790e5644 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2996,6 +2996,7 @@ public int getOrAllocateNumber(String key) { boolean sync ) throws + JabRefException, IllegalArgumentException, UnknownPropertyException, NotRemoveableException, @@ -3014,8 +3015,18 @@ public int getOrAllocateNumber(String key) { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { + XTextCursor cursor; // Get the cursor positioned by the user. - XTextCursor cursor = documentConnection.getViewCursor(); + try { + cursor = documentConnection.getViewCursor(); + } catch (RuntimeException ex){ + // com.sun.star.uno.RuntimeException + throw new JabRefException( + "Could not get the cursor", + Localization.lang( + "Could not get the cursor.") + ); + } sortBibEntryListForMulticite(entries, style); diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 2c3ace6ce53..9bb68874c95 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -557,6 +557,11 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP reportUndefinedCharacterFormat(ex); } catch (UndefinedParagraphFormatException ex) { reportUndefinedParagraphFormat(ex); + } catch (JabRefException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("JabRefException"), + ex.getLocalizedMessage() + ); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | BibEntryNotFoundException | IllegalTypeException | PropertyExistException | From 6cf6ef640a6dd19491adaf3600c919d17ae5bc21 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 9 Mar 2021 19:57:17 +0100 Subject: [PATCH 0442/1068] DocumentConnection.asTextContent --- .../org/jabref/gui/openoffice/OOBibBase.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 99a790e5644..d00cb7ebac7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -355,6 +355,13 @@ private static class DocumentConnection { return Arrays.asList(names); } + static XTextContent + asTextContent( Object mark ){ + if ( mark == null ){ + return null; + } + return unoQI(XTextContent.class, mark); + } /** * @return null if name not found, or if the result does not * support the XTextContent interface. @@ -368,7 +375,7 @@ private static class DocumentConnection { } try { Object referenceMark = nameAccess.getByName(name); - return unoQI(XTextContent.class, referenceMark); + return asTextContent(referenceMark); } catch (NoSuchElementException ex) { LOGGER.warn(String.format( "nameAccessGetTextContentByNameOrNull got NoSuchElementException" @@ -1261,7 +1268,7 @@ private static class ParsedRefMark { XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); for (String name1 : names) { Object bookmark = xNamedMarks.getByName(name1); - assert (null != unoQI(XTextContent.class, bookmark)); + assert (null != DocumentConnection.asTextContent(bookmark)); } // Collect to a flat list while keep only the first appearance. @@ -3703,13 +3710,13 @@ public int getOrAllocateNumber(String key) { while (pivot < (names.size() - 1)) { XTextRange range1 = - unoQI(XTextContent.class, - nameAccess.getByName(names.get(pivot))) + DocumentConnection.asTextContent( + nameAccess.getByName(names.get(pivot))) .getAnchor() .getEnd(); XTextRange range2 = - unoQI(XTextContent.class, + DocumentConnection.asTextContent( nameAccess.getByName(names.get(pivot + 1))) .getAnchor() .getStart(); // end of range2 is the start of (pivot + 1) @@ -3873,8 +3880,8 @@ public int getOrAllocateNumber(String key) { while (pivot < (names.size())) { XTextRange range1 = - unoQI(XTextContent.class, - nameAccess.getByName(names.get(pivot))) + DocumentConnection.asTextContent( + nameAccess.getByName(names.get(pivot))) .getAnchor(); XTextCursor textCursor = From 3ac14c282ae1c44840c9c84165eabbd915c014ab Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 10 Mar 2021 18:12:59 +0100 Subject: [PATCH 0443/1068] started create/fill separation createReferenceMarkForCitationGroup getFillCursorForCitationGroup fillCitationMarkInCursor --- .../org/jabref/gui/openoffice/OOBibBase.java | 400 ++++++++++++++---- 1 file changed, 306 insertions(+), 94 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d00cb7ebac7..84189d5ece4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -102,6 +102,18 @@ class OOBibBase { private static final Pattern CITE_PATTERN = Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + private static final boolean debug = true; + + private static final String zeroWidthSpace = "\u200b"; + // for debugging we may want visible bracket + private static final boolean referenceMarkUseInvisibleBrackets = !debug; + // Note we are relying on referenceMarkLeftBracket and referenceMarkRightBracket + // to be single-character strings that do not appear in reference mark content. + private static final String referenceMarkLeftBracket = + referenceMarkUseInvisibleBrackets ? zeroWidthSpace : "<"; + private static final String referenceMarkRightBracket = + referenceMarkUseInvisibleBrackets ? zeroWidthSpace : ">"; + /* Types of in-text citation. (itcType) * Their numeric values are used in reference mark names. */ @@ -454,15 +466,24 @@ private static class DocumentConnection { return textContent.getAnchor(); } + public XTextContent + getReferenceMarkAsTextContentOrNull(String name) + throws + NoDocumentException, + WrappedTargetException { + + XNameAccess nameAccess = this.getReferenceMarks(); + return nameAccessGetTextContentByNameOrNull(nameAccess, name); + } + public XTextRange getReferenceMarkRangeOrNull(String name) throws NoDocumentException, WrappedTargetException { - XNameAccess nameAccess = this.getReferenceMarks(); XTextContent textContent = - nameAccessGetTextContentByNameOrNull(nameAccess, name); + getReferenceMarkAsTextContentOrNull(name); if (textContent == null) { return null; } @@ -1623,9 +1644,11 @@ String format() { for (List partition : xxs.values()) { List oxs = sortPartitionByRegionStart(partition); - System.out.println("partition"); - for (RangeForOverlapCheck r : oxs) { - System.out.println(" " + r.format()); + if ( debug ){ + System.out.println("partition"); + for (RangeForOverlapCheck r : oxs) { + System.out.println(" " + r.format()); + } } checkSortedPartitionForOverlap(requireSeparation, oxs); } @@ -2849,20 +2872,144 @@ public int getOrAllocateNumber(String key) { * ***********************************/ /** + * Create an (empty) reference mark with the given name, at the + * end of position. * - * Insert a reference mark: creates and fills it. + * @param documentConnection + * @param name For the reference mark. + * @param position Collapsed to its end. + * @param insertSpaceAfter We insert a space after the mark, that + * carries on format of characters from + * the original position. * - * @param documentConnection Connection to a document. + * @return XTextCursor for the text to be inserted. + * + * On return position is collapsed, and is after the inserted space, + * or at the end of the (empty) range allocated for the text. * - * @param name Name of the reference mark to be created and also - * the name of the custom property holding the pageInfo part. */ - private void - insertReferenceMark( + private static XTextCursor + createReferenceMarkForCitationGroup( DocumentConnection documentConnection, String name, - String citationText, XTextCursor position, + boolean insertSpaceAfter, + String initialText + ) + throws + CreationException { + + // The cursor we received: we push it before us. + position.collapseToEnd(); + + XTextCursor cursor = position.getText().createTextCursorByRange(position.getEnd()); + if ( insertSpaceAfter ){ + cursor.getText().insertString(cursor, " ", false); + // go back to before the space + cursor.goLeft((short) 1, false); + } + + final String left = referenceMarkLeftBracket; + final String right = referenceMarkRightBracket; + String text = left + initialText + right; + cursor.getText().insertString(cursor, text, true); + XNamed mark = documentConnection.insertReferenceMark(name, cursor, true); + // Need a cursor that excludes left and right + XTextCursor full = cursor; + // DocumentConnection.getTextCursorOfTextContent( + // DocumentConnection.asTextContent(mark)); + full.collapseToStart(); + full.goRight( (short)1, false ); + full.goRight( (short)initialText.length(), true ); + return full; // yield a cursor in the bracket + } + + private static XTextCursor + getFillCursorForCitationGroup( + DocumentConnection documentConnection, + String name // Identifies group + ) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + final String left = referenceMarkLeftBracket; + final String right = referenceMarkRightBracket; + + XTextContent markAsTextContent = + documentConnection.getReferenceMarkAsTextContentOrNull( name ); + + if (markAsTextContent == null){ + throw new RuntimeException( + String.format( + "getFillCursorForCitationGroup: markAsTextContent(%s) == null", + name + )); + } + XTextCursor full = + DocumentConnection.getTextCursorOfTextContent( + markAsTextContent); + if (full == null ){ + throw new RuntimeException( + "getFillCursorForCitationGroup: full == null" + ); + } + String fulltext = full.getString(); + if ( debug ){ + System.out.println(String.format("getFillCursor: fulltext = '%s'", fulltext)); + } + + if (fulltext.length() < 2 || !fulltext.startsWith(left) || !fulltext.endsWith(right)){ + // damaged, recreate + if ( debug ){ + System.out.println(String.format("getFillCursor: damaged, recreate")); + } + full.setString(""); + if ( true ){ + if ( debug ){ + System.out.println(String.format("getFillCursor: removeReferenceMark go")); + } + try { + documentConnection.removeReferenceMark(name); + } catch (NoSuchElementException ex) { + LOGGER.warn(String.format( + "getFillCursorForCitationGroup got NoSuchElementException" + + " for '%s'", name)); + } + } else { + if ( debug ){ + System.out.println(String.format("getFillCursor: removeReferenceMark skipped")); + } + } + // What shall we put in the recreated version? + // User might have inserted stuff before or after? + String trimmedtext = fulltext.replaceAll( "[" + left + right +"]", "" ); + if (debug){ + System.out.println(String.format("getFillCursor: trimmedtext = '%s'", trimmedtext)); + } + return createReferenceMarkForCitationGroup( + documentConnection, + name, + full, + false, // insertSpaceAfter + trimmedtext ); + } else { + if (debug){ + System.out.println(String.format("getFillCursor: intact, reuse")); + } + full.collapseToStart(); + full.goRight( (short)1, false ); + full.goRight( (short)(fulltext.length()-2), true ); + return full; // yield a cursor in the bracket + } + } + + private static void + fillCitationMarkInCursor( + DocumentConnection documentConnection, + String name, // citationGroup + XTextCursor cursor, + String citationText, boolean withText, OOBibStyle style ) @@ -2874,10 +3021,6 @@ public int getOrAllocateNumber(String key) { UndefinedCharacterFormatException, CreationException { - // Last minute editing: If there is "page info" for this - // citation mark, inject it into the citation marker before - // inserting. - String citText; String pageInfo = getPageInfoForReferenceMarkName(documentConnection, name); @@ -2886,23 +3029,19 @@ public int getOrAllocateNumber(String key) { ? citationText : style.insertPageInfo(citationText, pageInfo); - /* - * We had a problem here, position.setString() not inserting the text. - * The solution seems to be: create a new cursor (c2), and use that. - */ - XTextCursor c2 = position.getText().createTextCursorByRange(position); if (withText) { - c2.setString(citText); - DocumentConnection.setCharLocaleNone(c2); + // setString: All styles are removed when applying this method. + cursor.setString(citText); + DocumentConnection.setCharLocaleNone(cursor); if (style.isFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(c2, charStyle); + DocumentConnection.setCharStyle(cursor, charStyle); } } else { - c2.setString(""); + cursor.setString(""); } - documentConnection.insertReferenceMark(name, c2, true); + // documentConnection.insertReferenceMark(name, cursor, true); // Last minute editing: find "et al." (OOBibStyle.ET_AL_STRING) and // format it as italic. @@ -2911,13 +3050,12 @@ public int getOrAllocateNumber(String key) { boolean italicize = style.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); if (italicize) { String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); - int index = citText.indexOf(etAlString); - if (index >= 0) { - italicizeRangeFromPosition(c2, index, index + etAlString.length()); + for (int index = citText.indexOf(etAlString) ; + index >= 0 ; + index = citText.indexOf(etAlString, index + 1)) { + italicizeRangeFromPosition(cursor, index, index + etAlString.length()); } } - - position.collapseToEnd(); } /** @@ -2930,7 +3068,7 @@ public int getOrAllocateNumber(String key) { * Why this API? This is used after finding "et al." string in a * citation marker. */ - private void + private static void italicizeRangeFromPosition( XTextCursor position, int start, @@ -2950,6 +3088,89 @@ public int getOrAllocateNumber(String key) { DocumentConnection.setCharFormatItalic(cursor); } + /** + * + * Insert a reference mark: creates and fills it. + * + * @param documentConnection Connection to a document. + * + * @param name Name of the reference mark to be created and also + * the name of the custom property holding the pageInfo part. + * + * @param position OUT: left collapsed, just after the space inserted, + * or after the reference mark inserted. + * xxx + */ + private void + insertReferenceMark( + DocumentConnection documentConnection, + String name, + String citationText, + XTextCursor position, + boolean withText, + OOBibStyle style, + boolean insertSpaceAfter + ) + throws + UnknownPropertyException, + WrappedTargetException, + PropertyVetoException, + IllegalArgumentException, + UndefinedCharacterFormatException, + CreationException { + + // Last minute editing: If there is "page info" for this + // citation mark, inject it into the citation marker before + // inserting. + + XTextCursor c2 = createReferenceMarkForCitationGroup(documentConnection, + name, + position, + insertSpaceAfter, + ""); + + fillCitationMarkInCursor( documentConnection, + name, + c2, + citationText, + withText, + style ); + position.collapseToEnd(); + } + + void assertCitationCharacterFormatIsOK( + XTextCursor cursor, + OOBibStyle style + ) + throws UndefinedCharacterFormatException { + + if (!style.isFormatCitations()) { + return; + } + + /* Do not mess with the cursor passed in, use a copy. */ + XTextCursor c2 = + cursor.getText().createTextCursorByRange(cursor.getEnd()); + + c2 + .getText() + .insertString(c2, "@", false); + + String charStyle = style.getCitationCharacterFormat(); + try { + c2.goLeft((short) 1, true); + DocumentConnection.setCharStyle(c2, charStyle); + } catch (UndefinedCharacterFormatException ex) { + // Setting the character format failed, so we + // throw an exception that will result in an + // error message for the user. + throw new UndefinedCharacterFormatException(charStyle); + } finally { + // Before returning, delete the character we inserted: + c2.setString(""); + } + } + /** * Called from: OpenOfficePanel.pushEntries, a GUI action for * "Cite", "Cite in-text", "Cite special" and "Insert empty @@ -3060,30 +3281,7 @@ public int getOrAllocateNumber(String key) { // may have removed the citation, thus the reference mark, // but pageInfo stored separately stays there. - // insert space: we will write our citation before this space. - cursor - .getText() - .insertString(cursor, " ", false); - - // format the space inserted - if (style.isFormatCitations()) { - String charStyle = style.getCitationCharacterFormat(); - try { - DocumentConnection.setCharStyle(cursor, charStyle); - } catch (UndefinedCharacterFormatException ex) { - // Setting the character format failed, so we - // throw an exception that will result in an - // error message for the user. - - // Before that, delete the space we inserted: - cursor.goLeft((short) 1, true); - cursor.setString(""); - throw new UndefinedCharacterFormatException(charStyle); - } - } - - // go back to before the space - cursor.goLeft((short) 1, false); + assertCitationCharacterFormatIsOK( cursor, style ); // Insert reference mark and text // { @@ -3115,13 +3313,15 @@ public int getOrAllocateNumber(String key) { citeText, cursor, withText, - style); - // } // end of scope for databaseMap, citeText + style, + true // insertSpaceAfter + ); + // } // end of scope for databaseMap, citeText - // Move to the right of the space and remember this - // position: we will come back here in the end. - cursor.collapseToEnd(); - cursor.goRight((short) 1, false); + // Move to the right of the space and remember this + // position: we will come back here in the end. + // cursor.collapseToEnd(); + // cursor.goRight((short) 1, false); XTextRange position = cursor.getEnd(); if (sync) { @@ -3239,8 +3439,6 @@ public int getOrAllocateNumber(String key) { assert (citMarkers.length == nRefMarks); assert (types.length == nRefMarks); - XNameAccess nameAccess = - documentConnection.getReferenceMarks(); final boolean hadBibSection = (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) != null); @@ -3257,37 +3455,46 @@ public int getOrAllocateNumber(String key) { final String name = referenceMarkNames.get(i); - XTextContent mark = - DocumentConnection.nameAccessGetTextContentByNameOrNull(nameAccess, name); - if (null == mark) { - LOGGER.warn(String.format( - "OOBibBase.applyNewCitationMarkers:" - + " lost reference mark '%s'", - name - )); - continue; - } - XTextCursor cursor = - DocumentConnection.getTextCursorOfTextContent(mark); + getFillCursorForCitationGroup( + documentConnection, + name // Identifies group + ); if (mustTestCharFormat) { - mustTestCharFormat = false; // need to do this only once - String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(cursor, charStyle); + assertCitationCharacterFormatIsOK( cursor, style ); + mustTestCharFormat = false; } - documentConnection.xText.removeTextContent(mark); - - insertReferenceMark( + fillCitationMarkInCursor( documentConnection, - name, - citMarkers[i], + name, // citationGroup cursor, - types[i] != OOBibBase.INVISIBLE_CIT, + citMarkers[i], // citationText, + types[i] != OOBibBase.INVISIBLE_CIT, // withText, style ); + /* + * XTextCursor cursor = + * DocumentConnection.getTextCursorOfTextContent(mark); + * + * if (mustTestCharFormat) { + * assertCitationCharacterFormatIsOK( cursor, style ); + * } + * + * documentConnection.xText.removeTextContent(mark); + * + * insertReferenceMark( + * documentConnection, + * name, + * citMarkers[i], + * cursor, + * types[i] != OOBibBase.INVISIBLE_CIT, + * style + * ); + */ + if (hadBibSection && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { // We have overwritten the marker for the start of the reference list. @@ -3825,14 +4032,16 @@ public int getOrAllocateNumber(String key) { documentConnection, keyString, OOBibBase.AUTHORYEAR_PAR); - + // xxx insertReferenceMark( documentConnection, newName, "tmp", textCursor, true, // withText - style); + style, + true // insertSpaceAfter + ); names.set(pivot + 1, newName); // <- put in the next-to-be-processed position madeModifications = true; @@ -3917,6 +4126,7 @@ public int getOrAllocateNumber(String key) { key, OOBibBase.AUTHORYEAR_PAR); + boolean insertSpaceAfter = (i != last); insertReferenceMark( documentConnection, newName, @@ -3924,14 +4134,16 @@ public int getOrAllocateNumber(String key) { textCursor, /* withText should be itcType != OOBibBase.INVISIBLE_CIT */ true, - style); + style, + true // insertSpaceAfter + ); textCursor.collapseToEnd(); - if (i != last) { - // space between citation markers: what style? - // DocumentConnection.setCharStyle(textCursor, "Standard"); - textCursor.setString(" "); - textCursor.collapseToEnd(); - } + // if (i != last) { + // // space between citation markers: what style? + // // DocumentConnection.setCharStyle(textCursor, "Standard"); + // textCursor.setString(" "); + // textCursor.collapseToEnd(); + // } i++; } madeModifications = true; From af6f5d5ed904d639d9c0c34bd898d71b8dd7c28d Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 10 Mar 2021 18:40:48 +0100 Subject: [PATCH 0444/1068] relocate pageInfo comment --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 84189d5ece4..e9e29a754aa 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3021,6 +3021,10 @@ public int getOrAllocateNumber(String key) { UndefinedCharacterFormatException, CreationException { + // Last minute editing: If there is "page info" for this + // citation mark, we should inject it into the citation marker + // when creating. + String citText; String pageInfo = getPageInfoForReferenceMarkName(documentConnection, name); @@ -3099,7 +3103,6 @@ public int getOrAllocateNumber(String key) { * * @param position OUT: left collapsed, just after the space inserted, * or after the reference mark inserted. - * xxx */ private void insertReferenceMark( @@ -3119,10 +3122,6 @@ public int getOrAllocateNumber(String key) { UndefinedCharacterFormatException, CreationException { - // Last minute editing: If there is "page info" for this - // citation mark, inject it into the citation marker before - // inserting. - XTextCursor c2 = createReferenceMarkForCitationGroup(documentConnection, name, position, From 3fd5735f2e3cdc0ee531a2b7e7bcca9b02448271 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 10 Mar 2021 18:42:39 +0100 Subject: [PATCH 0445/1068] comments --- .../org/jabref/gui/openoffice/OOBibBase.java | 50 ++++++++----------- 1 file changed, 21 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e9e29a754aa..e595ca2e588 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3137,6 +3137,19 @@ public int getOrAllocateNumber(String key) { position.collapseToEnd(); } + /** + * Test if we have a problem applying character style prescribe by + * the style. + * + * If the style prescribes an character style, we insert a + * character, format it and delete it. + * + * An UndefinedCharacterFormatException may be raised, indicating + * that the style requested is not available in the document. + * + * @param cursor Provides location where we insert, format and + * remove a character. + */ void assertCitationCharacterFormatIsOK( XTextCursor cursor, OOBibStyle style @@ -3147,7 +3160,7 @@ void assertCitationCharacterFormatIsOK( return; } - /* Do not mess with the cursor passed in, use a copy. */ + /* We do not want to change the cursor passed in, so using a copy. */ XTextCursor c2 = cursor.getText().createTextCursorByRange(cursor.getEnd()); @@ -3158,14 +3171,13 @@ void assertCitationCharacterFormatIsOK( String charStyle = style.getCitationCharacterFormat(); try { c2.goLeft((short) 1, true); + // The next line may throw + // UndefinedCharacterFormatException(charStyle). + // We let that propagate. DocumentConnection.setCharStyle(c2, charStyle); - } catch (UndefinedCharacterFormatException ex) { - // Setting the character format failed, so we - // throw an exception that will result in an - // error message for the user. - throw new UndefinedCharacterFormatException(charStyle); } finally { - // Before returning, delete the character we inserted: + // Before leaving this scope, always delete the character we + // inserted: c2.setString(""); } } @@ -3401,8 +3413,8 @@ void assertCitationCharacterFormatIsOK( } /** - * Visit each reference mark in referenceMarkNames, remove its - * text content, call insertReferenceMark. + * Visit each reference mark in referenceMarkNames, overwrite its + * text content. * * After each insertReferenceMark call check if we lost the * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. @@ -3474,26 +3486,6 @@ void assertCitationCharacterFormatIsOK( style ); - /* - * XTextCursor cursor = - * DocumentConnection.getTextCursorOfTextContent(mark); - * - * if (mustTestCharFormat) { - * assertCitationCharacterFormatIsOK( cursor, style ); - * } - * - * documentConnection.xText.removeTextContent(mark); - * - * insertReferenceMark( - * documentConnection, - * name, - * citMarkers[i], - * cursor, - * types[i] != OOBibBase.INVISIBLE_CIT, - * style - * ); - */ - if (hadBibSection && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { // We have overwritten the marker for the start of the reference list. From 935d9c754960d73aaebfc126e6ad42d7243e3959 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 10 Mar 2021 18:43:02 +0100 Subject: [PATCH 0446/1068] overwriting start of bibliography now throws RuntimeException --- .../org/jabref/gui/openoffice/OOBibBase.java | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e595ca2e588..7104bfbfff4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3488,12 +3488,21 @@ void assertCitationCharacterFormatIsOK( if (hadBibSection && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { - // We have overwritten the marker for the start of the reference list. - // We need to add it again. - cursor.collapseToEnd(); - OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - documentConnection.insertBookmark(OOBibBase.BIB_SECTION_NAME, cursor, true); - cursor.collapseToEnd(); + if (true){ + // Overwriting text already there is too harsh. + // I am making it an error, to see if we ever get here. + throw new RuntimeException( + "OOBibBase.applyNewCitationMarkers:" + + " just overwrote the bibsection marker. Sorry."); + } else { + // We have overwritten the marker for the start of the reference list. + // We need to add it again. + // --- + // cursor.collapseToEnd(); + // OOUtil.insertParagraphBreak(documentConnection.xText, cursor); + // documentConnection.insertBookmark(OOBibBase.BIB_SECTION_NAME, cursor, true); + // cursor.collapseToEnd(); + } } } } From 8473d146722d3b27b16f1d42dcffc708e28d7c49 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 10 Mar 2021 20:36:23 +0100 Subject: [PATCH 0447/1068] add DocumentConnection.lockControllers(), unlockControllers() Apply them to most GUI methods --- .../org/jabref/gui/openoffice/OOBibBase.java | 45 ++++++++++++++++--- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7104bfbfff4..a1b4b14ac02 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -174,6 +174,26 @@ private static class DocumentConnection { this.propertySet = unoQI(XPropertySet.class, userProperties); } + /* + * Disable screen refresh. + * + * Must be paired with unlockControllers() + * + * https://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XModel.html + * + * While there is at least one lock remaining, some + * notifications for display updates are not broadcasted. + */ + void lockControllers() { + XModel mo = unoQI(XModel.class, this.xCurrentComponent); + mo.lockControllers(); + } + + void unlockControllers() { + XModel mo = unoQI(XModel.class, this.xCurrentComponent); + mo.unlockControllers(); + } + /** * @return True if we cannot reach the current document. */ @@ -3254,6 +3274,7 @@ void assertCitationCharacterFormatIsOK( DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { + documentConnection.lockControllers(); XTextCursor cursor; // Get the cursor positioned by the user. try { @@ -3361,6 +3382,8 @@ void assertCitationCharacterFormatIsOK( // loaded before connection, and therefore cannot directly reference // or catch a DisposedException (which is in a OO JAR file). throw new ConnectionLostException(ex.getMessage()); + } finally { + documentConnection.unlockControllers(); } } @@ -3915,6 +3938,8 @@ void assertCitationCharacterFormatIsOK( XNameAccess nameAccess = documentConnection.getReferenceMarks(); while (pivot < (names.size() - 1)) { + try { + documentConnection.lockControllers(); XTextRange range1 = DocumentConnection.asTextContent( @@ -4051,6 +4076,8 @@ void assertCitationCharacterFormatIsOK( if (madeModifications) { updateSortedReferenceMarks(); refreshCiteMarkers(databases, style); + } finally { + documentConnection.unlockControllers(); } } @@ -4078,6 +4105,8 @@ void assertCitationCharacterFormatIsOK( NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + try { + documentConnection.lockControllers(); List names = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); @@ -4153,6 +4182,8 @@ void assertCitationCharacterFormatIsOK( if (madeModifications) { updateSortedReferenceMarks(); refreshCiteMarkers(databases, style); + } finally { + documentConnection.unlockControllers(); } } @@ -4262,11 +4293,15 @@ void assertCitationCharacterFormatIsOK( boolean requireSeparation = false; // may loose citation without requireSeparation=true CitationGroups cg = new CitationGroups(documentConnection); cg.checkRangeOverlaps(this.xDocumentConnection, requireSeparation); - - updateSortedReferenceMarks(); - List unresolvedKeys = refreshCiteMarkers(databases, style); - rebuildBibTextSection(databases, style); - return unresolvedKeys; + try { + documentConnection.lockControllers(); + updateSortedReferenceMarks(); + List unresolvedKeys = refreshCiteMarkers(databases, style); + rebuildBibTextSection(databases, style); + return unresolvedKeys; + } finally { + documentConnection.unlockControllers(); + } } } // end of OOBibBase From ee5b85a616ba769a9f24d1b7894192761bdfd9b7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 10 Mar 2021 20:39:19 +0100 Subject: [PATCH 0448/1068] Avoid assertCitationCharacterFormatIsOK leaving a formatted location behind --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a1b4b14ac02..c9448c47229 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3184,13 +3184,19 @@ void assertCitationCharacterFormatIsOK( XTextCursor c2 = cursor.getText().createTextCursorByRange(cursor.getEnd()); + /* + * Inserting, formatting and removing a single character + * still leaves a style change in place. + * Let us try with two characters, formatting only the first. + */ c2 .getText() - .insertString(c2, "@", false); + .insertString(c2, "@*", false); String charStyle = style.getCitationCharacterFormat(); try { - c2.goLeft((short) 1, true); + c2.goLeft((short) 1, false); // step over '*' + c2.goLeft((short) 1, true); // select '@' // The next line may throw // UndefinedCharacterFormatException(charStyle). // We let that propagate. @@ -3198,6 +3204,8 @@ void assertCitationCharacterFormatIsOK( } finally { // Before leaving this scope, always delete the character we // inserted: + c2.collapseToStart(); + c2.goRight((short) 2, true); // select '@*' c2.setString(""); } } From 580e82a29ed90a599ea73d34581d9e034b8e5316 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 10 Mar 2021 20:59:10 +0100 Subject: [PATCH 0449/1068] format --- .../org/jabref/gui/openoffice/OOBibBase.java | 378 +++++++++--------- 1 file changed, 195 insertions(+), 183 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c9448c47229..5480fd6c741 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3175,7 +3175,6 @@ void assertCitationCharacterFormatIsOK( OOBibStyle style ) throws UndefinedCharacterFormatException { - if (!style.isFormatCitations()) { return; } @@ -3239,12 +3238,13 @@ void assertCitationCharacterFormatIsOK( * with the same name as the reference mark. * * Related https://latex.org/forum/viewtopic.php?t=14331 - * + * """ * Q: What I would like is something like this: * (Jones, 2010, p. 12; Smith, 2003, pp. 21 - 23) * A: Not in a single \citep, no. * Use \citetext{\citealp[p.~12]{jones2010}; * \citealp[pp.~21--23]{smith2003}} + * """ * * @param sync Indicates whether the reference list and in-text citations * should be refreshed in the document. @@ -3311,6 +3311,16 @@ void assertCitationCharacterFormatIsOK( itcType); // If we should store metadata for page info, do that now: + // + // Note: the (single) pageInfo here gets associated with + // the citation group. At presentation it is inject + // to before the final parenthesis, appearing to + // belong to the last entry added here. + // + // But: (1) the last entry depends on the above + // sortBibEntryListForMulticite call; (2) On + // "Separate" it belongs to nobody. + // if (pageInfo != null) { LOGGER.info("Storing page info: " + pageInfo); documentConnection.setCustomProperty(newName, pageInfo); @@ -3922,93 +3932,94 @@ void assertCitationCharacterFormatIsOK( DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - // The testing for whitespace-only between (pivot) and (pivot+1) assumes that - // names are in textual order: textually consecutive pairs - // must appear as neighbours (and in textual order). - // We have a bit of a clash here: names is sorted by visual position, - // but we are testing if they are textually neighbours. - // In a two-column layout - // | a | c | - // | b | d | - // abcd is the textual order, but the visual order is acbd. - // So we will not find out that a and b are only separated by white space. - List names = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - - // XTextRangeCompare: compares the positions of two TextRanges within a Text. - // Only TextRange instances within the same Text can be compared. - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - documentConnection.xText); - - int pivot = 0; - boolean madeModifications = false; - boolean setCharStyleTested = false; - XNameAccess nameAccess = documentConnection.getReferenceMarks(); - - while (pivot < (names.size() - 1)) { try { documentConnection.lockControllers(); - XTextRange range1 = - DocumentConnection.asTextContent( - nameAccess.getByName(names.get(pivot))) - .getAnchor() - .getEnd(); - - XTextRange range2 = - DocumentConnection.asTextContent( - nameAccess.getByName(names.get(pivot + 1))) - .getAnchor() - .getStart(); // end of range2 is the start of (pivot + 1) - - if (range1.getText() != range2.getText()) { - /* pivot and (pivot+1) belong to different Text instances. - * Maybe to different footnotes? - * Cannot combine across boundaries, skip. - */ - pivot++; - continue; - } + // The testing for whitespace-only between (pivot) and (pivot+1) assumes that + // names are in textual order: textually consecutive pairs + // must appear as neighbours (and in textual order). + // We have a bit of a clash here: names is sorted by visual position, + // but we are testing if they are textually neighbours. + // In a two-column layout + // | a | c | + // | b | d | + // abcd is the textual order, but the visual order is acbd. + // So we will not find out that a and b are only separated by white space. + List names = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - // Start from end of text for pivot. - XTextCursor textCursor = - range1.getText().createTextCursorByRange(range1); - - // Select next character (if possible), and more, as long as we can and - // do not reach start of (pivot+1), which we now know to be - // in the same Text instance. - - // If there is no space between the two reference marks, - // the next line moves INTO the next. And probably will - // cover a non-whitespace character, inhibiting the merge. - // Empirically: does not merge. Probably a bug. - textCursor.goRight((short) 1, true); - boolean couldExpand = true; - while (couldExpand && (compare.compareRegionEnds(textCursor, range2) > 0)) { - couldExpand = textCursor.goRight((short) 1, true); - } + // XTextRangeCompare: compares the positions of two TextRanges within a Text. + // Only TextRange instances within the same Text can be compared. + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + documentConnection.xText); - // Take what we selected - String cursorText = textCursor.getString(); + int pivot = 0; + boolean madeModifications = false; + boolean setCharStyleTested = false; + XNameAccess nameAccess = documentConnection.getReferenceMarks(); + + while (pivot < (names.size() - 1)) { + + XTextRange range1 = + DocumentConnection.asTextContent( + nameAccess.getByName(names.get(pivot))) + .getAnchor() + .getEnd(); + + XTextRange range2 = + DocumentConnection.asTextContent( + nameAccess.getByName(names.get(pivot + 1))) + .getAnchor() + .getStart(); // end of range2 is the start of (pivot + 1) + + if (range1.getText() != range2.getText()) { + /* pivot and (pivot+1) belong to different Text instances. + * Maybe to different footnotes? + * Cannot combine across boundaries, skip. + */ + pivot++; + continue; + } - // Check if the string contains line breaks and any non-whitespace. - if ((cursorText.indexOf('\n') != -1) || !cursorText.trim().isEmpty()) { - pivot++; - continue; - } + // Start from end of text for pivot. + XTextCursor textCursor = + range1.getText().createTextCursorByRange(range1); + + // Select next character (if possible), and more, as long as we can and + // do not reach start of (pivot+1), which we now know to be + // in the same Text instance. + + // If there is no space between the two reference marks, + // the next line moves INTO the next. And probably will + // cover a non-whitespace character, inhibiting the merge. + // Empirically: does not merge. Probably a bug. + textCursor.goRight((short) 1, true); + boolean couldExpand = true; + while (couldExpand && (compare.compareRegionEnds(textCursor, range2) > 0)) { + couldExpand = textCursor.goRight((short) 1, true); + } - // If we are supposed to set character format for - // citations, test this before making any changes. This - // way we can throw an exception before any reference - // marks are removed, preventing damage to the user's - // document: - // Q: we may have zero characters selected. Is this a valid test - // in this case? - if (style.isFormatCitations() && !setCharStyleTested) { - String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(textCursor, charStyle); - setCharStyleTested = true; - } + // Take what we selected + String cursorText = textCursor.getString(); + + // Check if the string contains line breaks and any non-whitespace. + if ((cursorText.indexOf('\n') != -1) || !cursorText.trim().isEmpty()) { + pivot++; + continue; + } + + // If we are supposed to set character format for + // citations, test this before making any changes. This + // way we can throw an exception before any reference + // marks are removed, preventing damage to the user's + // document: + // Q: we may have zero characters selected. Is this a valid test + // in this case? + if (style.isFormatCitations() && !setCharStyleTested) { + String charStyle = style.getCitationCharacterFormat(); + DocumentConnection.setCharStyle(textCursor, charStyle); + setCharStyleTested = true; + } /* * This only gets the keys: itcType is discarded. @@ -4042,48 +4053,49 @@ void assertCitationCharacterFormatIsOK( // combineCiteMarkers: merging for same citation keys, // but different pageInfo looses information. - List keys = - parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); - keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); - - documentConnection.removeReferenceMark(names.get(pivot)); - documentConnection.removeReferenceMark(names.get(pivot + 1)); - - // Note: citation keys not found are silently left out from the - // combined reference mark name. Loosing information. - List entries = lookupEntriesInDatabasesSkipMissing(keys, databases); - entries.sort(new FieldComparator(StandardField.YEAR)); - - String keyString = - entries.stream() - .map(c -> c.getCitationKey().orElse("")) - .collect(Collectors.joining(",")); - - // Insert reference mark: - String newName = - getUniqueReferenceMarkName( + List keys = + parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); + keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); + + documentConnection.removeReferenceMark(names.get(pivot)); + documentConnection.removeReferenceMark(names.get(pivot + 1)); + + // Note: citation keys not found are silently left out from the + // combined reference mark name. Loosing information. + List entries = lookupEntriesInDatabasesSkipMissing(keys, databases); + entries.sort(new FieldComparator(StandardField.YEAR)); + + String keyString = + entries.stream() + .map(c -> c.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); + + // Insert reference mark: + String newName = + getUniqueReferenceMarkName( + documentConnection, + keyString, + OOBibBase.AUTHORYEAR_PAR); + // xxx + insertReferenceMark( documentConnection, - keyString, - OOBibBase.AUTHORYEAR_PAR); - // xxx - insertReferenceMark( - documentConnection, - newName, - "tmp", - textCursor, - true, // withText - style, - true // insertSpaceAfter - ); - names.set(pivot + 1, newName); // <- put in the next-to-be-processed position - madeModifications = true; + newName, + "tmp", + textCursor, + true, // withText + style, + true // insertSpaceAfter + ); + names.set(pivot + 1, newName); // <- put in the next-to-be-processed position + madeModifications = true; - pivot++; - } // while + pivot++; + } // while - if (madeModifications) { - updateSortedReferenceMarks(); - refreshCiteMarkers(databases, style); + if (madeModifications) { + updateSortedReferenceMarks(); + refreshCiteMarkers(databases, style); + } } finally { documentConnection.unlockControllers(); } @@ -4116,55 +4128,55 @@ void assertCitationCharacterFormatIsOK( try { documentConnection.lockControllers(); - List names = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - - int pivot = 0; - boolean madeModifications = false; - boolean setCharStyleTested = false; - XNameAccess nameAccess = documentConnection.getReferenceMarks(); - - while (pivot < (names.size())) { - XTextRange range1 = - DocumentConnection.asTextContent( - nameAccess.getByName(names.get(pivot))) - .getAnchor(); - - XTextCursor textCursor = - range1.getText().createTextCursorByRange(range1); - - // If we are supposed to set character format for - // citations, test this before making any changes. This - // way we can throw an exception before any reference - // marks are removed, preventing damage to the user's - // document: - if (style.isFormatCitations() && !setCharStyleTested) { - String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(textCursor, charStyle); - setCharStyleTested = true; - } + List names = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + + int pivot = 0; + boolean madeModifications = false; + boolean setCharStyleTested = false; + XNameAccess nameAccess = documentConnection.getReferenceMarks(); + + while (pivot < (names.size())) { + XTextRange range1 = + DocumentConnection.asTextContent( + nameAccess.getByName(names.get(pivot))) + .getAnchor(); + + XTextCursor textCursor = + range1.getText().createTextCursorByRange(range1); + + // If we are supposed to set character format for + // citations, test this before making any changes. This + // way we can throw an exception before any reference + // marks are removed, preventing damage to the user's + // document: + if (style.isFormatCitations() && !setCharStyleTested) { + String charStyle = style.getCitationCharacterFormat(); + DocumentConnection.setCharStyle(textCursor, charStyle); + setCharStyleTested = true; + } - List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); - if (keys.size() <= 1) { - pivot++; - continue; - } + List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); + if (keys.size() <= 1) { + pivot++; + continue; + } - documentConnection.removeReferenceMark(names.get(pivot)); + documentConnection.removeReferenceMark(names.get(pivot)); - // Insert bookmark for each key - int last = keys.size() - 1; - int i = 0; - for (String key : keys) { - // Note: instead of generating a new name, we should explicitly - // recover the original. Otherwise ... - String newName = getUniqueReferenceMarkName( - documentConnection, - key, - OOBibBase.AUTHORYEAR_PAR); + // Insert bookmark for each key + int last = keys.size() - 1; + int i = 0; + for (String key : keys) { + // Note: instead of generating a new name, we should explicitly + // recover the original. Otherwise ... + String newName = getUniqueReferenceMarkName( + documentConnection, + key, + OOBibBase.AUTHORYEAR_PAR); - boolean insertSpaceAfter = (i != last); - insertReferenceMark( + boolean insertSpaceAfter = (i != last); + insertReferenceMark( documentConnection, newName, "tmp", @@ -4173,28 +4185,28 @@ void assertCitationCharacterFormatIsOK( true, style, true // insertSpaceAfter - ); - textCursor.collapseToEnd(); - // if (i != last) { - // // space between citation markers: what style? - // // DocumentConnection.setCharStyle(textCursor, "Standard"); - // textCursor.setString(" "); - // textCursor.collapseToEnd(); - // } - i++; - } - madeModifications = true; + ); + textCursor.collapseToEnd(); + // if (i != last) { + // // space between citation markers: what style? + // // DocumentConnection.setCharStyle(textCursor, "Standard"); + // textCursor.setString(" "); + // textCursor.collapseToEnd(); + // } + i++; + } + madeModifications = true; - pivot++; - } - if (madeModifications) { - updateSortedReferenceMarks(); - refreshCiteMarkers(databases, style); + pivot++; + } + if (madeModifications) { + updateSortedReferenceMarks(); + refreshCiteMarkers(databases, style); + } } finally { documentConnection.unlockControllers(); } } - /** * Used from GUI: "Export cited" * From 69e9f3927d7354146577477172d6b8761c87f9d1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 10 Mar 2021 22:17:26 +0100 Subject: [PATCH 0450/1068] avoid useLockControllers for getJabRefReferenceMarkNamesSortedByPosition Probably viewCursor.gotoRange and findPositionOfTextRange(range, viewCursor) are not usefule with display updates locked. --- .../org/jabref/gui/openoffice/OOBibBase.java | 79 ++++++++++++++----- 1 file changed, 61 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5480fd6c741..bad8bef5d00 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -194,6 +194,11 @@ void unlockControllers() { mo.unlockControllers(); } + boolean hasControllersLocked(){ + XModel mo = unoQI(XModel.class, this.xCurrentComponent); + return mo.hasControllersLocked(); + } + /** * @return True if we cannot reach the current document. */ @@ -2221,6 +2226,14 @@ public int hashCode() { WrappedTargetException, NoDocumentException { + if ( documentConnection.hasControllersLocked() ) { + LOGGER.warn( + "getJabRefReferenceMarkNamesSortedByPosition:" + + " with ControllersLocked, viewCursor.gotoRange" + + " is pobably useless" + ); + } + List names = getJabRefReferenceMarkNames(documentConnection); // find coordinates @@ -3930,10 +3943,14 @@ void assertCitationCharacterFormatIsOK( BibEntryNotFoundException, NoDocumentException { + Objects.requireNonNull(databases); + Objects.requireNonNull(style); + + final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + boolean madeModifications = false; try { - documentConnection.lockControllers(); // The testing for whitespace-only between (pivot) and (pivot+1) assumes that // names are in textual order: textually consecutive pairs @@ -3948,13 +3965,15 @@ void assertCitationCharacterFormatIsOK( List names = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + if (useLockControllers) { + documentConnection.lockControllers(); + } // XTextRangeCompare: compares the positions of two TextRanges within a Text. // Only TextRange instances within the same Text can be compared. final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, documentConnection.xText); int pivot = 0; - boolean madeModifications = false; boolean setCharStyleTested = false; XNameAccess nameAccess = documentConnection.getReferenceMarks(); @@ -4092,12 +4111,14 @@ void assertCitationCharacterFormatIsOK( pivot++; } // while - if (madeModifications) { - updateSortedReferenceMarks(); - refreshCiteMarkers(databases, style); - } } finally { - documentConnection.unlockControllers(); + if (useLockControllers) { + documentConnection.unlockControllers(); + } + } + if (madeModifications) { + updateSortedReferenceMarks(); + refreshCiteMarkers(databases, style); } } @@ -4124,15 +4145,20 @@ void assertCitationCharacterFormatIsOK( BibEntryNotFoundException, NoDocumentException { + Objects.requireNonNull(databases); + Objects.requireNonNull(style); + + final boolean useLockControllers = true; DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + boolean madeModifications = false; + List names = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); try { - documentConnection.lockControllers(); - - List names = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + if (useLockControllers) { + documentConnection.lockControllers(); + } int pivot = 0; - boolean madeModifications = false; boolean setCharStyleTested = false; XNameAccess nameAccess = documentConnection.getReferenceMarks(); @@ -4199,14 +4225,26 @@ void assertCitationCharacterFormatIsOK( pivot++; } - if (madeModifications) { - updateSortedReferenceMarks(); + } finally { + if (useLockControllers) { + documentConnection.unlockControllers(); + } + } + if (madeModifications) { + updateSortedReferenceMarks(); + try { + if (useLockControllers) { + documentConnection.lockControllers(); + } refreshCiteMarkers(databases, style); + } finally { + if (useLockControllers) { + documentConnection.unlockControllers(); + } } - } finally { - documentConnection.unlockControllers(); } } + /** * Used from GUI: "Export cited" * @@ -4313,14 +4351,19 @@ void assertCitationCharacterFormatIsOK( boolean requireSeparation = false; // may loose citation without requireSeparation=true CitationGroups cg = new CitationGroups(documentConnection); cg.checkRangeOverlaps(this.xDocumentConnection, requireSeparation); + final boolean useLockControllers = true; try { - documentConnection.lockControllers(); updateSortedReferenceMarks(); + if (useLockControllers){ + documentConnection.lockControllers(); + } List unresolvedKeys = refreshCiteMarkers(databases, style); rebuildBibTextSection(databases, style); return unresolvedKeys; } finally { - documentConnection.unlockControllers(); + if (useLockControllers){ + documentConnection.unlockControllers(); + } } } From a7e292fe9b9692072c79ba3b01c9bbb9813965f8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 08:36:00 +0100 Subject: [PATCH 0451/1068] adjust controller locks --- .../org/jabref/gui/openoffice/OOBibBase.java | 28 +++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index bad8bef5d00..029ebdf316a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3293,9 +3293,7 @@ void assertCitationCharacterFormatIsOK( NoDocumentException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - try { - documentConnection.lockControllers(); XTextCursor cursor; // Get the cursor positioned by the user. try { @@ -3391,10 +3389,17 @@ void assertCitationCharacterFormatIsOK( // To account for numbering and for uniqueLetters, we // must refresh the cite markers: updateSortedReferenceMarks(); - refreshCiteMarkers(allBases, style); - // Insert it at the current position: - rebuildBibTextSection(allBases, style); + try { + documentConnection.lockControllers(); + + refreshCiteMarkers(allBases, style); + + // Insert it at the current position: + rebuildBibTextSection(allBases, style); + } finally { + documentConnection.unlockControllers(); + } /* * Problem: insertEntry in bibliography @@ -3413,8 +3418,6 @@ void assertCitationCharacterFormatIsOK( // loaded before connection, and therefore cannot directly reference // or catch a DisposedException (which is in a OO JAR file). throw new ConnectionLostException(ex.getMessage()); - } finally { - documentConnection.unlockControllers(); } } @@ -4118,7 +4121,16 @@ void assertCitationCharacterFormatIsOK( } if (madeModifications) { updateSortedReferenceMarks(); - refreshCiteMarkers(databases, style); + try { + if (useLockControllers) { + documentConnection.lockControllers(); + } + refreshCiteMarkers(databases, style); + } finally { + if (useLockControllers) { + documentConnection.unlockControllers(); + } + } } } From 8dc21976c1e7f45dfe310dbeb7f8f7387dfd8b8b Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 08:38:19 +0100 Subject: [PATCH 0452/1068] use assertCitationCharacterFormatIsOK --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 029ebdf316a..4bbca27c893 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4037,9 +4037,8 @@ void assertCitationCharacterFormatIsOK( // document: // Q: we may have zero characters selected. Is this a valid test // in this case? - if (style.isFormatCitations() && !setCharStyleTested) { - String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(textCursor, charStyle); + if (!setCharStyleTested) { + assertCitationCharacterFormatIsOK(textCursor, style); setCharStyleTested = true; } @@ -4188,9 +4187,8 @@ void assertCitationCharacterFormatIsOK( // way we can throw an exception before any reference // marks are removed, preventing damage to the user's // document: - if (style.isFormatCitations() && !setCharStyleTested) { - String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(textCursor, charStyle); + if (!setCharStyleTested) { + assertCitationCharacterFormatIsOK(textCursor, style); setCharStyleTested = true; } From 28fa3c6e32e2ec2126c7e71e8051cacd3fca99ec Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 08:40:26 +0100 Subject: [PATCH 0453/1068] fix bug: no merge without intervening space --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4bbca27c893..ba11045662a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4015,7 +4015,7 @@ void assertCitationCharacterFormatIsOK( // the next line moves INTO the next. And probably will // cover a non-whitespace character, inhibiting the merge. // Empirically: does not merge. Probably a bug. - textCursor.goRight((short) 1, true); + //textCursor.goRight((short) 1, true); boolean couldExpand = true; while (couldExpand && (compare.compareRegionEnds(textCursor, range2) > 0)) { couldExpand = textCursor.goRight((short) 1, true); From 8ba4c7bab476a3ba9ab74273192b456cc54f7a53 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 08:43:13 +0100 Subject: [PATCH 0454/1068] add styleIsRequired() --- .../org/jabref/gui/openoffice/OOBibBase.java | 27 +++++++++++++++++-- .../gui/openoffice/OpenOfficePanel.java | 10 +++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ba11045662a..652bf638e63 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3292,7 +3292,9 @@ void assertCitationCharacterFormatIsOK( UndefinedParagraphFormatException, NoDocumentException { + styleIsRequired(style); DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + try { XTextCursor cursor; // Get the cursor positioned by the user. @@ -3944,7 +3946,10 @@ void assertCitationCharacterFormatIsOK( PropertyVetoException, CreationException, BibEntryNotFoundException, - NoDocumentException { + NoDocumentException, + JabRefException { + + styleIsRequired(style); Objects.requireNonNull(databases); Objects.requireNonNull(style); @@ -4154,8 +4159,10 @@ void assertCitationCharacterFormatIsOK( PropertyVetoException, CreationException, BibEntryNotFoundException, - NoDocumentException { + NoDocumentException, + JabRefException { + styleIsRequired(style); Objects.requireNonNull(databases); Objects.requireNonNull(style); @@ -4330,6 +4337,20 @@ void assertCitationCharacterFormatIsOK( return resultDatabase; } + + void styleIsRequired( OOBibStyle style ) + throws JabRefException { + if ( style == null ) { + throw new JabRefException( + "This operation requires a style", + Localization.lang( + "This operation requires a style.\n" + + "Please select one." + ) + ); + } + } + /** * GUI action, refreshes citation markers and bibliography. * @@ -4357,6 +4378,8 @@ void assertCitationCharacterFormatIsOK( IOException, JabRefException { + styleIsRequired(style); + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); boolean requireSeparation = false; // may loose citation without requireSeparation=true CitationGroups cg = new CitationGroups(documentConnection); diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 9bb68874c95..fabbf0bc3ed 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -243,6 +243,11 @@ private void initPanel() { merge.setOnAction(e -> { try { ooBase.combineCiteMarkers(getBaseList(), style); + } catch (JabRefException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("JabRefException"), + ex.getLocalizedMessage() + ); } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); } catch (NoDocumentException ex) { @@ -259,6 +264,11 @@ private void initPanel() { unmerge.setOnAction(e -> { try { ooBase.unCombineCiteMarkers(getBaseList(), style); + } catch (JabRefException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("JabRefException"), + ex.getLocalizedMessage() + ); } catch (NoDocumentException ex) { showNoDocumentErrorMessage(); } catch (UndefinedCharacterFormatException ex) { From e1fb44fe5da8cf25b43798e744083f30d4a0442a Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 09:07:06 +0100 Subject: [PATCH 0455/1068] OOBibBase.insertEntry rename insertCitation --- .../org/jabref/gui/openoffice/OOBibBase.java | 2 +- .../gui/openoffice/OpenOfficePanel.java | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 652bf638e63..c52baedad92 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3265,7 +3265,7 @@ void assertCitationCharacterFormatIsOK( * */ public void - insertEntry( + insertCitation( List entries, BibDatabase database, List allBases, diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index fabbf0bc3ed..e61e6de2011 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -543,15 +543,16 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP if (style == null) { style = loader.getUsedStyle(); } - ooBase.insertEntry(entries, - database, - getBaseList(), - style, - inParenthesis, - withText, - pageInfo, - ooPrefs.getSyncWhenCiting() - ); + ooBase.insertCitation( + entries, + database, + getBaseList(), + style, + inParenthesis, + withText, + pageInfo, + ooPrefs.getSyncWhenCiting() + ); } catch (FileNotFoundException ex) { dialogService.showErrorDialogAndWait( From b18bbd1a06527cbdb97cdb10559bd2c6c7573f09 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 09:55:34 +0100 Subject: [PATCH 0456/1068] feature: when ignoring a "Cite" request, tell why --- .../org/jabref/gui/openoffice/OOBibBase.java | 12 +++++ .../gui/openoffice/OpenOfficePanel.java | 54 +++++++++++++++---- 2 files changed, 57 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c52baedad92..2952e4a58a1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3293,6 +3293,18 @@ void assertCitationCharacterFormatIsOK( NoDocumentException { styleIsRequired(style); + + if ( entries == null || entries.size() == 0 ) { + // System.out.println("insertCitation: throwing JabRefException"); + throw new JabRefException( + "No bibliography entries selected", + Localization.lang( + "No bibliography entries are selected for citation.\n" + + "Select some before citing." + ) + ); + } + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index e61e6de2011..07297dca2d0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -519,6 +519,50 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP } Boolean inParenthesis = inParenthesisIn; + + LibraryTab libraryTab = frame.getCurrentLibraryTab(); + final BibDatabase database = + (libraryTab == null + ? null + : libraryTab.getDatabase()); + + if (database == null) { + dialogService.showErrorDialogAndWait( + Localization.lang("No database"), + Localization.lang( + "No bibliography database is open for citation.\n" + + "Open one before citing." + ) + ); + return; + } + + List entries = libraryTab.getSelectedEntries(); + if (entries.isEmpty()){ + dialogService.showErrorDialogAndWait( + Localization.lang("No entries selected for citation"), + Localization.lang( + "No bibliography entries are selected for citation.\n" + + "Select some before citing." + ) + ); + return; + } + + if (style == null) { + style = loader.getUsedStyle(); + if (style == null) { + dialogService.showErrorDialogAndWait( + Localization.lang("No style for citation"), + Localization.lang( + "No bibliography style is selected for citation.\n" + + "Select one before citing." + ) + ); + return; + } + } + String pageInfo = null; if (addPageInfo) { @@ -533,16 +577,9 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP } } - LibraryTab libraryTab = frame.getCurrentLibraryTab(); - if (libraryTab != null) { - final BibDatabase database = libraryTab.getDatabase(); - List entries = libraryTab.getSelectedEntries(); - if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { + if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { try { - if (style == null) { - style = loader.getUsedStyle(); - } ooBase.insertCitation( entries, database, @@ -580,7 +617,6 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP LOGGER.warn("Could not insert entry", ex); } } - } } /** From 842790c5ba6674c0e3736fa7f514af55277555b5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 09:57:07 +0100 Subject: [PATCH 0457/1068] debugPartitions flag --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2952e4a58a1..d61ddecbd3e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1656,6 +1656,8 @@ String format() { WrappedTargetException, JabRefException { + final boolean debugPartitions = false; + List xs = citationRanges(documentConnection); xs.addAll(footnoteMarkRanges(documentConnection)); @@ -1669,7 +1671,8 @@ String format() { for (List partition : xxs.values()) { List oxs = sortPartitionByRegionStart(partition); - if ( debug ){ + + if ( debugPartitions ){ System.out.println("partition"); for (RangeForOverlapCheck r : oxs) { System.out.println(" " + r.format()); From d998739ae5e0526f81926b14bb77f753fdf0f80c Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 10:04:27 +0100 Subject: [PATCH 0458/1068] debugThisFun in getFillCursorForCitationGroup --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d61ddecbd3e..951155f18a7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2969,6 +2969,8 @@ public int getOrAllocateNumber(String key) { NoDocumentException, WrappedTargetException, CreationException { + + final boolean debugThisFun = false; final String left = referenceMarkLeftBracket; final String right = referenceMarkRightBracket; @@ -2991,18 +2993,18 @@ public int getOrAllocateNumber(String key) { ); } String fulltext = full.getString(); - if ( debug ){ + if ( debugThisFun ){ System.out.println(String.format("getFillCursor: fulltext = '%s'", fulltext)); } if (fulltext.length() < 2 || !fulltext.startsWith(left) || !fulltext.endsWith(right)){ // damaged, recreate - if ( debug ){ + if ( debugThisFun ){ System.out.println(String.format("getFillCursor: damaged, recreate")); } full.setString(""); if ( true ){ - if ( debug ){ + if ( debugThisFun ){ System.out.println(String.format("getFillCursor: removeReferenceMark go")); } try { @@ -3013,14 +3015,14 @@ public int getOrAllocateNumber(String key) { + " for '%s'", name)); } } else { - if ( debug ){ + if ( debugThisFun ){ System.out.println(String.format("getFillCursor: removeReferenceMark skipped")); } } // What shall we put in the recreated version? // User might have inserted stuff before or after? String trimmedtext = fulltext.replaceAll( "[" + left + right +"]", "" ); - if (debug){ + if (debugThisFun){ System.out.println(String.format("getFillCursor: trimmedtext = '%s'", trimmedtext)); } return createReferenceMarkForCitationGroup( @@ -3030,7 +3032,7 @@ public int getOrAllocateNumber(String key) { false, // insertSpaceAfter trimmedtext ); } else { - if (debug){ + if (debugThisFun){ System.out.println(String.format("getFillCursor: intact, reuse")); } full.collapseToStart(); From 45b145966da5bcbfb53d21ac351b49a60a0e054f Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 10:06:16 +0100 Subject: [PATCH 0459/1068] combineCiteMarkers: remove white space between consumed ciation markers --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 951155f18a7..c85d8573c21 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4100,6 +4100,8 @@ void assertCitationCharacterFormatIsOK( parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); + // Should also remove the spaces between. + textCursor.setString(""); documentConnection.removeReferenceMark(names.get(pivot)); documentConnection.removeReferenceMark(names.get(pivot + 1)); From 03d321b801fd28fc67d39100aa000d1b0827bc2a Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 16:18:31 +0100 Subject: [PATCH 0460/1068] DocumentConnection.comparable(XTextRange,XTextRange) and DocumentConnection.compareRegionStarts, compareRegionEnds --- .../org/jabref/gui/openoffice/OOBibBase.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c85d8573c21..00b457dd610 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -764,6 +764,40 @@ boolean hasControllersLocked(){ xcp.setPropertyValue("CharLocale", new Locale("zxx", "", "")); } + private static boolean + comparable( + XTextRange a, + XTextRange b + ) { + return a.getText() == b.getText(); + } + + /** + * @return 1 if (a < b), 0 if same start, (-1) if (b < a) + */ + private static int + compareRegionStarts( XTextRange a, XTextRange b ) { + if ( !comparable( a, b ) ){ + throw new RuntimeException( "compareRegionStarts: got incomparable regions" ); + } + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + a.getText()); + return compare.compareRegionStarts(a, b); + } + + /** + * @return 1 if (a < b), 0 if same start, (-1) if (b < a) + */ + private static int + compareRegionEnds( XTextRange a, XTextRange b ) { + if ( !comparable( a, b ) ){ + throw new RuntimeException( "compareRegionEnds: got incomparable regions" ); + } + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + a.getText()); + return compare.compareRegionEnds(a, b); + } + } // end DocumentConnection /** From 57a1860df7bd6cf98022b63faec629e9c70faa27 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 16:20:02 +0100 Subject: [PATCH 0461/1068] add recoverCitationKeyFromPossiblyUndefinedBibEntry --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 00b457dd610..79ca28f6712 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2040,6 +2040,16 @@ private static class FindCitedEntriesResult { return new FindCitedEntriesResult(entries, citeKeyToBibEntry); } + static String + recoverCitationKeyFromPossiblyUndefinedBibEntry( BibEntry entry ) { + if (entry instanceof UndefinedBibtexEntry) { + return ((UndefinedBibtexEntry) entry).getKey(); + } else { + Optional optKey = entry.getCitationKey(); + return optKey.get(); // may throw, but should not happen + } + } + /** * @return The list of citation keys from `instanceof * UndefinedBibtexEntry` elements of (keys of) `entries`. From 9eae550b2d488e63822306aa5516c66814d5afec Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 16:22:47 +0100 Subject: [PATCH 0462/1068] use visible brackets --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 79ca28f6712..37895442c01 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -106,7 +106,7 @@ class OOBibBase { private static final String zeroWidthSpace = "\u200b"; // for debugging we may want visible bracket - private static final boolean referenceMarkUseInvisibleBrackets = !debug; + private static final boolean referenceMarkUseInvisibleBrackets = false; // !debug; // Note we are relying on referenceMarkLeftBracket and referenceMarkRightBracket // to be single-character strings that do not appear in reference mark content. private static final String referenceMarkLeftBracket = From af22301b70e9a7f96ddb06f4031c62737d63cadd Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 16:23:22 +0100 Subject: [PATCH 0463/1068] reimplement combineCiteMarkers --- .../org/jabref/gui/openoffice/OOBibBase.java | 303 +++++++++++------- 1 file changed, 186 insertions(+), 117 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 37895442c01..51bc29d41f3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4015,149 +4015,219 @@ void assertCitationCharacterFormatIsOK( Objects.requireNonNull(databases); Objects.requireNonNull(style); + + final boolean debugCombineCiteMarkers = true; + final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); boolean madeModifications = false; - try { + // The testing for whitespace-only between (pivot) and (pivot+1) assumes that + // referenceMarkNames are in textual order: textually consecutive pairs + // must appear as neighbours (and in textual order). + // We have a bit of a clash here: referenceMarkNames is sorted by visual position, + // but we are testing if they are textually neighbours. + // In a two-column layout + // | a | c | + // | b | d | + // abcd is the textual order, but the visual order is acbd. + // So we will not find out that a and b are only separated by white space. + List referenceMarkNames = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + + final int nRefMarks = referenceMarkNames.size(); + int[] itcTypes = new int[nRefMarks]; + String[][] bibtexKeys = new String[nRefMarks][]; + parseRefMarkNamesToArrays(referenceMarkNames, itcTypes, bibtexKeys); + - // The testing for whitespace-only between (pivot) and (pivot+1) assumes that - // names are in textual order: textually consecutive pairs - // must appear as neighbours (and in textual order). - // We have a bit of a clash here: names is sorted by visual position, - // but we are testing if they are textually neighbours. - // In a two-column layout - // | a | c | - // | b | d | - // abcd is the textual order, but the visual order is acbd. - // So we will not find out that a and b are only separated by white space. - List names = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + try { if (useLockControllers) { documentConnection.lockControllers(); } - // XTextRangeCompare: compares the positions of two TextRanges within a Text. - // Only TextRange instances within the same Text can be compared. - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - documentConnection.xText); - int pivot = 0; - boolean setCharStyleTested = false; - XNameAccess nameAccess = documentConnection.getReferenceMarks(); + /* + * joinableGroups collects lists of indices of referenceMarkNames + * that we think are joinable. + * + * joinableGroupsCursors provides the range for each group + */ + List> joinableGroups = new ArrayList<>(); + List joinableGroupsCursors = new ArrayList<>(); - while (pivot < (names.size() - 1)) { + // current group + List currentGroup = new ArrayList<>(); + XTextCursor currentGroupCursor = null; + XTextCursor cursorBetween = null; + Integer prev = null; - XTextRange range1 = - DocumentConnection.asTextContent( - nameAccess.getByName(names.get(pivot))) - .getAnchor() - .getEnd(); + for ( int i=0; i < referenceMarkNames.size(); i++ ) { + final String name = referenceMarkNames.get(i); - XTextRange range2 = - DocumentConnection.asTextContent( - nameAccess.getByName(names.get(pivot + 1))) - .getAnchor() - .getStart(); // end of range2 is the start of (pivot + 1) - - if (range1.getText() != range2.getText()) { - /* pivot and (pivot+1) belong to different Text instances. - * Maybe to different footnotes? - * Cannot combine across boundaries, skip. - */ - pivot++; - continue; - } - // Start from end of text for pivot. - XTextCursor textCursor = - range1.getText().createTextCursorByRange(range1); + boolean addToGroup = true; + /* + * Decide if we add name to the group + */ - // Select next character (if possible), and more, as long as we can and - // do not reach start of (pivot+1), which we now know to be - // in the same Text instance. - - // If there is no space between the two reference marks, - // the next line moves INTO the next. And probably will - // cover a non-whitespace character, inhibiting the merge. - // Empirically: does not merge. Probably a bug. - //textCursor.goRight((short) 1, true); - boolean couldExpand = true; - while (couldExpand && (compare.compareRegionEnds(textCursor, range2) > 0)) { - couldExpand = textCursor.goRight((short) 1, true); + // Only combine (Author 2000) type citations + if ( itcTypes[i] != OOBibBase.AUTHORYEAR_PAR ) { + addToGroup = false; } - // Take what we selected - String cursorText = textCursor.getString(); + // Even if we combined other types of citations, we would not mix them + if (addToGroup && (prev != null) ) { + if ( itcTypes[i] != itcTypes[prev] ){ + addToGroup = false; + } + } - // Check if the string contains line breaks and any non-whitespace. - if ((cursorText.indexOf('\n') != -1) || !cursorText.trim().isEmpty()) { - pivot++; - continue; + if (addToGroup && (cursorBetween != null)) { + Objects.requireNonNull(currentGroupCursor); + // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() + if (DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + throw new RuntimeException( + "combineCiteMarkers: cursorBetween.end != currentGroupCursor.end"); + } + + XTextRange range2 = + documentConnection.getReferenceMarkRangeOrNull(name); + XTextRange range2Start = range2.getStart(); + + boolean couldExpand = true; + XTextCursor thisCharCursor = + range2.getText().createTextCursorByRange(cursorBetween.getEnd()); + while (couldExpand && + (DocumentConnection.compareRegionEnds(cursorBetween, range2Start) > 0)) { + couldExpand = cursorBetween.goRight((short) 1, true); + currentGroupCursor.goRight((short) 1, true); + // + thisCharCursor.goRight((short) 1, true); + String thisChar = thisCharCursor.getString(); + thisCharCursor.collapseToEnd(); + if (thisChar.isEmpty() + || thisChar == "\n" + || !thisChar.trim().isEmpty() ) { + couldExpand = false; + } + } + + if (!couldExpand) { + addToGroup = false; + } + if (DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + throw new RuntimeException( + "combineCiteMarkers: " + + "cursorBetween.end != currentGroupCursor.end (after expand)" ); + } } - // If we are supposed to set character format for - // citations, test this before making any changes. This - // way we can throw an exception before any reference - // marks are removed, preventing damage to the user's - // document: - // Q: we may have zero characters selected. Is this a valid test - // in this case? - if (!setCharStyleTested) { - assertCitationCharacterFormatIsOK(textCursor, style); - setCharStyleTested = true; + /* + * Even if we do not add it to an existing group, we might use it toi start + * a new group. + */ + // can it start a new group? + boolean canStartGroup = ( itcTypes[i] == OOBibBase.AUTHORYEAR_PAR ); + + if (!addToGroup){ + // close currentGroup + if (currentGroup.size() > 1) { + joinableGroups.add( currentGroup ); + joinableGroupsCursors.add( currentGroupCursor ); + } + // Start a new, empty group + currentGroup = new ArrayList<>(); + currentGroupCursor = null; + cursorBetween = null; + prev = null; + } + + if ( addToGroup || canStartGroup ) { + // Add the current entry to a group. + currentGroup.add(i); + // Set up cursorBetween + XTextRange range1Full = + documentConnection.getReferenceMarkRangeOrNull(name); + XTextRange range1End = range1Full.getEnd(); + cursorBetween = range1Full.getText().createTextCursorByRange(range1Full.getEnd()); + // currentGroupCursor + if ( currentGroupCursor == null ) { + currentGroupCursor = + range1Full.getText().createTextCursorByRange(range1Full.getStart()); + } + // include self in currentGroupCursor + currentGroupCursor.goRight( (short)( range1Full.getString().length() ), true ); + prev = i; } + } + + if (joinableGroups.size() > 0) { + XTextCursor textCursor = joinableGroupsCursors.get(0); + assertCitationCharacterFormatIsOK(textCursor, style); + } /* - * This only gets the keys: itcType is discarded. - * - * AUTHORYEAR_PAR: "(X and Y 2000)" - * AUTHORYEAR_INTEXT: "X and Y (2000)" - * INVISIBLE_CIT: "" - * - * We probably only want to collect citations with - * AUTHORYEAR_PAR itcType. - * - * No, "X and Y (2000,2001)" appears a meaningful - * case as well. - * - * Proposed rules: - * (1) Do not combine citations with different itcType - * (2) INVISIBLE_CIT: leave it alone - * (3) AUTHORYEAR_PAR: combine, present as AUTHORYEAR_PAR - * - * (4) AUTHORYEAR_INTEXT: Same list of authors with - * same or different years, possibly with - * uniqueLetters could be done. - * But with different list of authors? - * "(X, Y et al 2000) (X, Y et al 2001)" - * will depend on authors not shown here. - * + * Now we can process the joinable groups */ - // Note: silently drops duplicate keys. - // What if they have different pageInfo fields? + for (int gi = 0; gi < joinableGroups.size(); gi++ ){ - // combineCiteMarkers: merging for same citation keys, - // but different pageInfo looses information. - List keys = - parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); - keys.addAll(parseRefMarkNameToUniqueCitationKeys(names.get(pivot + 1))); + List allKeys = new ArrayList<>(); + for (int gj = 0; gj < joinableGroups.get(gi).size(); gj++) { + int rk = joinableGroups.get(gi).get(gj); + allKeys.addAll( Arrays.asList( bibtexKeys[rk] ) ); + } + // Note: silently drops duplicate keys. + // What if they have different pageInfo fields? + + // combineCiteMarkers: merging for same citation keys, + // but different pageInfo looses information. + List uniqueKeys = + (allKeys.stream() + .distinct() + .collect(Collectors.toList())); + + if (true) { + // Removing the old referenceMarkNames from the document + // is covered by removing the text. + // We might want somehting similar + for (int gj = 0; gj < joinableGroups.get(gi).size(); gj++) { + int rk = joinableGroups.get(gi).get(gj); + documentConnection.removeReferenceMark(referenceMarkNames.get(rk)); + } + } + XTextCursor textCursor = joinableGroupsCursors.get(gi); // Should also remove the spaces between. textCursor.setString(""); - documentConnection.removeReferenceMark(names.get(pivot)); - documentConnection.removeReferenceMark(names.get(pivot + 1)); // Note: citation keys not found are silently left out from the // combined reference mark name. Loosing information. - List entries = lookupEntriesInDatabasesSkipMissing(keys, databases); - entries.sort(new FieldComparator(StandardField.YEAR)); - - String keyString = - entries.stream() - .map(c -> c.getCitationKey().orElse("")) - .collect(Collectors.joining(",")); + boolean oldStrategy = false; + List entries ; + String keyString; + if (oldStrategy) { + entries = lookupEntriesInDatabasesSkipMissing(uniqueKeys, databases); + entries.sort(new FieldComparator(StandardField.YEAR)); + keyString = + entries.stream() + .map(c -> c.getCitationKey().orElse("")) + .collect(Collectors.joining(",")); + } else { + FindCitedEntriesResult fcr = findCitedEntries( uniqueKeys, databases ); + // entries contains UndefinedBibtexEntry for keys not found in databases + entries = new ArrayList<>(); + for (Map.Entry kv : fcr.entries.entrySet()) { + entries.add( kv.getKey() ); + } + // Now we do not sort the entries here. + // entries.sort(new FieldComparator(StandardField.YEAR)); + keyString = + entries.stream() + .map(OOBibBase::recoverCitationKeyFromPossiblyUndefinedBibEntry) + .collect(Collectors.joining(",")); + } // Insert reference mark: String newName = @@ -4165,7 +4235,7 @@ void assertCitationCharacterFormatIsOK( documentConnection, keyString, OOBibBase.AUTHORYEAR_PAR); - // xxx + insertReferenceMark( documentConnection, newName, @@ -4173,19 +4243,18 @@ void assertCitationCharacterFormatIsOK( textCursor, true, // withText style, - true // insertSpaceAfter + false // insertSpaceAfter: no, it is already there (or could be) ); - names.set(pivot + 1, newName); // <- put in the next-to-be-processed position - madeModifications = true; + } // for gi - pivot++; - } // while + madeModifications = (joinableGroups.size() > 0); } finally { if (useLockControllers) { documentConnection.unlockControllers(); } } + if (madeModifications) { updateSortedReferenceMarks(); try { From b19c9be9ffee2d5e7101aa95fd09d5d291e3a75e Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 17:54:04 +0100 Subject: [PATCH 0464/1068] bug: must close last group --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 51bc29d41f3..acdfb17b884 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4162,6 +4162,20 @@ void assertCitationCharacterFormatIsOK( } } + if (true) { + // close currentGroup + if (currentGroup.size() > 1) { + joinableGroups.add( currentGroup ); + joinableGroupsCursors.add( currentGroupCursor ); + } + // clean variables + currentGroup = null; + currentGroupCursor = null; + cursorBetween = null; + prev = null; + } + + if (joinableGroups.size() > 0) { XTextCursor textCursor = joinableGroupsCursors.get(0); assertCitationCharacterFormatIsOK(textCursor, style); From 4d8d80230f60b6475a71f7792f7c20b3fd16292d Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 18:12:41 +0100 Subject: [PATCH 0465/1068] mark code to be revisited with xxx --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index acdfb17b884..e269882d641 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4218,10 +4218,11 @@ void assertCitationCharacterFormatIsOK( // Note: citation keys not found are silently left out from the // combined reference mark name. Loosing information. - boolean oldStrategy = false; + boolean oldStrategy = false; //xxx List entries ; String keyString; if (oldStrategy) { + //xxx entries = lookupEntriesInDatabasesSkipMissing(uniqueKeys, databases); entries.sort(new FieldComparator(StandardField.YEAR)); keyString = From d1852c37e8d0e31e4215f58fd0ad93bd93ec2db0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 19:09:34 +0100 Subject: [PATCH 0466/1068] DocumentConnection.enterUndoContext, leaveUndoContext --- .../org/jabref/gui/openoffice/OOBibBase.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e269882d641..75ab76df967 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -55,6 +55,8 @@ import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; import com.sun.star.document.XDocumentPropertiesSupplier; +import com.sun.star.document.XUndoManagerSupplier; +import com.sun.star.document.XUndoManager; import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XController; import com.sun.star.frame.XDesktop; @@ -84,6 +86,7 @@ import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; +import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -159,6 +162,8 @@ private static class DocumentConnection { this.mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); // unoQI(XDocumentIndexesSupplier.class, component); + + // get a reference to the body text of the document this.xText = mxDoc.getText(); @@ -174,6 +179,26 @@ private static class DocumentConnection { this.propertySet = unoQI(XPropertySet.class, userProperties); } + /** + * Each call to enterUndoContext must be paired by a call to + * leaveUndoContext, otherwise, the document's undo stack is + * left in an inconsistent state. + */ + void enterUndoContext(String title) { + XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); + XUndoManager um = mxUndoManagerSupplier.getUndoManager(); + // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html + um.enterUndoContext( title ); + } + + void leaveUndoContext() + throws InvalidStateException { + XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); + XUndoManager um = mxUndoManagerSupplier.getUndoManager(); + // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html + um.leaveUndoContext(); + } + /* * Disable screen refresh. * From f640c7cd975f5a4ebbc8dc08308ddbb1ce4867f8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 19:10:11 +0100 Subject: [PATCH 0467/1068] combineCiteMarkers uses enterUndoContext --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 ++++++++-- .../org/jabref/gui/openoffice/OpenOfficePanel.java | 2 ++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 75ab76df967..1980a9747e0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4033,18 +4033,21 @@ void assertCitationCharacterFormatIsOK( CreationException, BibEntryNotFoundException, NoDocumentException, - JabRefException { + JabRefException, + InvalidStateException { styleIsRequired(style); Objects.requireNonNull(databases); Objects.requireNonNull(style); - final boolean debugCombineCiteMarkers = true; final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + try { + documentConnection.enterUndoContext("Merge citations"); + boolean madeModifications = false; // The testing for whitespace-only between (pivot) and (pivot+1) assumes that @@ -4308,6 +4311,9 @@ void assertCitationCharacterFormatIsOK( } } } + } finally { + documentConnection.leaveUndoContext(); + } } /** diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 07297dca2d0..b98df3f7ec9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -63,6 +63,7 @@ import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; +import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -254,6 +255,7 @@ private void initPanel() { showNoDocumentErrorMessage(); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | + InvalidStateException | BibEntryNotFoundException ex) { LOGGER.warn("Problem combining cite markers", ex); } From 20a660098977c36f97985a2af9cdd3a9d8ba8ffb Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 19:16:38 +0100 Subject: [PATCH 0468/1068] feature: Undo for "Separate citations" --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 +++++++- .../java/org/jabref/gui/openoffice/OpenOfficePanel.java | 1 + 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1980a9747e0..1b02db7a9b8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4338,7 +4338,8 @@ void assertCitationCharacterFormatIsOK( CreationException, BibEntryNotFoundException, NoDocumentException, - JabRefException { + JabRefException, + InvalidStateException { styleIsRequired(style); Objects.requireNonNull(databases); @@ -4346,6 +4347,8 @@ void assertCitationCharacterFormatIsOK( final boolean useLockControllers = true; DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + try { + documentConnection.enterUndoContext("Separate citations"); boolean madeModifications = false; List names = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); @@ -4438,6 +4441,9 @@ void assertCitationCharacterFormatIsOK( } } } + } finally { + documentConnection.leaveUndoContext(); + } } /** diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index b98df3f7ec9..f97bbf1a0a1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -277,6 +277,7 @@ private void initPanel() { reportUndefinedCharacterFormat(ex); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | + InvalidStateException | BibEntryNotFoundException ex) { LOGGER.warn("Problem uncombining cite markers", ex); } From 05600d7e5b10e375ab821ea2019fc7cfbf366545 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 19:36:45 +0100 Subject: [PATCH 0469/1068] insertCitation uses undo context "Insert citation" --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +++++++++++++++++-- .../gui/openoffice/OpenOfficePanel.java | 2 ++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1b02db7a9b8..e62331541bb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3301,6 +3301,11 @@ void assertCitationCharacterFormatIsOK( * "Cite", "Cite in-text", "Cite special" and "Insert empty * citation". * + * Uses LO undo context "Insert citation". + * + * Note: Undo does not remove custom properties. Presumably + * neither does it reestablish them. + * * This method inserts a reference mark in the text (at the * cursor) citing the entries, and (if sync is true) refreshes the * citation markers and the bibliography. @@ -3364,7 +3369,8 @@ void assertCitationCharacterFormatIsOK( CreationException, BibEntryNotFoundException, UndefinedParagraphFormatException, - NoDocumentException { + NoDocumentException, + InvalidStateException { styleIsRequired(style); @@ -3382,6 +3388,7 @@ void assertCitationCharacterFormatIsOK( DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { + documentConnection.enterUndoContext("Insert citation"); XTextCursor cursor; // Get the cursor positioned by the user. try { @@ -3506,6 +3513,8 @@ void assertCitationCharacterFormatIsOK( // loaded before connection, and therefore cannot directly reference // or catch a DisposedException (which is in a OO JAR file). throw new ConnectionLostException(ex.getMessage()); + } finally { + documentConnection.leaveUndoContext(); } } @@ -4560,11 +4569,15 @@ void styleIsRequired( OOBibStyle style ) UndefinedCharacterFormatException, BibEntryNotFoundException, IOException, - JabRefException { + JabRefException, + InvalidStateException { styleIsRequired(style); DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + try { + documentConnection.enterUndoContext("Refresh bibliography"); + boolean requireSeparation = false; // may loose citation without requireSeparation=true CitationGroups cg = new CitationGroups(documentConnection); cg.checkRangeOverlaps(this.xDocumentConnection, requireSeparation); @@ -4582,6 +4595,9 @@ void styleIsRequired( OOBibStyle style ) documentConnection.unlockControllers(); } } + } finally { + documentConnection.leaveUndoContext(); + } } } // end of OOBibBase diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index f97bbf1a0a1..1511de4b76f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -234,6 +234,7 @@ private void initPanel() { "Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", ex.getCitationKey())); } catch (com.sun.star.lang.IllegalArgumentException | PropertyVetoException | UnknownPropertyException | WrappedTargetException | NoSuchElementException | + InvalidStateException | CreationException ex) { LOGGER.warn("Could not update bibliography", ex); } @@ -616,6 +617,7 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | BibEntryNotFoundException | IllegalTypeException | PropertyExistException | + InvalidStateException | NotRemoveableException ex) { LOGGER.warn("Could not insert entry", ex); } From 78af70b15a6220969935cc02657757376f0f1cc9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 19:52:10 +0100 Subject: [PATCH 0470/1068] no undo for applyCitationEntries --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e62331541bb..5d33d71579f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1887,7 +1887,11 @@ String format() { * Apply editable parts of citationEntries to the document: store * pageInfo. * - * Does not chaneg presentation. + * Does not change presentation. + * + * Note: we use no undo context here, beacuse only + * documentConnection.setCustomProperty() is called, + * and Undo in LO will not undo that. * * GUI: "Manage citations" dialog "OK" button. * Called from: ManageCitationsDialogViewModel.storeSettings From e8506e93ee2fb97a2dadfa525d7b8a0b02bb89e2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 20:29:07 +0100 Subject: [PATCH 0471/1068] refactor: OOBibBase.exportCitedHelper Collects multiple calls from the GUI into one --- .../org/jabref/gui/openoffice/OOBibBase.java | 31 +++++++++++++++ .../gui/openoffice/OpenOfficePanel.java | 39 ++++++++++++------- 2 files changed, 57 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5d33d71579f..39459bdf9ca 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3528,6 +3528,37 @@ void assertCitationCharacterFormatIsOK( * * **************************************************/ + class ExportCitedHelperResult { + /** + * null: not done; isempty: no unresolved + */ + List unresolvedKeys; + BibDatabase newDatabase; + } + + public ExportCitedHelperResult exportCitedHelper( + List databases, + OOBibStyle style + ) + throws + WrappedTargetException, + NoSuchElementException, + NoDocumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException { + ExportCitedHelperResult res = new ExportCitedHelperResult(); + + this.updateSortedReferenceMarks(); // NoDocumentException + res.unresolvedKeys = this.refreshCiteMarkers(databases, style); + res.newDatabase = this.generateDatabase(databases); + + return res; + } + /** * Refresh all citation markers in the document. * diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 1511de4b76f..3d112e4352c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -346,28 +346,41 @@ private void exportEntries() { return; } - ooBase.updateSortedReferenceMarks(); // NoDocumentException - List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style); - BibDatabase newDatabase = ooBase.generateDatabase(databases); - if (!unresolvedKeys.isEmpty()) { + OOBibBase.ExportCitedHelperResult r = ooBase.exportCitedHelper( databases, style ); + if ( r.unresolvedKeys == null ){ + throw new RuntimeException("OpenOfficePanel.exportEntries: r.unresolvedKeys is null"); + } + if ( r.newDatabase == null ){ + throw new RuntimeException("OpenOfficePanel.exportEntries: r.newDatabase is null"); + } + if (!r.unresolvedKeys.isEmpty()) { dialogService.showErrorDialogAndWait(Localization.lang("Unable to generate new library"), Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - unresolvedKeys.get(0))); + r.unresolvedKeys.get(0))); } - BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase); + BibDatabaseContext databaseContext = new BibDatabaseContext(r.newDatabase); this.frame.addTab(databaseContext, true); - } catch (NoDocumentException ex) { + } catch (NoDocumentException ex) { showNoDocumentErrorMessage(); } catch (BibEntryNotFoundException ex) { LOGGER.debug("BibEntry not found", ex); - dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), - Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - ex.getCitationKey())); - } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | - UndefinedCharacterFormatException | NoSuchElementException | WrappedTargetException | IOException | - CreationException e) { + dialogService.showErrorDialogAndWait( + Localization.lang("Unable to synchronize bibliography"), + Localization.lang( + "Your OpenOffice/LibreOffice document references the citation key '%0'," + + " which could not be found in your current library.", + ex.getCitationKey())); + } catch (com.sun.star.lang.IllegalArgumentException + | UnknownPropertyException + | PropertyVetoException + | UndefinedCharacterFormatException + | NoSuchElementException + | WrappedTargetException + | IOException + | CreationException e + ) { LOGGER.warn("Problem generating new database.", e); } } From cfb4dd2a8b9c6202b73f78fbb96d4fe3edb50aab Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 20:44:43 +0100 Subject: [PATCH 0472/1068] exportCitedHelper now has Undo (although it should not need it) --- .../org/jabref/gui/openoffice/OOBibBase.java | 23 +++++++++++++++---- .../gui/openoffice/OpenOfficePanel.java | 1 + 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 39459bdf9ca..c8c1d4af8c2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3536,6 +3536,12 @@ class ExportCitedHelperResult { BibDatabase newDatabase; } + /** + * Helper for GUI action "Export cited" + * + * Refreshes citation markers, (although the user did not ask for that). + * Does not refresh the bibliography. + */ public ExportCitedHelperResult exportCitedHelper( List databases, OOBibStyle style @@ -3549,13 +3555,20 @@ public ExportCitedHelperResult exportCitedHelper( PropertyVetoException, IOException, CreationException, - BibEntryNotFoundException { - ExportCitedHelperResult res = new ExportCitedHelperResult(); + BibEntryNotFoundException, + InvalidStateException { - this.updateSortedReferenceMarks(); // NoDocumentException - res.unresolvedKeys = this.refreshCiteMarkers(databases, style); - res.newDatabase = this.generateDatabase(databases); + ExportCitedHelperResult res = new ExportCitedHelperResult(); + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + try { + documentConnection.enterUndoContext("Changes during \"Export cited\""); + this.updateSortedReferenceMarks(); // NoDocumentException + res.unresolvedKeys = this.refreshCiteMarkers(databases, style); + res.newDatabase = this.generateDatabase(databases); + } finally { + documentConnection.leaveUndoContext(); + } return res; } diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 3d112e4352c..508b407361d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -379,6 +379,7 @@ private void exportEntries() { | NoSuchElementException | WrappedTargetException | IOException + | InvalidStateException | CreationException e ) { LOGGER.warn("Problem generating new database.", e); From 879cb93a2a619cae2a6617a02277f6abf73baad5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 20:59:27 +0100 Subject: [PATCH 0473/1068] refactor: refreshCiteMarkers can be private now --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c8c1d4af8c2..1718573d74c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3575,13 +3575,13 @@ public ExportCitedHelperResult exportCitedHelper( /** * Refresh all citation markers in the document. * - * GUI: called as part of "Export cited" + * Called from exportCitedHelper * * @param databases The databases to get entries from. * @param style The bibliography style to use. * @return A list of those referenced citation keys that could not be resolved. */ - public List + private List refreshCiteMarkers( List databases, OOBibStyle style) From a8cc1b17954e7d7e735626146bf4bd2c8b81ba60 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 21:00:30 +0100 Subject: [PATCH 0474/1068] Refresh now reports all unresolved keys --- .../java/org/jabref/gui/openoffice/OpenOfficePanel.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 508b407361d..e74f8650774 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -206,10 +206,9 @@ private void initPanel() { .showErrorDialogAndWait( Localization.lang("Unable to synchronize bibliography"), Localization.lang("Your OpenOffice/LibreOffice document references" - + " the citation key '%0'," - + " which could not be found in your current library.", - unresolvedKeys.get(0)) - ); + + " citation keys which could not be found" + + " in your current library: %0", + String.join(" ", unresolvedKeys))); } } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( From 0d1f8741430741de5d5a562e3fb5be6743ff7609 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 21:19:35 +0100 Subject: [PATCH 0475/1068] drop jabRefReferenceMarkNamesSortedByPosition, updateSortedReferenceMarks jabRefReferenceMarkNamesSortedByPosition is now passed around explicitly --- .../org/jabref/gui/openoffice/OOBibBase.java | 75 ++++++++----------- 1 file changed, 32 insertions(+), 43 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1718573d74c..be91be16432 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -843,13 +843,6 @@ boolean hasControllersLocked(){ */ private final Map xUniqueLetters = new HashMap<>(); - /** - * Names of reference marks belonging to JabRef sorted by visual - * position. - * - */ - private List jabRefReferenceMarkNamesSortedByPosition; - /* * Constructor */ @@ -2362,25 +2355,6 @@ public int hashCode() { return result; } - /** - * Refresh list of JabRef reference marks (sorts by position). - * - * Probably should be called at the start of actions from the GUI, - * that rely on jabRefReferenceMarkNamesSortedByPosition to be up-to-date. - */ - public void - updateSortedReferenceMarks() - throws - WrappedTargetException, - NoSuchElementException, - NoDocumentException { - - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - - this.jabRefReferenceMarkNamesSortedByPosition = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - } - /** * Return bibliography entries sorted according to the order of * first appearance in referenceMarkNames. @@ -3487,15 +3461,16 @@ void assertCitationCharacterFormatIsOK( if (sync) { // To account for numbering and for uniqueLetters, we // must refresh the cite markers: - updateSortedReferenceMarks(); + List jabRefReferenceMarkNamesSortedByPosition = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); try { documentConnection.lockControllers(); - refreshCiteMarkers(allBases, style); + refreshCiteMarkers(allBases, style, jabRefReferenceMarkNamesSortedByPosition); // Insert it at the current position: - rebuildBibTextSection(allBases, style); + rebuildBibTextSection(allBases, style, jabRefReferenceMarkNamesSortedByPosition); } finally { documentConnection.unlockControllers(); } @@ -3563,8 +3538,12 @@ public ExportCitedHelperResult exportCitedHelper( try { documentConnection.enterUndoContext("Changes during \"Export cited\""); - this.updateSortedReferenceMarks(); // NoDocumentException - res.unresolvedKeys = this.refreshCiteMarkers(databases, style); + List jabRefReferenceMarkNamesSortedByPosition = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + res.unresolvedKeys = + this.refreshCiteMarkers(databases, + style, + jabRefReferenceMarkNamesSortedByPosition); res.newDatabase = this.generateDatabase(databases); } finally { documentConnection.leaveUndoContext(); @@ -3584,7 +3563,8 @@ public ExportCitedHelperResult exportCitedHelper( private List refreshCiteMarkers( List databases, - OOBibStyle style) + OOBibStyle style, + List jabRefReferenceMarkNamesSortedByPosition) throws WrappedTargetException, IllegalArgumentException, @@ -3605,7 +3585,8 @@ public ExportCitedHelperResult exportCitedHelper( documentConnection, databases, style, - this.xUniqueLetters); + this.xUniqueLetters, + jabRefReferenceMarkNamesSortedByPosition); } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference @@ -3724,7 +3705,8 @@ public ExportCitedHelperResult exportCitedHelper( DocumentConnection documentConnection, List databases, OOBibStyle style, - final Map uniqueLetters + final Map uniqueLetters, + List jabRefReferenceMarkNamesSortedByPosition ) throws WrappedTargetException, @@ -3822,7 +3804,9 @@ public ExportCitedHelperResult exportCitedHelper( public void rebuildBibTextSection( List databases, - OOBibStyle style) + OOBibStyle style, + List jabRefReferenceMarkNamesSortedByPosition + ) throws NoSuchElementException, WrappedTargetException, @@ -4356,12 +4340,13 @@ public ExportCitedHelperResult exportCitedHelper( } if (madeModifications) { - updateSortedReferenceMarks(); + List jabRefReferenceMarkNamesSortedByPosition = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); try { if (useLockControllers) { documentConnection.lockControllers(); } - refreshCiteMarkers(databases, style); + refreshCiteMarkers(databases, style, jabRefReferenceMarkNamesSortedByPosition); } finally { if (useLockControllers) { documentConnection.unlockControllers(); @@ -4486,12 +4471,13 @@ public ExportCitedHelperResult exportCitedHelper( } } if (madeModifications) { - updateSortedReferenceMarks(); + List jabRefReferenceMarkNamesSortedByPosition = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); try { if (useLockControllers) { documentConnection.lockControllers(); } - refreshCiteMarkers(databases, style); + refreshCiteMarkers(databases, style, jabRefReferenceMarkNamesSortedByPosition); } finally { if (useLockControllers) { documentConnection.unlockControllers(); @@ -4599,7 +4585,6 @@ void styleIsRequired( OOBibStyle style ) * @param style Style. * @return List of unresolved citation keys. * - * Note: calls updateSortedReferenceMarks(); */ public List updateDocumentActionHelper( @@ -4631,12 +4616,16 @@ void styleIsRequired( OOBibStyle style ) cg.checkRangeOverlaps(this.xDocumentConnection, requireSeparation); final boolean useLockControllers = true; try { - updateSortedReferenceMarks(); + List jabRefReferenceMarkNamesSortedByPosition = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); if (useLockControllers){ documentConnection.lockControllers(); } - List unresolvedKeys = refreshCiteMarkers(databases, style); - rebuildBibTextSection(databases, style); + List unresolvedKeys = + refreshCiteMarkers(databases, + style, + jabRefReferenceMarkNamesSortedByPosition); + rebuildBibTextSection(databases, style, jabRefReferenceMarkNamesSortedByPosition); return unresolvedKeys; } finally { if (useLockControllers){ From 912bd1864d359bdbbf1a7ec8466e76f772bb2270 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 11 Mar 2021 22:19:56 +0100 Subject: [PATCH 0476/1068] localization strings --- .../org/jabref/gui/openoffice/OOBibBase.java | 14 +++++------ .../gui/openoffice/OpenOfficePanel.java | 24 ++++++++++--------- src/main/resources/l10n/JabRef_en.properties | 20 ++++++++++++++++ 3 files changed, 39 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index be91be16432..594578a66e2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3357,9 +3357,9 @@ void assertCitationCharacterFormatIsOK( throw new JabRefException( "No bibliography entries selected", Localization.lang( - "No bibliography entries are selected for citation.\n" - + "Select some before citing." - ) + "No bibliography entries are selected for citation.") + + "\n" + + Localization.lang("Select some before citing.") ); } @@ -4564,16 +4564,14 @@ public ExportCitedHelperResult exportCitedHelper( return resultDatabase; } - void styleIsRequired( OOBibStyle style ) throws JabRefException { if ( style == null ) { throw new JabRefException( "This operation requires a style", - Localization.lang( - "This operation requires a style.\n" - + "Please select one." - ) + Localization.lang("This operation requires a style.") + + "\n" + + Localization.lang("Please select one.") ); } } diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index e74f8650774..8eae192e84b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -207,8 +207,9 @@ private void initPanel() { Localization.lang("Unable to synchronize bibliography"), Localization.lang("Your OpenOffice/LibreOffice document references" + " citation keys which could not be found" - + " in your current library: %0", - String.join(" ", unresolvedKeys))); + + " in your current library.") + + "\n" + + String.join(" ", unresolvedKeys)); } } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( @@ -547,9 +548,9 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP dialogService.showErrorDialogAndWait( Localization.lang("No database"), Localization.lang( - "No bibliography database is open for citation.\n" - + "Open one before citing." - ) + "No bibliography database is open for citation.") + + "\n" + + Localization.lang("Open one before citing.") ); return; } @@ -559,9 +560,9 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP dialogService.showErrorDialogAndWait( Localization.lang("No entries selected for citation"), Localization.lang( - "No bibliography entries are selected for citation.\n" - + "Select some before citing." - ) + "No bibliography entries are selected for citation.") + + "\n" + + Localization.lang("Select some before citing.") ); return; } @@ -572,9 +573,10 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP dialogService.showErrorDialogAndWait( Localization.lang("No style for citation"), Localization.lang( - "No bibliography style is selected for citation.\n" - + "Select one before citing." - ) + "No bibliography style is selected for citation.") + + "\n" + + Localization.lang( + "Select one before citing.") ); return; } diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 787ee746e93..1c7fe0081e9 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1037,7 +1037,10 @@ Connected\ to\ document=Connected to document Insert\ a\ citation\ without\ text\ (the\ entry\ will\ appear\ in\ the\ reference\ list)=Insert a citation without text (the entry will appear in the reference list) Cite\ selected\ entries\ with\ extra\ information=Cite selected entries with extra information Ensure\ that\ the\ bibliography\ is\ up-to-date=Ensure that the bibliography is up-to-date +Your\ OpenOffice/LibreOffice\ document\ references\ citation\ keys\ which\ could\ not\ be\ found\ in\ your\ current\ library.=Your OpenOffice/LibreOffice document references citation keys which could not be found in your current library. + Your\ OpenOffice/LibreOffice\ document\ references\ the\ citation\ key\ '%0',\ which\ could\ not\ be\ found\ in\ your\ current\ library.=Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library. + Unable\ to\ synchronize\ bibliography=Unable to synchronize bibliography Combine\ pairs\ of\ citations\ that\ are\ separated\ by\ spaces\ only=Combine pairs of citations that are separated by spaces only Autodetection\ failed=Autodetection failed @@ -1534,6 +1537,23 @@ Custom=Custom Export\ cited=Export cited Unable\ to\ generate\ new\ library=Unable to generate new library +Could\ not\ get\ the\ cursor.=Could not get the cursor. +JabRefException=JabRefException +No\ bibliography\ database\ is\ open\ for\ citation.=No bibliography database is open for citation. +No\ bibliography\ entries\ are\ selected\ for\ citation.=No bibliography entries are selected for citation. +No\ bibliography\ style\ is\ selected\ for\ citation.=No bibliography style is selected for citation. +No\ database=No database +No\ entries\ selected\ for\ citation=No entries selected for citation +No\ style\ for\ citation=No style for citation +Open\ one\ before\ citing.=Open one before citing. +Please\ select\ one.=Please select one. +Ranges\ of\ '%0'\ and\ '%1'\ are\ not\ separated=Ranges of '%0' and '%1' are not separated +Ranges\ of\ '%0'\ and\ '%1'\ overlap=Ranges of '%0' and '%1' overlap +Select\ one\ before\ citing.=Select one before citing. +Select\ some\ before\ citing.=Select some before citing. +This\ operation\ requires\ a\ style.=This operation requires a style. + + Note\:\ Use\ the\ placeholder\ %DIR%\ for\ the\ location\ of\ the\ opened\ library\ file.=Note: Use the placeholder %DIR% for the location of the opened library file. Error\ occured\ while\ executing\ the\ command\ \"%0\".=Error occured while executing the command \"%0\". Reformat\ ISSN=Reformat ISSN From a26b0832ba3ee79b9b6d4b339aa1b258d13d0098 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 12 Mar 2021 00:05:43 +0100 Subject: [PATCH 0477/1068] drop OOBibBase.xUniqueLetters, split refreshCiteMarkers new: produceCitationMarkers --- .../org/jabref/gui/openoffice/OOBibBase.java | 252 +++++++++++++----- 1 file changed, 189 insertions(+), 63 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 594578a66e2..b3e03617da5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -841,7 +841,7 @@ boolean hasControllersLocked(){ * * Depends on: style, citations and their order. */ - private final Map xUniqueLetters = new HashMap<>(); + // private final Map xUniqueLetters = new HashMap<>(); /* * Constructor @@ -2451,10 +2451,10 @@ public int hashCode() { * * Note: bibtexKeys[i][j] may be null (from UndefinedBibtexEntry) */ - void updateUniqueLetters( + Map + createUniqueLetters( String[][] bibtexKeys, - String[][] normCitMarkers, - final Map uniqueLetters + String[][] normCitMarkers ) { final int nRefMarks = bibtexKeys.length; @@ -2488,7 +2488,8 @@ void updateUniqueLetters( } } - uniqueLetters.clear(); + // uniqueLetters.clear(); + Map uniqueLetters = new HashMap<>(); // Go through the collected lists and see where we need to // add unique letters to the year. @@ -2507,6 +2508,7 @@ void updateUniqueLetters( } } } + return uniqueLetters; } /** @@ -2853,18 +2855,27 @@ public int getOrAllocateNumber(String key) { * @param uniqueLetters Filled with new values here. * @param style Bibliography style. */ - String[] + class CitationMarkersWithUniqueLetters { + String[] citMarkers; + Map uniqueLetters; + CitationMarkersWithUniqueLetters( + String[] citMarkers, + Map uniqueLetters ) { + this.citMarkers = citMarkers; + this.uniqueLetters = uniqueLetters; + } + } + + CitationMarkersWithUniqueLetters produceCitationMarkersForNormalStyle( List referenceMarkNames, String[][] bibtexKeysIn, Map citeKeyToBibEntry, int[] itcTypes, Map entries, - final Map uniqueLetters, OOBibStyle style ) throws BibEntryNotFoundException { - uniqueLetters.clear(); assert !style.isCitationKeyCiteMarkers(); assert !style.isNumberEntries(); @@ -2888,7 +2899,8 @@ public int getOrAllocateNumber(String key) { String[][] normCitMarkers = normalizedCitationMarkersForNormalStyle(cEntriesForAll, entries, style); - updateUniqueLetters(bibtexKeys, normCitMarkers, uniqueLetters); + Map uniqueLetters = + createUniqueLetters(bibtexKeys, normCitMarkers); // Finally, go through all citation markers, and update // those referring to entries in our current list: @@ -2945,7 +2957,7 @@ public int getOrAllocateNumber(String key) { ); } - return citMarkers; + return new CitationMarkersWithUniqueLetters( citMarkers, uniqueLetters ); } /* *********************************** @@ -3386,7 +3398,7 @@ void assertCitationCharacterFormatIsOK( entries.stream() .map(entry -> entry.getCitationKey().orElse("")) .collect(Collectors.joining(",")); - // Generate unique bookmark-name + // Generate unique mark-name int itcType = citationTypeFromOptions(withText, inParenthesis); String newName = getUniqueReferenceMarkName( @@ -3461,16 +3473,35 @@ void assertCitationCharacterFormatIsOK( if (sync) { // To account for numbering and for uniqueLetters, we // must refresh the cite markers: - List jabRefReferenceMarkNamesSortedByPosition = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + //List jabRefReferenceMarkNamesSortedByPosition = + // getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + ProduceCitationMarkersResult x = + produceCitationMarkers( + documentConnection, + allBases, + style + ); try { documentConnection.lockControllers(); - refreshCiteMarkers(allBases, style, jabRefReferenceMarkNamesSortedByPosition); + //refreshCiteMarkers(allBases, style, jabRefReferenceMarkNamesSortedByPosition); + applyNewCitationMarkers( + documentConnection, + x.jabRefReferenceMarkNamesSortedByPosition, + x.citMarkers, + x.itcTypes, + style); // Insert it at the current position: - rebuildBibTextSection(allBases, style, jabRefReferenceMarkNamesSortedByPosition); + rebuildBibTextSection( + documentConnection, + allBases, + style, + x.jabRefReferenceMarkNamesSortedByPosition, + x.uniqueLetters, + x.fce + ); } finally { documentConnection.unlockControllers(); } @@ -3540,11 +3571,13 @@ public ExportCitedHelperResult exportCitedHelper( List jabRefReferenceMarkNamesSortedByPosition = getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - res.unresolvedKeys = - this.refreshCiteMarkers(databases, - style, - jabRefReferenceMarkNamesSortedByPosition); - res.newDatabase = this.generateDatabase(databases); + ProduceCitationMarkersResult x = + produceCitationMarkers( + documentConnection, + databases, + style); + res.unresolvedKeys = x.unresolvedKeys; + res.newDatabase = this.generateDatabase(databases); } finally { documentConnection.leaveUndoContext(); } @@ -3556,15 +3589,18 @@ public ExportCitedHelperResult exportCitedHelper( * * Called from exportCitedHelper * + * @param documentConnection Connection. * @param databases The databases to get entries from. * @param style The bibliography style to use. * @return A list of those referenced citation keys that could not be resolved. */ - private List + /* + private ProduceCitationMarkersResult refreshCiteMarkers( + DocumentConnection documentConnection, List databases, - OOBibStyle style, - List jabRefReferenceMarkNamesSortedByPosition) + OOBibStyle style + ) throws WrappedTargetException, IllegalArgumentException, @@ -3577,16 +3613,25 @@ public ExportCitedHelperResult exportCitedHelper( BibEntryNotFoundException, NoDocumentException { - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { - return - refreshCiteMarkersInternal( + ProduceCitationMarkersResult x = + produceCitationMarkers( documentConnection, databases, - style, - this.xUniqueLetters, - jabRefReferenceMarkNamesSortedByPosition); + style + ); + + // Refresh all reference marks with the citation markers + // we computed: + applyNewCitationMarkers( + documentConnection, + x.referenceMarkNames, + x.citMarkers, + x.itcTypes, + style); + return x; + } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference @@ -3594,7 +3639,8 @@ public ExportCitedHelperResult exportCitedHelper( throw new ConnectionLostException(ex.getMessage()); } } - + */ + /** * Visit each reference mark in referenceMarkNames, overwrite its * text content. @@ -3690,6 +3736,7 @@ public ExportCitedHelperResult exportCitedHelper( } } + /** * Refresh citation markers according to `style`. * @@ -3700,13 +3747,41 @@ public ExportCitedHelperResult exportCitedHelper( * @param style Style. * @param uniqueLetters Will be cleared and potentially filled with new values. */ - private List - refreshCiteMarkersInternal( + + class ProduceCitationMarkersResult { + List jabRefReferenceMarkNamesSortedByPosition; + int[] itcTypes; + String[][] bibtexKeys; + String[] citMarkers; + Map uniqueLetters; + FindCitedEntriesResult fce; + List unresolvedKeys; + ProduceCitationMarkersResult( + List jabRefReferenceMarkNamesSortedByPosition, + int[] itcTypes, + String[][] bibtexKeys, + String[] citMarkers, + Map uniqueLetters, + FindCitedEntriesResult fce, + List unresolvedKeys + ) { + this.jabRefReferenceMarkNamesSortedByPosition = jabRefReferenceMarkNamesSortedByPosition; + this.itcTypes = itcTypes; + this.bibtexKeys = bibtexKeys; + this.citMarkers = citMarkers; + this.uniqueLetters = uniqueLetters; + this.fce = fce; + this.unresolvedKeys = unresolvedKeys; + } + } + + private ProduceCitationMarkersResult + produceCitationMarkers( DocumentConnection documentConnection, List databases, - OOBibStyle style, - final Map uniqueLetters, - List jabRefReferenceMarkNamesSortedByPosition + OOBibStyle style + // Map uniqueLetters, + // List jabRefReferenceMarkNamesSortedByPosition ) throws WrappedTargetException, @@ -3721,6 +3796,10 @@ public ExportCitedHelperResult exportCitedHelper( // Normally we sort the reference marks according to their // order of appearance: + + List jabRefReferenceMarkNamesSortedByPosition = + getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + List referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; final int nRefMarks = referenceMarkNames.size(); @@ -3740,6 +3819,7 @@ public ExportCitedHelperResult exportCitedHelper( String[] citMarkers; // fill citMarkers + Map uniqueLetters = new HashMap<>(); uniqueLetters.clear(); /* ModifiesParameter */ if (style.isCitationKeyCiteMarkers()) { citMarkers = @@ -3765,28 +3845,31 @@ public ExportCitedHelperResult exportCitedHelper( style); } } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { - citMarkers = + CitationMarkersWithUniqueLetters x = produceCitationMarkersForNormalStyle( referenceMarkNames, bibtexKeys, fce.citeKeyToBibEntry, itcTypes, fce.entries, - uniqueLetters, style); + citMarkers = x.citMarkers; + uniqueLetters = x.uniqueLetters; } - // Refresh all reference marks with the citation markers we computed: - applyNewCitationMarkers( - documentConnection, - referenceMarkNames, - citMarkers, + return new ProduceCitationMarkersResult( + jabRefReferenceMarkNamesSortedByPosition, itcTypes, - style); - - return unresolvedKeysFromEntries(fce.entries); + bibtexKeys, + citMarkers, + uniqueLetters, + fce, + unresolvedKeysFromEntries(fce.entries) + ); } + + /* ************************************************** * * Bibliography: needs uniqueLetters or numbers @@ -3801,11 +3884,14 @@ public ExportCitedHelperResult exportCitedHelper( * Note: assumes fresh `jabRefReferenceMarkNamesSortedByPosition` * if `style.isSortByPosition()` */ - public void + private void rebuildBibTextSection( + DocumentConnection documentConnection, List databases, OOBibStyle style, - List jabRefReferenceMarkNamesSortedByPosition + List jabRefReferenceMarkNamesSortedByPosition, + final Map uniqueLetters, + FindCitedEntriesResult fce ) throws NoSuchElementException, @@ -3817,13 +3903,15 @@ public ExportCitedHelperResult exportCitedHelper( UndefinedParagraphFormatException, NoDocumentException { - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + // DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + /* FindCitedEntriesResult fce = findCitedEntries( findCitedKeys(documentConnection), databases ); + */ Map entries; @@ -3845,7 +3933,7 @@ public ExportCitedHelperResult exportCitedHelper( documentConnection, entries, style, - this.xUniqueLetters); + uniqueLetters); } /** @@ -4340,13 +4428,25 @@ public ExportCitedHelperResult exportCitedHelper( } if (madeModifications) { - List jabRefReferenceMarkNamesSortedByPosition = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + // List jabRefReferenceMarkNamesSortedByPosition = + // getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + ProduceCitationMarkersResult x = + produceCitationMarkers( + documentConnection, + databases, + style + ); try { if (useLockControllers) { documentConnection.lockControllers(); } - refreshCiteMarkers(databases, style, jabRefReferenceMarkNamesSortedByPosition); + // refreshCiteMarkers(databases, style, jabRefReferenceMarkNamesSortedByPosition); + applyNewCitationMarkers( + documentConnection, + x.jabRefReferenceMarkNamesSortedByPosition, + x.citMarkers, + x.itcTypes, + style); } finally { if (useLockControllers) { documentConnection.unlockControllers(); @@ -4471,13 +4571,25 @@ public ExportCitedHelperResult exportCitedHelper( } } if (madeModifications) { - List jabRefReferenceMarkNamesSortedByPosition = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + // List jabRefReferenceMarkNamesSortedByPosition = + // getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + ProduceCitationMarkersResult x = + produceCitationMarkers( + documentConnection, + databases, + style + ); try { if (useLockControllers) { documentConnection.lockControllers(); } - refreshCiteMarkers(databases, style, jabRefReferenceMarkNamesSortedByPosition); + // refreshCiteMarkers(databases, style, jabRefReferenceMarkNamesSortedByPosition); + applyNewCitationMarkers( + documentConnection, + x.jabRefReferenceMarkNamesSortedByPosition, + x.citMarkers, + x.itcTypes, + style); } finally { if (useLockControllers) { documentConnection.unlockControllers(); @@ -4614,17 +4726,31 @@ void styleIsRequired( OOBibStyle style ) cg.checkRangeOverlaps(this.xDocumentConnection, requireSeparation); final boolean useLockControllers = true; try { - List jabRefReferenceMarkNamesSortedByPosition = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + ProduceCitationMarkersResult x = + produceCitationMarkers( + documentConnection, + databases, + style + ); + if (useLockControllers){ documentConnection.lockControllers(); } - List unresolvedKeys = - refreshCiteMarkers(databases, - style, - jabRefReferenceMarkNamesSortedByPosition); - rebuildBibTextSection(databases, style, jabRefReferenceMarkNamesSortedByPosition); - return unresolvedKeys; + applyNewCitationMarkers( + documentConnection, + x.jabRefReferenceMarkNamesSortedByPosition, + x.citMarkers, + x.itcTypes, + style); + rebuildBibTextSection( + documentConnection, + databases, + style, + x.jabRefReferenceMarkNamesSortedByPosition, + x.uniqueLetters, + x.fce + ); + return x.unresolvedKeys; } finally { if (useLockControllers){ documentConnection.unlockControllers(); From 36f61413a0178572d87f832e419dabad6f76e64d Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 12 Mar 2021 22:04:55 +0100 Subject: [PATCH 0478/1068] discovered two-pages-side-by-side problem --- .../org/jabref/gui/openoffice/OOBibBase.java | 44 ++++++++++++++++--- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b3e03617da5..c2dc746d305 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4268,16 +4268,16 @@ class ProduceCitationMarkersResult { || !thisChar.trim().isEmpty() ) { couldExpand = false; } + if (DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + throw new RuntimeException( + "combineCiteMarkers: " + + "cursorBetween.end != currentGroupCursor.end (during expand)" ); + } } if (!couldExpand) { addToGroup = false; } - if (DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) != 0) { - throw new RuntimeException( - "combineCiteMarkers: " - + "cursorBetween.end != currentGroupCursor.end (after expand)" ); - } } /* @@ -4303,18 +4303,50 @@ class ProduceCitationMarkersResult { if ( addToGroup || canStartGroup ) { // Add the current entry to a group. currentGroup.add(i); + // ... and start new cursorBetween // Set up cursorBetween XTextRange range1Full = documentConnection.getReferenceMarkRangeOrNull(name); + // XTextRange range1End = range1Full.getEnd(); cursorBetween = range1Full.getText().createTextCursorByRange(range1Full.getEnd()); - // currentGroupCursor + // If new group, create currentGroupCursor if ( currentGroupCursor == null ) { currentGroupCursor = range1Full.getText().createTextCursorByRange(range1Full.getStart()); } // include self in currentGroupCursor currentGroupCursor.goRight( (short)( range1Full.getString().length() ), true ); + + if (DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + /* + * A problem discovered using this check: when + * viewing the document in + * two-pages-side-by-side mode, our visual + * firstAppearanceOrder follows the visual + * ordering on the screen. The problem this + * caused: it sees a citation on the 2nd line + * of the 1st page as appearing after one at + * the 1st line of 2nd page. Since we create + * cursorBetween at the end of range1Full (on + * 1st page), it is now BEFORE + * currentGroupCursor (on 2nd page). + */ + throw new RuntimeException( + String.format( + "combineCiteMarkers: " + + "cursorBetween.end != currentGroupCursor.end" + + " (after addToGroup || canStartGroup)" + + "%d\n" + + "a: %s\n" + + "b: %s\n" + + "c: %s\n" + , DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) + , cursorBetween.getString() + , range1Full.getString() + , currentGroupCursor.getString() + )); + } prev = i; } } From 17a8029829627e64f834e00281dff691a17951c6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 13 Mar 2021 00:11:21 +0100 Subject: [PATCH 0479/1068] do not try to merge citations in the opposite order than jabRefReferenceMarkNamesSortedByPosition --- .../org/jabref/gui/openoffice/OOBibBase.java | 93 +++++++++++++------ 1 file changed, 63 insertions(+), 30 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c2dc746d305..21803e82eab 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4218,10 +4218,12 @@ class ProduceCitationMarkersResult { XTextCursor currentGroupCursor = null; XTextCursor cursorBetween = null; Integer prev = null; + XTextRange prevRange = null; for ( int i=0; i < referenceMarkNames.size(); i++ ) { final String name = referenceMarkNames.get(i); - + XTextRange currentRange = documentConnection.getReferenceMarkRangeOrNull(name); + Objects.requireNonNull(currentRange); boolean addToGroup = true; /* @@ -4229,17 +4231,44 @@ class ProduceCitationMarkersResult { */ // Only combine (Author 2000) type citations - if ( itcTypes[i] != OOBibBase.AUTHORYEAR_PAR ) { + if ( itcTypes[i] != OOBibBase.AUTHORYEAR_PAR + // allow "Author (2000)" + // && itcTypes[i] != OOBibBase.AUTHORYEAR_INTEXT + ) { addToGroup = false; } - // Even if we combined other types of citations, we would not mix them + // Even if we combine AUTHORYEAR_INTEXT citations, we + // would not mix them with AUTHORYEAR_PAR if (addToGroup && (prev != null) ) { if ( itcTypes[i] != itcTypes[prev] ){ addToGroup = false; } } + if ( addToGroup && prev != null ) { + Objects.requireNonNull(prevRange); + Objects.requireNonNull(currentRange); + if ( ! DocumentConnection.comparable( prevRange, currentRange ) ) { + addToGroup = false; + } else { + int textOrder = DocumentConnection.compareRegionStarts(prevRange, + currentRange); + if ( textOrder != 1 ) { + String msg = String.format( + "combineCiteMarkers: \"%s\" supposed to be followed by \"%s\", but %s", + prevRange.getString(), + currentRange.getString(), + ((textOrder == 0) + ? "they start at the same position" + : "the latter precedes the first") + ); + LOGGER.warn(msg); + addToGroup = false; + } + } + } + if (addToGroup && (cursorBetween != null)) { Objects.requireNonNull(currentGroupCursor); // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() @@ -4248,15 +4277,13 @@ class ProduceCitationMarkersResult { "combineCiteMarkers: cursorBetween.end != currentGroupCursor.end"); } - XTextRange range2 = - documentConnection.getReferenceMarkRangeOrNull(name); - XTextRange range2Start = range2.getStart(); + XTextRange rangeStart = currentRange.getStart(); boolean couldExpand = true; XTextCursor thisCharCursor = - range2.getText().createTextCursorByRange(cursorBetween.getEnd()); + currentRange.getText().createTextCursorByRange(cursorBetween.getEnd()); while (couldExpand && - (DocumentConnection.compareRegionEnds(cursorBetween, range2Start) > 0)) { + (DocumentConnection.compareRegionEnds(cursorBetween, rangeStart) > 0)) { couldExpand = cursorBetween.goRight((short) 1, true); currentGroupCursor.goRight((short) 1, true); // @@ -4298,6 +4325,7 @@ class ProduceCitationMarkersResult { currentGroupCursor = null; cursorBetween = null; prev = null; + prevRange = null; } if ( addToGroup || canStartGroup ) { @@ -4305,18 +4333,16 @@ class ProduceCitationMarkersResult { currentGroup.add(i); // ... and start new cursorBetween // Set up cursorBetween - XTextRange range1Full = - documentConnection.getReferenceMarkRangeOrNull(name); // - XTextRange range1End = range1Full.getEnd(); - cursorBetween = range1Full.getText().createTextCursorByRange(range1Full.getEnd()); + XTextRange rangeEnd = currentRange.getEnd(); + cursorBetween = currentRange.getText().createTextCursorByRange(rangeEnd); // If new group, create currentGroupCursor if ( currentGroupCursor == null ) { currentGroupCursor = - range1Full.getText().createTextCursorByRange(range1Full.getStart()); + currentRange.getText().createTextCursorByRange(currentRange.getStart()); } // include self in currentGroupCursor - currentGroupCursor.goRight( (short)( range1Full.getString().length() ), true ); + currentGroupCursor.goRight( (short)( currentRange.getString().length() ), true ); if (DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) != 0) { /* @@ -4333,25 +4359,31 @@ class ProduceCitationMarkersResult { * currentGroupCursor (on 2nd page). */ throw new RuntimeException( - String.format( - "combineCiteMarkers: " - + "cursorBetween.end != currentGroupCursor.end" - + " (after addToGroup || canStartGroup)" - + "%d\n" - + "a: %s\n" - + "b: %s\n" - + "c: %s\n" - , DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) - , cursorBetween.getString() - , range1Full.getString() - , currentGroupCursor.getString() - )); + "combineCiteMarkers: " + + "cursorBetween.end != currentGroupCursor.end" + + String.format( + " (after %s", addToGroup ? "addToGroup" : "startGroup") + + (addToGroup + ? String.format( + "comparisonResult: %d\n" + + "cursorBetween: %s\n" + + "currentRange: %s\n" + + "currentGroupCursor: %s\n" + , DocumentConnection.compareRegionEnds( + cursorBetween, currentGroupCursor) + , cursorBetween.getString() + , currentRange.getString() + , currentGroupCursor.getString() + ) + : "") + ); } prev = i; - } - } + prevRange = currentRange; + } // for i + } // try - if (true) { + if (true) { // close currentGroup if (currentGroup.size() > 1) { joinableGroups.add( currentGroup ); @@ -4362,6 +4394,7 @@ class ProduceCitationMarkersResult { currentGroupCursor = null; cursorBetween = null; prev = null; + prevRange = null; } From 25487faac3cb106e45f5ff49c4f055f6d92e3448 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 13 Mar 2021 14:12:17 +0100 Subject: [PATCH 0480/1068] prefix compareRegionXXX with return conventions --- .../org/jabref/gui/openoffice/OOBibBase.java | 122 +++++++++++++----- 1 file changed, 87 insertions(+), 35 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 21803e82eab..add1e0d8f7b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -798,12 +798,13 @@ boolean hasControllersLocked(){ } /** - * @return 1 if (a < b), 0 if same start, (-1) if (b < a) + * @return follows OO conventions, the opposite of java conventions: + * 1 if (a < b), 0 if same start, (-1) if (b < a) */ private static int - compareRegionStarts( XTextRange a, XTextRange b ) { + ooCompareRegionStarts( XTextRange a, XTextRange b ) { if ( !comparable( a, b ) ){ - throw new RuntimeException( "compareRegionStarts: got incomparable regions" ); + throw new RuntimeException( "ooCompareRegionStarts: got incomparable regions" ); } final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, a.getText()); @@ -811,18 +812,35 @@ boolean hasControllersLocked(){ } /** - * @return 1 if (a < b), 0 if same start, (-1) if (b < a) + * @return follows OO conventions, the opposite of java conventions: + * 1 if (a < b), 0 if same start, (-1) if (b < a) */ private static int - compareRegionEnds( XTextRange a, XTextRange b ) { + ooCompareRegionEnds( XTextRange a, XTextRange b ) { if ( !comparable( a, b ) ){ - throw new RuntimeException( "compareRegionEnds: got incomparable regions" ); + throw new RuntimeException( "ooCompareRegionEnds: got incomparable regions" ); } final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, a.getText()); return compare.compareRegionEnds(a, b); } + /** + * @return follows java conventions + * + */ + private static int + javaCompareRegionStarts( XTextRange a, XTextRange b ) { + return (-1) * ooCompareRegionStarts(a, b); + } + + /** + * @return follows java conventions + */ + private static int + javaCompareRegionEnds( XTextRange a, XTextRange b ) { + return (-1) * ooCompareRegionEnds(a, b); + } } // end DocumentConnection /** @@ -1518,12 +1536,24 @@ String format() { } // class X + /** * Assumes a.getText() == b.getText(), and both belong to documentConnection.xText + * + * Note: OpenOffice XTextRangeCompare and java use different + * (opposite) conventions. The "java" prefix in the + * functions name is intended to emphasize, that the + * value returned is adjusted to use java conventions + * (by muliplying the result with (-1)). + * + * @return -1 for (a < b), 1 for (a > b); 0 for equal. + * + * @throws RuntimeException if a and b are not comparable + * */ public int - compareRegionStarts(RangeForOverlapCheck a, - RangeForOverlapCheck b) { + javaCompareRegionStarts(RangeForOverlapCheck a, + RangeForOverlapCheck b) { // // XTextRange cannot be compared, only == or != is available. // @@ -1537,27 +1567,19 @@ String format() { if (ra.getText() != rb.getText()) { throw new RuntimeException( String.format( - "OOBibBase.CitationGroups.compareRegionStarts:" + "OOBibBase.CitationGroups.javaCompareRegionStarts:" + " incomparable regions: %s %s", a.format(), b.format()) ); } - /* - * documentConnection.xText cannot compare two ranges in - * the same footnote. We must use XTextRangeCompare interface - * of the ranges themselves. - */ - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - ra.getText()); - try { - return (-1) * compare.compareRegionStarts(ra, rb); + return DocumentConnection.javaCompareRegionStarts(ra, rb); } catch (IllegalArgumentException ex) { throw new RuntimeException( String.format( - "OOBibBase.CitationGroups.compareRegionStarts:" + "OOBibBase.CitationGroups.javaCompareRegionStarts:" + " caught IllegalArgumentException: %s %s", a.format(), b.format() @@ -1566,15 +1588,37 @@ String format() { } } + /** + * + */ public int - compareRegionEndToStart(RangeForOverlapCheck a, - RangeForOverlapCheck b) { + javaCompareRegionEndToStart(RangeForOverlapCheck a, + RangeForOverlapCheck b) { - XTextRange ra = a.range.getEnd(); - XTextRange rb = b.range.getStart(); - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - ra.getText()); - return (-1) * compare.compareRegionStarts(ra, rb); + XTextRange ra = a.range; + XTextRange rb = b.range; + if (ra.getText() != rb.getText()) { + throw new RuntimeException( + String.format( + "OOBibBase.CitationGroups.javaCompareRegionEndToStart:" + + " incomparable regions: %s %s", + a.format(), + b.format()) + ); + } + + try { + return DocumentConnection.javaCompareRegionStarts(ra.getEnd(), rb.getStart()); + } catch (IllegalArgumentException ex) { + throw new RuntimeException( + String.format( + "OOBibBase.CitationGroups.javaCompareRegionEndToStart:" + + " caught IllegalArgumentException: %s %s", + a.format(), + b.format() + ) + ); + } } /** @@ -1669,7 +1713,7 @@ String format() { sortPartitionByRegionStart(List xs) { return xs.stream() - .sorted(this::compareRegionStarts) + .sorted(this::javaCompareRegionStarts) .collect(Collectors.toList()); } @@ -1680,7 +1724,7 @@ String format() { for (int i = 0; (i + 1) < oxs.size(); i++) { RangeForOverlapCheck a = oxs.get(i); RangeForOverlapCheck b = oxs.get(i + 1); - int cmp = compareRegionEndToStart(a, b); + int cmp = javaCompareRegionEndToStart(a, b); //xxx if (cmp > 0) { // found overlap throw new JabRefException( @@ -4252,8 +4296,12 @@ class ProduceCitationMarkersResult { if ( ! DocumentConnection.comparable( prevRange, currentRange ) ) { addToGroup = false; } else { - int textOrder = DocumentConnection.compareRegionStarts(prevRange, - currentRange); + + int textOrder = + DocumentConnection.javaCompareRegionStarts( + prevRange, + currentRange); + if ( textOrder != 1 ) { String msg = String.format( "combineCiteMarkers: \"%s\" supposed to be followed by \"%s\", but %s", @@ -4272,7 +4320,8 @@ class ProduceCitationMarkersResult { if (addToGroup && (cursorBetween != null)) { Objects.requireNonNull(currentGroupCursor); // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() - if (DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + if (DocumentConnection.javaCompareRegionEnds( + cursorBetween, currentGroupCursor) != 0) { throw new RuntimeException( "combineCiteMarkers: cursorBetween.end != currentGroupCursor.end"); } @@ -4283,7 +4332,8 @@ class ProduceCitationMarkersResult { XTextCursor thisCharCursor = currentRange.getText().createTextCursorByRange(cursorBetween.getEnd()); while (couldExpand && - (DocumentConnection.compareRegionEnds(cursorBetween, rangeStart) > 0)) { + (DocumentConnection.javaCompareRegionEnds( + cursorBetween, rangeStart) > 0)) { couldExpand = cursorBetween.goRight((short) 1, true); currentGroupCursor.goRight((short) 1, true); // @@ -4295,7 +4345,8 @@ class ProduceCitationMarkersResult { || !thisChar.trim().isEmpty() ) { couldExpand = false; } - if (DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + if (DocumentConnection.javaCompareRegionEnds( + cursorBetween, currentGroupCursor) != 0) { throw new RuntimeException( "combineCiteMarkers: " + "cursorBetween.end != currentGroupCursor.end (during expand)" ); @@ -4344,7 +4395,8 @@ class ProduceCitationMarkersResult { // include self in currentGroupCursor currentGroupCursor.goRight( (short)( currentRange.getString().length() ), true ); - if (DocumentConnection.compareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + if (DocumentConnection.javaCompareRegionEnds( + cursorBetween, currentGroupCursor) != 0) { /* * A problem discovered using this check: when * viewing the document in @@ -4369,7 +4421,7 @@ class ProduceCitationMarkersResult { + "cursorBetween: %s\n" + "currentRange: %s\n" + "currentGroupCursor: %s\n" - , DocumentConnection.compareRegionEnds( + , DocumentConnection.javaCompareRegionEnds( cursorBetween, currentGroupCursor) , cursorBetween.getString() , currentRange.getString() From 878c70aa75f16eb4cb8cb171043731eae20bf977 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 13 Mar 2021 22:06:56 +0100 Subject: [PATCH 0481/1068] Describe som OOUtil methods --- .../org/jabref/logic/openoffice/OOUtil.java | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 9efab82773c..7273e6580ca 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -98,7 +98,13 @@ public static void insertFullReferenceAtCurrentLocation(XText text, XTextCursor } /** - * Insert a text with formatting indicated by HTML-like tags, into a text at the position given by a cursor. + * Insert a text with formatting indicated by HTML-like tags, into + * a text at the position given by a cursor. + * + * Set {@code parStyle}, process {@code ltext} in chunks between + * HTML-tags, while updating current formatting state at HTML-tags. + * + * Finally: {@code cursor.collapseToEnd()} * * @param text The text to insert in. * @param cursor The cursor giving the insert location. @@ -184,6 +190,18 @@ public static void insertParagraphBreak(XText text, XTextCursor cursor) throws I cursor.collapseToEnd(); } + /** + * Set cursor range content to {@code string}, apply {@code + * formatting} to it, {@code cursor.collapseToEnd()}. + * + * Insert {@code string} into {@code text} at {@code cursor}, while removing the content + * of the cursor's range. The cursor's content is {@code string} now. + * + * Apply character direct formatting from {@code + * formatting}. Features not in {@code formatting} are removed by setting to NONE. + * + * Finally: {@code cursor.collapseToEnd();} + */ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, String string, List formatting) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, @@ -258,6 +276,17 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S cursor.collapseToEnd(); } + /** + * Set cursor range content to {@code string}, apply {@code + * parStyle} to it, {@code cursor.collapseToEnd()}. + * + * Insert {@code string} into {@code text} at {@code cursor}, while removing the content + * of the cursor's range. The cursor's content is {@code string} now. + * + * Set paragraph style to {@code parStyle} + * + * Finally: {@code cursor.collapseToEnd();} + */ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, String string, String parStyle) throws WrappedTargetException, PropertyVetoException, UnknownPropertyException, UndefinedParagraphFormatException { From fb5d3558b9c2061f88eacf689a256bc0488a2937 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 13 Mar 2021 22:46:31 +0100 Subject: [PATCH 0482/1068] try not to depend on bracket length --- .../org/jabref/gui/openoffice/OOBibBase.java | 78 ++++++++++++------- 1 file changed, 52 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index add1e0d8f7b..04fc4ef26be 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -109,13 +109,15 @@ class OOBibBase { private static final String zeroWidthSpace = "\u200b"; // for debugging we may want visible bracket - private static final boolean referenceMarkUseInvisibleBrackets = false; // !debug; - // Note we are relying on referenceMarkLeftBracket and referenceMarkRightBracket + private static final boolean REFERENCE_MARK_USE_INVISIBLE_BRACKETS = false; // !debug; + + // Note we were relying on referenceMarkLeftBracket and referenceMarkRightBracket // to be single-character strings that do not appear in reference mark content. - private static final String referenceMarkLeftBracket = - referenceMarkUseInvisibleBrackets ? zeroWidthSpace : "<"; - private static final String referenceMarkRightBracket = - referenceMarkUseInvisibleBrackets ? zeroWidthSpace : ">"; + // Now we probably rely on this no more, empty, or longar brackets should work as well. + private static final String REFERENCE_MARK_LEFT_BRACKET = + REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<"; + private static final String REFERENCE_MARK_RIGHT_BRACKET = + REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; /* Types of in-text citation. (itcType) * Their numeric values are used in reference mark names. @@ -3048,18 +3050,27 @@ class CitationMarkersWithUniqueLetters { cursor.goLeft((short) 1, false); } - final String left = referenceMarkLeftBracket; - final String right = referenceMarkRightBracket; + final String left = REFERENCE_MARK_LEFT_BRACKET; + final String right = REFERENCE_MARK_RIGHT_BRACKET; + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); + String text = left + initialText + right; cursor.getText().insertString(cursor, text, true); - XNamed mark = documentConnection.insertReferenceMark(name, cursor, true); + XNamed mark = documentConnection.insertReferenceMark( + name, + cursor, + true // absorb + ); // Need a cursor that excludes left and right XTextCursor full = cursor; // DocumentConnection.getTextCursorOfTextContent( // DocumentConnection.asTextContent(mark)); - full.collapseToStart(); - full.goRight( (short)1, false ); - full.goRight( (short)initialText.length(), true ); + if (leftLength + rightLength > 0 ) { + full.collapseToStart(); + full.goRight((short) left.length(), false); + full.goRight((short) initialText.length(), true); + } return full; // yield a cursor in the bracket } @@ -3074,8 +3085,10 @@ class CitationMarkersWithUniqueLetters { CreationException { final boolean debugThisFun = false; - final String left = referenceMarkLeftBracket; - final String right = referenceMarkRightBracket; + final String left = REFERENCE_MARK_LEFT_BRACKET; + final String right = REFERENCE_MARK_RIGHT_BRACKET; + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); XTextContent markAsTextContent = documentConnection.getReferenceMarkAsTextContentOrNull( name ); @@ -3100,15 +3113,18 @@ class CitationMarkersWithUniqueLetters { System.out.println(String.format("getFillCursor: fulltext = '%s'", fulltext)); } - if (fulltext.length() < 2 || !fulltext.startsWith(left) || !fulltext.endsWith(right)){ + + if (fullText.length() < (leftLength+rightLength) + || !fullText.startsWith(left) + || !fullText.endsWith(right)) { // damaged, recreate - if ( debugThisFun ){ - System.out.println(String.format("getFillCursor: damaged, recreate")); + if (debugThisFun) { + System.out.println("getFillCursor: damaged, recreate"); } full.setString(""); - if ( true ){ - if ( debugThisFun ){ - System.out.println(String.format("getFillCursor: removeReferenceMark go")); + if (true) { + if (debugThisFun) { + System.out.println("getFillCursor: removeReferenceMark go"); } try { documentConnection.removeReferenceMark(name); @@ -3124,9 +3140,17 @@ class CitationMarkersWithUniqueLetters { } // What shall we put in the recreated version? // User might have inserted stuff before or after? - String trimmedtext = fulltext.replaceAll( "[" + left + right +"]", "" ); - if (debugThisFun){ - System.out.println(String.format("getFillCursor: trimmedtext = '%s'", trimmedtext)); + // We try to remove only brackets of exactly 1 character, + // not of length zero or more than one. + String trimmedText = fullText; + if (leftLength == 1) { + trimmedText = trimmedText.replaceAll("[" + left + "]", ""); + } + if (rightLength == 1) { + trimmedText = trimmedText.replaceAll("[" + right + "]", ""); + } + if (debugThisFun) { + System.out.println(String.format("getFillCursor: trimmedText = '%s'", trimmedText)); } return createReferenceMarkForCitationGroup( documentConnection, @@ -3138,9 +3162,11 @@ class CitationMarkersWithUniqueLetters { if (debugThisFun){ System.out.println(String.format("getFillCursor: intact, reuse")); } - full.collapseToStart(); - full.goRight( (short)1, false ); - full.goRight( (short)(fulltext.length()-2), true ); + if (leftLength + rightLength > 0) { + full.collapseToStart(); + full.goRight((short) left.length(), false); + full.goRight((short) (fullText.length() - (left.length()+right.length())), true); + } return full; // yield a cursor in the bracket } } From bfffd6fcfbf12f7433a6f853842d3d4f35ee4631 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 14 Mar 2021 12:20:18 +0100 Subject: [PATCH 0483/1068] refactor: style check, IDEA --- .../org/jabref/gui/openoffice/OOBibBase.java | 399 +++++++----------- 1 file changed, 154 insertions(+), 245 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 04fc4ef26be..680cc254f6a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -55,8 +55,8 @@ import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; import com.sun.star.document.XDocumentPropertiesSupplier; -import com.sun.star.document.XUndoManagerSupplier; import com.sun.star.document.XUndoManager; +import com.sun.star.document.XUndoManagerSupplier; import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XController; import com.sun.star.frame.XDesktop; @@ -105,15 +105,13 @@ class OOBibBase { private static final Pattern CITE_PATTERN = Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); - private static final boolean debug = true; - - private static final String zeroWidthSpace = "\u200b"; + private static final String ZERO_WIDTH_SPACE = "\u200b"; // for debugging we may want visible bracket private static final boolean REFERENCE_MARK_USE_INVISIBLE_BRACKETS = false; // !debug; // Note we were relying on referenceMarkLeftBracket and referenceMarkRightBracket // to be single-character strings that do not appear in reference mark content. - // Now we probably rely on this no more, empty, or longar brackets should work as well. + // Now we probably rely on this no more, empty, or longer brackets should work as well. private static final String REFERENCE_MARK_LEFT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<"; private static final String REFERENCE_MARK_RIGHT_BRACKET = @@ -164,8 +162,6 @@ private static class DocumentConnection { this.mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); // unoQI(XDocumentIndexesSupplier.class, component); - - // get a reference to the body text of the document this.xText = mxDoc.getText(); @@ -190,7 +186,7 @@ void enterUndoContext(String title) { XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); XUndoManager um = mxUndoManagerSupplier.getUndoManager(); // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html - um.enterUndoContext( title ); + um.enterUndoContext(title); } void leaveUndoContext() @@ -221,7 +217,7 @@ void unlockControllers() { mo.unlockControllers(); } - boolean hasControllersLocked(){ + boolean hasControllersLocked() { XModel mo = unoQI(XModel.class, this.xCurrentComponent); return mo.hasControllersLocked(); } @@ -420,12 +416,13 @@ boolean hasControllersLocked(){ } static XTextContent - asTextContent( Object mark ){ - if ( mark == null ){ + asTextContent(Object mark) { + if (mark == null) { return null; } return unoQI(XTextContent.class, mark); } + /** * @return null if name not found, or if the result does not * support the XTextContent interface. @@ -606,6 +603,13 @@ boolean hasControllersLocked(){ * The text in the cursor range will be the text with gray * background. * + * 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. @@ -618,6 +622,7 @@ boolean hasControllersLocked(){ ) throws CreationException { + return insertNamedTextContent( "com.sun.star.text.ReferenceMark", @@ -631,11 +636,18 @@ boolean hasControllersLocked(){ * 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. * + * 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 XNamed insertBookmark( @@ -662,6 +674,9 @@ boolean hasControllersLocked(){ * @param name The desired name for the section. * @param range The location to insert at. * + * 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. */ private XNamed insertTextSection( @@ -804,9 +819,9 @@ boolean hasControllersLocked(){ * 1 if (a < b), 0 if same start, (-1) if (b < a) */ private static int - ooCompareRegionStarts( XTextRange a, XTextRange b ) { - if ( !comparable( a, b ) ){ - throw new RuntimeException( "ooCompareRegionStarts: got incomparable regions" ); + ooCompareRegionStarts(XTextRange a, XTextRange b) { + if (!comparable(a, b)) { + throw new RuntimeException("ooCompareRegionStarts: got incomparable regions"); } final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, a.getText()); @@ -818,9 +833,9 @@ boolean hasControllersLocked(){ * 1 if (a < b), 0 if same start, (-1) if (b < a) */ private static int - ooCompareRegionEnds( XTextRange a, XTextRange b ) { - if ( !comparable( a, b ) ){ - throw new RuntimeException( "ooCompareRegionEnds: got incomparable regions" ); + ooCompareRegionEnds(XTextRange a, XTextRange b) { + if (!comparable(a, b)) { + throw new RuntimeException("ooCompareRegionEnds: got incomparable regions"); } final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, a.getText()); @@ -832,7 +847,7 @@ boolean hasControllersLocked(){ * */ private static int - javaCompareRegionStarts( XTextRange a, XTextRange b ) { + javaCompareRegionStarts(XTextRange a, XTextRange b) { return (-1) * ooCompareRegionStarts(a, b); } @@ -840,7 +855,7 @@ boolean hasControllersLocked(){ * @return follows java conventions */ private static int - javaCompareRegionEnds( XTextRange a, XTextRange b ) { + javaCompareRegionEnds(XTextRange a, XTextRange b) { return (-1) * ooCompareRegionEnds(a, b); } } // end DocumentConnection @@ -1538,7 +1553,6 @@ String format() { } // class X - /** * Assumes a.getText() == b.getText(), and both belong to documentConnection.xText * @@ -1546,7 +1560,7 @@ String format() { * (opposite) conventions. The "java" prefix in the * functions name is intended to emphasize, that the * value returned is adjusted to use java conventions - * (by muliplying the result with (-1)). + * (by multiplying the result with (-1)). * * @return -1 for (a < b), 1 for (a > b); 0 for equal. * @@ -1561,8 +1575,7 @@ String format() { // // XTextRangeCompare: compares the positions of two TextRanges within a Text. // Only TextRange instances within the same Text can be compared. - // final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - // documentConnection.xText); + // And XTextRangeCompare must be obtained from their Text. XTextRange ra = a.range; XTextRange rb = b.range; @@ -1726,7 +1739,7 @@ String format() { for (int i = 0; (i + 1) < oxs.size(); i++) { RangeForOverlapCheck a = oxs.get(i); RangeForOverlapCheck b = oxs.get(i + 1); - int cmp = javaCompareRegionEndToStart(a, b); //xxx + int cmp = javaCompareRegionEndToStart(a, b); if (cmp > 0) { // found overlap throw new JabRefException( @@ -1764,13 +1777,11 @@ String format() { Map> xxs = partitionByGetText(xs); // Sort xs by x.getText() and x.getStart() // Then, within each getText() value, we need x[i].getEnd() <= x[i+1].getStart() - // final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - // documentConnection.xText); for (List partition : xxs.values()) { List oxs = sortPartitionByRegionStart(partition); - if ( debugPartitions ){ + if (debugPartitions) { System.out.println("partition"); for (RangeForOverlapCheck r : oxs) { System.out.println(" " + r.format()); @@ -1928,7 +1939,7 @@ String format() { * * Does not change presentation. * - * Note: we use no undo context here, beacuse only + * Note: we use no undo context here, because only * documentConnection.setCustomProperty() is called, * and Undo in LO will not undo that. * @@ -2109,7 +2120,7 @@ private static class FindCitedEntriesResult { } static String - recoverCitationKeyFromPossiblyUndefinedBibEntry( BibEntry entry ) { + recoverCitationKeyFromPossiblyUndefinedBibEntry(BibEntry entry) { if (entry instanceof UndefinedBibtexEntry) { return ((UndefinedBibtexEntry) entry).getKey(); } else { @@ -2341,11 +2352,11 @@ public int hashCode() { WrappedTargetException, NoDocumentException { - if ( documentConnection.hasControllersLocked() ) { + if (documentConnection.hasControllersLocked()) { LOGGER.warn( "getJabRefReferenceMarkNamesSortedByPosition:" + " with ControllersLocked, viewCursor.gotoRange" - + " is pobably useless" + + " is probably useless" ); } @@ -2889,29 +2900,32 @@ public int getOrAllocateNumber(String key) { return citMarkers; } - /** - * Produce citMarkers for normal (!isCitationKeyCiteMarkers && ! isNumberEntries) styles. - * - * @param referenceMarkNames Names of reference marks. - * @param bibtexKeysIn Bibtex citation keys. - * @param citeKeyToBibEntry Maps citation keys to BibEntry. - * @param itcTypes Citation types. - * @param entries Map BibEntry to BibDatabase. - * @param uniqueLetters Filled with new values here. - * @param style Bibliography style. + * Return type used by produceCitationMarkersForNormalStyle */ - class CitationMarkersWithUniqueLetters { + static class CitationMarkersWithUniqueLetters { String[] citMarkers; Map uniqueLetters; + CitationMarkersWithUniqueLetters( String[] citMarkers, - Map uniqueLetters ) { + Map uniqueLetters) { this.citMarkers = citMarkers; this.uniqueLetters = uniqueLetters; } } + /** + * Produce citMarkers for normal + * (!isCitationKeyCiteMarkers && !isNumberEntries) styles. + * + * @param referenceMarkNames Names of reference marks. + * @param bibtexKeysIn Bibtex citation keys. + * @param citeKeyToBibEntry Maps citation keys to BibEntry. + * @param itcTypes Citation types. + * @param entries Map BibEntry to BibDatabase. + * @param style Bibliography style. + */ CitationMarkersWithUniqueLetters produceCitationMarkersForNormalStyle( List referenceMarkNames, @@ -3003,7 +3017,7 @@ class CitationMarkersWithUniqueLetters { ); } - return new CitationMarkersWithUniqueLetters( citMarkers, uniqueLetters ); + return new CitationMarkersWithUniqueLetters(citMarkers, uniqueLetters); } /* *********************************** @@ -3016,7 +3030,7 @@ class CitationMarkersWithUniqueLetters { * Create an (empty) reference mark with the given name, at the * end of position. * - * @param documentConnection + * @param documentConnection Connection to document. * @param name For the reference mark. * @param position Collapsed to its end. * @param insertSpaceAfter We insert a space after the mark, that @@ -3044,29 +3058,31 @@ class CitationMarkersWithUniqueLetters { position.collapseToEnd(); XTextCursor cursor = position.getText().createTextCursorByRange(position.getEnd()); - if ( insertSpaceAfter ){ + if (insertSpaceAfter) { cursor.getText().insertString(cursor, " ", false); + + // space between citation markers: what style? + // DocumentConnection.setCharStyle(cursor, "Standard"); + // go back to before the space cursor.goLeft((short) 1, false); } final String left = REFERENCE_MARK_LEFT_BRACKET; final String right = REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); String text = left + initialText + right; cursor.getText().insertString(cursor, text, true); - XNamed mark = documentConnection.insertReferenceMark( + /* XNamed mark = */ documentConnection.insertReferenceMark( name, cursor, true // absorb ); // Need a cursor that excludes left and right XTextCursor full = cursor; - // DocumentConnection.getTextCursorOfTextContent( - // DocumentConnection.asTextContent(mark)); - if (leftLength + rightLength > 0 ) { + if (leftLength + rightLength > 0) { full.collapseToStart(); full.goRight((short) left.length(), false); full.goRight((short) initialText.length(), true); @@ -3087,13 +3103,13 @@ class CitationMarkersWithUniqueLetters { final boolean debugThisFun = false; final String left = REFERENCE_MARK_LEFT_BRACKET; final String right = REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); XTextContent markAsTextContent = - documentConnection.getReferenceMarkAsTextContentOrNull( name ); + documentConnection.getReferenceMarkAsTextContentOrNull(name); - if (markAsTextContent == null){ + if (markAsTextContent == null) { throw new RuntimeException( String.format( "getFillCursorForCitationGroup: markAsTextContent(%s) == null", @@ -3103,18 +3119,17 @@ class CitationMarkersWithUniqueLetters { XTextCursor full = DocumentConnection.getTextCursorOfTextContent( markAsTextContent); - if (full == null ){ + if (full == null) { throw new RuntimeException( "getFillCursorForCitationGroup: full == null" ); } - String fulltext = full.getString(); - if ( debugThisFun ){ - System.out.println(String.format("getFillCursor: fulltext = '%s'", fulltext)); + String fullText = full.getString(); + if (debugThisFun) { + System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); } - - if (fullText.length() < (leftLength+rightLength) + if (fullText.length() < (leftLength + rightLength) || !fullText.startsWith(left) || !fullText.endsWith(right)) { // damaged, recreate @@ -3122,21 +3137,12 @@ class CitationMarkersWithUniqueLetters { System.out.println("getFillCursor: damaged, recreate"); } full.setString(""); - if (true) { - if (debugThisFun) { - System.out.println("getFillCursor: removeReferenceMark go"); - } - try { - documentConnection.removeReferenceMark(name); - } catch (NoSuchElementException ex) { - LOGGER.warn(String.format( + try { + documentConnection.removeReferenceMark(name); + } catch (NoSuchElementException ex) { + LOGGER.warn(String.format( "getFillCursorForCitationGroup got NoSuchElementException" + " for '%s'", name)); - } - } else { - if ( debugThisFun ){ - System.out.println(String.format("getFillCursor: removeReferenceMark skipped")); - } } // What shall we put in the recreated version? // User might have inserted stuff before or after? @@ -3150,22 +3156,24 @@ class CitationMarkersWithUniqueLetters { trimmedText = trimmedText.replaceAll("[" + right + "]", ""); } if (debugThisFun) { - System.out.println(String.format("getFillCursor: trimmedText = '%s'", trimmedText)); + System.out.printf("getFillCursor: trimmedText = '%s'%n", trimmedText); } return createReferenceMarkForCitationGroup( documentConnection, name, full, false, // insertSpaceAfter - trimmedtext ); + trimmedText); } else { - if (debugThisFun){ - System.out.println(String.format("getFillCursor: intact, reuse")); + if (debugThisFun) { + System.out.println("getFillCursor: intact, reuse"); } if (leftLength + rightLength > 0) { full.collapseToStart(); full.goRight((short) left.length(), false); - full.goRight((short) (fullText.length() - (left.length()+right.length())), true); + short contentLength = + (short) (fullText.length() - (left.length() + right.length())); + full.goRight(contentLength, true); } return full; // yield a cursor in the bracket } @@ -3185,8 +3193,7 @@ class CitationMarkersWithUniqueLetters { WrappedTargetException, PropertyVetoException, IllegalArgumentException, - UndefinedCharacterFormatException, - CreationException { + UndefinedCharacterFormatException { // Last minute editing: If there is "page info" for this // citation mark, we should inject it into the citation marker @@ -3221,8 +3228,8 @@ class CitationMarkersWithUniqueLetters { boolean italicize = style.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); if (italicize) { String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); - for (int index = citText.indexOf(etAlString) ; - index >= 0 ; + for (int index = citText.indexOf(etAlString); + index >= 0; index = citText.indexOf(etAlString, index + 1)) { italicizeRangeFromPosition(cursor, index, index + etAlString.length()); } @@ -3295,12 +3302,12 @@ class CitationMarkersWithUniqueLetters { insertSpaceAfter, ""); - fillCitationMarkInCursor( documentConnection, - name, - c2, - citationText, - withText, - style ); + fillCitationMarkInCursor(documentConnection, + name, + c2, + citationText, + withText, + style); position.collapseToEnd(); } @@ -3434,7 +3441,7 @@ void assertCitationCharacterFormatIsOK( styleIsRequired(style); - if ( entries == null || entries.size() == 0 ) { + if (entries == null || entries.size() == 0) { // System.out.println("insertCitation: throwing JabRefException"); throw new JabRefException( "No bibliography entries selected", @@ -3453,7 +3460,7 @@ void assertCitationCharacterFormatIsOK( // Get the cursor positioned by the user. try { cursor = documentConnection.getViewCursor(); - } catch (RuntimeException ex){ + } catch (RuntimeException ex) { // com.sun.star.uno.RuntimeException throw new JabRefException( "Could not get the cursor", @@ -3497,7 +3504,7 @@ void assertCitationCharacterFormatIsOK( // may have removed the citation, thus the reference mark, // but pageInfo stored separately stays there. - assertCitationCharacterFormatIsOK( cursor, style ); + assertCitationCharacterFormatIsOK(cursor, style); // Insert reference mark and text // { @@ -3543,8 +3550,6 @@ void assertCitationCharacterFormatIsOK( if (sync) { // To account for numbering and for uniqueLetters, we // must refresh the cite markers: - //List jabRefReferenceMarkNamesSortedByPosition = - // getJabRefReferenceMarkNamesSortedByPosition(documentConnection); ProduceCitationMarkersResult x = produceCitationMarkers( documentConnection, @@ -3555,7 +3560,6 @@ void assertCitationCharacterFormatIsOK( try { documentConnection.lockControllers(); - //refreshCiteMarkers(allBases, style, jabRefReferenceMarkNamesSortedByPosition); applyNewCitationMarkers( documentConnection, x.jabRefReferenceMarkNamesSortedByPosition, @@ -3566,7 +3570,6 @@ void assertCitationCharacterFormatIsOK( // Insert it at the current position: rebuildBibTextSection( documentConnection, - allBases, style, x.jabRefReferenceMarkNamesSortedByPosition, x.uniqueLetters, @@ -3604,7 +3607,7 @@ void assertCitationCharacterFormatIsOK( * * **************************************************/ - class ExportCitedHelperResult { + static class ExportCitedHelperResult { /** * null: not done; isempty: no unresolved */ @@ -3639,9 +3642,7 @@ public ExportCitedHelperResult exportCitedHelper( try { documentConnection.enterUndoContext("Changes during \"Export cited\""); - List jabRefReferenceMarkNamesSortedByPosition = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - ProduceCitationMarkersResult x = + ProduceCitationMarkersResult x = produceCitationMarkers( documentConnection, databases, @@ -3654,63 +3655,6 @@ public ExportCitedHelperResult exportCitedHelper( return res; } - /** - * Refresh all citation markers in the document. - * - * Called from exportCitedHelper - * - * @param documentConnection Connection. - * @param databases The databases to get entries from. - * @param style The bibliography style to use. - * @return A list of those referenced citation keys that could not be resolved. - */ - /* - private ProduceCitationMarkersResult - refreshCiteMarkers( - DocumentConnection documentConnection, - List databases, - OOBibStyle style - ) - throws - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - IOException, - CreationException, - BibEntryNotFoundException, - NoDocumentException { - - - try { - ProduceCitationMarkersResult x = - produceCitationMarkers( - documentConnection, - databases, - style - ); - - // Refresh all reference marks with the citation markers - // we computed: - applyNewCitationMarkers( - documentConnection, - x.referenceMarkNames, - x.citMarkers, - x.itcTypes, - style); - return x; - - } catch (DisposedException ex) { - // We need to catch this one here because the OpenOfficePanel class is - // loaded before connection, and therefore cannot directly reference - // or catch a DisposedException (which is in a OO JAR file). - throw new ConnectionLostException(ex.getMessage()); - } - } - */ - /** * Visit each reference mark in referenceMarkNames, overwrite its * text content. @@ -3738,7 +3682,6 @@ public ExportCitedHelperResult exportCitedHelper( ) throws NoDocumentException, - NoSuchElementException, UndefinedCharacterFormatException, UnknownPropertyException, CreationException, @@ -3749,7 +3692,6 @@ public ExportCitedHelperResult exportCitedHelper( assert (citMarkers.length == nRefMarks); assert (types.length == nRefMarks); - final boolean hadBibSection = (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) != null); @@ -3772,7 +3714,7 @@ public ExportCitedHelperResult exportCitedHelper( ); if (mustTestCharFormat) { - assertCitationCharacterFormatIsOK( cursor, style ); + assertCitationCharacterFormatIsOK(cursor, style); mustTestCharFormat = false; } @@ -3787,13 +3729,13 @@ public ExportCitedHelperResult exportCitedHelper( if (hadBibSection && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { - if (true){ + // if (true) { // Overwriting text already there is too harsh. // I am making it an error, to see if we ever get here. throw new RuntimeException( "OOBibBase.applyNewCitationMarkers:" - + " just overwrote the bibsection marker. Sorry."); - } else { + + " just overwrote the bibliography section marker. Sorry."); + // } else { // We have overwritten the marker for the start of the reference list. // We need to add it again. // --- @@ -3801,31 +3743,30 @@ public ExportCitedHelperResult exportCitedHelper( // OOUtil.insertParagraphBreak(documentConnection.xText, cursor); // documentConnection.insertBookmark(OOBibBase.BIB_SECTION_NAME, cursor, true); // cursor.collapseToEnd(); - } + // } } } } - /** - * Refresh citation markers according to `style`. - * - * - Requires an up-to-date jabRefReferenceMarkNamesSortedByPosition - * - * @param documentConnection Connection. - * @param databases For look up by citation key. Must have at least one. - * @param style Style. - * @param uniqueLetters Will be cleared and potentially filled with new values. + * The main field is citMarkers, the rest is for reuse in caller. */ - - class ProduceCitationMarkersResult { + static class ProduceCitationMarkersResult { + /** JabRef reference mark names, sorted by position */ List jabRefReferenceMarkNamesSortedByPosition; + /** AUTHORYEAR_PAR, AUTHORYEAR_INTEXT or INVISIBLE_CIT */ int[] itcTypes; + /** citation keys */ String[][] bibtexKeys; + /** citation markers */ String[] citMarkers; + /** Letters making cited sources unique. */ Map uniqueLetters; + /** Results from findCitedEntries */ FindCitedEntriesResult fce; + /** Citation keys not found in databases */ List unresolvedKeys; + ProduceCitationMarkersResult( List jabRefReferenceMarkNamesSortedByPosition, int[] itcTypes, @@ -3850,17 +3791,11 @@ class ProduceCitationMarkersResult { DocumentConnection documentConnection, List databases, OOBibStyle style - // Map uniqueLetters, - // List jabRefReferenceMarkNamesSortedByPosition ) throws WrappedTargetException, IllegalArgumentException, NoSuchElementException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - CreationException, BibEntryNotFoundException, NoDocumentException { @@ -3890,7 +3825,7 @@ class ProduceCitationMarkersResult { // fill citMarkers Map uniqueLetters = new HashMap<>(); - uniqueLetters.clear(); /* ModifiesParameter */ + if (style.isCitationKeyCiteMarkers()) { citMarkers = produceCitationMarkersForIsCitationKeyCiteMarkers( @@ -3928,18 +3863,16 @@ class ProduceCitationMarkersResult { } return new ProduceCitationMarkersResult( - jabRefReferenceMarkNamesSortedByPosition, - itcTypes, - bibtexKeys, - citMarkers, - uniqueLetters, - fce, - unresolvedKeysFromEntries(fce.entries) - ); + jabRefReferenceMarkNamesSortedByPosition, + itcTypes, + bibtexKeys, + citMarkers, + uniqueLetters, + fce, + unresolvedKeysFromEntries(fce.entries) + ); } - - /* ************************************************** * * Bibliography: needs uniqueLetters or numbers @@ -3949,15 +3882,12 @@ class ProduceCitationMarkersResult { /** * Rebuilds the bibliography. * - * @param databases Must have at least one. - * * Note: assumes fresh `jabRefReferenceMarkNamesSortedByPosition` * if `style.isSortByPosition()` */ private void rebuildBibTextSection( DocumentConnection documentConnection, - List databases, OOBibStyle style, List jabRefReferenceMarkNamesSortedByPosition, final Map uniqueLetters, @@ -3970,18 +3900,7 @@ class ProduceCitationMarkersResult { CreationException, PropertyVetoException, UnknownPropertyException, - UndefinedParagraphFormatException, - NoDocumentException { - - // DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - - /* - FindCitedEntriesResult fce = - findCitedEntries( - findCitedKeys(documentConnection), - databases - ); - */ + UndefinedParagraphFormatException { Map entries; @@ -4083,7 +4002,7 @@ class ProduceCitationMarkersResult { } /** - * Insert a paragraph break and creates a text section for the bibliography. + * Insert a paragraph break and create a text section for the bibliography. * * Only called from `clearBibTextSectionContent2` */ @@ -4240,8 +4159,6 @@ class ProduceCitationMarkersResult { Objects.requireNonNull(databases); Objects.requireNonNull(style); - final boolean debugCombineCiteMarkers = true; - final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); try { @@ -4267,7 +4184,6 @@ class ProduceCitationMarkersResult { String[][] bibtexKeys = new String[nRefMarks][]; parseRefMarkNamesToArrays(referenceMarkNames, itcTypes, bibtexKeys); - try { if (useLockControllers) { @@ -4475,7 +4391,6 @@ class ProduceCitationMarkersResult { prevRange = null; } - if (joinableGroups.size() > 0) { XTextCursor textCursor = joinableGroupsCursors.get(0); assertCitationCharacterFormatIsOK(textCursor, style); @@ -4484,13 +4399,12 @@ class ProduceCitationMarkersResult { /* * Now we can process the joinable groups */ + for (int gi = 0; gi < joinableGroups.size(); gi++) { - for (int gi = 0; gi < joinableGroups.size(); gi++ ){ - - List allKeys = new ArrayList<>(); + List allKeys = new ArrayList<>(); for (int gj = 0; gj < joinableGroups.get(gi).size(); gj++) { int rk = joinableGroups.get(gi).get(gj); - allKeys.addAll( Arrays.asList( bibtexKeys[rk] ) ); + allKeys.addAll(Arrays.asList(bibtexKeys[rk])); } // Note: silently drops duplicate keys. @@ -4503,26 +4417,24 @@ class ProduceCitationMarkersResult { .distinct() .collect(Collectors.toList())); - if (true) { - // Removing the old referenceMarkNames from the document - // is covered by removing the text. - // We might want somehting similar - for (int gj = 0; gj < joinableGroups.get(gi).size(); gj++) { - int rk = joinableGroups.get(gi).get(gj); - documentConnection.removeReferenceMark(referenceMarkNames.get(rk)); - } + // Remove the old referenceMarkNames from the document. + // We might want to do this via backends. + for (int gj = 0; gj < joinableGroups.get(gi).size(); gj++) { + int rk = joinableGroups.get(gi).get(gj); + documentConnection.removeReferenceMark(referenceMarkNames.get(rk)); } + XTextCursor textCursor = joinableGroupsCursors.get(gi); - // Should also remove the spaces between. + // Also remove the spaces between. textCursor.setString(""); - // Note: citation keys not found are silently left out from the - // combined reference mark name. Loosing information. - boolean oldStrategy = false; //xxx - List entries ; + boolean oldStrategy = false; + List entries; String keyString; if (oldStrategy) { - //xxx + // Note: citation keys not found are silently left + // out from the combined reference mark + // name. Losing information. entries = lookupEntriesInDatabasesSkipMissing(uniqueKeys, databases); entries.sort(new FieldComparator(StandardField.YEAR)); keyString = @@ -4530,13 +4442,17 @@ class ProduceCitationMarkersResult { .map(c -> c.getCitationKey().orElse("")) .collect(Collectors.joining(",")); } else { - FindCitedEntriesResult fcr = findCitedEntries( uniqueKeys, databases ); + FindCitedEntriesResult fcr = findCitedEntries(uniqueKeys, databases); // entries contains UndefinedBibtexEntry for keys not found in databases entries = new ArrayList<>(); for (Map.Entry kv : fcr.entries.entrySet()) { - entries.add( kv.getKey() ); + entries.add(kv.getKey()); } // Now we do not sort the entries here. + // + // TODO: the sorting skipped here should be done + // when creating the presentation. Check if it is there. + // // entries.sort(new FieldComparator(StandardField.YEAR)); keyString = entries.stream() @@ -4693,15 +4609,9 @@ class ProduceCitationMarkersResult { /* withText should be itcType != OOBibBase.INVISIBLE_CIT */ true, style, - true // insertSpaceAfter + insertSpaceAfter ); textCursor.collapseToEnd(); - // if (i != last) { - // // space between citation markers: what style? - // // DocumentConnection.setCharStyle(textCursor, "Standard"); - // textCursor.setString(" "); - // textCursor.collapseToEnd(); - // } i++; } madeModifications = true; @@ -4819,9 +4729,9 @@ class ProduceCitationMarkersResult { return resultDatabase; } - void styleIsRequired( OOBibStyle style ) + void styleIsRequired(OOBibStyle style) throws JabRefException { - if ( style == null ) { + if (style == null) { throw new JabRefException( "This operation requires a style", Localization.lang("This operation requires a style.") @@ -4876,7 +4786,7 @@ void styleIsRequired( OOBibStyle style ) style ); - if (useLockControllers){ + if (useLockControllers) { documentConnection.lockControllers(); } applyNewCitationMarkers( @@ -4887,7 +4797,6 @@ void styleIsRequired( OOBibStyle style ) style); rebuildBibTextSection( documentConnection, - databases, style, x.jabRefReferenceMarkNamesSortedByPosition, x.uniqueLetters, @@ -4895,7 +4804,7 @@ void styleIsRequired( OOBibStyle style ) ); return x.unresolvedKeys; } finally { - if (useLockControllers){ + if (useLockControllers) { documentConnection.unlockControllers(); } } From bcfb6c6455d58974e943cbf5c66bc318fcf69afb Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 14 Mar 2021 12:23:54 +0100 Subject: [PATCH 0484/1068] csop for loop variables --- .../org/jabref/gui/openoffice/OOBibBase.java | 330 +++++++++--------- 1 file changed, 165 insertions(+), 165 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 680cc254f6a..6fc50b3f6ce 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4199,196 +4199,196 @@ static class ProduceCitationMarkersResult { List> joinableGroups = new ArrayList<>(); List joinableGroupsCursors = new ArrayList<>(); - // current group - List currentGroup = new ArrayList<>(); - XTextCursor currentGroupCursor = null; - XTextCursor cursorBetween = null; - Integer prev = null; - XTextRange prevRange = null; - - for ( int i=0; i < referenceMarkNames.size(); i++ ) { - final String name = referenceMarkNames.get(i); - XTextRange currentRange = documentConnection.getReferenceMarkRangeOrNull(name); - Objects.requireNonNull(currentRange); - - boolean addToGroup = true; - /* - * Decide if we add name to the group - */ + if (referenceMarkNames.size() > 0) { + // current group + List currentGroup = new ArrayList<>(); + XTextCursor currentGroupCursor = null; + XTextCursor cursorBetween = null; + Integer prev = null; + XTextRange prevRange = null; + + for (int i = 0; i < referenceMarkNames.size(); i++) { + final String name = referenceMarkNames.get(i); + XTextRange currentRange = documentConnection.getReferenceMarkRangeOrNull(name); + Objects.requireNonNull(currentRange); - // Only combine (Author 2000) type citations - if ( itcTypes[i] != OOBibBase.AUTHORYEAR_PAR - // allow "Author (2000)" - // && itcTypes[i] != OOBibBase.AUTHORYEAR_INTEXT - ) { - addToGroup = false; - } + boolean addToGroup = true; + /* + * Decide if we add name to the group + */ - // Even if we combine AUTHORYEAR_INTEXT citations, we - // would not mix them with AUTHORYEAR_PAR - if (addToGroup && (prev != null) ) { - if ( itcTypes[i] != itcTypes[prev] ){ + // Only combine (Author 2000) type citations + if (itcTypes[i] != OOBibBase.AUTHORYEAR_PAR + // allow "Author (2000)" + // && itcTypes[i] != OOBibBase.AUTHORYEAR_INTEXT + ) { addToGroup = false; } - } - if ( addToGroup && prev != null ) { - Objects.requireNonNull(prevRange); - Objects.requireNonNull(currentRange); - if ( ! DocumentConnection.comparable( prevRange, currentRange ) ) { - addToGroup = false; - } else { - - int textOrder = - DocumentConnection.javaCompareRegionStarts( - prevRange, - currentRange); - - if ( textOrder != 1 ) { - String msg = String.format( - "combineCiteMarkers: \"%s\" supposed to be followed by \"%s\", but %s", - prevRange.getString(), - currentRange.getString(), - ((textOrder == 0) - ? "they start at the same position" - : "the latter precedes the first") - ); - LOGGER.warn(msg); + // Even if we combine AUTHORYEAR_INTEXT citations, we + // would not mix them with AUTHORYEAR_PAR + if (addToGroup && (prev != null)) { + if (itcTypes[i] != itcTypes[prev]) { addToGroup = false; } } - } - if (addToGroup && (cursorBetween != null)) { - Objects.requireNonNull(currentGroupCursor); - // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() - if (DocumentConnection.javaCompareRegionEnds( - cursorBetween, currentGroupCursor) != 0) { - throw new RuntimeException( - "combineCiteMarkers: cursorBetween.end != currentGroupCursor.end"); + if (addToGroup && prev != null) { + Objects.requireNonNull(prevRange); + Objects.requireNonNull(currentRange); + if (!DocumentConnection.comparable(prevRange, currentRange)) { + addToGroup = false; + } else { + + int textOrder = + DocumentConnection.javaCompareRegionStarts( + prevRange, + currentRange); + + if (textOrder != 1) { + String msg = String.format( + "combineCiteMarkers: \"%s\" supposed to be followed by \"%s\", but %s", + prevRange.getString(), + currentRange.getString(), + ((textOrder == 0) + ? "they start at the same position" + : "the latter precedes the first") + ); + LOGGER.warn(msg); + addToGroup = false; + } + } } - XTextRange rangeStart = currentRange.getStart(); - - boolean couldExpand = true; - XTextCursor thisCharCursor = - currentRange.getText().createTextCursorByRange(cursorBetween.getEnd()); - while (couldExpand && - (DocumentConnection.javaCompareRegionEnds( - cursorBetween, rangeStart) > 0)) { - couldExpand = cursorBetween.goRight((short) 1, true); - currentGroupCursor.goRight((short) 1, true); - // - thisCharCursor.goRight((short) 1, true); - String thisChar = thisCharCursor.getString(); - thisCharCursor.collapseToEnd(); - if (thisChar.isEmpty() - || thisChar == "\n" - || !thisChar.trim().isEmpty() ) { - couldExpand = false; - } + if (addToGroup && (cursorBetween != null)) { + Objects.requireNonNull(currentGroupCursor); + // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() if (DocumentConnection.javaCompareRegionEnds( cursorBetween, currentGroupCursor) != 0) { throw new RuntimeException( - "combineCiteMarkers: " - + "cursorBetween.end != currentGroupCursor.end (during expand)" ); + "combineCiteMarkers: cursorBetween.end != currentGroupCursor.end"); } - } - if (!couldExpand) { - addToGroup = false; - } - } + XTextRange rangeStart = currentRange.getStart(); + + boolean couldExpand = true; + XTextCursor thisCharCursor = + currentRange.getText() + .createTextCursorByRange(cursorBetween.getEnd()); + while (couldExpand && + (DocumentConnection.javaCompareRegionEnds( + cursorBetween, rangeStart) > 0)) { + couldExpand = cursorBetween.goRight((short) 1, true); + currentGroupCursor.goRight((short) 1, true); + // + thisCharCursor.goRight((short) 1, true); + String thisChar = thisCharCursor.getString(); + thisCharCursor.collapseToEnd(); + if (thisChar.isEmpty() + || thisChar.equals("\n") + || !thisChar.trim().isEmpty()) { + couldExpand = false; + } + if (DocumentConnection.javaCompareRegionEnds( + cursorBetween, currentGroupCursor) != 0) { + throw new RuntimeException( + "combineCiteMarkers:" + + " cursorBetween.end != currentGroupCursor.end" + + " (during expand)"); + } + } - /* - * Even if we do not add it to an existing group, we might use it toi start - * a new group. - */ - // can it start a new group? - boolean canStartGroup = ( itcTypes[i] == OOBibBase.AUTHORYEAR_PAR ); - - if (!addToGroup){ - // close currentGroup - if (currentGroup.size() > 1) { - joinableGroups.add( currentGroup ); - joinableGroupsCursors.add( currentGroupCursor ); + if (!couldExpand) { + addToGroup = false; + } } - // Start a new, empty group - currentGroup = new ArrayList<>(); - currentGroupCursor = null; - cursorBetween = null; - prev = null; - prevRange = null; - } - if ( addToGroup || canStartGroup ) { - // Add the current entry to a group. - currentGroup.add(i); - // ... and start new cursorBetween - // Set up cursorBetween - // - XTextRange rangeEnd = currentRange.getEnd(); - cursorBetween = currentRange.getText().createTextCursorByRange(rangeEnd); - // If new group, create currentGroupCursor - if ( currentGroupCursor == null ) { - currentGroupCursor = - currentRange.getText().createTextCursorByRange(currentRange.getStart()); + /* + * Even if we do not add it to an existing group, + * we might use it to start a new group. + * + * Can it start a new group? + */ + boolean canStartGroup = (itcTypes[i] == OOBibBase.AUTHORYEAR_PAR); + + if (!addToGroup) { + // close currentGroup + if (currentGroup.size() > 1) { + joinableGroups.add(currentGroup); + joinableGroupsCursors.add(currentGroupCursor); + } + // Start a new, empty group + currentGroup = new ArrayList<>(); + currentGroupCursor = null; + cursorBetween = null; + prev = null; + prevRange = null; } - // include self in currentGroupCursor - currentGroupCursor.goRight( (short)( currentRange.getString().length() ), true ); - - if (DocumentConnection.javaCompareRegionEnds( - cursorBetween, currentGroupCursor) != 0) { - /* - * A problem discovered using this check: when - * viewing the document in - * two-pages-side-by-side mode, our visual - * firstAppearanceOrder follows the visual - * ordering on the screen. The problem this - * caused: it sees a citation on the 2nd line - * of the 1st page as appearing after one at - * the 1st line of 2nd page. Since we create - * cursorBetween at the end of range1Full (on - * 1st page), it is now BEFORE - * currentGroupCursor (on 2nd page). - */ - throw new RuntimeException( - "combineCiteMarkers: " - + "cursorBetween.end != currentGroupCursor.end" - + String.format( - " (after %s", addToGroup ? "addToGroup" : "startGroup") - + (addToGroup - ? String.format( - "comparisonResult: %d\n" - + "cursorBetween: %s\n" - + "currentRange: %s\n" - + "currentGroupCursor: %s\n" - , DocumentConnection.javaCompareRegionEnds( - cursorBetween, currentGroupCursor) - , cursorBetween.getString() - , currentRange.getString() - , currentGroupCursor.getString() - ) - : "") - ); + + if (addToGroup || canStartGroup) { + // Add the current entry to a group. + currentGroup.add(i); + // ... and start new cursorBetween + // Set up cursorBetween + // + XTextRange rangeEnd = currentRange.getEnd(); + cursorBetween = + currentRange.getText().createTextCursorByRange(rangeEnd); + // If new group, create currentGroupCursor + if (currentGroupCursor == null) { + currentGroupCursor = + currentRange.getText() + .createTextCursorByRange(currentRange.getStart()); + } + // include self in currentGroupCursor + currentGroupCursor.goRight( + (short) (currentRange.getString().length()), true); + + if (DocumentConnection.javaCompareRegionEnds( + cursorBetween, currentGroupCursor) != 0) { + /* + * A problem discovered using this check: when + * viewing the document in + * two-pages-side-by-side mode, our visual + * firstAppearanceOrder follows the visual + * ordering on the screen. The problem this + * caused: it sees a citation on the 2nd line + * of the 1st page as appearing after one at + * the 1st line of 2nd page. Since we create + * cursorBetween at the end of range1Full (on + * 1st page), it is now BEFORE + * currentGroupCursor (on 2nd page). + */ + throw new RuntimeException( + "combineCiteMarkers: " + + "cursorBetween.end != currentGroupCursor.end" + + String.format( + " (after %s", addToGroup ? "addToGroup" : "startGroup") + + (addToGroup + ? String.format( + "comparisonResult: %d\n" + + "cursorBetween: %s\n" + + "currentRange: %s\n" + + "currentGroupCursor: %s\n", + DocumentConnection.javaCompareRegionEnds( + cursorBetween, currentGroupCursor), + cursorBetween.getString(), + currentRange.getString(), + currentGroupCursor.getString() + ) + : "") + ); + } + prev = i; + prevRange = currentRange; } - prev = i; - prevRange = currentRange; - } // for i - } // try + } - if (true) { // close currentGroup if (currentGroup.size() > 1) { - joinableGroups.add( currentGroup ); - joinableGroupsCursors.add( currentGroupCursor ); + joinableGroups.add(currentGroup); + joinableGroupsCursors.add(currentGroupCursor); } - // clean variables - currentGroup = null; - currentGroupCursor = null; - cursorBetween = null; - prev = null; - prevRange = null; } if (joinableGroups.size() > 0) { From e389445b67639b3bc5db0b89d13aaa66f4e2148a Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 14 Mar 2021 21:52:50 +0100 Subject: [PATCH 0485/1068] javaCompareRegionStarts sign correction --- .../org/jabref/gui/openoffice/OOBibBase.java | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6fc50b3f6ce..3c11176cf54 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -845,6 +845,7 @@ boolean hasControllersLocked() { /** * @return follows java conventions * + * 1 if (a > b); (-1) if (a < b) */ private static int javaCompareRegionStarts(XTextRange a, XTextRange b) { @@ -4245,14 +4246,14 @@ static class ProduceCitationMarkersResult { prevRange, currentRange); - if (textOrder != 1) { + if (textOrder != (-1)) { String msg = String.format( "combineCiteMarkers: \"%s\" supposed to be followed by \"%s\", but %s", prevRange.getString(), currentRange.getString(), ((textOrder == 0) ? "they start at the same position" - : "the latter precedes the first") + : "the start of the latter precedes the start of the first") ); LOGGER.warn(msg); addToGroup = false; @@ -4277,7 +4278,7 @@ static class ProduceCitationMarkersResult { .createTextCursorByRange(cursorBetween.getEnd()); while (couldExpand && (DocumentConnection.javaCompareRegionEnds( - cursorBetween, rangeStart) > 0)) { + cursorBetween, rangeStart) < 0)) { couldExpand = cursorBetween.goRight((short) 1, true); currentGroupCursor.goRight((short) 1, true); // @@ -4363,13 +4364,13 @@ static class ProduceCitationMarkersResult { "combineCiteMarkers: " + "cursorBetween.end != currentGroupCursor.end" + String.format( - " (after %s", addToGroup ? "addToGroup" : "startGroup") + " (after %s)", addToGroup ? "addToGroup" : "startGroup") + (addToGroup ? String.format( - "comparisonResult: %d\n" - + "cursorBetween: %s\n" - + "currentRange: %s\n" - + "currentGroupCursor: %s\n", + " comparisonResult: %d\n" + + "cursorBetween: '%s'\n" + + "currentRange: '%s'\n" + + "currentGroupCursor: '%s'\n", DocumentConnection.javaCompareRegionEnds( cursorBetween, currentGroupCursor), cursorBetween.getString(), From 784189e223dc8df7f23b2ffc8d48f095d2ab9958 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 14 Mar 2021 21:54:31 +0100 Subject: [PATCH 0486/1068] minimize user-visible reference mark bracketing To minimize changes from JabRef 5.2 representation, for reference marks with length >= 2 brackets are removed after filling their content. Practically only "Insert empty citation" leaves brackets (two zero-width spaces) --- .../org/jabref/gui/openoffice/OOBibBase.java | 366 +++++++++++++----- 1 file changed, 274 insertions(+), 92 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3c11176cf54..466cba25813 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -106,16 +106,16 @@ class OOBibBase { Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); private static final String ZERO_WIDTH_SPACE = "\u200b"; + // for debugging we may want visible bracket - private static final boolean REFERENCE_MARK_USE_INVISIBLE_BRACKETS = false; // !debug; + private static final boolean + REFERENCE_MARK_USE_INVISIBLE_BRACKETS = true; // !debug; + + private static final String + REFERENCE_MARK_LEFT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<"; - // Note we were relying on referenceMarkLeftBracket and referenceMarkRightBracket - // to be single-character strings that do not appear in reference mark content. - // Now we probably rely on this no more, empty, or longer brackets should work as well. - private static final String REFERENCE_MARK_LEFT_BRACKET = - REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<"; - private static final String REFERENCE_MARK_RIGHT_BRACKET = - REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; + private static final String + REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; /* Types of in-text citation. (itcType) * Their numeric values are used in reference mark names. @@ -3028,9 +3028,69 @@ static class CitationMarkersWithUniqueLetters { * ***********************************/ /** - * Create an (empty) reference mark with the given name, at the + * Insert {@code n} spaces in a way that reference + * marks just before or just after the cursor are not affected. + * + * This is based on the observation, that starting two + * new paragraphs separates us from a reference mark on either side. + * + * The pattern used is: + * {@code safeInsertSpaces(n): para, para, left, space(n), right-delete, left(n), left-delete} + * + * @param position Where to insert (at position.getStart()) + * @param n Number of spaces to insert. + * + * @return a new cursor, covering the just-inserted spaces. + * + * This could be generalized to insert arbitrary text safely + * between two reference marks. But we do not need that now. + */ + private static XTextCursor + safeInsertSpacesBetweenReferencMarks(XTextRange position, int n) { + // Start with an empty cursor at position.getStart(); + XText text = position.getText(); + XTextCursor cursor = text.createTextCursorByRange(position.getStart()); + text.insertString(cursor,"\r\r",false); // para, para + cursor.goLeft((short) 1,false); // left + text.insertString(cursor," ".repeat(n),false); // space(n) + cursor.goRight((short) 1,true); cursor.setString(""); // right-delete + cursor.goLeft((short) n,false); // left(n) + cursor.goLeft((short) 1,true); cursor.setString(""); // left-delete + cursor.goRight((short) n,true); + return cursor; + } + + /** + * Create a reference mark with the given name, at the * end of position. * + * Change of plan: to reduce the difference from the original + * representation, we only insist on having at least two + * characters inside. These may be ZERO_WIDTH_SPACE characters or other + * placeholder not likely to appear in a citation mark. + * + * This placeholder is only needed if the citation mark is + * otherwise empty (e.g. when we just create it). + * + * getFillCursorForCitationGroup yields a bracketed cursor, that + * can be used to fill in / overwrite the value inside. + * + * After each getFillCursorForCitationGroup, we require a call to + * cleanFillCursorForCitationGroup, which removes the brackets, + * unless if it would make the content less + * than two characters. If we need only one placeholder, we keep the left bracket. + * If we need two, then the content is empty. + * + * Thus the only user-visible difference in citation marks is + * that instead of empty marks we use two brackets, for + * single-character marks we add a left bracket before. + * + * Character-attribute inheritance: updates inherit from the + * first character inside, not from the left. + * + * On return {@code position} is collapsed, and is after the + * inserted space, or at the end of the reference mark. + * * @param documentConnection Connection to document. * @param name For the reference mark. * @param position Collapsed to its end. @@ -3038,61 +3098,63 @@ static class CitationMarkersWithUniqueLetters { * carries on format of characters from * the original position. * - * @return XTextCursor for the text to be inserted. - * - * On return position is collapsed, and is after the inserted space, - * or at the end of the (empty) range allocated for the text. + * @return Nothing (was: XTextCursor for the text to be inserted) * */ - private static XTextCursor + private static void createReferenceMarkForCitationGroup( DocumentConnection documentConnection, String name, XTextCursor position, - boolean insertSpaceAfter, - String initialText + boolean insertSpaceAfter ) throws - CreationException { + CreationException, + NoDocumentException, + WrappedTargetException { // The cursor we received: we push it before us. position.collapseToEnd(); - XTextCursor cursor = position.getText().createTextCursorByRange(position.getEnd()); - if (insertSpaceAfter) { - cursor.getText().insertString(cursor, " ", false); + XTextCursor cursor = safeInsertSpacesBetweenReferencMarks(position.getEnd(), 2); - // space between citation markers: what style? - // DocumentConnection.setCharStyle(cursor, "Standard"); + // cursors before the first and after the last space + XTextCursor cursorBefore = + cursor.getText().createTextCursorByRange(cursor.getStart()); + XTextCursor cursorAfter = + cursor.getText().createTextCursorByRange(cursor.getEnd()); - // go back to before the space - cursor.goLeft((short) 1, false); - } + cursor.collapseToStart(); + cursor.goRight( (short) 1, false ); + // now we are between two spaces final String left = REFERENCE_MARK_LEFT_BRACKET; final String right = REFERENCE_MARK_RIGHT_BRACKET; final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); - String text = left + initialText + right; - cursor.getText().insertString(cursor, text, true); + cursor.getText().insertString( + cursor, + left+right, + true); /* XNamed mark = */ documentConnection.insertReferenceMark( name, cursor, true // absorb ); - // Need a cursor that excludes left and right - XTextCursor full = cursor; - if (leftLength + rightLength > 0) { - full.collapseToStart(); - full.goRight((short) left.length(), false); - full.goRight((short) initialText.length(), true); - } - return full; // yield a cursor in the bracket + + cursorBefore.goRight((short) 1, true); cursorBefore.setString(""); + if ( !insertSpaceAfter ) { + cursorAfter.goLeft((short) 1, true); cursorAfter.setString(""); + } } - private static XTextCursor - getFillCursorForCitationGroup( + /** + * Remove brackets, but if the result would become empty, leave + * them; if the result would be a single characer, leave the left bracket. + */ + private static void + cleanFillCursorForCitationGroup( DocumentConnection documentConnection, String name // Identifies group ) @@ -3101,7 +3163,6 @@ static class CitationMarkersWithUniqueLetters { WrappedTargetException, CreationException { - final boolean debugThisFun = false; final String left = REFERENCE_MARK_LEFT_BRACKET; final String right = REFERENCE_MARK_RIGHT_BRACKET; final short leftLength = (short) left.length(); @@ -3113,7 +3174,7 @@ static class CitationMarkersWithUniqueLetters { if (markAsTextContent == null) { throw new RuntimeException( String.format( - "getFillCursorForCitationGroup: markAsTextContent(%s) == null", + "cleanFillCursorForCitationGroup: markAsTextContent(%s) == null", name )); } @@ -3122,64 +3183,170 @@ static class CitationMarkersWithUniqueLetters { markAsTextContent); if (full == null) { throw new RuntimeException( - "getFillCursorForCitationGroup: full == null" + "cleanFillCursorForCitationGroup: full == null" ); } String fullText = full.getString(); - if (debugThisFun) { - System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); + + XTextCursor alpha = full.getText().createTextCursorByRange(full); + alpha.collapseToStart(); + + XTextCursor beta = full.getText().createTextCursorByRange(full); + beta.collapseToStart(); + beta.goRight(leftLength, false); + + XTextCursor omega = full.getText().createTextCursorByRange(full); + omega.collapseToEnd(); + + if (!fullText.startsWith( left )) { + throw new RuntimeException( + String.format( + "cleanFillCursorForCitationGroup:" + + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", + name + )); } - if (fullText.length() < (leftLength + rightLength) - || !fullText.startsWith(left) - || !fullText.endsWith(right)) { - // damaged, recreate - if (debugThisFun) { - System.out.println("getFillCursor: damaged, recreate"); - } - full.setString(""); - try { - documentConnection.removeReferenceMark(name); - } catch (NoSuchElementException ex) { - LOGGER.warn(String.format( - "getFillCursorForCitationGroup got NoSuchElementException" - + " for '%s'", name)); - } - // What shall we put in the recreated version? - // User might have inserted stuff before or after? - // We try to remove only brackets of exactly 1 character, - // not of length zero or more than one. - String trimmedText = fullText; - if (leftLength == 1) { - trimmedText = trimmedText.replaceAll("[" + left + "]", ""); - } - if (rightLength == 1) { - trimmedText = trimmedText.replaceAll("[" + right + "]", ""); + if (!fullText.endsWith( right )) { + throw new RuntimeException( + String.format( + "cleanFillCursorForCitationGroup:" + + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", + name + )); + } + + if ( fullText.length() < (leftLength + rightLength)) { + throw new RuntimeException( + String.format( + "cleanFillCursorForCitationGroup: length(%s) < (leftLength + rightLength)", + name + )); + } + + if ( fullText.length() >= (leftLength + rightLength + 1)) { + // have at least 1 character content + omega.goLeft((short) rightLength, true); omega.setString(""); + } + + if ( fullText.length() >= (leftLength + rightLength + 2)) { + // have at least 2 character content + alpha.goRight((short) leftLength, true); alpha.setString(""); + } + } + + private static XTextCursor + getFillCursorForCitationGroup( + DocumentConnection documentConnection, + String name // Identifies group + ) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + final boolean debugThisFun = false; + final String left = REFERENCE_MARK_LEFT_BRACKET; + final String right = REFERENCE_MARK_RIGHT_BRACKET; + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); + + XTextCursor full=null; + String fullText=null; + for (int i = 1; i <= 2; i++) { + XTextContent markAsTextContent = + documentConnection.getReferenceMarkAsTextContentOrNull(name); + + if (markAsTextContent == null) { + throw new RuntimeException( + String.format( + "getFillCursorForCitationGroup: markAsTextContent(%s) == null (attempt %d)", + name, i + )); } - if (debugThisFun) { - System.out.printf("getFillCursor: trimmedText = '%s'%n", trimmedText); + full = + DocumentConnection.getTextCursorOfTextContent( + markAsTextContent); + if (full == null) { + throw new RuntimeException( + String.format( + "getFillCursorForCitationGroup: full == null (attempt %d)", i + ) + ); } - return createReferenceMarkForCitationGroup( - documentConnection, - name, - full, - false, // insertSpaceAfter - trimmedText); - } else { + + fullText = full.getString(); if (debugThisFun) { - System.out.println("getFillCursor: intact, reuse"); + System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); } - if (leftLength + rightLength > 0) { - full.collapseToStart(); - full.goRight((short) left.length(), false); - short contentLength = - (short) (fullText.length() - (left.length() + right.length())); - full.goRight(contentLength, true); + + if (fullText.length() >= 2) { + break; + } else { + // (fullText.length() < 2) + if (i == 2) { + throw new RuntimeException( + String.format( + "getFillCursorForCitationGroup:" + + " (fullText.length() < 2) (attempt %d)", i + ) + ); + } + // too short, recreate + if (debugThisFun) { + System.out.println("getFillCursor: too short, recreate"); + } + full.setString(""); + try { + documentConnection.removeReferenceMark(name); + } catch (NoSuchElementException ex) { + LOGGER.warn(String.format( + "getFillCursorForCitationGroup got NoSuchElementException" + + " for '%s'", name)); + } + createReferenceMarkForCitationGroup( + documentConnection, + name, + full, + false // insertSpaceAfter + ); } - return full; // yield a cursor in the bracket } + + if (full == null) { + throw new RuntimeException( + "getFillCursorForCitationGroup: full == null (after loop)" + ); + } + if (fullText == null) { + throw new RuntimeException( + "getFillCursorForCitationGroup: fullText == null (after loop)" + ); + } + + // we have at least two characters inside + XTextCursor alpha = full.getText().createTextCursorByRange(full); + alpha.collapseToStart(); + XTextCursor omega = full.getText().createTextCursorByRange(full); + omega.collapseToEnd(); + + XTextCursor beta = full.getText().createTextCursorByRange(full); + beta.collapseToStart(); + beta.goRight((short) 1, false); + beta.goRight((short) (fullText.length()-2), true); + beta.setString(left+right); + beta.collapseToEnd(); + beta.goLeft(rightLength, false); + // drop the inital character + alpha.goRight((short) 1, true); + alpha.setString(""); + // drop the last character + omega.goLeft((short) 1, true); + omega.setString(""); + return beta; } + private static void fillCitationMarkInCursor( DocumentConnection documentConnection, @@ -3295,13 +3462,16 @@ static class CitationMarkersWithUniqueLetters { PropertyVetoException, IllegalArgumentException, UndefinedCharacterFormatException, - CreationException { + CreationException, + NoDocumentException { + + createReferenceMarkForCitationGroup(documentConnection, + name, + position, + insertSpaceAfter); - XTextCursor c2 = createReferenceMarkForCitationGroup(documentConnection, - name, - position, - insertSpaceAfter, - ""); + XTextCursor c2 = getFillCursorForCitationGroup(documentConnection, + name); fillCitationMarkInCursor(documentConnection, name, @@ -3309,6 +3479,9 @@ static class CitationMarkersWithUniqueLetters { citationText, withText, style); + + cleanFillCursorForCitationGroup(documentConnection, + name); position.collapseToEnd(); } @@ -3455,8 +3628,12 @@ void assertCitationCharacterFormatIsOK( DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + boolean useUndoContext = true; + try { - documentConnection.enterUndoContext("Insert citation"); + if (useUndoContext) { + documentConnection.enterUndoContext("Insert citation"); + } XTextCursor cursor; // Get the cursor positioned by the user. try { @@ -3598,7 +3775,9 @@ void assertCitationCharacterFormatIsOK( // or catch a DisposedException (which is in a OO JAR file). throw new ConnectionLostException(ex.getMessage()); } finally { - documentConnection.leaveUndoContext(); + if (useUndoContext) { + documentConnection.leaveUndoContext(); + } } } @@ -3728,6 +3907,9 @@ public ExportCitedHelperResult exportCitedHelper( style ); + cleanFillCursorForCitationGroup(documentConnection, + name); + if (hadBibSection && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { // if (true) { From 0ec7b616bfafbec09dad3be42df0d8aefdf1a111 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 15 Mar 2021 11:47:07 +0100 Subject: [PATCH 0487/1068] remove brackets after filling the content --- .../org/jabref/gui/openoffice/OOBibBase.java | 137 ++++++++++++------ 1 file changed, 92 insertions(+), 45 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 466cba25813..9a26fa4c8da 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -117,6 +117,10 @@ class OOBibBase { private static final String REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; + /** Should we always fully remove reference mark brackets? */ + private static final boolean + REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS = true; + /* Types of in-text citation. (itcType) * Their numeric values are used in reference mark names. */ @@ -3064,9 +3068,9 @@ static class CitationMarkersWithUniqueLetters { * Create a reference mark with the given name, at the * end of position. * - * Change of plan: to reduce the difference from the original - * representation, we only insist on having at least two - * characters inside. These may be ZERO_WIDTH_SPACE characters or other + * To reduce the difference from the original representation, we + * only insist on having at least two characters inside reference + * marks. These may be ZERO_WIDTH_SPACE characters or other * placeholder not likely to appear in a citation mark. * * This placeholder is only needed if the citation mark is @@ -3077,9 +3081,15 @@ static class CitationMarkersWithUniqueLetters { * * After each getFillCursorForCitationGroup, we require a call to * cleanFillCursorForCitationGroup, which removes the brackets, - * unless if it would make the content less - * than two characters. If we need only one placeholder, we keep the left bracket. - * If we need two, then the content is empty. + * unless if it would make the content less than two + * characters. If we need only one placeholder, we keep the left + * bracket. If we need two, then the content is empty. The + * removeBracketsFromEmpty parameter of + * cleanFillCursorForCitationGroup overrides this, and for empty + * citations it will remove the brackets, leaving an empty + * reference mark. The idea behind this is that we do not need to + * refill empty marks (itcTypes INVISIBLE_CIT), and the caller + * can tell us that we are dealing with one of these. * * Thus the only user-visible difference in citation marks is * that instead of empty marks we use two brackets, for @@ -3098,6 +3108,9 @@ static class CitationMarkersWithUniqueLetters { * carries on format of characters from * the original position. * + * @param withoutBrackets Force empty reference mark (no brackets). + * For use with INVISIBLE_CIT. + * * @return Nothing (was: XTextCursor for the text to be inserted) * */ @@ -3106,7 +3119,8 @@ static class CitationMarkersWithUniqueLetters { DocumentConnection documentConnection, String name, XTextCursor position, - boolean insertSpaceAfter + boolean insertSpaceAfter, + boolean withoutBrackets ) throws CreationException, @@ -3132,11 +3146,15 @@ static class CitationMarkersWithUniqueLetters { final String right = REFERENCE_MARK_RIGHT_BRACKET; final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); + String bracketedContent = (withoutBrackets + ? "" + : left+right); cursor.getText().insertString( cursor, - left+right, + bracketedContent, true); + /* XNamed mark = */ documentConnection.insertReferenceMark( name, cursor, @@ -3152,11 +3170,16 @@ static class CitationMarkersWithUniqueLetters { /** * Remove brackets, but if the result would become empty, leave * them; if the result would be a single characer, leave the left bracket. + * + * @param removeBracketsFromEmpty is intended to force removal if + * we are working on an "Empty citation" (INVISIBLE_CIT). */ private static void cleanFillCursorForCitationGroup( DocumentConnection documentConnection, - String name // Identifies group + String name, // Identifies group + boolean removeBracketsFromEmpty, + boolean alwaysRemoveBrackets ) throws NoDocumentException, @@ -3186,7 +3209,8 @@ static class CitationMarkersWithUniqueLetters { "cleanFillCursorForCitationGroup: full == null" ); } - String fullText = full.getString(); + final String fullText = full.getString(); + final int fullTextLength = fullText.length(); XTextCursor alpha = full.getText().createTextCursorByRange(full); alpha.collapseToStart(); @@ -3216,21 +3240,33 @@ static class CitationMarkersWithUniqueLetters { )); } - if ( fullText.length() < (leftLength + rightLength)) { + final int contentLength = (fullTextLength - (leftLength + rightLength)); + if ( contentLength < 0) { throw new RuntimeException( String.format( - "cleanFillCursorForCitationGroup: length(%s) < (leftLength + rightLength)", + "cleanFillCursorForCitationGroup: length(%s) < 0", name )); } - if ( fullText.length() >= (leftLength + rightLength + 1)) { + boolean removeRight = ( // have at least 1 character content + (contentLength >= 1) + || ((contentLength == 0) && removeBracketsFromEmpty) + || alwaysRemoveBrackets + ); + boolean removeLeft = ( + // have at least 2 character content + (contentLength >= 2) + || ((contentLength == 0) && removeBracketsFromEmpty) + || alwaysRemoveBrackets + ); + + if (removeRight) { omega.goLeft((short) rightLength, true); omega.setString(""); } - if ( fullText.length() >= (leftLength + rightLength + 2)) { - // have at least 2 character content + if (removeLeft) { alpha.goRight((short) leftLength, true); alpha.setString(""); } } @@ -3308,7 +3344,8 @@ static class CitationMarkersWithUniqueLetters { documentConnection, name, full, - false // insertSpaceAfter + false, // insertSpaceAfter + false // withoutBrackets ); } } @@ -3468,20 +3505,25 @@ static class CitationMarkersWithUniqueLetters { createReferenceMarkForCitationGroup(documentConnection, name, position, - insertSpaceAfter); + insertSpaceAfter, + !withText); - XTextCursor c2 = getFillCursorForCitationGroup(documentConnection, - name); + if (withText) { + XTextCursor c2 = getFillCursorForCitationGroup(documentConnection, + name); - fillCitationMarkInCursor(documentConnection, - name, - c2, - citationText, - withText, - style); + fillCitationMarkInCursor(documentConnection, + name, + c2, + citationText, + withText, + style); - cleanFillCursorForCitationGroup(documentConnection, - name); + cleanFillCursorForCitationGroup(documentConnection, + name, + !withText, + REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); + } position.collapseToEnd(); } @@ -3887,29 +3929,34 @@ public ExportCitedHelperResult exportCitedHelper( final String name = referenceMarkNames.get(i); - XTextCursor cursor = - getFillCursorForCitationGroup( + boolean withText = (types[i] != OOBibBase.INVISIBLE_CIT); + if (withText) { + XTextCursor cursor = + getFillCursorForCitationGroup( + documentConnection, + name // Identifies group + ); + + if (mustTestCharFormat) { + assertCitationCharacterFormatIsOK(cursor, style); + mustTestCharFormat = false; + } + + fillCitationMarkInCursor( documentConnection, - name // Identifies group + name, // citationGroup + cursor, + citMarkers[i], // citationText, + withText, + style ); - if (mustTestCharFormat) { - assertCitationCharacterFormatIsOK(cursor, style); - mustTestCharFormat = false; + cleanFillCursorForCitationGroup(documentConnection, + name, + !withText, + REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); } - fillCitationMarkInCursor( - documentConnection, - name, // citationGroup - cursor, - citMarkers[i], // citationText, - types[i] != OOBibBase.INVISIBLE_CIT, // withText, - style - ); - - cleanFillCursorForCitationGroup(documentConnection, - name); - if (hadBibSection && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { // if (true) { From 9e38452dd1434d97d0f6f31c5ccb8783734b08ba Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 15 Mar 2021 14:05:43 +0100 Subject: [PATCH 0488/1068] add DocumentConnection.java --- .../gui/openoffice/DocumentConnection.java | 874 ++++++++++++++++++ .../org/jabref/gui/openoffice/OOBibBase.java | 777 +--------------- 2 files changed, 888 insertions(+), 763 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/DocumentConnection.java diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java new file mode 100644 index 00000000000..149ef2a9818 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java @@ -0,0 +1,874 @@ +package org.jabref.gui.openoffice; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import org.jabref.architecture.AllowedToUseAwt; +import org.jabref.gui.DialogService; +import org.jabref.logic.JabRefException; +import org.jabref.logic.bibtex.comparator.FieldComparator; +import org.jabref.logic.bibtex.comparator.FieldComparatorStack; +import org.jabref.logic.l10n.Localization; +import org.jabref.logic.layout.Layout; +import org.jabref.logic.openoffice.CitationEntry; +import org.jabref.logic.openoffice.OOBibStyle; +import org.jabref.logic.openoffice.OOPreFormatter; +import org.jabref.logic.openoffice.OOUtil; +import org.jabref.logic.openoffice.UndefinedBibtexEntry; +import org.jabref.logic.openoffice.UndefinedParagraphFormatException; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.StandardField; + +import com.sun.star.awt.Point; +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.Property; +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.comp.helper.BootstrapException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XEnumeration; +import com.sun.star.container.XEnumerationAccess; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNamed; +import com.sun.star.document.XDocumentPropertiesSupplier; +import com.sun.star.document.XUndoManager; +import com.sun.star.document.XUndoManagerSupplier; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XController; +import com.sun.star.frame.XDesktop; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.XModel; +import com.sun.star.lang.DisposedException; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.Locale; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.text.XBookmarksSupplier; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XReferenceMarksSupplier; +import com.sun.star.text.XText; +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.XTextRangeCompare; +import com.sun.star.text.XTextSection; +import com.sun.star.text.XTextSectionsSupplier; +import com.sun.star.text.XTextViewCursor; +import com.sun.star.text.XTextViewCursorSupplier; +import com.sun.star.uno.Any; +import com.sun.star.uno.Type; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.util.InvalidStateException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Document-connection related variables. + */ +class DocumentConnection { + /** https://wiki.openoffice.org/wiki/Documentation/BASIC_Guide/ + * Structure_of_Text_Documents#Character_Properties + * "CharStyleName" is an OpenOffice Property name. + */ + private static final String CHAR_STYLE_NAME = "CharStyleName"; + private static final Logger LOGGER = + LoggerFactory.getLogger(DocumentConnection.class); + + + public XTextDocument mxDoc; + public XComponent xCurrentComponent; + public XMultiServiceFactory mxDocFactory; + public XText xText; + public XTextViewCursorSupplier xViewCursorSupplier; + public XPropertyContainer userProperties; + public XPropertySet propertySet; + + DocumentConnection( + XTextDocument mxDoc + ) { + this.mxDoc = mxDoc; + this.xCurrentComponent = unoQI(XComponent.class, mxDoc); + this.mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); + // unoQI(XDocumentIndexesSupplier.class, component); + + // get a reference to the body text of the document + this.xText = mxDoc.getText(); + + XModel mo = unoQI(XModel.class, this.xCurrentComponent); + XController co = mo.getCurrentController(); + this.xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); + + XDocumentPropertiesSupplier supp = + unoQI(XDocumentPropertiesSupplier.class, mxDoc); + this.userProperties = + supp.getDocumentProperties().getUserDefinedProperties(); + + this.propertySet = unoQI(XPropertySet.class, userProperties); + } + + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if available, + * otherwise null + */ + private static T + unoQI( + Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + + /** + * 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 void + enterUndoContext(String title) { + XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); + XUndoManager um = mxUndoManagerSupplier.getUndoManager(); + // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html + um.enterUndoContext(title); + } + + public void + leaveUndoContext() + throws InvalidStateException { + XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); + XUndoManager um = mxUndoManagerSupplier.getUndoManager(); + // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html + um.leaveUndoContext(); + } + + /* + * Disable screen refresh. + * + * Must be paired with unlockControllers() + * + * https://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XModel.html + * + * While there is at least one lock remaining, some + * notifications for display updates are not broadcasted. + */ + public void + lockControllers() { + XModel mo = unoQI(XModel.class, this.xCurrentComponent); + mo.lockControllers(); + } + + public void + unlockControllers() { + XModel mo = unoQI(XModel.class, this.xCurrentComponent); + mo.unlockControllers(); + } + + public boolean + hasControllersLocked() { + XModel mo = unoQI(XModel.class, this.xCurrentComponent); + return mo.hasControllersLocked(); + } + + /** + * @return True if we cannot reach the current document. + */ + public boolean + documentConnectionMissing() { + + boolean missing = false; + // These are set by DocumentConnection constructor. + if (null == this.mxDoc + || null == this.xCurrentComponent + || null == this.mxDocFactory + || null == this.xText + || null == this.xViewCursorSupplier + || null == this.userProperties + || null == this.propertySet) { + missing = true; + } + + // Attempt to check document is really available + if (!missing) { + try { + getReferenceMarks(); + } catch (NoDocumentException ex) { + missing = true; + } + } + + if (missing) { + // release it + this.mxDoc = null; + this.xCurrentComponent = null; + this.mxDocFactory = null; + this.xText = null; + this.xViewCursorSupplier = null; + this.userProperties = null; + this.propertySet = null; + } + return missing; + } + + /** + * @param doc The XTextDocument we want the title for. Null allowed. + * @return The title or Optional.empty() + */ + public static Optional + getDocumentTitle(XTextDocument doc) { + + if (doc == null) { + return Optional.empty(); + } + + try { + XFrame frame = doc.getCurrentController().getFrame(); + Object frameTitleObj = OOUtil.getProperty(frame, "Title"); + String frameTitleString = String.valueOf(frameTitleObj); + return Optional.of(frameTitleString); + } catch (UnknownPropertyException | WrappedTargetException e) { + LOGGER.warn("Could not get document title", e); + return Optional.empty(); + } + } + + /** + * Get the title of the connected document. + */ + public Optional + getDocumentTitle() { + return DocumentConnection.getDocumentTitle(this.mxDoc); + } + + public List + getCustomPropertyNames() { + assert (this.propertySet != null); + + XPropertySetInfo psi = (this.propertySet + .getPropertySetInfo()); + + List names = new ArrayList<>(); + for (Property p : psi.getProperties()) { + names.add(p.Name); + } + return names; + } + + /** + * @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 Optional + getCustomProperty(String property) + throws + UnknownPropertyException, + WrappedTargetException { + + assert (this.propertySet != null); + + XPropertySetInfo psi = (this.propertySet + .getPropertySetInfo()); + + if (psi.hasPropertyByName(property)) { + String v = + this.propertySet + .getPropertyValue(property) + .toString(); + return Optional.ofNullable(v); + } + return Optional.empty(); + } + + /** + * @param property Name of a custom document property in the + * current document. + * + * @param value The value to be stored. + */ + public void + setCustomProperty(String property, String value) + throws + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException { + + XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + + if (psi.hasPropertyByName(property)) { + this.userProperties.removeProperty(property); + } + + if (value != null) { + this.userProperties + .addProperty( + property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value)); + } + } + + /** + * @throws NoDocumentException If cannot get reference marks + * + * Note: also used by `documentConnectionMissing` to test if + * we have a working connection. + * + */ + public XNameAccess + getReferenceMarks() + throws NoDocumentException { + + XReferenceMarksSupplier supplier = + unoQI( + XReferenceMarksSupplier.class, + this.xCurrentComponent + ); + try { + return supplier.getReferenceMarks(); + } catch (DisposedException ex) { + throw new NoDocumentException("getReferenceMarks failed with" + ex); + } + } + + /** + * Provides access to bookmarks by name. + */ + public XNameAccess + getBookmarks() { + + XBookmarksSupplier supplier = + unoQI( + XBookmarksSupplier.class, + this.xCurrentComponent + ); + return supplier.getBookmarks(); + } + + /** + * @return An XNameAccess to find sections by name. + */ + public XNameAccess + getTextSections() + throws + IllegalArgumentException { + + XTextSectionsSupplier supplier = + unoQI( + XTextSectionsSupplier.class, + this.mxDoc + ); + return supplier.getTextSections(); + } + + /** + * Names of all reference marks. + * + * Empty list for nothing. + */ + public List + getReferenceMarkNames() + throws NoDocumentException { + + XNameAccess nameAccess = getReferenceMarks(); + String[] names = nameAccess.getElementNames(); + if (names == null) { + return new ArrayList<>(); + } + return Arrays.asList(names); + } + + /** + * Get the {@cod XTextContent} interface. + * + * @return null for null and for no-such-interface + */ + public static XTextContent + asTextContent(Object mark) { + if (mark == null) { + return null; + } + return unoQI(XTextContent.class, mark); + } + + /** + * @return null if name not found, or if the result does not + * support the XTextContent interface. + */ + public static XTextContent + nameAccessGetTextContentByNameOrNull(XNameAccess nameAccess, String name) + throws WrappedTargetException { + + if (!nameAccess.hasByName(name)) { + return null; + } + try { + Object referenceMark = nameAccess.getByName(name); + return asTextContent(referenceMark); + } catch (NoSuchElementException ex) { + LOGGER.warn(String.format( + "nameAccessGetTextContentByNameOrNull got NoSuchElementException" + + " for '%s'", name)); + return null; + } + } + + /** + * Create a text cursor for a textContent. + * + * @return null if mark is null, otherwise cursor. + * + */ + public static XTextCursor + getTextCursorOfTextContent(XTextContent mark) { + if (mark == null) { + return null; + } + XTextRange markAnchor = mark.getAnchor(); + return + markAnchor.getText() + .createTextCursorByRange(markAnchor); + } + + /** + * Remove the named reference mark. + * + * Removes both the text and the mark itself. + */ + public void + removeReferenceMark(String name) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException { + + XNameAccess xReferenceMarks = this.getReferenceMarks(); + + if (xReferenceMarks.hasByName(name)) { + XTextContent mark = + nameAccessGetTextContentByNameOrNull(xReferenceMarks, name); + if (mark == null) { + return; + } + this.xText.removeTextContent(mark); + } + } + + /** + * Get the cursor positioned by the user. + * + */ + public XTextViewCursor + getViewCursor() { + return this.xViewCursorSupplier.getViewCursor(); + } + + /** + * Get the XTextRange corresponding to the named bookmark. + * + * @param name The name of the bookmark to find. + * @return The XTextRange for the bookmark, or null. + */ + public XTextRange + getBookmarkRangeOrNull(String name) + throws + WrappedTargetException { + + XNameAccess nameAccess = this.getBookmarks(); + XTextContent textContent = + nameAccessGetTextContentByNameOrNull(nameAccess, name); + if (textContent == null) { + return null; + } + return textContent.getAnchor(); + } + + /** + * @return reference mark as XTextContent, null if not found. + */ + public XTextContent + getReferenceMarkAsTextContentOrNull(String name) + throws + NoDocumentException, + WrappedTargetException { + + XNameAccess nameAccess = this.getReferenceMarks(); + return nameAccessGetTextContentByNameOrNull(nameAccess, name); + } + + /** + * XTextRange for the named reference mark, null if not found. + */ + public XTextRange + getReferenceMarkRangeOrNull(String name) + throws + NoDocumentException, + WrappedTargetException { + + XTextContent textContent = + getReferenceMarkAsTextContentOrNull(name); + if (textContent == null) { + return null; + } + return textContent.getAnchor(); + } + + /** + * 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". + * + * Passed to this.mxDocFactory.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. + * + */ + private XNamed + insertNamedTextContent( + String service, + String name, + XTextRange range, + boolean absorb + ) + throws + CreationException { + + Object xObject; + try { + xObject = + this.mxDocFactory + .createInstance(service); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + + XNamed xNamed = unoQI(XNamed.class, xObject); + xNamed.setName(name); + + // get XTextContent interface + XTextContent xTextContent = unoQI(XTextContent.class, xObject); + range.getText().insertTextContent(range, xTextContent, absorb); + return xNamed; + } + + /** + * Insert a new reference mark at the provided cursor + * position. + * + * The text in the cursor range will be the text with gray + * background. + * + * 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 XNamed + insertReferenceMark( + String name, + XTextRange range, + boolean absorb + ) + throws + CreationException { + + return + insertNamedTextContent( + "com.sun.star.text.ReferenceMark", + name, + range, + absorb // was true + ); + } + + /** + * 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. + * + * 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 XNamed + insertBookmark( + String name, + XTextRange range, + boolean absorb) + throws + IllegalArgumentException, + CreationException { + + return + insertNamedTextContent( + "com.sun.star.text.Bookmark", + name, + range, + absorb // was true + ); + } + + /** + * 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. + * + * 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 XNamed + insertTextSection( + String name, + XTextRange range, + boolean absorb) + throws + IllegalArgumentException, + CreationException { + + return + insertNamedTextContent( + "com.sun.star.text.TextSection", + name, + range, + absorb // was false + ); + } + + /** + * Get an XTextSection by name. + */ + public XTextSection + getTextSectionByName(String name) + throws + NoSuchElementException, + WrappedTargetException { + + XTextSectionsSupplier supplier = + unoQI(XTextSectionsSupplier.class, + this.mxDoc); + + return ((XTextSection) + ((Any) supplier.getTextSections().getByName(name)) + .getObject()); + } + + /** + * If original is in a footnote, return a range containing + * the corresponding footnote marker. + * + * Returns null if not in a footnote. + */ + static XTextRange + getFootnoteMarkRangeOrNull(XTextRange original) { + // If we are inside a footnote: + if (unoQI(XFootnote.class, original.getText()) != null) { + // Find the linking footnote marker: + XFootnote footer = unoQI(XFootnote.class, original.getText()); + // The footnote's anchor gives the correct position in the text: + return footer.getAnchor(); + } + return null; + } + + /** + * Apply a character style to a range of text selected by a + * cursor. + * + * @param position The range to apply to. + * @param charStyle Name of the character style as known by Openoffice. + */ + public static void + setCharStyle( + XTextCursor position, // TODO: maybe an XTextRange is sufficient here + String charStyle + ) + throws UndefinedCharacterFormatException { + + XPropertySet xCursorProps = unoQI(XPropertySet.class, position); + + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + throw new UndefinedCharacterFormatException(charStyle); + // Setting the character format failed, so we throw an exception that + // will result in an error message for the user: + } + } + + /** + * Apply direct character format "Italic" to a range of text. + * + * Ref: https://www.openoffice.org/api/docs/common/ref/com/sun/star/style/CharacterProperties.html + */ + public static void + setCharFormatItalic(XTextRange textRange) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + XPropertySet xcp = unoQI(XPropertySet.class, textRange); + xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); + } + + /** + * Apply direct character format "Bold" to a range of text. + */ + public static void + setCharFormatBold(XTextRange textRange) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + XPropertySet xcp = unoQI(XPropertySet.class, textRange); + xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD); + } + + /** + * Set language to [None] + * + * Note: "zxx" is an https://en.wikipedia.org/wiki/ISO_639 code for + * "No linguistic information at all" + */ + public static void + setCharLocaleNone(XTextRange textRange) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + XPropertySet xcp = unoQI(XPropertySet.class, textRange); + xcp.setPropertyValue("CharLocale", new Locale("zxx", "", "")); + } + + /** + * Test if two XTextRange values are comparable (i.e. they share + * the same getText()). + */ + public static boolean + comparable( + XTextRange a, + XTextRange b + ) { + return a.getText() == b.getText(); + } + + /** + * @return follows OO conventions, the opposite of java conventions: + * 1 if (a < b), 0 if same start, (-1) if (b < a) + */ + private static int + ooCompareRegionStarts(XTextRange a, XTextRange b) { + if (!comparable(a, b)) { + throw new RuntimeException("ooCompareRegionStarts: got incomparable regions"); + } + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + a.getText()); + return compare.compareRegionStarts(a, b); + } + + /** + * @return follows OO conventions, the opposite of java conventions: + * 1 if (a < b), 0 if same start, (-1) if (b < a) + */ + private static int + ooCompareRegionEnds(XTextRange a, XTextRange b) { + if (!comparable(a, b)) { + throw new RuntimeException("ooCompareRegionEnds: got incomparable regions"); + } + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + a.getText()); + return compare.compareRegionEnds(a, b); + } + + /** + * @return follows java conventions + * + * 1 if (a > b); (-1) if (a < b) + */ + public static int + javaCompareRegionStarts(XTextRange a, XTextRange b) { + return (-1) * ooCompareRegionStarts(a, b); + } + + /** + * @return follows java conventions + * + * 1 if (a > b); (-1) if (a < b) + */ + public static int + javaCompareRegionEnds(XTextRange a, XTextRange b) { + return (-1) * ooCompareRegionEnds(a, b); + } +} // end DocumentConnection diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9a26fa4c8da..2bca64d22ed 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -23,6 +23,7 @@ import org.jabref.architecture.AllowedToUseAwt; import org.jabref.gui.DialogService; +import org.jabref.gui.openoffice.DocumentConnection; import org.jabref.logic.JabRefException; import org.jabref.logic.bibtex.comparator.FieldComparator; import org.jabref.logic.bibtex.comparator.FieldComparatorStack; @@ -63,7 +64,6 @@ import com.sun.star.frame.XFrame; import com.sun.star.frame.XModel; import com.sun.star.lang.DisposedException; -import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XComponent; @@ -112,7 +112,7 @@ class OOBibBase { REFERENCE_MARK_USE_INVISIBLE_BRACKETS = true; // !debug; private static final String - REFERENCE_MARK_LEFT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<"; + REFERENCE_MARK_LEFT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<"; private static final String REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; @@ -137,733 +137,6 @@ class OOBibBase { private final Comparator entryComparator; private final Comparator yearAuthorTitleComparator; - /** - * Document-connection related variables. - */ - private static class DocumentConnection { - /** https://wiki.openoffice.org/wiki/Documentation/BASIC_Guide/ - * Structure_of_Text_Documents#Character_Properties - * "CharStyleName" is an OpenOffice Property name. - */ - private static final String CHAR_STYLE_NAME = "CharStyleName"; - private static final Logger LOGGER = - LoggerFactory.getLogger(OOBibBase.DocumentConnection.class); - - - public XTextDocument mxDoc; - public XComponent xCurrentComponent; - public XMultiServiceFactory mxDocFactory; - public XText xText; - public XTextViewCursorSupplier xViewCursorSupplier; - public XPropertyContainer userProperties; - public XPropertySet propertySet; - - DocumentConnection( - XTextDocument mxDoc - ) { - this.mxDoc = mxDoc; - this.xCurrentComponent = unoQI(XComponent.class, mxDoc); - this.mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); - // unoQI(XDocumentIndexesSupplier.class, component); - - // get a reference to the body text of the document - this.xText = mxDoc.getText(); - - XModel mo = unoQI(XModel.class, this.xCurrentComponent); - XController co = mo.getCurrentController(); - this.xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); - - XDocumentPropertiesSupplier supp = - unoQI(XDocumentPropertiesSupplier.class, mxDoc); - this.userProperties = - supp.getDocumentProperties().getUserDefinedProperties(); - - this.propertySet = unoQI(XPropertySet.class, userProperties); - } - - /** - * Each call to enterUndoContext must be paired by a call to - * leaveUndoContext, otherwise, the document's undo stack is - * left in an inconsistent state. - */ - void enterUndoContext(String title) { - XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); - XUndoManager um = mxUndoManagerSupplier.getUndoManager(); - // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html - um.enterUndoContext(title); - } - - void leaveUndoContext() - throws InvalidStateException { - XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); - XUndoManager um = mxUndoManagerSupplier.getUndoManager(); - // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html - um.leaveUndoContext(); - } - - /* - * Disable screen refresh. - * - * Must be paired with unlockControllers() - * - * https://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XModel.html - * - * While there is at least one lock remaining, some - * notifications for display updates are not broadcasted. - */ - void lockControllers() { - XModel mo = unoQI(XModel.class, this.xCurrentComponent); - mo.lockControllers(); - } - - void unlockControllers() { - XModel mo = unoQI(XModel.class, this.xCurrentComponent); - mo.unlockControllers(); - } - - boolean hasControllersLocked() { - XModel mo = unoQI(XModel.class, this.xCurrentComponent); - return mo.hasControllersLocked(); - } - - /** - * @return True if we cannot reach the current document. - */ - public boolean - documentConnectionMissing() { - - boolean missing = false; - // These are set by DocumentConnection constructor. - if (null == this.mxDoc - || null == this.xCurrentComponent - || null == this.mxDocFactory - || null == this.xText - || null == this.xViewCursorSupplier - || null == this.userProperties - || null == this.propertySet) { - missing = true; - } - - // Attempt to check document is really available - if (!missing) { - try { - getReferenceMarks(); - } catch (NoDocumentException ex) { - missing = true; - } - } - - if (missing) { - // release it - this.mxDoc = null; - this.xCurrentComponent = null; - this.mxDocFactory = null; - this.xText = null; - this.xViewCursorSupplier = null; - this.userProperties = null; - this.propertySet = null; - } - return missing; - } - - /** - * Get the title of the connected document. - */ - public Optional - getDocumentTitle() { - return OOBibBase.getDocumentTitle(this.mxDoc); - } - - List - getCustomPropertyNames() { - assert (this.propertySet != null); - - XPropertySetInfo psi = (this.propertySet - .getPropertySetInfo()); - - List names = new ArrayList<>(); - for (Property p : psi.getProperties()) { - names.add(p.Name); - } - return names; - } - - /** - * @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. - * - */ - private Optional - getCustomProperty(String property) - throws - UnknownPropertyException, - WrappedTargetException { - - assert (this.propertySet != null); - - XPropertySetInfo psi = (this.propertySet - .getPropertySetInfo()); - - if (psi.hasPropertyByName(property)) { - String v = - this.propertySet - .getPropertyValue(property) - .toString(); - return Optional.ofNullable(v); - } - return Optional.empty(); - } - - /** - * @param property Name of a custom document property in the - * current document. - * - * @param value The value to be stored. - */ - private void - setCustomProperty(String property, String value) - throws - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException { - - XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); - - if (psi.hasPropertyByName(property)) { - this.userProperties.removeProperty(property); - } - - if (value != null) { - this.userProperties - .addProperty( - property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value)); - } - } - - /** - * @throws NoDocumentException If cannot get reference marks - * - * Note: also used by `documentConnectionMissing` to test if - * we have a working connection. - * - */ - private XNameAccess - getReferenceMarks() - throws NoDocumentException { - - XReferenceMarksSupplier supplier = - unoQI( - XReferenceMarksSupplier.class, - this.xCurrentComponent - ); - try { - return supplier.getReferenceMarks(); - } catch (DisposedException ex) { - throw new NoDocumentException("getReferenceMarks failed with" + ex); - } - } - - /** - * Provides access to bookmarks by name. - */ - private XNameAccess - getBookmarks() { - - XBookmarksSupplier supplier = - unoQI( - XBookmarksSupplier.class, - this.xCurrentComponent - ); - return supplier.getBookmarks(); - } - - /** - * @return An XNameAccess to find sections by name. - */ - private XNameAccess - getTextSections() - throws - IllegalArgumentException { - - XTextSectionsSupplier supplier = - unoQI( - XTextSectionsSupplier.class, - this.mxDoc - ); - return supplier.getTextSections(); - } - - /** - * Names of all reference marks. - * - * Empty list for nothing. - */ - List - getReferenceMarkNames() - throws NoDocumentException { - - XNameAccess nameAccess = getReferenceMarks(); - String[] names = nameAccess.getElementNames(); - if (names == null) { - return new ArrayList<>(); - } - return Arrays.asList(names); - } - - static XTextContent - asTextContent(Object mark) { - if (mark == null) { - return null; - } - return unoQI(XTextContent.class, mark); - } - - /** - * @return null if name not found, or if the result does not - * support the XTextContent interface. - */ - static XTextContent - nameAccessGetTextContentByNameOrNull(XNameAccess nameAccess, String name) - throws WrappedTargetException { - - if (!nameAccess.hasByName(name)) { - return null; - } - try { - Object referenceMark = nameAccess.getByName(name); - return asTextContent(referenceMark); - } catch (NoSuchElementException ex) { - LOGGER.warn(String.format( - "nameAccessGetTextContentByNameOrNull got NoSuchElementException" - + " for '%s'", name)); - return null; - } - } - - /** - * Create a text cursor for a textContent. - * - * @return null if mark is null, otherwise cursor. - * - */ - static XTextCursor - getTextCursorOfTextContent(XTextContent mark) { - if (mark == null) { - return null; - } - XTextRange markAnchor = mark.getAnchor(); - return - markAnchor.getText() - .createTextCursorByRange(markAnchor); - } - - /** - * Remove the named reference mark. - * - * Removes both the text and the mark itself. - */ - public void - removeReferenceMark(String name) - throws - WrappedTargetException, - NoDocumentException, - NoSuchElementException { - - XNameAccess xReferenceMarks = this.getReferenceMarks(); - - if (xReferenceMarks.hasByName(name)) { - XTextContent mark = - nameAccessGetTextContentByNameOrNull(xReferenceMarks, name); - if (mark == null) { - return; - } - this.xText.removeTextContent(mark); - } - } - - /** - * Get the cursor positioned by the user. - * - */ - public XTextViewCursor - getViewCursor() { - return this.xViewCursorSupplier.getViewCursor(); - } - - /** - * Get the XTextRange corresponding to the named bookmark. - * - * @param name The name of the bookmark to find. - * @return The XTextRange for the bookmark, or null. - */ - public XTextRange - getBookmarkRangeOrNull(String name) - throws - WrappedTargetException { - - XNameAccess nameAccess = this.getBookmarks(); - XTextContent textContent = - nameAccessGetTextContentByNameOrNull(nameAccess, name); - if (textContent == null) { - return null; - } - return textContent.getAnchor(); - } - - public XTextContent - getReferenceMarkAsTextContentOrNull(String name) - throws - NoDocumentException, - WrappedTargetException { - - XNameAccess nameAccess = this.getReferenceMarks(); - return nameAccessGetTextContentByNameOrNull(nameAccess, name); - } - - public XTextRange - getReferenceMarkRangeOrNull(String name) - throws - NoDocumentException, - WrappedTargetException { - - XTextContent textContent = - getReferenceMarkAsTextContentOrNull(name); - if (textContent == null) { - return null; - } - return textContent.getAnchor(); - } - - /** - * 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". - * - * Passed to this.mxDocFactory.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. - * - */ - private XNamed - insertNamedTextContent( - String service, - String name, - XTextRange range, - boolean absorb - ) - throws - CreationException { - - Object xObject; - try { - xObject = - this.mxDocFactory - .createInstance(service); - } catch (Exception e) { - throw new CreationException(e.getMessage()); - } - - XNamed xNamed = unoQI(XNamed.class, xObject); - xNamed.setName(name); - - // get XTextContent interface - XTextContent xTextContent = unoQI(XTextContent.class, xObject); - range.getText().insertTextContent(range, xTextContent, absorb); - return xNamed; - } - - /** - * Insert a new reference mark at the provided cursor - * position. - * - * The text in the cursor range will be the text with gray - * background. - * - * 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 XNamed - insertReferenceMark( - String name, - XTextRange range, - boolean absorb - ) - throws - CreationException { - - return - insertNamedTextContent( - "com.sun.star.text.ReferenceMark", - name, - range, - absorb // was true - ); - } - - /** - * 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. - * - * 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 XNamed - insertBookmark( - String name, - XTextRange range, - boolean absorb) - throws - IllegalArgumentException, - CreationException { - - return - insertNamedTextContent( - "com.sun.star.text.Bookmark", - name, - range, - absorb // was true - ); - } - - /** - * 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. - * - * 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. - */ - private XNamed - insertTextSection( - String name, - XTextRange range, - boolean absorb) - throws - IllegalArgumentException, - CreationException { - - return - insertNamedTextContent( - "com.sun.star.text.TextSection", - name, - range, - absorb // was false - ); - } - - /** - * Get an XTextSection by name. - */ - public XTextSection - getTextSectionByName(String name) - throws - NoSuchElementException, - WrappedTargetException { - - XTextSectionsSupplier supplier = - unoQI(XTextSectionsSupplier.class, - this.mxDoc); - - return ((XTextSection) - ((Any) supplier.getTextSections().getByName(name)) - .getObject()); - } - - /** - * If original is in a footnote, return a range containing - * the corresponding footnote marker. - * - * Returns null if not in a footnote. - */ - static XTextRange - getFootnoteMarkRangeOrNull(XTextRange original) { - // If we are inside a footnote: - if (unoQI(XFootnote.class, original.getText()) != null) { - // Find the linking footnote marker: - XFootnote footer = unoQI(XFootnote.class, original.getText()); - // The footnote's anchor gives the correct position in the text: - return footer.getAnchor(); - } - return null; - } - - /** - * Apply a character style to a range of text selected by a - * cursor. - * - * @param position The range to apply to. - * @param charStyle Name of the character style as known by Openoffice. - */ - private static void - setCharStyle( - XTextCursor position, - String charStyle - ) - throws UndefinedCharacterFormatException { - - XPropertySet xCursorProps = unoQI(XPropertySet.class, position); - - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - throw new UndefinedCharacterFormatException(charStyle); - // Setting the character format failed, so we throw an exception that - // will result in an error message for the user: - } - } - - /** - * Apply direct character format "Italic" to a range of text. - * - * Ref: https://www.openoffice.org/api/docs/common/ref/com/sun/star/style/CharacterProperties.html - */ - private static void - setCharFormatItalic(XTextRange textRange) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - XPropertySet xcp = unoQI(XPropertySet.class, textRange); - xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); - } - - /* - * Apply direct character format "Bold" to a range of text. - */ - /* unused: - private static void - setCharFormatBold(XTextRange textRange) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - XPropertySet xcp = unoQI(XPropertySet.class, textRange); - xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD); - } - */ - - /** - * Set language to [None] - * - * Note: "zxx" is an https://en.wikipedia.org/wiki/ISO_639 code for - * "No linguistic information at all" - */ - private static void - setCharLocaleNone(XTextRange textRange) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - XPropertySet xcp = unoQI(XPropertySet.class, textRange); - xcp.setPropertyValue("CharLocale", new Locale("zxx", "", "")); - } - - private static boolean - comparable( - XTextRange a, - XTextRange b - ) { - return a.getText() == b.getText(); - } - - /** - * @return follows OO conventions, the opposite of java conventions: - * 1 if (a < b), 0 if same start, (-1) if (b < a) - */ - private static int - ooCompareRegionStarts(XTextRange a, XTextRange b) { - if (!comparable(a, b)) { - throw new RuntimeException("ooCompareRegionStarts: got incomparable regions"); - } - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - a.getText()); - return compare.compareRegionStarts(a, b); - } - - /** - * @return follows OO conventions, the opposite of java conventions: - * 1 if (a < b), 0 if same start, (-1) if (b < a) - */ - private static int - ooCompareRegionEnds(XTextRange a, XTextRange b) { - if (!comparable(a, b)) { - throw new RuntimeException("ooCompareRegionEnds: got incomparable regions"); - } - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - a.getText()); - return compare.compareRegionEnds(a, b); - } - - /** - * @return follows java conventions - * - * 1 if (a > b); (-1) if (a < b) - */ - private static int - javaCompareRegionStarts(XTextRange a, XTextRange b) { - return (-1) * ooCompareRegionStarts(a, b); - } - - /** - * @return follows java conventions - */ - private static int - javaCompareRegionEnds(XTextRange a, XTextRange b) { - return (-1) * ooCompareRegionEnds(a, b); - } - } // end DocumentConnection /** * Created when connected to a document. @@ -967,28 +240,6 @@ boolean hasControllersLocked() { return result; } - /** - * @param doc The XTextDocument we want the title for. Null allowed. - * @return The title or Optional.empty() - */ - private static Optional - getDocumentTitle(XTextDocument doc) { - - if (doc == null) { - return Optional.empty(); - } - - try { - XFrame frame = doc.getCurrentController().getFrame(); - Object frameTitleObj = OOUtil.getProperty(frame, "Title"); - String frameTitleString = String.valueOf(frameTitleObj); - return Optional.of(frameTitleString); - } catch (UnknownPropertyException | WrappedTargetException e) { - LOGGER.warn("Could not get document title", e); - return Optional.empty(); - } - } - /** * Run a dialog allowing the user to choose among the documents in `list`. * @@ -1008,7 +259,7 @@ class DocumentTitleViewModel { public DocumentTitleViewModel(XTextDocument xTextDocument) { this.xTextDocument = xTextDocument; - this.description = OOBibBase.getDocumentTitle(xTextDocument).orElse(""); + this.description = DocumentConnection.getDocumentTitle(xTextDocument).orElse(""); } public XTextDocument getXtextDocument() { @@ -3050,17 +2301,19 @@ static class CitationMarkersWithUniqueLetters { * between two reference marks. But we do not need that now. */ private static XTextCursor - safeInsertSpacesBetweenReferencMarks(XTextRange position, int n) { + safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { // Start with an empty cursor at position.getStart(); XText text = position.getText(); XTextCursor cursor = text.createTextCursorByRange(position.getStart()); - text.insertString(cursor,"\r\r",false); // para, para - cursor.goLeft((short) 1,false); // left - text.insertString(cursor," ".repeat(n),false); // space(n) - cursor.goRight((short) 1,true); cursor.setString(""); // right-delete - cursor.goLeft((short) n,false); // left(n) - cursor.goLeft((short) 1,true); cursor.setString(""); // left-delete - cursor.goRight((short) n,true); + text.insertString(cursor, "\r\r", false); // para, para + cursor.goLeft((short) 1, false); // left + text.insertString(cursor, " ".repeat(n), false); // space(n) + cursor.goRight((short) 1, true); + cursor.setString(""); // right-delete + cursor.goLeft((short) n, false); // left(n) + cursor.goLeft((short) 1, true); + cursor.setString(""); // left-delete + cursor.goRight((short) n, true); return cursor; } @@ -3111,8 +2364,6 @@ static class CitationMarkersWithUniqueLetters { * @param withoutBrackets Force empty reference mark (no brackets). * For use with INVISIBLE_CIT. * - * @return Nothing (was: XTextCursor for the text to be inserted) - * */ private static void createReferenceMarkForCitationGroup( @@ -3130,7 +2381,7 @@ static class CitationMarkersWithUniqueLetters { // The cursor we received: we push it before us. position.collapseToEnd(); - XTextCursor cursor = safeInsertSpacesBetweenReferencMarks(position.getEnd(), 2); + XTextCursor cursor = safeInsertSpacesBetweenReferenceMarks(position.getEnd(), 2); // cursors before the first and after the last space XTextCursor cursorBefore = From 960450e265e1a7ad62543bcc167995d8dbe871cb Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 15 Mar 2021 21:35:15 +0100 Subject: [PATCH 0489/1068] split out RangeForOverlapCheck, RangeKeyedMapList --- .../gui/openoffice/DocumentConnection.java | 110 +++++---- .../org/jabref/gui/openoffice/OOBibBase.java | 230 ++++++++---------- .../gui/openoffice/RangeForOverlapCheck.java | 38 +++ .../jabref/gui/openoffice/RangeKeyedMap.java | 71 ++++++ .../gui/openoffice/RangeKeyedMapList.java | 117 +++++++++ src/main/resources/l10n/JabRef_en.properties | 6 +- 6 files changed, 390 insertions(+), 182 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java create mode 100644 src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java create mode 100644 src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java index 149ef2a9818..b0d763fee37 100644 --- a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java @@ -1,44 +1,44 @@ package org.jabref.gui.openoffice; -import java.io.IOException; -import java.nio.file.Path; +// import java.io.IOException; +// import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; +// import java.util.Collections; +// import java.util.Comparator; +// import java.util.HashMap; +// import java.util.HashSet; +// import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; -import java.util.Objects; +// import java.util.Map; +// import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.gui.DialogService; -import org.jabref.logic.JabRefException; -import org.jabref.logic.bibtex.comparator.FieldComparator; -import org.jabref.logic.bibtex.comparator.FieldComparatorStack; -import org.jabref.logic.l10n.Localization; -import org.jabref.logic.layout.Layout; -import org.jabref.logic.openoffice.CitationEntry; -import org.jabref.logic.openoffice.OOBibStyle; -import org.jabref.logic.openoffice.OOPreFormatter; +// import java.util.Set; +// import java.util.SortedMap; +// import java.util.TreeMap; +// import java.util.TreeSet; +// import java.util.regex.Matcher; +// import java.util.regex.Pattern; +// import java.util.stream.Collectors; + +// import org.jabref.architecture.AllowedToUseAwt; +// import org.jabref.gui.DialogService; +// import org.jabref.logic.JabRefException; +// import org.jabref.logic.bibtex.comparator.FieldComparator; +// import org.jabref.logic.bibtex.comparator.FieldComparatorStack; +// import org.jabref.logic.l10n.Localization; +// import org.jabref.logic.layout.Layout; +// import org.jabref.logic.openoffice.CitationEntry; +// import org.jabref.logic.openoffice.OOBibStyle; +// import org.jabref.logic.openoffice.OOPreFormatter; import org.jabref.logic.openoffice.OOUtil; -import org.jabref.logic.openoffice.UndefinedBibtexEntry; -import org.jabref.logic.openoffice.UndefinedParagraphFormatException; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.StandardField; +// import org.jabref.logic.openoffice.UndefinedBibtexEntry; +// import org.jabref.logic.openoffice.UndefinedParagraphFormatException; +// import org.jabref.model.database.BibDatabase; +// import org.jabref.model.entry.BibEntry; +// import org.jabref.model.entry.field.StandardField; -import com.sun.star.awt.Point; +// import com.sun.star.awt.Point; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.Property; @@ -48,18 +48,18 @@ import com.sun.star.beans.XPropertyContainer; import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; -import com.sun.star.comp.helper.BootstrapException; +// import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XEnumeration; -import com.sun.star.container.XEnumerationAccess; +// import com.sun.star.container.XEnumeration; +// import com.sun.star.container.XEnumerationAccess; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; import com.sun.star.document.XDocumentPropertiesSupplier; import com.sun.star.document.XUndoManager; import com.sun.star.document.XUndoManagerSupplier; -import com.sun.star.frame.XComponentLoader; +// import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XController; -import com.sun.star.frame.XDesktop; +// import com.sun.star.frame.XDesktop; import com.sun.star.frame.XFrame; import com.sun.star.frame.XModel; import com.sun.star.lang.DisposedException; @@ -67,7 +67,7 @@ import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XComponent; -import com.sun.star.lang.XMultiComponentFactory; +// import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XFootnote; @@ -85,7 +85,7 @@ import com.sun.star.uno.Any; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; +// import com.sun.star.uno.XComponentContext; import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -728,7 +728,7 @@ class DocumentConnection { * * Returns null if not in a footnote. */ - static XTextRange + public static XTextRange getFootnoteMarkRangeOrNull(XTextRange original) { // If we are inside a footnote: if (unoQI(XFootnote.class, original.getText()) != null) { @@ -817,20 +817,42 @@ class DocumentConnection { * the same getText()). */ public static boolean - comparable( + comparableRanges( XTextRange a, XTextRange b ) { return a.getText() == b.getText(); } + /** + * Test if two XTextRange values are equal. + */ + public static boolean + equalRanges( + XTextRange a, + XTextRange b + ) { + if (!comparableRanges(a,b)) { + return false; + } + final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, + a.getText()); + if (compare.compareRegionStarts(a, b) != 0) { + return false; + } + if (compare.compareRegionEnds(a, b) != 0) { + return false; + } + return true; + } + /** * @return follows OO conventions, the opposite of java conventions: * 1 if (a < b), 0 if same start, (-1) if (b < a) */ private static int ooCompareRegionStarts(XTextRange a, XTextRange b) { - if (!comparable(a, b)) { + if (!comparableRanges(a, b)) { throw new RuntimeException("ooCompareRegionStarts: got incomparable regions"); } final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, @@ -844,7 +866,7 @@ class DocumentConnection { */ private static int ooCompareRegionEnds(XTextRange a, XTextRange b) { - if (!comparable(a, b)) { + if (!comparableRanges(a, b)) { throw new RuntimeException("ooCompareRegionEnds: got incomparable regions"); } final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2bca64d22ed..2764b6cff98 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -20,10 +20,12 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.function.Function; +import java.util.function.Predicate; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.gui.DialogService; -import org.jabref.gui.openoffice.DocumentConnection; import org.jabref.logic.JabRefException; import org.jabref.logic.bibtex.comparator.FieldComparator; import org.jabref.logic.bibtex.comparator.FieldComparatorStack; @@ -785,30 +787,6 @@ public CitationGroups(DocumentConnection documentConnection) return documentConnection.getReferenceMarkRangeOrNull(names[i]); } - class RangeForOverlapCheck { - final static int REFERENCE_MARK_KIND = 0; - final static int FOOTNOTE_MARK_KIND = 1; - - XTextRange range; - int i; - int kind; - String description; - - RangeForOverlapCheck(XTextRange range, int i, int kind, String description) { - this.range = range; - this.i = i; - this.kind = kind; - this.description = description; - } - - String format() { - return description; - // String[] prefixes = { "", "FootnoteMark for " } ; - // return prefixes[kind] + names[ this.i ]; - } - - } // class X - /** * Assumes a.getText() == b.getText(), and both belong to documentConnection.xText * @@ -823,6 +801,7 @@ String format() { * @throws RuntimeException if a and b are not comparable * */ + /* public int javaCompareRegionStarts(RangeForOverlapCheck a, RangeForOverlapCheck b) { @@ -858,10 +837,11 @@ String format() { ); } } - + */ /** * */ + /* public int javaCompareRegionEndToStart(RangeForOverlapCheck a, RangeForOverlapCheck b) { @@ -891,6 +871,7 @@ String format() { ); } } + */ /** * @return A RangeForOverlapCheck for each citation group. @@ -928,31 +909,25 @@ String format() { throws NoDocumentException, WrappedTargetException { + // Avoid inserting the same mark twice. - List seen = new ArrayList<>(); - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - documentConnection.xText); + // Could use RangeSet if we had that. + RangeKeyedMap seen = new RangeKeyedMap<>(); List xs = new ArrayList<>(); + for (int i = 0; i < names.length; i++) { XTextRange r = this.getReferenceMarkRangeOrNull(documentConnection, i); + XTextRange footnoteMarkRange = DocumentConnection.getFootnoteMarkRangeOrNull(r); if (footnoteMarkRange != null) { // Problem: quadratic complexity. Each new footnoteMarkRange // is compared to all we have seen before. - boolean seenContains = false; - for (XTextRange s : seen) { - if (s.getText() == footnoteMarkRange.getText() && - compare.compareRegionStarts(s, footnoteMarkRange) == 0 && - compare.compareRegionEnds(s, footnoteMarkRange) == 0) { - seenContains = true; - break; - } - } + boolean seenContains = seen.containsKey( footnoteMarkRange ); if (!seenContains) { - seen.add(footnoteMarkRange); + seen.put(footnoteMarkRange, true); xs.add(new RangeForOverlapCheck( footnoteMarkRange, i, // index of citation group @@ -965,88 +940,69 @@ String format() { return xs; } - private Map> - partitionByGetText(List xs) { - Map> xxs = new HashMap<>(); - for (RangeForOverlapCheck x : xs) { - XTextRange xr = x.range; - XText t = xr.getText(); - if (xxs.containsKey(t)) { - xxs.get(t).add(x); - } else { - xxs.put(t, new ArrayList<>(List.of(x))); - } - } - return xxs; - } + } // class citationGroups - private List - sortPartitionByRegionStart(List xs) { - return - xs.stream() - .sorted(this::javaCompareRegionStarts) - .collect(Collectors.toList()); - } - private void - checkSortedPartitionForOverlap(boolean requireSeparation, - List oxs) - throws JabRefException { - for (int i = 0; (i + 1) < oxs.size(); i++) { - RangeForOverlapCheck a = oxs.get(i); - RangeForOverlapCheck b = oxs.get(i + 1); - int cmp = javaCompareRegionEndToStart(a, b); - if (cmp > 0) { - // found overlap - throw new JabRefException( - "Range overlap found", - Localization.lang( - "Ranges of '%0' and '%1' overlap", a.format(), b.format()) - ); - } - if (requireSeparation && cmp == 0) { - throw new JabRefException( - "Ranges with no gap found", - Localization.lang( - "Ranges of '%0' and '%1' are not separated", - a.format(), b.format()) - ); - } - } + + /** + * @param requireSeparation Report range pairs that only share a boundary. + * @param atMost Limit number of overlaps reported (0 for no limit) + */ + public void + checkRangeOverlaps( + CitationGroups cgs, + DocumentConnection documentConnection, + boolean requireSeparation, + int atMost + ) + throws + NoDocumentException, + WrappedTargetException, + JabRefException { + + final boolean debugPartitions = false; + + List xs = cgs.citationRanges(documentConnection); + xs.addAll(cgs.footnoteMarkRanges(documentConnection)); + + RangeKeyedMapList xall = new RangeKeyedMapList<>(); + for (RangeForOverlapCheck x : xs) { + XTextRange key = x.range; + xall.add(key,x); } - public void - checkRangeOverlaps(DocumentConnection documentConnection, - boolean requireSeparation) - throws - NoDocumentException, - WrappedTargetException, - JabRefException { - - final boolean debugPartitions = false; - - List xs = citationRanges(documentConnection); - xs.addAll(footnoteMarkRanges(documentConnection)); - - // We can only compare ranges with equal .getText(), - // so partition the list. - Map> xxs = partitionByGetText(xs); - // Sort xs by x.getText() and x.getStart() - // Then, within each getText() value, we need x[i].getEnd() <= x[i+1].getStart() - for (List partition : xxs.values()) { - List oxs = - sortPartitionByRegionStart(partition); - - if (debugPartitions) { - System.out.println("partition"); - for (RangeForOverlapCheck r : oxs) { - System.out.println(" " + r.format()); - } + List.RangeOverlap> ovs = + xall.findOverlappingRanges(atMost, requireSeparation); + + //checkSortedPartitionForOverlap(requireSeparation, oxs); + if (ovs.size() > 0) { + String msg = ""; + for (RangeKeyedMapList.RangeOverlap e : ovs) { + String l = + (": " + + (e.vs.stream() + .map(v -> String.format("'%s'", v.format())) + .collect(Collectors.joining(", "))) + + "\n"); + + switch (e.kind) { + case EQUAL_RANGE: + msg = msg + Localization.lang("Found identical ranges") + l; + break; + case OVERLAP: + msg = msg + Localization.lang("Found overlapping ranges") + l; + break; + case TOUCH: + msg = msg + Localization.lang("Found touching ranges") + l; + break; } - checkSortedPartitionForOverlap(requireSeparation, oxs); } + throw new JabRefException( + "Found overlapping or touching ranges", + msg + ); } - } // class citationGroups + } /** * GUI: Get a list of CitationEntry objects corresponding to citations @@ -2390,7 +2346,7 @@ static class CitationMarkersWithUniqueLetters { cursor.getText().createTextCursorByRange(cursor.getEnd()); cursor.collapseToStart(); - cursor.goRight( (short) 1, false ); + cursor.goRight((short) 1, false); // now we are between two spaces final String left = REFERENCE_MARK_LEFT_BRACKET; @@ -2399,7 +2355,7 @@ static class CitationMarkersWithUniqueLetters { final short rightLength = (short) right.length(); String bracketedContent = (withoutBrackets ? "" - : left+right); + : left + right); cursor.getText().insertString( cursor, @@ -2412,9 +2368,11 @@ static class CitationMarkersWithUniqueLetters { true // absorb ); - cursorBefore.goRight((short) 1, true); cursorBefore.setString(""); - if ( !insertSpaceAfter ) { - cursorAfter.goLeft((short) 1, true); cursorAfter.setString(""); + cursorBefore.goRight((short) 1, true); + cursorBefore.setString(""); + if (!insertSpaceAfter) { + cursorAfter.goLeft((short) 1, true); + cursorAfter.setString(""); } } @@ -2466,14 +2424,14 @@ static class CitationMarkersWithUniqueLetters { XTextCursor alpha = full.getText().createTextCursorByRange(full); alpha.collapseToStart(); - XTextCursor beta = full.getText().createTextCursorByRange(full); + XTextCursor beta = full.getText().createTextCursorByRange(full); beta.collapseToStart(); beta.goRight(leftLength, false); XTextCursor omega = full.getText().createTextCursorByRange(full); omega.collapseToEnd(); - if (!fullText.startsWith( left )) { + if (!fullText.startsWith(left)) { throw new RuntimeException( String.format( "cleanFillCursorForCitationGroup:" @@ -2482,7 +2440,7 @@ static class CitationMarkersWithUniqueLetters { )); } - if (!fullText.endsWith( right )) { + if (!fullText.endsWith(right)) { throw new RuntimeException( String.format( "cleanFillCursorForCitationGroup:" @@ -2492,7 +2450,7 @@ static class CitationMarkersWithUniqueLetters { } final int contentLength = (fullTextLength - (leftLength + rightLength)); - if ( contentLength < 0) { + if (contentLength < 0) { throw new RuntimeException( String.format( "cleanFillCursorForCitationGroup: length(%s) < 0", @@ -2502,7 +2460,7 @@ static class CitationMarkersWithUniqueLetters { boolean removeRight = ( // have at least 1 character content - (contentLength >= 1) + (contentLength >= 1) || ((contentLength == 0) && removeBracketsFromEmpty) || alwaysRemoveBrackets ); @@ -2514,11 +2472,13 @@ static class CitationMarkersWithUniqueLetters { ); if (removeRight) { - omega.goLeft((short) rightLength, true); omega.setString(""); + omega.goLeft(rightLength, true); + omega.setString(""); } if (removeLeft) { - alpha.goRight((short) leftLength, true); alpha.setString(""); + alpha.goRight(leftLength, true); + alpha.setString(""); } } @@ -2538,8 +2498,8 @@ static class CitationMarkersWithUniqueLetters { final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); - XTextCursor full=null; - String fullText=null; + XTextCursor full = null; + String fullText = null; for (int i = 1; i <= 2; i++) { XTextContent markAsTextContent = documentConnection.getReferenceMarkAsTextContentOrNull(name); @@ -2621,11 +2581,11 @@ static class CitationMarkersWithUniqueLetters { XTextCursor beta = full.getText().createTextCursorByRange(full); beta.collapseToStart(); beta.goRight((short) 1, false); - beta.goRight((short) (fullText.length()-2), true); - beta.setString(left+right); + beta.goRight((short) (fullText.length() - 2), true); + beta.setString(left + right); beta.collapseToEnd(); beta.goLeft(rightLength, false); - // drop the inital character + // drop the initial character alpha.goRight((short) 1, true); alpha.setString(""); // drop the last character @@ -2634,7 +2594,6 @@ static class CitationMarkersWithUniqueLetters { return beta; } - private static void fillCitationMarkInCursor( DocumentConnection documentConnection, @@ -3717,7 +3676,7 @@ static class ProduceCitationMarkersResult { if (addToGroup && prev != null) { Objects.requireNonNull(prevRange); Objects.requireNonNull(currentRange); - if (!DocumentConnection.comparable(prevRange, currentRange)) { + if (!DocumentConnection.comparableRanges(prevRange, currentRange)) { addToGroup = false; } else { @@ -4256,8 +4215,9 @@ void styleIsRequired(OOBibStyle style) documentConnection.enterUndoContext("Refresh bibliography"); boolean requireSeparation = false; // may loose citation without requireSeparation=true - CitationGroups cg = new CitationGroups(documentConnection); - cg.checkRangeOverlaps(this.xDocumentConnection, requireSeparation); + CitationGroups cgs = new CitationGroups(documentConnection); + int maxReportedOverlaps = 10; + checkRangeOverlaps(cgs, this.xDocumentConnection, requireSeparation, maxReportedOverlaps); final boolean useLockControllers = true; try { ProduceCitationMarkersResult x = diff --git a/src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java b/src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java new file mode 100644 index 00000000000..8771c8fec67 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java @@ -0,0 +1,38 @@ +package org.jabref.gui.openoffice; + +import com.sun.star.text.XTextRange; + +/** + * Describe a protected range for overlap checking and reporting. + * + * To check that our protected ranges do not overlap, we collect + * these ranges. To check for overlaps between these, we need the + * {@code range} itself. To report the results of overlap + * checking, we need a {@code description} that can be understood + * by the user. + * + * To be able to refer back to more extended data, we might need + * to identify its {@code kind}, and index ({@code i}) in the + * corresponding tables. + * + */ +class RangeForOverlapCheck { + final static int REFERENCE_MARK_KIND = 0; + final static int FOOTNOTE_MARK_KIND = 1; + + XTextRange range; + int kind; + int i; + String description; + + RangeForOverlapCheck(XTextRange range, int i, int kind, String description) { + this.range = range; + this.kind = kind; + this.i = i; + this.description = description; + } + + String format() { + return description; + } +} diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java new file mode 100644 index 00000000000..3fea1a993f6 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java @@ -0,0 +1,71 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +//import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import java.util.TreeMap; +import com.sun.star.text.XText; +import com.sun.star.text.XTextRange; + +/** + * Map XTextRange values to some value of type V. + * + * Since XTextRange values are only comparable if they share the same + * r.getText(), we group them by these. + * + * Within such groups (partitions) we may define comparison, here + * based on (r.getStart(),r.getEnd()), thus equality means identical + * ranges. + * + * For finding overlapping ranges we use RangeKeyedMapList, that + * allows a list of values to be associated with a single XTextRange. + * + */ +class RangeKeyedMap { + Map> xxs; + + public + RangeKeyedMap() { + this.xxs = new HashMap<>(); + } + + public boolean + containsKey(XTextRange r) { + return xxs.containsKey( r.getText() ) && xxs.get(r).containsKey(r); + } + + public V + get(XTextRange r) { + TreeMap xs = xxs.get(r.getText()); + if ( xs == null ){ + return null; + } + return( xs.get(r) ); + } + + private static int + comparator( XTextRange a, XTextRange b ) { + int startOrder = DocumentConnection.javaCompareRegionStarts( a, b ); + if ( startOrder != 0 ){ + return startOrder; + } + return DocumentConnection.javaCompareRegionEnds( a, b ); + } + + public V + put(XTextRange r, V value) { + TreeMap xs = xxs.get(r.getText()); + if ( xs == null ){ + xs = new TreeMap<>( RangeKeyedMap::comparator ); + } + return xs.put( r, value ); + } + + public List> + partitionValues() { + return new ArrayList(xxs.values()); + } +} diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java new file mode 100644 index 00000000000..196e6615d37 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java @@ -0,0 +1,117 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import com.sun.star.text.XText; +import com.sun.star.text.XTextRange; + +class RangeKeyedMapList { + RangeKeyedMap> xxs; + + public + RangeKeyedMapList() { + this.xxs = new RangeKeyedMap<>(); + } + + public boolean + containsKey(XTextRange r) { + return xxs.containsKey(r); + } + + public List + get(XTextRange r) { + return xxs.get(r); + } + + public void + add( XTextRange r, V value) { + List vs = xxs.get(r); + if (vs == null){ + vs = new ArrayList<>(); + vs.add(value); + xxs.put(r,vs); + } else { + vs.add(value); + } + } + + enum OverlapKind { + TOUCH, + OVERLAP, + EQUAL_RANGE + } + + /** + * Used in reporting range overlaps. + * + * You probably want {@code V} to include information + * identifying the ranges. + */ + class RangeOverlap { + OverlapKind kind; + List vs; + + public + RangeOverlap( OverlapKind kind, List vs ) { + this.kind = kind; + this.vs = vs; + } + } + + /** + * Report identical, overlapping or touching ranges. + * + * For overlapping and touching, only report consecutive ranges + * and only with a single sample of otherwise identical ranges. + * + * @param atMost Limit the number of records returneed to atMost. + * Zero or negative {@code atMost} means no limit. + */ + List + findOverlappingRanges(int atMost, boolean includeTouching) { + List res = new ArrayList<>(); + for (TreeMap> xs : xxs.partitionValues()) { + List oxs = new ArrayList<>(xs.keySet()); + for (int i = 0; i < oxs.size(); i++) { + XTextRange a = oxs.get(i); + List avs = xs.get(a); + if (avs.size() > 1) { + res.add( + new RangeOverlap( + OverlapKind.EQUAL_RANGE, + avs + ) + ); + if ( atMost > 0 && res.size() >= atMost ) { + return res; + } + } + if ((i + 1) < oxs.size()) { + XTextRange b = oxs.get(i + 1); + int cmp = DocumentConnection.javaCompareRegionStarts(a.getEnd(), b.getStart()); + if (cmp > 0 || (includeTouching && (cmp == 0))) { + // found overlap or touch + List bvs = xs.get(b); + List vs = new ArrayList<>(); + vs.add( avs.get(0) ); + vs.add( bvs.get(0) ); + res.add( + new RangeOverlap( + (cmp == 0) ? OverlapKind.TOUCH : OverlapKind.OVERLAP, + vs + ) + ); + } + if ( atMost > 0 && res.size() >= atMost ) { + return res; + } + } + } + } + return res; + } + +} diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 1c7fe0081e9..cb8c7231075 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1547,12 +1547,12 @@ No\ entries\ selected\ for\ citation=No entries selected for citation No\ style\ for\ citation=No style for citation Open\ one\ before\ citing.=Open one before citing. Please\ select\ one.=Please select one. -Ranges\ of\ '%0'\ and\ '%1'\ are\ not\ separated=Ranges of '%0' and '%1' are not separated -Ranges\ of\ '%0'\ and\ '%1'\ overlap=Ranges of '%0' and '%1' overlap Select\ one\ before\ citing.=Select one before citing. Select\ some\ before\ citing.=Select some before citing. This\ operation\ requires\ a\ style.=This operation requires a style. - +Found\ identical\ ranges=Found identical ranges +Found\ overlapping\ ranges=Found overlapping ranges +Found\ touching\ ranges=Found touching ranges Note\:\ Use\ the\ placeholder\ %DIR%\ for\ the\ location\ of\ the\ opened\ library\ file.=Note: Use the placeholder %DIR% for the location of the opened library file. Error\ occured\ while\ executing\ the\ command\ \"%0\".=Error occured while executing the command \"%0\". From ada1a820d76c296ff39cff544fa9fed7018d9c7a Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 20 Mar 2021 21:08:23 +0100 Subject: [PATCH 0490/1068] refactor: CitationGroupsV001 Reorganized from using arrays to objects. Compiles, but needs testing. --- .../gui/openoffice/CitationGroupsV001.java | 1533 +++++++++ .../gui/openoffice/DocumentConnection.java | 18 +- .../openoffice/ManageCitationsDialogView.java | 38 +- .../ManageCitationsDialogViewModel.java | 22 +- ...ava => ManageCitationsEntryViewModel.java} | 6 +- .../org/jabref/gui/openoffice/OOBibBase.java | 2875 +++++++---------- .../gui/openoffice/RangeForOverlapCheck.java | 6 +- .../jabref/gui/openoffice/RangeKeyedMap.java | 3 + .../gui/openoffice/RangeKeyedMapList.java | 8 + src/main/resources/l10n/JabRef_en.properties | 1 + 10 files changed, 2794 insertions(+), 1716 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java rename src/main/java/org/jabref/gui/openoffice/{CitationEntryViewModel.java => ManageCitationsEntryViewModel.java} (83%) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java new file mode 100644 index 00000000000..896beeb1511 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -0,0 +1,1533 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Collections; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XText; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextRange; +import com.sun.star.util.InvalidStateException; + +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/* + * At the start of GUI actions we may want to check the state of the document. + * + * Operations: + * createCitationGroup + * deleteCitationGroup + * + */ +class CitationGroupsV001 { + + private static final Logger LOGGER = + LoggerFactory.getLogger(CitedKeys.class); + + private static final String BIB_CITATION = "JR_cite"; + private static final Pattern CITE_PATTERN = + Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + + private static final String ZERO_WIDTH_SPACE = "\u200b"; + + // for debugging we may want visible bracket + private static final boolean + REFERENCE_MARK_USE_INVISIBLE_BRACKETS = true; // !debug; + + private static final String + REFERENCE_MARK_LEFT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<"; + + private static final String + REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; + + /** Should we always fully remove reference mark brackets? */ + public static final boolean + REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS = true; + + class CitationGroupID { + String id; + CitationGroupID(String id){ + this.id = id; + } + + /** + * CitationEntry needs refMark or other identifying string + */ + String asString() { + return id; + } + + CitationGroupID fromString(String s) { + return new CitationGroupID(s); + } + } + + + class Citation { + + /** key in database */ + String citationKey; + Optional db; + Optional number; + Optional uniqueLetter; + + /* missing: something that differentiates this from other + * citations of the same citationKey + */ + + Citation( String citationKey ) { + this.citationKey = citationKey; + this.db = Optional.empty(); + this.number = Optional.empty(); + this.uniqueLetter = Optional.empty(); + } + } + + List makeIndices( int n ) { + return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); + } + + class CitationGroup { + CitationGroupID cgid; + int itcType; + List citations; + List localOrder; + // Currently pageInfo belongs to the group + Optional pageInfo; + /** + * Locator in document + */ + String referenceMarkName; + + CitationGroup( + CitationGroupID cgid, + int itcType, + List citations, + Optional pageInfo, + String referenceMarkName) { + this.cgid = cgid; + this.itcType = itcType; + this.citations = citations; + this.pageInfo = pageInfo; + this.referenceMarkName = referenceMarkName; + this.localOrder = makeIndices( citations.size() ); + } + + List + getSortedCitations() { + List res = new ArrayList<>(citations.size()); + for (int i : localOrder) { + res.add(citations.get(i)); + } + return res; + } + + List + getSortedNumbers() { + List cits = getSortedCitations(); + List numbers = + cits.stream() + .map( cit -> cit.number.get() ) + .collect(Collectors.toList()); + return numbers; + } + + class CitationAndIndex { + Citation c; + int i; + CitationAndIndex( Citation c, int i ){ + this.c = c; + this.i = i; + } + } + + class SortCitations implements Comparator { + + Comparator entryComparator; + + SortCitations(Comparator entryComparator) { + this.entryComparator = entryComparator; + } + + public int compare(CitationAndIndex a, CitationAndIndex b) { + if ( a.c.db.isEmpty() && b.c.db.isEmpty() ){ + // compare by citation key + String ack = a.c.citationKey; + String bck = b.c.citationKey; + return ack.compareTo(bck); + } + if ( a.c.db.isEmpty() ){ + return 1; + } + if ( b.c.db.isEmpty() ){ + return -1; + } + return entryComparator.compare( + a.c.db.get().entry, + b.c.db.get().entry + ); + } + } + + void + imposeLocalOrderByComparator(Comparator entryComparator) { + List cks = new ArrayList<>(); + for (int i = 0; i < citations.size(); i++) { + Citation c = citations.get(i); + cks.add( new CitationAndIndex(c,i) ); + } + Collections.sort(cks, new SortCitations(entryComparator)); + + List o = new ArrayList<>(); + for (CitationAndIndex ck : cks) { + o.add(ck.i); + } + this.localOrder = o; + } + } + + /** + * Original CitationGroups Data + */ + Map citationGroups; + + /** + * Extra Data + */ + // For custom properties belonging to us, but + // without a corresponding reference mark. + // These can be deleted. + private List pageInfoThrash; + + private Optional> globalOrder; + + private Optional citedKeysAfterDatabaseLookup; + /** + * This is going to be the bibliography + */ + private Optional bibliography; + + + /** + * Constructor + */ + public CitationGroupsV001(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + // Get the citationGroupNames + List citationGroupNames = + getJabRefReferenceMarkNames(documentConnection); + + { + // Collect unused jabrefPropertyNames + Set citationGroupNamesSet = + citationGroupNames.stream().collect(Collectors.toSet()); + + List pageInfoThrash = new ArrayList<>(); + List jabrefPropertyNames = + documentConnection.getCustomPropertyNames() + .stream() + .filter(CitationGroupsV001::isJabRefReferenceMarkName) + .collect(Collectors.toList()); + for (String pn : jabrefPropertyNames) { + if (!citationGroupNamesSet.contains(pn)) { + pageInfoThrash.add(pn); + } + } + this.pageInfoThrash = pageInfoThrash; + } + + { + Map citationGroups = new HashMap<>(); + for (int i = 0; i < citationGroupNames.size(); i++) { + final String name = citationGroupNames.get(i); + CitationGroup cg = + readCitationGroupFromDocumentOrThrow(documentConnection, name); + citationGroups.put(cg.cgid, cg); + } + this.citationGroups = citationGroups; + } + // Now we have almost every information from the document about citations. + // What is left out: the ranges controlled by the reference marks. + // But (I guess) those change too easily, so we only ask when actually needed. + + this.citedKeysAfterDatabaseLookup = Optional.empty(); + this.bibliography = Optional.empty(); + } + + private CitationGroup + readCitationGroupFromDocumentOrThrow(DocumentConnection documentConnection, + String refMarkName) + throws + WrappedTargetException { + + Optional op = parseRefMarkName(refMarkName); + if (op.isEmpty()) { + // We have a problem. We want types[i] and bibtexKeys[i] + // to correspond to referenceMarkNames.get(i). + // And do not want null in bibtexKeys (or error code in types) + // on return. + throw new IllegalArgumentException( + "citationGroups: found unparsable referenceMarkName"); + } + ParsedRefMark ov = op.get(); + CitationGroupID id = new CitationGroupID(refMarkName); + List citations = ((ov.citationKeys == null) + ? new ArrayList<>() + : (ov.citationKeys.stream() + .map(Citation::new) + .collect(Collectors.toList()))); + + Optional pageInfo = documentConnection.getCustomProperty(refMarkName); + + CitationGroup cg = new CitationGroup(id, + ov.itcType, + citations, + pageInfo, + refMarkName); + return cg; + } + + class CitationPath { + CitationGroupID group; + int storageIndexInGroup; + CitationPath(CitationGroupID group, + int storageIndexInGroup) { + this.group = group; + this.storageIndexInGroup = storageIndexInGroup; + } + } + + class DatabaseLookupResult { + BibEntry entry; + BibDatabase database; + DatabaseLookupResult( BibEntry entry, BibDatabase database ) { + this.entry = entry; + this.database = database; + } + } + + class CitedKey { + String key; + LinkedHashSet where; + Optional db; + Optional number; + Optional uniqueLetter; + Optional normCitMarker; + + CitedKey( String key, CitationPath p, Citation cit ) { + this.key = key; + this.where = new LinkedHashSet<>(); // remember order + this.where.add(p); + this.db = cit.db; + this.number = cit.number; + this.uniqueLetter = cit.uniqueLetter; + this.normCitMarker = Optional.empty(); + } + + void addPath( CitationPath p, Citation cit ) { + this.where.add(p); + if (cit.db != this.db) { + throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); + } + if (cit.number != this.number) { + throw new RuntimeException("CitedKey.addPath: mismatch on cit.number"); + } + if (cit.uniqueLetter != this.uniqueLetter) { + throw new RuntimeException("CitedKey.addPath: mismatch on cit.uniqueLetter"); + } + } + + void lookupInDatabases(List databases) { + Optional res = Optional.empty(); + for (BibDatabase database : databases) { + Optional entry = database.getEntryByCitationKey(key); + if (entry.isPresent()) { + res = Optional.of(new DatabaseLookupResult(entry.get(), database)); + break; + } + } + // store result + this.db = res; + } + + void distributeDatabaseLookupResult(CitationGroupsV001 cgs) { + cgs.setDatabaseLookupResults(where, db); + } + + void distributeNumber(CitationGroupsV001 cgs) { + cgs.setNumbers(where, number); + } + + void distributeUniqueLetter(CitationGroupsV001 cgs) { + cgs.setUniqueLetters(where, uniqueLetter); + } + } + + class CitedKeys { + + LinkedHashMap data; + + CitedKeys(LinkedHashMap data) { + this.data = data; + } + + /** + * The cited keys in sorted order. + */ + public List + values() { + return new ArrayList<>(data.values()); + } + + class SortCitedKeys implements Comparator { + + Comparator entryComparator; + + SortCitedKeys(Comparator entryComparator) { + this.entryComparator = entryComparator; + } + + public int compare(CitedKey a, CitedKey b) { + if (a.db.isEmpty() && b.db.isEmpty()) { + return a.key.compareTo(b.key); + } + if (a.db.isEmpty()){ + return 1; + } + if (b.db.isEmpty()){ + return -1; + } + return entryComparator.compare(a.db.get().entry, + b.db.get().entry); + } + } + + void + sortByComparator(Comparator entryComparator) { + List cks = new ArrayList(data.values()); + Collections.sort(cks, new SortCitedKeys(entryComparator)); + LinkedHashMap newData = new LinkedHashMap<>(); + for (CitedKey ck : cks) { + newData.put(ck.key, ck); + } + data = newData; + } + + void + numberCitedKeysInCurrentOrder() { + int i=1; + for (CitedKey ck : data.values()) { + ck.number = Optional.of(i); // was: -1 for UndefinedBibtexEntry + i++; + } + } + + void + lookupInDatabases(List databases) { + for (CitedKey ck : this.data.values()) { + ck.lookupInDatabases(databases); + } + } + + void distributeDatabaseLookupResults(CitationGroupsV001 cgs) { + for (CitedKey ck : this.data.values()) { + ck.distributeDatabaseLookupResult(cgs); + } + } + + void distributeNumbers(CitationGroupsV001 cgs) { + for (CitedKey ck : this.data.values()) { + ck.distributeNumber(cgs); + } + } + + void distributeUniqueLetters(CitationGroupsV001 cgs) { + for (CitedKey ck : this.data.values()) { + ck.distributeUniqueLetter(cgs); + } + } + + } + + public void + setDatabaseLookupResults(Set where, + Optional db) { + for (CitationPath p : where) { + CitationGroup cg = this.citationGroups.get(p.group); + if (cg == null){ + LOGGER.warn("CitationGroups.setDatabaseLookupResult: group missing"); + continue; + } + Citation cit = cg.citations.get(p.storageIndexInGroup); + cit.db = db; + } + } + + public CitationGroupsV001.CitedKeys + lookupEntriesInDatabases(List databases) { + CitationGroupsV001 cgs = this; + + CitationGroupsV001.CitedKeys cks = cgs.getCitedKeys(); + + cks.lookupInDatabases(databases); + cks.distributeDatabaseLookupResults(cgs); + // record we did a database lookup + // and allow extracting unresolved keys. + this.citedKeysAfterDatabaseLookup = Optional.of(cks); + return cks; + } + + public void + setNumbers(Set where, + Optional number) { + for (CitationPath p : where) { + CitationGroup cg = this.citationGroups.get(p.group); + if (cg == null){ + LOGGER.warn("CitationGroups.setNumbers: group missing"); + continue; + } + Citation cit = cg.citations.get(p.storageIndexInGroup); + cit.number = number; + } + } + + public void + setUniqueLetters(Set where, + Optional uniqueLetter) { + for (CitationPath p : where) { + CitationGroup cg = this.citationGroups.get(p.group); + if (cg == null) { + LOGGER.warn("CitationGroups.setUniqueLetters: group missing"); + continue; + } + Citation cit = cg.citations.get(p.storageIndexInGroup); + cit.uniqueLetter = uniqueLetter; + } + } + + public void + imposeLocalOrderByComparator(Comparator entryComparator) { + for (CitationGroup cg : citationGroups.values()) { + cg.imposeLocalOrderByComparator(entryComparator); + } + } + + public CitedKeys + getCitedKeys() { + LinkedHashMap res = new LinkedHashMap<>(); + for (CitationGroup cg : citationGroups.values()) { + int storageIndexInGroup = 0; + for (Citation cit : cg.citations) { + String key = cit.citationKey; + CitationPath p = new CitationPath(cg.cgid, storageIndexInGroup); + if ( res.containsKey(key) ) { + res.get(key).addPath(p,cit); + } else { + res.put(key, new CitedKey( key, p, cit )); + } + storageIndexInGroup++; + } + } + return new CitedKeys(res); + } + + + /** + * CitedKeys created iterating citations in (globalOrder,localOrder) + */ + public CitedKeys + getCitedKeysSortedInOrderOfAppearance() { + LinkedHashMap res = new LinkedHashMap<>(); + if (globalOrder.isEmpty()) { + throw new RuntimeException("getSortedCitedKeys: no globalOrder"); + } + for (CitationGroupID cgid : globalOrder.get()) { + CitationGroup cg = getCitationGroup(cgid) + .orElseThrow(RuntimeException::new); + for (int i : cg.localOrder) { + Citation cit = cg.citations.get(i); + String citationKey = cit.citationKey; + CitationPath p = new CitationPath(cgid,i); + if (res.containsKey(citationKey)) { + res.get(citationKey).addPath(p,cit); + } else { + res.put(citationKey, new CitedKey(citationKey, p, cit)); + } + } + } + return new CitedKeys(res); + } + + Optional getBibliography() { + return bibliography; + } + + public void + createNumberedBibliogaphySortedInOrderOfAppearance() { + CitationGroupsV001 cgs = this; + if (!cgs.bibliography.isEmpty()) { + throw new RuntimeException( + "createNumberedBibliogaphySortedInOrderOfAppearance: already have a bibliography" + ); + } + CitationGroupsV001.CitedKeys sortedCitedKeys = + cgs.getCitedKeysSortedInOrderOfAppearance(); + sortedCitedKeys.numberCitedKeysInCurrentOrder(); + sortedCitedKeys.distributeNumbers(cgs); + cgs.bibliography = Optional.of(sortedCitedKeys); + } + + public void + createNumberedBibliogaphySortedByComparator( Comparator entryComparator ) { + CitationGroupsV001 cgs = this; + if (!cgs.bibliography.isEmpty()) { + throw new RuntimeException( + "createNumberedBibliogaphySortedByComparator: already have a bibliography" + ); + } + CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); + citedKeys.sortByComparator( entryComparator ); // TODO: must be after database lookup + citedKeys.numberCitedKeysInCurrentOrder(); + citedKeys.distributeNumbers(cgs); + this.bibliography = Optional.of(citedKeys); + } + + public void + createPlainBibliogaphySortedByComparator( Comparator entryComparator ) { + CitationGroupsV001 cgs = this; + if (!this.bibliography.isEmpty()) { + throw new RuntimeException( + "createPlainBibliogaphySortedByComparator: already have a bibliography" + ); + } + CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); + citedKeys.sortByComparator( entryComparator ); // TODO: must be after database lookup + // citedKeys.numberCitedKeysInCurrentOrder(); + // citedKeys.distributeNumbers(); + this.bibliography = Optional.of(citedKeys); + } + + public Set + getCitationGroupIDs() { + return citationGroups.keySet(); + } + + public List + getSortedCitationGroupIDs() { + if ( globalOrder.isEmpty() ) { + throw new RuntimeException("getSortedCitationGroupIDs: not ordered yet"); + } + return globalOrder.get(); + } + + public void + setGlobalOrder( List globalOrder ) { + this.globalOrder = Optional.of(globalOrder); + } + + public Optional + getCitationGroup(CitationGroupID cgid) { + CitationGroup e = citationGroups.get(cgid); + return Optional.ofNullable(e); + } + + private Optional + getReferenceMarkName(CitationGroupID cgid) { + return getCitationGroup(cgid).map(cg -> cg.referenceMarkName); + } + + private Optional + getItcType(CitationGroupID cgid) { + return getCitationGroup(cgid).map(cg -> cg.itcType); + } + + public int + numberOfCitationGroups() { + return citationGroups.size(); + } + + public Optional + getPageInfo(CitationGroupID cgid) { + return ( + getCitationGroup(cgid) + .map(cg -> cg.pageInfo) + .flatMap(x -> x) + ); + } + + public Optional> + getCitations(CitationGroupID cgid) { + return getCitationGroup(cgid).map(cg -> cg.citations); + } + + public List + getSortedCitations(CitationGroupID cgid) { + Optional cg = getCitationGroup(cgid); + if ( cg.isEmpty() ) { + throw new RuntimeException( "getSortedCitations: invalid cgid" ); + } + return cg.get().getSortedCitations(); + } + + + /* *********************************** + * + * modifies both storage and presentation + * + * ***********************************/ + + /** + * Insert {@code n} spaces in a way that reference + * marks just before or just after the cursor are not affected. + * + * This is based on the observation, that starting two + * new paragraphs separates us from a reference mark on either side. + * + * The pattern used is: + * {@code safeInsertSpaces(n): para, para, left, space(n), right-delete, left(n), left-delete} + * + * @param position Where to insert (at position.getStart()) + * @param n Number of spaces to insert. + * + * @return a new cursor, covering the just-inserted spaces. + * + * This could be generalized to insert arbitrary text safely + * between two reference marks. But we do not need that now. + */ + private static XTextCursor + safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { + // Start with an empty cursor at position.getStart(); + XText text = position.getText(); + XTextCursor cursor = text.createTextCursorByRange(position.getStart()); + text.insertString(cursor, "\r\r", false); // para, para + cursor.goLeft((short) 1, false); // left + text.insertString(cursor, " ".repeat(n), false); // space(n) + cursor.goRight((short) 1, true); + cursor.setString(""); // right-delete + cursor.goLeft((short) n, false); // left(n) + cursor.goLeft((short) 1, true); + cursor.setString(""); // left-delete + cursor.goRight((short) n, true); + return cursor; + } + + /** + * Create a reference mark with the given name, at the + * end of position. + * + * To reduce the difference from the original representation, we + * only insist on having at least two characters inside reference + * marks. These may be ZERO_WIDTH_SPACE characters or other + * placeholder not likely to appear in a citation mark. + * + * This placeholder is only needed if the citation mark is + * otherwise empty (e.g. when we just create it). + * + * getFillCursorForCitationGroup yields a bracketed cursor, that + * can be used to fill in / overwrite the value inside. + * + * After each getFillCursorForCitationGroup, we require a call to + * cleanFillCursorForCitationGroup, which removes the brackets, + * unless if it would make the content less than two + * characters. If we need only one placeholder, we keep the left + * bracket. If we need two, then the content is empty. The + * removeBracketsFromEmpty parameter of + * cleanFillCursorForCitationGroup overrides this, and for empty + * citations it will remove the brackets, leaving an empty + * reference mark. The idea behind this is that we do not need to + * refill empty marks (itcTypes INVISIBLE_CIT), and the caller + * can tell us that we are dealing with one of these. + * + * Thus the only user-visible difference in citation marks is + * that instead of empty marks we use two brackets, for + * single-character marks we add a left bracket before. + * + * Character-attribute inheritance: updates inherit from the + * first character inside, not from the left. + * + * On return {@code position} is collapsed, and is after the + * inserted space, or at the end of the reference mark. + * + * @param documentConnection Connection to document. + * @param name For the reference mark. + * @param position Collapsed to its end. + * @param insertSpaceAfter We insert a space after the mark, that + * carries on format of characters from + * the original position. + * + * @param withoutBrackets Force empty reference mark (no brackets). + * For use with INVISIBLE_CIT. + * + */ + public CitationGroupID + createCitationGroup( + DocumentConnection documentConnection, + List citationKeys, + Optional pageInfo, + int itcType, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets + ) + throws + CreationException, + NoDocumentException, + WrappedTargetException { + + String xkey = + citationKeys.stream() + .collect(Collectors.joining(",")); + + String refMarkName = + getUniqueReferenceMarkName( + documentConnection, + xkey, + itcType + ); + + CitationGroupID cgid = new CitationGroupID(refMarkName); + + List citations = + citationKeys.stream() + .map(Citation::new) + .collect(Collectors.toList()); + + /* + new ArrayList<>(citationKeys.size()); + for (int j = 0; j < ov.citationKeys.size(); j++) { + citatitons.add( new Citation( citationKeys.get(j) ) ); + } + */ + + CitationGroup cg = new CitationGroup(cgid, + itcType, + citations, + pageInfo, + refMarkName); + + // add to our data + this.citationGroups.put( cgid, cg ); + // invalidate globalOrder. + // TODO: look out for localOrder! + this.globalOrder = Optional.empty(); + + /* + * Apply to document + */ + + createReferenceMarkForCitationGroup( + documentConnection, + refMarkName, + position, + insertSpaceAfter, + withoutBrackets); + return cgid; + } + + private static void + createReferenceMarkForCitationGroup( + DocumentConnection documentConnection, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets + ) + throws + CreationException { + + // The cursor we received: we push it before us. + position.collapseToEnd(); + + XTextCursor cursor = safeInsertSpacesBetweenReferenceMarks(position.getEnd(), 2); + + // cursors before the first and after the last space + XTextCursor cursorBefore = + cursor.getText().createTextCursorByRange(cursor.getStart()); + XTextCursor cursorAfter = + cursor.getText().createTextCursorByRange(cursor.getEnd()); + + cursor.collapseToStart(); + cursor.goRight((short) 1, false); + // now we are between two spaces + + final String left = REFERENCE_MARK_LEFT_BRACKET; + final String right = REFERENCE_MARK_RIGHT_BRACKET; + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); + String bracketedContent = (withoutBrackets + ? "" + : left + right); + + cursor.getText().insertString( + cursor, + bracketedContent, + true); + + /* XNamed mark = */ documentConnection.insertReferenceMark( + refMarkName, + cursor, + true // absorb + ); + + cursorBefore.goRight((short) 1, true); + cursorBefore.setString(""); + if (!insertSpaceAfter) { + cursorAfter.goLeft((short) 1, true); + cursorAfter.setString(""); + } + } + + /* + * Remove it from the {@code this} and the document. + * + * TODO: either invalidate or update the extra data we are storing + * (bibliography). Update may be complicated, since we do + * not know how the bibliography was generated: it was partially done + * outside CitationGroupsV001, and we did not store how. + */ + public void + removeCitationGroups( List cgs, DocumentConnection documentConnection ) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException { + + for (CitationGroup cg : cgs) { + documentConnection.removeReferenceMark(cg.referenceMarkName); + this.citationGroups.remove(cg.cgid); + this.globalOrder.map(l -> l.remove(cg.cgid)); + + // Invalidate CitedKeys + this.citedKeysAfterDatabaseLookup = Optional.empty(); + this.bibliography = Optional.empty(); + /* + * this.citedKeysAfterDatabaseLookup.map(cks -> cks.forgetCitationGroup(cg.cgid) ); + * this.bibliography.map(cks -> cks.forgetCitationGroup(cg.cgid)); + */ + } + } + + public void + removeCitationGroup( CitationGroup cg, DocumentConnection documentConnection ) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException { + + removeCitationGroups( Collections.singletonList(cg), documentConnection ); + } + + /** + * Remove brackets, but if the result would become empty, leave + * them; if the result would be a single characer, leave the left bracket. + * + * @param removeBracketsFromEmpty is intended to force removal if + * we are working on an "Empty citation" (INVISIBLE_CIT). + */ + public void + cleanFillCursorForCitationGroup( + DocumentConnection documentConnection, + CitationGroupID cgid, // String name, // Identifies group + boolean removeBracketsFromEmpty, + boolean alwaysRemoveBrackets + ) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + final String left = REFERENCE_MARK_LEFT_BRACKET; + final String right = REFERENCE_MARK_RIGHT_BRACKET; + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); + + CitationGroupsV001 cgs = this; + /* + // XTextContent markAsTextContent = documentConnection.getReferenceMarkAsTextContentOrNull(name); + XTextContent markAsTextContent = cgs.getReferenceMarkRangeOrNull(cgid,documentConnection); + + if (markAsTextContent == null) { + throw new RuntimeException( + String.format( + "cleanFillCursorForCitationGroup: markAsTextContent(%s) == null", + name + )); + } + XTextCursor full = + DocumentConnection.getTextCursorOfTextContent( + markAsTextContent); + if (full == null) { + throw new RuntimeException( + "cleanFillCursorForCitationGroup: full == null" + ); + } + */ + String name = cgs.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); + + XTextCursor full = cgs.getRawCursorForCitationGroup(cgid, documentConnection); + final String fullText = full.getString(); + final int fullTextLength = fullText.length(); + + XTextCursor alpha = full.getText().createTextCursorByRange(full); + alpha.collapseToStart(); + + XTextCursor beta = full.getText().createTextCursorByRange(full); + beta.collapseToStart(); + beta.goRight(leftLength, false); + + XTextCursor omega = full.getText().createTextCursorByRange(full); + omega.collapseToEnd(); + + if (!fullText.startsWith(left)) { + throw new RuntimeException( + String.format( + "cleanFillCursorForCitationGroup:" + + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", + name + )); + } + + if (!fullText.endsWith(right)) { + throw new RuntimeException( + String.format( + "cleanFillCursorForCitationGroup:" + + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", + name + )); + } + + final int contentLength = (fullTextLength - (leftLength + rightLength)); + if (contentLength < 0) { + throw new RuntimeException( + String.format( + "cleanFillCursorForCitationGroup: length(%s) < 0", + name + )); + } + + boolean removeRight = ( + // have at least 1 character content + (contentLength >= 1) + || ((contentLength == 0) && removeBracketsFromEmpty) + || alwaysRemoveBrackets + ); + boolean removeLeft = ( + // have at least 2 character content + (contentLength >= 2) + || ((contentLength == 0) && removeBracketsFromEmpty) + || alwaysRemoveBrackets + ); + + if (removeRight) { + omega.goLeft(rightLength, true); + omega.setString(""); + } + + if (removeLeft) { + alpha.goRight(leftLength, true); + alpha.setString(""); + } + } + + /** + * Cursor for the reference marks as is, not prepared for filling, + * but does not need cleanFillCursorForCitationGroup either. + */ + public XTextCursor + getRawCursorForCitationGroup( + CitationGroupID cgid, // Identifies group + DocumentConnection documentConnection + ) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + String name = this.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); + XTextCursor full = null; + + XTextContent markAsTextContent = + documentConnection.getReferenceMarkAsTextContentOrNull(name); + + if (markAsTextContent == null) { + throw new RuntimeException( + String.format( + "getRawCursorForCitationGroup: markAsTextContent(%s) == null", + name + )); + } + full = + DocumentConnection.getTextCursorOfTextContent( + markAsTextContent); + if (full == null) { + throw new RuntimeException( + "getRawCursorForCitationGroup: full == null" + ); + } + return full; + } + + public XTextCursor + getFillCursorForCitationGroup( + DocumentConnection documentConnection, + CitationGroupID cgid // Identifies group + ) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + String name = this.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); + + final boolean debugThisFun = false; + final String left = REFERENCE_MARK_LEFT_BRACKET; + final String right = REFERENCE_MARK_RIGHT_BRACKET; + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); + + XTextCursor full = null; + String fullText = null; + for (int i = 1; i <= 2; i++) { + XTextContent markAsTextContent = + documentConnection.getReferenceMarkAsTextContentOrNull(name); + + if (markAsTextContent == null) { + throw new RuntimeException( + String.format( + "getFillCursorForCitationGroup: markAsTextContent(%s) == null (attempt %d)", + name, i + )); + } + full = + DocumentConnection.getTextCursorOfTextContent( + markAsTextContent); + if (full == null) { + throw new RuntimeException( + String.format( + "getFillCursorForCitationGroup: full == null (attempt %d)", i + ) + ); + } + + fullText = full.getString(); + if (debugThisFun) { + System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); + } + + if (fullText.length() >= 2) { + break; + } else { + // (fullText.length() < 2) + if (i == 2) { + throw new RuntimeException( + String.format( + "getFillCursorForCitationGroup:" + + " (fullText.length() < 2) (attempt %d)", i + ) + ); + } + // too short, recreate + if (debugThisFun) { + System.out.println("getFillCursor: too short, recreate"); + } + full.setString(""); + try { + documentConnection.removeReferenceMark(name); + } catch (NoSuchElementException ex) { + LOGGER.warn(String.format( + "getFillCursorForCitationGroup got NoSuchElementException" + + " for '%s'", name)); + } + createReferenceMarkForCitationGroup( + documentConnection, + name, + full, + false, // insertSpaceAfter + false // withoutBrackets + ); + } + } + + if (full == null) { + throw new RuntimeException( + "getFillCursorForCitationGroup: full == null (after loop)" + ); + } + if (fullText == null) { + throw new RuntimeException( + "getFillCursorForCitationGroup: fullText == null (after loop)" + ); + } + + // we have at least two characters inside + XTextCursor alpha = full.getText().createTextCursorByRange(full); + alpha.collapseToStart(); + XTextCursor omega = full.getText().createTextCursorByRange(full); + omega.collapseToEnd(); + + XTextCursor beta = full.getText().createTextCursorByRange(full); + beta.collapseToStart(); + beta.goRight((short) 1, false); + beta.goRight((short) (fullText.length() - 2), true); + beta.setString(left + right); + beta.collapseToEnd(); + beta.goLeft(rightLength, false); + // drop the initial character + alpha.goRight((short) 1, true); + alpha.setString(""); + // drop the last character + omega.goLeft((short) 1, true); + omega.setString(""); + return beta; + } + + /** + * Produce a reference mark name for JabRef for the given citation + * key and itcType that does not yet appear among the reference + * marks of the document. + * + * @param bibtexKey The citation key. + * @param itcType Encodes the effect of withText and + * inParenthesis options. + * + * The first occurrence of bibtexKey gets no serial number, the + * second gets 0, the third 1 ... + * + * Or the first unused in this series, after removals. + */ + private String + getUniqueReferenceMarkName( + DocumentConnection documentConnection, + String bibtexKey, + int itcType) + throws NoDocumentException { + + XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); + int i = 0; + String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; + while (xNamedRefMarks.hasByName(name)) { + name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; + i++; + } + return name; + } + + /** + * This is what we get back from parsing a refMarkName. + * + */ + private static class ParsedRefMark { + /** "", "0", "1" ... */ + public String i; + /** in-text-citation type */ + public int itcType; + /** Citation keys embedded in the reference mark. */ + public List citationKeys; + + ParsedRefMark(String i, int itcType, List citationKeys) { + this.i = i; + this.itcType = itcType; + this.citationKeys = citationKeys; + } + } + + /** + * Parse a JabRef reference mark name. + * + * @return Optional.empty() on failure. + * + */ + private static Optional + parseRefMarkName(String refMarkName) { + + Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); + if (!citeMatcher.find()) { + return Optional.empty(); + } + + List keys = Arrays.asList(citeMatcher.group(3).split(",")); + String i = citeMatcher.group(1); + int itcType = Integer.parseInt(citeMatcher.group(2)); + return (Optional.of(new CitationGroupsV001.ParsedRefMark(i, itcType, keys))); + } + + /** + * Extract the list of citation keys from a reference mark name. + * + * @param name The reference mark name. + * @return The list of citation keys encoded in the name. + * + * In case of duplicated citation keys, + * only the first occurrence. + * Otherwise their order is preserved. + * + * If name does not match CITE_PATTERN, + * an empty list of strings is returned. + */ + private List + parseRefMarkNameToUniqueCitationKeys(String name) { + Optional op = parseRefMarkName(name); + return + op.map( + parsedRefMark -> + parsedRefMark.citationKeys.stream() + .distinct() + .collect(Collectors.toList()) + ) + .orElseGet(ArrayList::new); + } + + /** + * @return true if name matches the pattern used for JabRef + * reference mark names. + */ + private static boolean + isJabRefReferenceMarkName(String name) { + return (CITE_PATTERN.matcher(name).find()); + } + + /** + * Filter a list of reference mark names by `isJabRefReferenceMarkName` + * + * @param names The list to be filtered. + */ + private static List + filterIsJabRefReferenceMarkName(List names) { + return (names + .stream() + .filter(CitationGroupsV001::isJabRefReferenceMarkName) + .collect(Collectors.toList()) + ); + } + + /** + * Get reference mark names from the document matching the pattern + * used for JabRef reference mark names. + * + * Note: the names returned are in arbitrary order. + * + * + * + */ + private List + getJabRefReferenceMarkNames(DocumentConnection documentConnection) + throws NoDocumentException { + List allNames = documentConnection.getReferenceMarkNames(); + return filterIsJabRefReferenceMarkName(allNames); + } + + /** + * For each name in referenceMarkNames set types[i] and + * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) + * + * @param referenceMarkNames Should only contain parsable names. + * @param types OUT Must be same length as referenceMarkNames. + * @param bibtexKeys OUT First level must be same length as referenceMarkNames. + */ + private static void + parseRefMarkNamesToArrays( + List referenceMarkNames, + int[] types, + String[][] bibtexKeys + ) { + final int nRefMarks = referenceMarkNames.size(); + assert (types.length == nRefMarks); + assert (bibtexKeys.length == nRefMarks); + for (int i = 0; i < nRefMarks; i++) { + final String name = referenceMarkNames.get(i); + Optional op = parseRefMarkName(name); + if (op.isEmpty()) { + // We have a problem. We want types[i] and bibtexKeys[i] + // to correspond to referenceMarkNames.get(i). + // And do not want null in bibtexKeys (or error code in types) + // on return. + throw new IllegalArgumentException( + "parseRefMarkNamesToArrays expects parsable referenceMarkNames" + ); + } + ParsedRefMark ov = op.get(); + types[i] = ov.itcType; + bibtexKeys[i] = ov.citationKeys.toArray(String[]::new); + } + } + + /** + * Extract citation keys from names of referenceMarks in the document. + * + * Each citation key is listed only once, in the order of first appearance + * (in `names`, which itself is in arbitrary order) + * + * doc.referenceMarks.names.map(parse).flatten.unique + */ + private List + findCitedKeys(DocumentConnection documentConnection) + throws + NoSuchElementException, + WrappedTargetException, + NoDocumentException { + + List names = getJabRefReferenceMarkNames(documentConnection); + + // assert it supports XTextContent + XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); + for (String name1 : names) { + Object bookmark = xNamedMarks.getByName(name1); + assert (null != DocumentConnection.asTextContent(bookmark)); + } + + // Collect to a flat list while keep only the first appearance. + List keys = new ArrayList<>(); + for (String name1 : names) { + List newKeys = parseRefMarkNameToUniqueCitationKeys(name1); + for (String key : newKeys) { + if (!keys.contains(key)) { + keys.add(key); + } + } + } + + return keys; + } + + + + /** + * Given the name of a reference mark, get the corresponding + * pageInfo text. + * + * @param documentConnection Connection to a document. + * @param name Name of the custom property to query. + * @return "" for missing or empty pageInfo + */ + private static String + getPageInfoForReferenceMarkName( + DocumentConnection documentConnection, + String name) + throws WrappedTargetException, + UnknownPropertyException { + + Optional pageInfo = documentConnection.getCustomProperty(name); + if (pageInfo.isEmpty() || pageInfo.get().isEmpty()) { + return ""; + } + return pageInfo.get(); + } + + + /* + * ranges controlled by citation groups should not overlap with each other. + * + * @param cgid : Must be known. + * @return Null if the reference mark is missing. + */ + public XTextRange + getReferenceMarkRangeOrNull(DocumentConnection documentConnection, CitationGroupID cgid) + throws + NoDocumentException, + WrappedTargetException { + String name = this.getReferenceMarkName( cgid ) + .orElseThrow(RuntimeException::new); + return documentConnection.getReferenceMarkRangeOrNull(name); + } + + /** + * @return A RangeForOverlapCheck for each citation group. + * + * result.size() == nRefMarks + */ + List + citationRanges(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + List xs = new ArrayList<>(numberOfCitationGroups()); + + List cgids = + new ArrayList<>(this.getCitationGroupIDs()); + + for (CitationGroupID cgid : cgids) { + XTextRange r = this.getReferenceMarkRangeOrNull(documentConnection, cgid); + String name = this.getCitationGroup(cgid).get().referenceMarkName; + xs.add(new RangeForOverlapCheck( + r, cgid, + RangeForOverlapCheck.REFERENCE_MARK_KIND, + name + )); + } + return xs; + } + + /** + * @return A range for each footnote mark where the footnote + * contains at least one citation group. + * + * Purpose: We do not want markers of footnotes containing + * reference marks to overlap with reference + * marks. Overwriting these footnote marks might kill our + * reference marks in the footnote. + * + */ + List + footnoteMarkRanges(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + // Avoid inserting the same mark twice. + // Could use RangeSet if we had that. + RangeKeyedMap seen = new RangeKeyedMap<>(); + + List xs = new ArrayList<>(); + + List citRanges = citationRanges(documentConnection); + + for (RangeForOverlapCheck base : citRanges) { + XTextRange r = base.range; + + XTextRange footnoteMarkRange = + DocumentConnection.getFootnoteMarkRangeOrNull(r); + + if (footnoteMarkRange != null) { + boolean seenContains = seen.containsKey( footnoteMarkRange ); + if (!seenContains) { + seen.put(footnoteMarkRange, true); + xs.add(new RangeForOverlapCheck( + footnoteMarkRange, + base.i, // cgid :: identifies of citation group + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + base.description + )); + } + } + } + return xs; + } + +} // class citationGroups + diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java index b0d763fee37..6091ff1689c 100644 --- a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java @@ -294,7 +294,7 @@ class DocumentConnection { public Optional getCustomProperty(String property) throws - UnknownPropertyException, + // UnknownPropertyException, WrappedTargetException { assert (this.propertySet != null); @@ -303,11 +303,17 @@ class DocumentConnection { .getPropertySetInfo()); if (psi.hasPropertyByName(property)) { - String v = - this.propertySet - .getPropertyValue(property) - .toString(); - return Optional.ofNullable(v); + try { + String v = + this.propertySet + .getPropertyValue(property) + .toString(); + return Optional.ofNullable(v); + } catch (UnknownPropertyException ex) { + // LOGGER.warn("getCustomProperty: cought UnknownPropertyException: ", ex); + // return Optional.empty(); + throw new RuntimeException("getCustomProperty: cought UnknownPropertyException"); + } } return Optional.empty(); } diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index 64d95322472..79b5e5ee50f 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -30,9 +30,9 @@ public class ManageCitationsDialogView extends BaseDialog { private final OOBibBase ooBase; - @FXML private TableView citationsTableView; - @FXML private TableColumn citation; - @FXML private TableColumn extraInfo; + @FXML private TableView citationsTableView; + @FXML private TableColumn citation; + @FXML private TableColumn extraInfo; @Inject private DialogService dialogService; @@ -57,34 +57,31 @@ public ManageCitationsDialogView(OOBibBase ooBase) { @FXML private void initialize() - throws NoSuchElementException, - WrappedTargetException, - UnknownPropertyException, - NoDocumentException { + throws NoSuchElementException, + WrappedTargetException, + UnknownPropertyException, + NoDocumentException { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); citation.setCellValueFactory(cellData -> cellData.getValue() - .citationProperty() - ); + .citationProperty()); - new ValueTableCellFactory() - .withGraphic(this::getText) - .install(citation); + new ValueTableCellFactory() + .withGraphic(this::getText) + .install(citation); - extraInfo.setCellValueFactory(cellData - -> + extraInfo.setCellValueFactory(cellData -> cellData.getValue() - .extraInformationProperty() - ); + .extraInformationProperty()); extraInfo.setEditable(true); citationsTableView.setEditable(true); citationsTableView.itemsProperty().bindBidirectional(viewModel.citationsProperty()); - extraInfo.setOnEditCommit((CellEditEvent cell) -> { + extraInfo.setOnEditCommit((CellEditEvent cell) -> { cell.getRowValue().setExtraInfo(cell.getNewValue()); }); extraInfo.setCellFactory(TextFieldTableCell.forTableColumn()); @@ -92,9 +89,12 @@ private void initialize() private Node getText(String citationContext) { - String inBetween = StringUtil.substringBetween(citationContext, HTML_BOLD_START_TAG, HTML_BOLD_END_TAG); + String inBetween = StringUtil.substringBetween(citationContext, + HTML_BOLD_START_TAG, + HTML_BOLD_END_TAG); String start = citationContext.substring(0, citationContext.indexOf(HTML_BOLD_START_TAG)); - String end = citationContext.substring(citationContext.lastIndexOf(HTML_BOLD_END_TAG) + HTML_BOLD_END_TAG.length()); + String end = citationContext.substring(citationContext.lastIndexOf(HTML_BOLD_END_TAG) + + HTML_BOLD_END_TAG.length()); Text startText = new Text(start); Text inBetweenText = new Text(inBetween); diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 63132c58b32..c0869cb5380 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -25,7 +25,7 @@ public class ManageCitationsDialogViewModel { private static final Logger LOGGER = LoggerFactory.getLogger(ManageCitationsDialogViewModel.class); - private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList()); private final OOBibBase ooBase; private final DialogService dialogService; @@ -38,10 +38,18 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, this.ooBase = ooBase; this.dialogService = dialogService; - List cts = ooBase.getCitationEntries(); - for (CitationEntry entry : cts) { - CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); - citations.add(itemViewModelEntry); + try { + List cts = ooBase.getCitationEntries(); + for (CitationEntry entry : cts) { + ManageCitationsEntryViewModel itemViewModelEntry = new ManageCitationsEntryViewModel(entry); + citations.add(itemViewModelEntry); + } + } catch (UnknownPropertyException + | WrappedTargetException + | NoDocumentException + | CreationException ex) { + LOGGER.warn("Problem collecting citations", ex); + dialogService.showErrorDialogAndWait(Localization.lang("Problem collecting citations"), ex); } } @@ -49,7 +57,7 @@ public void storeSettings() { List citationEntries = citations.stream() - .map(CitationEntryViewModel::toCitationEntry) + .map(ManageCitationsEntryViewModel::toCitationEntry) .collect(Collectors.toList()); try { @@ -66,7 +74,7 @@ public void storeSettings() { } } - public ListProperty citationsProperty() { + public ListProperty citationsProperty() { return citations; } } diff --git a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsEntryViewModel.java similarity index 83% rename from src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java rename to src/main/java/org/jabref/gui/openoffice/ManageCitationsEntryViewModel.java index 028990a6bc8..24fde5e076c 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsEntryViewModel.java @@ -5,19 +5,19 @@ import org.jabref.logic.openoffice.CitationEntry; -public class CitationEntryViewModel { +public class ManageCitationsEntryViewModel { private final StringProperty citation = new SimpleStringProperty(""); private final StringProperty extraInformation = new SimpleStringProperty(""); private final String refMarkName; - public CitationEntryViewModel(String refMarkName, String citation, String extraInfo) { + public ManageCitationsEntryViewModel(String refMarkName, String citation, String extraInfo) { this.refMarkName = refMarkName; this.citation.setValue(citation); this.extraInformation.setValue(extraInfo); } - public CitationEntryViewModel(CitationEntry citationEntry) { + public ManageCitationsEntryViewModel(CitationEntry citationEntry) { this(citationEntry.getRefMarkName(), citationEntry.getContext(), citationEntry.getPageInfo().orElse("")); } diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2764b6cff98..036e4605bbb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -103,25 +103,6 @@ class OOBibBase { private static final String BIB_SECTION_NAME = "JR_bib"; private static final String BIB_SECTION_END_NAME = "JR_bib_end"; - private static final String BIB_CITATION = "JR_cite"; - private static final Pattern CITE_PATTERN = - Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); - - private static final String ZERO_WIDTH_SPACE = "\u200b"; - - // for debugging we may want visible bracket - private static final boolean - REFERENCE_MARK_USE_INVISIBLE_BRACKETS = true; // !debug; - - private static final String - REFERENCE_MARK_LEFT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<"; - - private static final String - REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; - - /** Should we always fully remove reference mark brackets? */ - private static final boolean - REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS = true; /* Types of in-text citation. (itcType) * Their numeric values are used in reference mark names. @@ -130,15 +111,41 @@ class OOBibBase { private static final int AUTHORYEAR_INTEXT = 2; private static final int INVISIBLE_CIT = 3; + private static final Comparator entryComparator = makeEntryComparator(); + private static final Comparator yearAuthorTitleComparator = makeYearAuthorTitleComparator(); + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); /* variables */ private final DialogService dialogService; private final XDesktop xDesktop; - private final Comparator entryComparator; - private final Comparator yearAuthorTitleComparator; + static Comparator + makeEntryComparator() { + FieldComparator a = new FieldComparator(StandardField.AUTHOR); + FieldComparator y = new FieldComparator(StandardField.YEAR); + FieldComparator t = new FieldComparator(StandardField.TITLE); + + List> ayt = new ArrayList<>(3); + ayt.add(a); + ayt.add(y); + ayt.add(t); + return new FieldComparatorStack<>(ayt); + } + + static Comparator + makeYearAuthorTitleComparator() { + FieldComparator y = new FieldComparator(StandardField.YEAR); + FieldComparator a = new FieldComparator(StandardField.AUTHOR); + FieldComparator t = new FieldComparator(StandardField.TITLE); + + List> yat = new ArrayList<>(3); + yat.add(y); + yat.add(a); + yat.add(t); + return new FieldComparatorStack<>(yat); + } /** * Created when connected to a document. @@ -147,16 +154,6 @@ class OOBibBase { */ private DocumentConnection xDocumentConnection; - /** - * Map citation keys to letters ("a", "b") that - * make the citation markers unique. - * - * Used directly (apart from passing around as `uniqueLetters`): - * refreshCiteMarkers, rebuildBibTextSection. - * - * Depends on: style, citations and their order. - */ - // private final Map xUniqueLetters = new HashMap<>(); /* * Constructor @@ -170,6 +167,7 @@ class OOBibBase { this.dialogService = dialogService; + /* FieldComparator a = new FieldComparator(StandardField.AUTHOR); FieldComparator y = new FieldComparator(StandardField.YEAR); FieldComparator t = new FieldComparator(StandardField.TITLE); @@ -185,6 +183,7 @@ class OOBibBase { yat.add(a); yat.add(t); this.yearAuthorTitleComparator = new FieldComparatorStack<>(yat); + */ this.xDesktop = simpleBootstrap(loPath); } @@ -429,14 +428,14 @@ public boolean documentConnectionMissing() { * * We store some information in the document about * - * Citations : citation key, pageInfo, citation group. - * Each belongs to exactly one group. + * Citation groups: * - * Citation groups (in case of multiple citation keys also - * known as "multicite", "merged citations"): + * - citations belonging to the group. + * - Range of text owned (where the citation marks go). + * - pageInfo * - * Which citations belong to the group. - * Range of text owned (where the citation marks go). + * Citations : citation key + * Each belongs to exactly one group. * * From these, the databases and the style we create and update * the presentation (citation marks) @@ -468,479 +467,7 @@ public boolean documentConnectionMissing() { * * **************************************/ - /** - * Produce a reference mark name for JabRef for the given citation - * key and itcType that does not yet appear among the reference - * marks of the document. - * - * @param bibtexKey The citation key. - * @param itcType Encodes the effect of withText and - * inParenthesis options. - * - * The first occurrence of bibtexKey gets no serial number, the - * second gets 0, the third 1 ... - * - * Or the first unused in this series, after removals. - */ - private String - getUniqueReferenceMarkName( - DocumentConnection documentConnection, - String bibtexKey, - int itcType) - throws NoDocumentException { - - XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); - int i = 0; - String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; - while (xNamedRefMarks.hasByName(name)) { - name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; - i++; - } - return name; - } - - /** - * This is what we get back from parsing a refMarkName. - * - */ - private static class ParsedRefMark { - /** "", "0", "1" ... */ - public String i; - /** in-text-citation type */ - public int itcType; - /** Citation keys embedded in the reference mark. */ - public List citedKeys; - - ParsedRefMark(String i, int itcType, List citedKeys) { - this.i = i; - this.itcType = itcType; - this.citedKeys = citedKeys; - } - } - - /** - * Parse a JabRef reference mark name. - * - * @return Optional.empty() on failure. - * - */ - private static Optional - parseRefMarkName(String refMarkName) { - - Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); - if (!citeMatcher.find()) { - return Optional.empty(); - } - - List keys = Arrays.asList(citeMatcher.group(3).split(",")); - String i = citeMatcher.group(1); - int itcType = Integer.parseInt(citeMatcher.group(2)); - return (Optional.of(new OOBibBase.ParsedRefMark(i, itcType, keys))); - } - - /** - * Extract the list of citation keys from a reference mark name. - * - * @param name The reference mark name. - * @return The list of citation keys encoded in the name. - * - * In case of duplicated citation keys, - * only the first occurrence. - * Otherwise their order is preserved. - * - * If name does not match CITE_PATTERN, - * an empty list of strings is returned. - */ - private List - parseRefMarkNameToUniqueCitationKeys(String name) { - Optional op = parseRefMarkName(name); - return - op.map( - parsedRefMark -> - parsedRefMark.citedKeys.stream() - .distinct() - .collect(Collectors.toList()) - ) - .orElseGet(ArrayList::new); - } - - /** - * @return true if name matches the pattern used for JabRef - * reference mark names. - */ - private static boolean - isJabRefReferenceMarkName(String name) { - return (CITE_PATTERN.matcher(name).find()); - } - - /** - * Filter a list of reference mark names by `isJabRefReferenceMarkName` - * - * @param names The list to be filtered. - */ - private static List - filterIsJabRefReferenceMarkName(List names) { - return (names - .stream() - .filter(OOBibBase::isJabRefReferenceMarkName) - .collect(Collectors.toList()) - ); - } - - /** - * Get reference mark names from the document matching the pattern - * used for JabRef reference mark names. - * - * Note: the names returned are in arbitrary order. - * - * See also: `getJabRefReferenceMarkNamesSortedByPosition` - * - */ - private List - getJabRefReferenceMarkNames(DocumentConnection documentConnection) - throws NoDocumentException { - List allNames = documentConnection.getReferenceMarkNames(); - return filterIsJabRefReferenceMarkName(allNames); - } - - /** - * For each name in referenceMarkNames set types[i] and - * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) - * - * @param referenceMarkNames Should only contain parsable names. - * @param types OUT Must be same length as referenceMarkNames. - * @param bibtexKeys OUT First level must be same length as referenceMarkNames. - */ - private static void - parseRefMarkNamesToArrays( - List referenceMarkNames, - int[] types, - String[][] bibtexKeys - ) { - final int nRefMarks = referenceMarkNames.size(); - assert (types.length == nRefMarks); - assert (bibtexKeys.length == nRefMarks); - for (int i = 0; i < nRefMarks; i++) { - final String name = referenceMarkNames.get(i); - Optional op = parseRefMarkName(name); - if (op.isEmpty()) { - // We have a problem. We want types[i] and bibtexKeys[i] - // to correspond to referenceMarkNames.get(i). - // And do not want null in bibtexKeys (or error code in types) - // on return. - throw new IllegalArgumentException( - "parseRefMarkNamesToArrays expects parsable referenceMarkNames" - ); - } - ParsedRefMark ov = op.get(); - types[i] = ov.itcType; - bibtexKeys[i] = ov.citedKeys.toArray(String[]::new); - } - } - - /** - * Extract citation keys from names of referenceMarks in the document. - * - * Each citation key is listed only once, in the order of first appearance - * (in `names`, which itself is in arbitrary order) - * - * doc.referenceMarks.names.map(parse).flatten.unique - */ - private List - findCitedKeys(DocumentConnection documentConnection) - throws - NoSuchElementException, - WrappedTargetException, - NoDocumentException { - - List names = getJabRefReferenceMarkNames(documentConnection); - - // assert it supports XTextContent - XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); - for (String name1 : names) { - Object bookmark = xNamedMarks.getByName(name1); - assert (null != DocumentConnection.asTextContent(bookmark)); - } - - // Collect to a flat list while keep only the first appearance. - List keys = new ArrayList<>(); - for (String name1 : names) { - List newKeys = parseRefMarkNameToUniqueCitationKeys(name1); - for (String key : newKeys) { - if (!keys.contains(key)) { - keys.add(key); - } - } - } - - return keys; - } - - /** - * Given the name of a reference mark, get the corresponding - * pageInfo text. - * - * @param documentConnection Connection to a document. - * @param name Name of the custom property to query. - * @return "" for missing or empty pageInfo - */ - private static String - getPageInfoForReferenceMarkName( - DocumentConnection documentConnection, - String name) - throws WrappedTargetException, - UnknownPropertyException { - - Optional pageInfo = documentConnection.getCustomProperty(name); - if (pageInfo.isEmpty() || pageInfo.get().isEmpty()) { - return ""; - } - return pageInfo.get(); - } - - /* - * At the start of GUI actions we may want to check the state of the document. - */ - class CitationGroups { - private final Map indexByName; - private final String[] names; - // After parsing - private final int[] itcTypes; - private final String[][] citationKeys; - - // Probably wrong, but currently pageInfo belongs to the group - private final String[] pageInfo; - - // For custom properties belonging to us, but - // without a corresponding reference mark. - // These can be deleted. - private List pageInfoThrash; - - // After database lookup: - // private BibEntry[][] entries; - // private BibDatabase[][] entryDatabases; - - public CitationGroups(DocumentConnection documentConnection) - throws NoDocumentException { - // Get the names - this.names = - getJabRefReferenceMarkNames(documentConnection) - .toArray(String[]::new); - - // Fill indexByName - this.indexByName = new HashMap<>(); - for (int i = 0; i < this.names.length; i++) { - indexByName.put(names[i], i); - } - // collect pageInfo - this.pageInfo = new String[names.length]; - List jabrefPropertyNames = - documentConnection.getCustomPropertyNames() - .stream() - .filter(OOBibBase::isJabRefReferenceMarkName) - .collect(Collectors.toList()); - // For each name: either put into place or - // put into thrash collector. - this.pageInfoThrash = new ArrayList<>(); - for (String n : jabrefPropertyNames) { - if (indexByName.containsKey(n)) { - int i = indexByName.get(n); - pageInfo[i] = n; - } else { - pageInfoThrash.add(n); - } - } - // parse names - this.itcTypes = new int[names.length]; - this.citationKeys = new String[names.length][]; - for (int i = 0; i < names.length; i++) { - final String name = names[i]; - Optional op = parseRefMarkName(name); - if (op.isEmpty()) { - // We have a problem. We want types[i] and bibtexKeys[i] - // to correspond to referenceMarkNames.get(i). - // And do not want null in bibtexKeys (or error code in types) - // on return. - throw new IllegalArgumentException( - "citationGroups: found unparsable referenceMarkName" - ); - } - ParsedRefMark ov = op.get(); - itcTypes[i] = ov.itcType; - citationKeys[i] = ov.citedKeys.toArray(String[]::new); - } - // Now we have almost every information from the document about citations. - // What is left out: the ranges controlled by the reference marks. - // But (I guess) those change too easily, so we only ask when actually needed. - } - - /* - * ranges controlled by citation groups should not overlap with each other. - * - * - */ - public XTextRange - getReferenceMarkRangeOrNull(DocumentConnection documentConnection, int i) - throws - NoDocumentException, - WrappedTargetException { - return documentConnection.getReferenceMarkRangeOrNull(names[i]); - } - - /** - * Assumes a.getText() == b.getText(), and both belong to documentConnection.xText - * - * Note: OpenOffice XTextRangeCompare and java use different - * (opposite) conventions. The "java" prefix in the - * functions name is intended to emphasize, that the - * value returned is adjusted to use java conventions - * (by multiplying the result with (-1)). - * - * @return -1 for (a < b), 1 for (a > b); 0 for equal. - * - * @throws RuntimeException if a and b are not comparable - * - */ - /* - public int - javaCompareRegionStarts(RangeForOverlapCheck a, - RangeForOverlapCheck b) { - // - // XTextRange cannot be compared, only == or != is available. - // - // XTextRangeCompare: compares the positions of two TextRanges within a Text. - // Only TextRange instances within the same Text can be compared. - // And XTextRangeCompare must be obtained from their Text. - - XTextRange ra = a.range; - XTextRange rb = b.range; - if (ra.getText() != rb.getText()) { - throw new RuntimeException( - String.format( - "OOBibBase.CitationGroups.javaCompareRegionStarts:" - + " incomparable regions: %s %s", - a.format(), - b.format()) - ); - } - - try { - return DocumentConnection.javaCompareRegionStarts(ra, rb); - } catch (IllegalArgumentException ex) { - throw new RuntimeException( - String.format( - "OOBibBase.CitationGroups.javaCompareRegionStarts:" - + " caught IllegalArgumentException: %s %s", - a.format(), - b.format() - ) - ); - } - } - */ - /** - * - */ - /* - public int - javaCompareRegionEndToStart(RangeForOverlapCheck a, - RangeForOverlapCheck b) { - - XTextRange ra = a.range; - XTextRange rb = b.range; - if (ra.getText() != rb.getText()) { - throw new RuntimeException( - String.format( - "OOBibBase.CitationGroups.javaCompareRegionEndToStart:" - + " incomparable regions: %s %s", - a.format(), - b.format()) - ); - } - - try { - return DocumentConnection.javaCompareRegionStarts(ra.getEnd(), rb.getStart()); - } catch (IllegalArgumentException ex) { - throw new RuntimeException( - String.format( - "OOBibBase.CitationGroups.javaCompareRegionEndToStart:" - + " caught IllegalArgumentException: %s %s", - a.format(), - b.format() - ) - ); - } - } - */ - - /** - * @return A RangeForOverlapCheck for each citation group. - */ - List - citationRanges(DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException { - - List xs = new ArrayList<>(names.length); - for (int i = 0; i < names.length; i++) { - XTextRange r = this.getReferenceMarkRangeOrNull(documentConnection, i); - xs.add(new RangeForOverlapCheck( - r, i, - RangeForOverlapCheck.REFERENCE_MARK_KIND, - names[i] - )); - } - return xs; - } - - /** - * @return A range for each footnote mark where the footnote - * contains at least one citation group. - * - * Purpose: We do not want markers of footnotes containing - * reference marks to overlap with reference - * marks. Overwriting these footnote marks might kill our - * reference marks in the footnote. - * - */ - List - footnoteMarkRanges(DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException { - - // Avoid inserting the same mark twice. - // Could use RangeSet if we had that. - RangeKeyedMap seen = new RangeKeyedMap<>(); - - List xs = new ArrayList<>(); - - for (int i = 0; i < names.length; i++) { - XTextRange r = this.getReferenceMarkRangeOrNull(documentConnection, i); - - XTextRange footnoteMarkRange = - DocumentConnection.getFootnoteMarkRangeOrNull(r); - - if (footnoteMarkRange != null) { - // Problem: quadratic complexity. Each new footnoteMarkRange - // is compared to all we have seen before. - boolean seenContains = seen.containsKey( footnoteMarkRange ); - if (!seenContains) { - seen.put(footnoteMarkRange, true); - xs.add(new RangeForOverlapCheck( - footnoteMarkRange, - i, // index of citation group - RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + names[i] - )); - } - } - } - return xs; - } - } // class citationGroups @@ -950,7 +477,7 @@ public CitationGroups(DocumentConnection documentConnection) */ public void checkRangeOverlaps( - CitationGroups cgs, + CitationGroupsV001 cgs, DocumentConnection documentConnection, boolean requireSeparation, int atMost @@ -1043,19 +570,23 @@ public CitationGroups(DocumentConnection documentConnection) throws UnknownPropertyException, WrappedTargetException, - NoDocumentException { + NoDocumentException, + CreationException { DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); - List names = this.getJabRefReferenceMarkNames(documentConnection); + // List names = this.getJabRefReferenceMarkNames(documentConnection); - List citations = new ArrayList<>(names.size()); - for (String name : names) { + int n = cgs.numberOfCitationGroups(); + List citations = new ArrayList<>(n); + for (CitationGroupsV001.CitationGroupID cgid : cgs.getCitationGroupIDs()) { + String name = cgid.asString(); CitationEntry entry = new CitationEntry( name, - this.getCitationContext(documentConnection, name, 30, 30, true), - documentConnection.getCustomProperty(name) + this.getCitationContext(cgs, cgid, documentConnection, 30, 30, true), + cgs.getPageInfo(cgid) //documentConnection.getCustomProperty(name) ); citations.add(entry); } @@ -1074,18 +605,21 @@ public CitationGroups(DocumentConnection documentConnection) * @param htmlMarkup If true, the text belonging to the * reference mark is surrounded by bold html tag. */ - public String + private String getCitationContext( + CitationGroupsV001 cgs, + CitationGroupsV001.CitationGroupID cgid, DocumentConnection documentConnection, - String refMarkName, int charBefore, int charAfter, boolean htmlMarkup ) throws WrappedTargetException, - NoDocumentException { + NoDocumentException, + CreationException { + /* XNameAccess nameAccess = documentConnection.getReferenceMarks(); XTextContent mark = DocumentConnection.nameAccessGetTextContentByNameOrNull(nameAccess, refMarkName); @@ -1098,6 +632,8 @@ public CitationGroups(DocumentConnection documentConnection) return String.format("(Could not retrieve context for %s)", refMarkName); } XTextCursor cursor = DocumentConnection.getTextCursorOfTextContent(mark); + */ + XTextCursor cursor = cgs.getRawCursorForCitationGroup(cgid, documentConnection); String citPart = cursor.getString(); @@ -1374,6 +910,8 @@ private static class FindCitedEntriesResult { * * The term used here is "multicite". The option controlling the * order is "MultiCiteChronological" in style files. + * + * Yes, they are always sorted one way or another. */ private Comparator comparatorForMulticite(OOBibStyle style) { @@ -1478,9 +1016,20 @@ private static class FindCitedEntriesResult { /* first appearance order, based on visual order */ /** - * Given a location, return its position: - * coordinates relative to the top left position - * of the first page of the document. + * Given a location, return its position: coordinates relative to + * the top left position of the first page of the document. + * + * Note: for text layouts with two or more columns, this gives the + * wrong order: top-down/left-to-right does not match + * reading order. + * + * Note: The "relative to the top left position of the first page" + * is meant "as it appears on the screen". + * + * In particular: when viewing pages side-by-side, the top + * half of the right page is higher than the lower half of + * the left page. Again, top-down/left-to-right does not + * match reading order. * * @param range Location. * @param cursor To get the position, we need az XTextViewCursor. @@ -1495,30 +1044,36 @@ private static class FindCitedEntriesResult { /** * A reference mark name paired with its visual position. * - * Comparison is based on (Y,X): vertical compared first, horizontal second. + * Comparison is based on (Y,X,indexInPosition): vertical compared + * first, horizontal second, indexInPosition third. * * Used for sorting reference marks by their visual positions. * - * Note: for text layouts with two or more columns, this gives the wrong order. + * * */ - private static class ComparableMark implements Comparable { + private static class ComparableMark implements Comparable> { - private final String name; private final Point position; + private final int indexInPosition; + private final T content; - public ComparableMark(String name, Point position) { - this.name = name; + public ComparableMark(Point position, int indexInPosition, T content) { this.position = position; + this.indexInPosition = indexInPosition; + this.content = content; } @Override public int compareTo(ComparableMark other) { - if (position.Y == other.position.Y) { - return position.X - other.position.X; - } else { + + if (position.Y != other.position.Y) { return position.Y - other.position.Y; } + if (position.X != other.position.X) { + return position.X - other.position.X; + } + return indexInPosition - other.indexInPosition; } @Override @@ -1531,21 +1086,32 @@ public boolean equals(Object o) { ComparableMark other = (ComparableMark) o; return ((this.position.X == other.position.X) && (this.position.Y == other.position.Y) - && Objects.equals(this.name, other.name)); + && (this.indexInPosition == other.indexInPosition) + && Objects.equals(this.content, other.content) + ); } return false; } - public String getName() { - return name; + public T getContent() { + return content; } @Override public int hashCode() { - return Objects.hash(position, name); + return Objects.hash(position, content); } } + /** + * + */ + interface VisualSortable { + public XTextRange getRange(); + public int getIndexInPosition(); + public T getContent(); + } + /** * Read reference mark names from the document, keep only those * with JabRef naming convention, get their visual positions, @@ -1556,156 +1122,256 @@ public int hashCode() { * left-right) order does not match the expected (textual) * order. * + * TODO: refmarks in the same footnote get the same position. + * After sorting, they may get the wrong order. + * */ - private List - getJabRefReferenceMarkNamesSortedByPosition( - DocumentConnection documentConnection) - throws - WrappedTargetException, - NoDocumentException { + class VisualSortEntry implements VisualSortable { + public XTextRange range; + public int indexInPosition; + public T content; - if (documentConnection.hasControllersLocked()) { - LOGGER.warn( - "getJabRefReferenceMarkNamesSortedByPosition:" - + " with ControllersLocked, viewCursor.gotoRange" - + " is probably useless" - ); + VisualSortEntry( + XTextRange range, + int indexInPosition, + T content + ) { + this.range = range; + this.indexInPosition = indexInPosition; + this.content = content; } - List names = getJabRefReferenceMarkNames(documentConnection); - - // find coordinates - List positions = new ArrayList<>(names.size()); - - XNameAccess nameAccess = documentConnection.getReferenceMarks(); - XTextViewCursor viewCursor = documentConnection.getViewCursor(); - // initialPos: to be restored before return - XTextRange initialPos = viewCursor.getStart(); - for (String name : names) { - - XTextContent textContent = - DocumentConnection.nameAccessGetTextContentByNameOrNull(nameAccess, name); - // unoQI(XTextContent.class, nameAccess.getByName(name)); - if (null == textContent) { - LOGGER.warn(String.format( - "OOBibBase.getJabRefReferenceMarkNames:" - + " could not retrieve reference mark: '%s'", - name - )); - continue; // just skip it - } - - XTextRange range = textContent.getAnchor(); - - // Adjust range if we are inside a footnote: - if (unoQI(XFootnote.class, range.getText()) != null) { - // Find the linking footnote marker: - XFootnote footer = unoQI(XFootnote.class, range.getText()); - // The footnote's anchor gives the correct position in the text: - range = footer.getAnchor(); - } - positions.add(findPositionOfTextRange(range, viewCursor)); + @Override + public XTextRange getRange() { + return range; } - // restore cursor position - viewCursor.gotoRange(initialPos, false); - // order by position - Set set = new TreeSet<>(); - for (int i = 0; i < positions.size(); i++) { - set.add(new ComparableMark(names.get(i), positions.get(i))); + @Override + public int getIndexInPosition() { + return indexInPosition; } - // collect referenceMarkNames in order - List result = new ArrayList<>(set.size()); - for (ComparableMark mark : set) { - result.add(mark.getName()); + @Override + public T getContent() { + return content; } - - return result; } - /** - * Return bibliography entries sorted according to the order of - * first appearance in referenceMarkNames. - * - * @param referenceMarkNames Names of reference marks. - * @param citeKeyToBibEntry Helps to find the entries - * @return LinkedHashMap from BibEntry to BibDatabase with - * iteration order as first appearance in referenceMarkNames. - * - * Note: Within citation group (a reference mark) the order is - * as appears there. - * - */ - private Map - sortEntriesByRefMarkNames( - List referenceMarkNames, - Map citeKeyToBibEntry, - Map entries - ) { - // LinkedHashMap: iteration order is insertion-order, not - // affected if a key is re-inserted. - Map newList = new LinkedHashMap<>(); + List> + createVisualSortInput(CitationGroupsV001 cgs, + DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + NoDocumentException, + WrappedTargetException + { - for (String name : referenceMarkNames) { - Optional op = parseRefMarkName(name); - if (op.isEmpty()) { - continue; + // final int nMarks = cgs.numberOfCitationGroups(); + + List cgids = + new ArrayList<>(cgs.getCitationGroupIDs()); + + List vses = new ArrayList<>(); + for (CitationGroupsV001.CitationGroupID cgid : cgids) { + XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); + if (range == null) { + throw new RuntimeException( "getReferenceMarkRangeOrNull returned null" ); } + vses.add( new VisualSortEntry(range, 0, cgid) ); + } - List keys = op.get().citedKeys; - // no need to look in the database again - for (String key : keys) { - BibEntry origEntry = citeKeyToBibEntry.get(key); - if (origEntry != null) { - if (!newList.containsKey(origEntry)) { - BibDatabase database = entries.get(origEntry); - newList.put(origEntry, database); + /* + * At this point we are almost ready to return vses. + * + * For example we may want to number citations in a footnote + * as if it appeared where the footnote mark is. + * + * The following code replaces ranges within footnotes with + * the range for the corresponding footnote mark. + * + * This brings further ambiguity if we have multiple + * citations within the same footnote: for the comparison + * they become indistinguishable. Numbering between them is + * not controlled. Also combineCiteMarkers will see them in + * the wrong order (if we use this comparison), and will not + * be able to merge. To avoid these, we sort textually within + * each .getText() partition and add indexInPosition + * accordingly. + * + */ + + // Sort within partitions + RangeKeyedMapList> xxs + = new RangeKeyedMapList<>(); + + for (VisualSortEntry v : vses) { + xxs.add( v.getRange(), v ); + } + + // build final list + List> res = new ArrayList<>(); + for (TreeMap>> + xs : xxs.partitionValues()) { + List oxs = new ArrayList<>(xs.keySet()); + for (int i = 0; i < oxs.size(); i++) { + XTextRange a = oxs.get(i); + List> avs = xs.get(a); + for (int j=0; j v = avs.get(j); + v.indexInPosition = j; + if ( mapFootnotesToFootnoteMarks ) { + // Adjust range if we are inside a footnote: + if (unoQI(XFootnote.class, v.range.getText()) != null) { + // Find the linking footnote marker: + XFootnote footer = unoQI(XFootnote.class, v.range.getText()); + // The footnote's anchor gives the correct position in the text: + v.range = footer.getAnchor(); + } } - } else { - LOGGER.info("Citation key not found: '" + key + "'"); - LOGGER.info("Problem with reference mark: '" + name + "'"); - newList.put(new UndefinedBibtexEntry(key), null); + res.add(v); } } } - return newList; + return res.stream().map(e -> e).collect(Collectors.toList()); + } + + private List> + visualSort( + // getJabRefReferenceMarkNamesSortedByPosition( + // CitationGroupsV001 cgs, + List> vses, + DocumentConnection documentConnection + //boolean mapFootnotesToFootnoteMarks + ) + throws + WrappedTargetException, + NoDocumentException { + + if (documentConnection.hasControllersLocked()) { + LOGGER.warn( + "visualSort:" + + " with ControllersLocked, viewCursor.gotoRange" + + " is probably useless" + ); + } + + XTextViewCursor viewCursor = documentConnection.getViewCursor(); + // initialPos: to be restored before return + XTextRange initialPos = viewCursor.getStart(); + // for (String name : names) { + + + //final int nMarks = vses.size(); + + // find coordinates + List positions = new ArrayList<>(vses.size()); + + for (VisualSortable v : vses) { + positions.add( + findPositionOfTextRange( + v.getRange(), + viewCursor) + ); + } + + // restore cursor position + viewCursor.gotoRange(initialPos, false); + + // order by position + Set>> set = new TreeSet<>(); + for (int i = 0; i < vses.size(); i++) { + set.add( + new ComparableMark<>( + positions.get(i), + vses.get(i).getIndexInPosition(), + vses.get(i) + ) + ); + } + + // collect CitationGroupIDs in order + List> result = new ArrayList<>(set.size()); + for (ComparableMark> mark : set) { + result.add(mark.getContent()); + } + return result; + } + + + private List + getVisuallySortedCitationGroupIDs( + // getJabRefReferenceMarkNamesSortedByPosition( + CitationGroupsV001 cgs, + // List vses, + DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks + ) + throws + WrappedTargetException, + NoDocumentException { + + List> vses = + createVisualSortInput( + cgs, + documentConnection, + mapFootnotesToFootnoteMarks); + + + List> sorted = + visualSort( vses, documentConnection ); + + return + sorted.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList()) + ; } + /* *************************************** * * Make them unique: uniqueLetters or numbers * * **************************************/ - private String[][] - normalizedCitationMarkersForNormalStyle( - BibEntry[][] cEntriesForAll, - Map entries, + private String + normalizedCitationMarkerForNormalStyle( + CitationGroupsV001.CitedKey ck, OOBibStyle style ) { + if (ck.db.isEmpty()){ + return String.format("(Unresolved(%s))", ck.key); + } + BibEntry ce = ck.db.get().entry; + Map entries = new HashMap<>(); + entries.put( ce, ck.db.get().database ); + // We need "normalized" (in parenthesis) markers + // for uniqueness checking purposes: + return + style.getCitationMarker( + Collections.singletonList(ce), + entries, + true, + null, + new int[] {-1} // no limit on authors + ); + } - final int nRefMarks = cEntriesForAll.length; + /** + * Fills + */ + private void + normalizedCitationMarkersForNormalStyle( + CitationGroupsV001.CitedKeys sortedCitedKeys, + OOBibStyle style + ) { - String[][] normCitMarkers = new String[nRefMarks][]; - for (int i = 0; i < nRefMarks; i++) { - BibEntry[] cEntries = cEntriesForAll[i]; - // We need "normalized" (in parenthesis) markers - // for uniqueness checking purposes: - normCitMarkers[i] = - Arrays.stream(cEntries) - .map(ce -> - style.getCitationMarker( - Collections.singletonList(undefinedBibEntryToNull(ce)), - entries, - true, - null, - new int[] {-1} // no limit on authors - ) - ) - .toArray(String[]::new); + for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.data.values()) { + ck.normCitMarker = Optional.of( + normalizedCitationMarkerForNormalStyle( ck, style ) + ); } - return normCitMarkers; + // return normCitMarkers; } /** @@ -1719,46 +1385,48 @@ public int hashCode() { * added after the year (null for none). * * Note: bibtexKeys[i][j] may be null (from UndefinedBibtexEntry) + * + * Map citation keys to letters ("a", "b") that + * make the citation markers unique. + * + * Depends on: style, citations and their order. */ - Map + void createUniqueLetters( - String[][] bibtexKeys, - String[][] normCitMarkers + CitationGroupsV001.CitedKeys sortedCitedKeys, + CitationGroupsV001 cgs ) { - final int nRefMarks = bibtexKeys.length; - assert nRefMarks == normCitMarkers.length; + //final int nRefMarks = bibtexKeys.length; + //assert nRefMarks == normCitMarkers.length; // refKeys: (normCitMarker) to (list of citation keys sharing it). // The entries in the lists are ordered as in // normCitMarkers[i][j] Map> refKeys = new HashMap<>(); - - for (int i = 0; i < nRefMarks; i++) { - // Compare normalized markers, since the actual - // markers can be different. - String[] markers = normCitMarkers[i]; - for (int j = 0; j < markers.length; j++) { - String marker = markers[j]; - String currentKey = bibtexKeys[i][j]; - // containsKey(null) is OK, contains(null) is OK. - if (refKeys.containsKey(marker)) { - // Ok, we have seen this exact marker before. - if (!refKeys.get(marker).contains(currentKey)) { - // ... but not for this entry. - refKeys.get(marker).add(currentKey); - } - } else { - // add as new entry - List l = new ArrayList<>(1); - l.add(currentKey); - refKeys.put(marker, l); + for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.data.values()) { + String marker = ck.normCitMarker.get(); + String currentKey = ck.key; + + if (refKeys.containsKey(marker)) { + // Ok, we have seen this exact marker before. + if (!refKeys.get(marker).contains(currentKey)) { + // ... but not for this entry. + refKeys.get(marker).add(currentKey); } + } else { + // add as new entry + List l = new ArrayList<>(1); + l.add(currentKey); + refKeys.put(marker, l); } } - // uniqueLetters.clear(); Map uniqueLetters = new HashMap<>(); + // uniqueLetters.clear(); + for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.data.values()) { + ck.uniqueLetter = Optional.empty(); + } // Go through the collected lists and see where we need to // add unique letters to the year. @@ -1777,97 +1445,15 @@ public int hashCode() { } } } - return uniqueLetters; - } - - /** - * Number source for (1-based) numbering of citations. - */ - private static class CitationNumberingState { - /** - * numbers : Remembers keys we have seen - * and what number did they receive. - */ - private final Map numbers; - - /** - * The highest number we ever allocated. - */ - private int lastNum; - - CitationNumberingState() { - this.numbers = new HashMap<>(); - this.lastNum = 0; - } - - /** - * The first call returns 1. - */ - public int getOrAllocateNumber(String key) { - int result; - if (numbers.containsKey(key)) { - // Already seen - result = numbers.get(key); - } else { - // First time to see. Allocate number. - lastNum++; - numbers.put(key, lastNum); - result = lastNum; - } - return result; - } - } - - /** - * Gets number for a BibEntry. (-1) for UndefinedBibtexEntry - * - * BibEntry.getCitationKey() must not be Optional.empty(), except - * for UndefinedBibtexEntry. - * - */ - private static int - numberPossiblyUndefinedBibEntry( - BibEntry ce, - CitationNumberingState cns - ) { - - if (ce instanceof UndefinedBibtexEntry) { - return (-1); + // return uniqueLetters; + for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.data.values()) { + String key = ck.key; + Optional ul = Optional.ofNullable(key); + ck.uniqueLetter = ul; } - - String key = (ce.getCitationKey() - .orElseThrow(IllegalArgumentException::new)); - - return cns.getOrAllocateNumber(key); + sortedCitedKeys.distributeUniqueLetters(cgs); } - /** - * Resolve the citation key from a citation reference marker name, - * and look up the index of the key in a list of keys. - * - * @param keysCitedHere The citation keys needing indices. - * @param orderedCiteKeys A List of citation keys representing the - * entries in the bibliography. - * - * @return The (1-based) indices of the cited keys, - * or (-1) if a key is not found. - */ - private static List - findCitedEntryIndices( - List keysCitedHere, - List orderedCiteKeys - ) { - List result = new ArrayList<>(keysCitedHere.size()); - for (String key : keysCitedHere) { - int ind = orderedCiteKeys.indexOf(key); - result.add( - ind == -1 - ? -1 - : 1 + ind // 1-based - ); - } - return result; - } /* *************************************** * @@ -1992,31 +1578,32 @@ public int getOrAllocateNumber(String key) { * Produce citation markers for the case when the citation * markers are the citation keys themselves, separated by commas. */ - private static String[] + private static Map produceCitationMarkersForIsCitationKeyCiteMarkers( - List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry, + CitationGroupsV001 cgs, + // List sortedCitationGroupIDs, OOBibStyle style ) throws BibEntryNotFoundException { assert style.isCitationKeyCiteMarkers(); - final int nRefMarks = referenceMarkNames.size(); + cgs.createPlainBibliogaphySortedByComparator( OOBibBase.entryComparator ); - assert nRefMarks == bibtexKeys.length; - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, - "produceCitationMarkersForIsCitationKeyCiteMarkers"); + //final int nRefMarks = sortedCitationGroupIDs.size(); - String[] citMarkers = new String[nRefMarks]; - for (int i = 0; i < nRefMarks; i++) { - citMarkers[i] = - Arrays.stream(bibtexKeys[i]) - .map(citeKeyToBibEntry::get) - .map(c -> c.getCitationKey().orElse("")) + //String[] citMarkers = new String[nRefMarks]; + Map citMarkers = new HashMap<>(); + + for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + List cits = cgs.getSortedCitations(cgid); + String citMarker = + cits.stream() + .map(cit -> cit.citationKey) .collect(Collectors.joining(",")); + citMarkers.put(cgid, citMarker); } + // Finally: return citMarkers; } @@ -2038,11 +1625,9 @@ public int getOrAllocateNumber(String key) { * in bibtexKeys[i][j] * */ - private static String[] + private static Map produceCitationMarkersForIsNumberEntriesIsSortByPosition( - List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry, + CitationGroupsV001 cgs, OOBibStyle style ) throws BibEntryNotFoundException { @@ -2050,30 +1635,26 @@ public int getOrAllocateNumber(String key) { assert style.isNumberEntries(); assert style.isSortByPosition(); - final int nRefMarks = referenceMarkNames.size(); - assert (nRefMarks == bibtexKeys.length); - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeys, citeKeyToBibEntry, - "produceCitationMarkersForIsNumberEntriesIsSortByPosition"); - - String[] citMarkers = new String[nRefMarks]; - CitationNumberingState cns = new CitationNumberingState(); + cgs.createNumberedBibliogaphySortedInOrderOfAppearance(); final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - for (int i = 0; i < referenceMarkNames.size(); i++) { - - // numbers: Numbers for cited sources. (-1) for UndefinedBibtexEntry. - List numbers = - Arrays.stream(bibtexKeys[i]) - .map(citeKeyToBibEntry::get) - .map(ce -> numberPossiblyUndefinedBibEntry(ce, cns)) - .collect(Collectors.toList()); - - citMarkers[i] = - style.getNumCitationMarker(numbers, minGroupingCount, false); + Map citMarkers = new HashMap<>(); + + for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + CitationGroupsV001.CitationGroup cg = + cgs.getCitationGroup(cgid) + .orElseThrow( IllegalStateException::new ) + ; + List numbers = cg.getSortedNumbers(); + citMarkers.put( + cgid, + style.getNumCitationMarker(numbers, minGroupingCount, false) + ); } + return citMarkers; } @@ -2081,51 +1662,35 @@ public int getOrAllocateNumber(String key) { * Produce citation markers for the case of numbered citations * when the bibliography is not sorted by position. */ - private String[] + private Map produceCitationMarkersForIsNumberEntriesNotSortByPosition( - List referenceMarkNames, - String[][] bibtexKeys, - Map entries, + CitationGroupsV001 cgs, OOBibStyle style ) { assert style.isNumberEntries(); assert !style.isSortByPosition(); - final int nRefMarks = referenceMarkNames.size(); - assert (nRefMarks == bibtexKeys.length); - String[] citMarkers = new String[nRefMarks]; - - List sortedCited = - citationKeysOrNullInBibliographyOrderFromEntries(entries); + cgs.createNumberedBibliogaphySortedByComparator( entryComparator ); final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - for (int i = 0; i < referenceMarkNames.size(); i++) { - List numbers = - findCitedEntryIndices( - Arrays.asList(bibtexKeys[i]), - sortedCited - ); - citMarkers[i] = style.getNumCitationMarker(numbers, minGroupingCount, false); + Map citMarkers = new HashMap<>(); + + for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + CitationGroupsV001.CitationGroup cg = + cgs.getCitationGroup(cgid) + .orElseThrow( IllegalStateException::new ) + ; + List numbers = cg.getSortedNumbers(); + citMarkers.put( + cgid, + style.getNumCitationMarker(numbers, minGroupingCount, false) + ); } return citMarkers; } - /** - * Return type used by produceCitationMarkersForNormalStyle - */ - static class CitationMarkersWithUniqueLetters { - String[] citMarkers; - Map uniqueLetters; - - CitationMarkersWithUniqueLetters( - String[] citMarkers, - Map uniqueLetters) { - this.citMarkers = citMarkers; - this.uniqueLetters = uniqueLetters; - } - } /** * Produce citMarkers for normal @@ -2138,13 +1703,9 @@ static class CitationMarkersWithUniqueLetters { * @param entries Map BibEntry to BibDatabase. * @param style Bibliography style. */ - CitationMarkersWithUniqueLetters + private Map produceCitationMarkersForNormalStyle( - List referenceMarkNames, - String[][] bibtexKeysIn, - Map citeKeyToBibEntry, - int[] itcTypes, - Map entries, + CitationGroupsV001 cgs, OOBibStyle style ) throws BibEntryNotFoundException { @@ -2153,42 +1714,35 @@ static class CitationMarkersWithUniqueLetters { assert !style.isNumberEntries(); // Citations in (Au1, Au2 2000) form - final int nRefMarks = referenceMarkNames.size(); - assert (bibtexKeysIn.length == nRefMarks); - assert (itcTypes.length == nRefMarks); - assertAllKeysInCiteKeyToBibEntry(referenceMarkNames, bibtexKeysIn, citeKeyToBibEntry, - "produceCitationMarkersForNormalStyle"); - - BibEntry[][] cEntriesForAll = - getBibEntriesSortedWithinReferenceMarks(bibtexKeysIn, citeKeyToBibEntry, style); + CitationGroupsV001.CitedKeys sortedCitedKeys = + cgs.getCitedKeysSortedInOrderOfAppearance(); - // Update bibtexKeys to match the new sorting (within each referenceMark) - String[][] bibtexKeys = mapBibEntriesToCitationKeysOrNullForAll(cEntriesForAll); - // Note: bibtexKeys[i][j] may be null, for UndefinedBibtexEntry + normalizedCitationMarkersForNormalStyle( sortedCitedKeys, style ); + createUniqueLetters( sortedCitedKeys, cgs ); // calls distributeUniqueLetters(cgs) + cgs.createPlainBibliogaphySortedByComparator( entryComparator ); - assert (bibtexKeys.length == nRefMarks); - - String[][] normCitMarkers = - normalizedCitationMarkersForNormalStyle(cEntriesForAll, entries, style); - - Map uniqueLetters = - createUniqueLetters(bibtexKeys, normCitMarkers); // Finally, go through all citation markers, and update // those referring to entries in our current list: final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); - String[] citMarkers = new String[nRefMarks]; - - for (int i = 0; i < nRefMarks; i++) { - - final int nCitedEntries = bibtexKeys[i].length; + //String[] citMarkers = new String[nRefMarks]; + Map citMarkers = new HashMap<>(); + + for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + // for (int i = 0; i < nRefMarks; i++) { + CitationGroupsV001.CitationGroup cg = + cgs.getCitationGroup(cgid) + .orElseThrow( IllegalStateException::new ) + ; + List cits = cg.getSortedCitations(); + final int nCitedEntries = cits.size(); int[] firstLimAuthors = new int[nCitedEntries]; String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; for (int j = 0; j < nCitedEntries; j++) { - String currentKey = bibtexKeys[i][j]; // nullable + String currentKey = cits.get(j).citationKey; // nullable // firstLimAuthors will be (-1) except at the first // refMark it appears at, where a positive @@ -2207,397 +1761,92 @@ static class CitationMarkersWithUniqueLetters { seenBefore.add(currentKey); } - String uniqueLetterForKey = uniqueLetters.get(currentKey); - uniqueLetterForCitedEntry[j] = - (uniqueLetterForKey == null - ? "" - : uniqueLetterForKey); - } - - List cEntries = - Arrays.stream(cEntriesForAll[i]) - .map(OOBibBase::undefinedBibEntryToNull) - .collect(Collectors.toList()); - - citMarkers[i] = - style.getCitationMarker( - cEntries, - entries, - itcTypes[i] == OOBibBase.AUTHORYEAR_PAR, - uniqueLetterForCitedEntry, - firstLimAuthors - ); - } - - return new CitationMarkersWithUniqueLetters(citMarkers, uniqueLetters); - } - - /* *********************************** - * - * modifies both storage and presentation - * - * ***********************************/ - - /** - * Insert {@code n} spaces in a way that reference - * marks just before or just after the cursor are not affected. - * - * This is based on the observation, that starting two - * new paragraphs separates us from a reference mark on either side. - * - * The pattern used is: - * {@code safeInsertSpaces(n): para, para, left, space(n), right-delete, left(n), left-delete} - * - * @param position Where to insert (at position.getStart()) - * @param n Number of spaces to insert. - * - * @return a new cursor, covering the just-inserted spaces. - * - * This could be generalized to insert arbitrary text safely - * between two reference marks. But we do not need that now. - */ - private static XTextCursor - safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { - // Start with an empty cursor at position.getStart(); - XText text = position.getText(); - XTextCursor cursor = text.createTextCursorByRange(position.getStart()); - text.insertString(cursor, "\r\r", false); // para, para - cursor.goLeft((short) 1, false); // left - text.insertString(cursor, " ".repeat(n), false); // space(n) - cursor.goRight((short) 1, true); - cursor.setString(""); // right-delete - cursor.goLeft((short) n, false); // left(n) - cursor.goLeft((short) 1, true); - cursor.setString(""); // left-delete - cursor.goRight((short) n, true); - return cursor; - } - - /** - * Create a reference mark with the given name, at the - * end of position. - * - * To reduce the difference from the original representation, we - * only insist on having at least two characters inside reference - * marks. These may be ZERO_WIDTH_SPACE characters or other - * placeholder not likely to appear in a citation mark. - * - * This placeholder is only needed if the citation mark is - * otherwise empty (e.g. when we just create it). - * - * getFillCursorForCitationGroup yields a bracketed cursor, that - * can be used to fill in / overwrite the value inside. - * - * After each getFillCursorForCitationGroup, we require a call to - * cleanFillCursorForCitationGroup, which removes the brackets, - * unless if it would make the content less than two - * characters. If we need only one placeholder, we keep the left - * bracket. If we need two, then the content is empty. The - * removeBracketsFromEmpty parameter of - * cleanFillCursorForCitationGroup overrides this, and for empty - * citations it will remove the brackets, leaving an empty - * reference mark. The idea behind this is that we do not need to - * refill empty marks (itcTypes INVISIBLE_CIT), and the caller - * can tell us that we are dealing with one of these. - * - * Thus the only user-visible difference in citation marks is - * that instead of empty marks we use two brackets, for - * single-character marks we add a left bracket before. - * - * Character-attribute inheritance: updates inherit from the - * first character inside, not from the left. - * - * On return {@code position} is collapsed, and is after the - * inserted space, or at the end of the reference mark. - * - * @param documentConnection Connection to document. - * @param name For the reference mark. - * @param position Collapsed to its end. - * @param insertSpaceAfter We insert a space after the mark, that - * carries on format of characters from - * the original position. - * - * @param withoutBrackets Force empty reference mark (no brackets). - * For use with INVISIBLE_CIT. - * - */ - private static void - createReferenceMarkForCitationGroup( - DocumentConnection documentConnection, - String name, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets - ) - throws - CreationException, - NoDocumentException, - WrappedTargetException { - - // The cursor we received: we push it before us. - position.collapseToEnd(); - - XTextCursor cursor = safeInsertSpacesBetweenReferenceMarks(position.getEnd(), 2); - - // cursors before the first and after the last space - XTextCursor cursorBefore = - cursor.getText().createTextCursorByRange(cursor.getStart()); - XTextCursor cursorAfter = - cursor.getText().createTextCursorByRange(cursor.getEnd()); - - cursor.collapseToStart(); - cursor.goRight((short) 1, false); - // now we are between two spaces - - final String left = REFERENCE_MARK_LEFT_BRACKET; - final String right = REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); - String bracketedContent = (withoutBrackets - ? "" - : left + right); - - cursor.getText().insertString( - cursor, - bracketedContent, - true); - - /* XNamed mark = */ documentConnection.insertReferenceMark( - name, - cursor, - true // absorb - ); - - cursorBefore.goRight((short) 1, true); - cursorBefore.setString(""); - if (!insertSpaceAfter) { - cursorAfter.goLeft((short) 1, true); - cursorAfter.setString(""); - } - } - - /** - * Remove brackets, but if the result would become empty, leave - * them; if the result would be a single characer, leave the left bracket. - * - * @param removeBracketsFromEmpty is intended to force removal if - * we are working on an "Empty citation" (INVISIBLE_CIT). - */ - private static void - cleanFillCursorForCitationGroup( - DocumentConnection documentConnection, - String name, // Identifies group - boolean removeBracketsFromEmpty, - boolean alwaysRemoveBrackets - ) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - final String left = REFERENCE_MARK_LEFT_BRACKET; - final String right = REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); - - XTextContent markAsTextContent = - documentConnection.getReferenceMarkAsTextContentOrNull(name); - - if (markAsTextContent == null) { - throw new RuntimeException( - String.format( - "cleanFillCursorForCitationGroup: markAsTextContent(%s) == null", - name - )); - } - XTextCursor full = - DocumentConnection.getTextCursorOfTextContent( - markAsTextContent); - if (full == null) { - throw new RuntimeException( - "cleanFillCursorForCitationGroup: full == null" - ); - } - final String fullText = full.getString(); - final int fullTextLength = fullText.length(); - - XTextCursor alpha = full.getText().createTextCursorByRange(full); - alpha.collapseToStart(); - - XTextCursor beta = full.getText().createTextCursorByRange(full); - beta.collapseToStart(); - beta.goRight(leftLength, false); - - XTextCursor omega = full.getText().createTextCursorByRange(full); - omega.collapseToEnd(); - - if (!fullText.startsWith(left)) { - throw new RuntimeException( - String.format( - "cleanFillCursorForCitationGroup:" - + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", - name - )); - } - - if (!fullText.endsWith(right)) { - throw new RuntimeException( - String.format( - "cleanFillCursorForCitationGroup:" - + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", - name - )); - } - - final int contentLength = (fullTextLength - (leftLength + rightLength)); - if (contentLength < 0) { - throw new RuntimeException( - String.format( - "cleanFillCursorForCitationGroup: length(%s) < 0", - name - )); - } - - boolean removeRight = ( - // have at least 1 character content - (contentLength >= 1) - || ((contentLength == 0) && removeBracketsFromEmpty) - || alwaysRemoveBrackets - ); - boolean removeLeft = ( - // have at least 2 character content - (contentLength >= 2) - || ((contentLength == 0) && removeBracketsFromEmpty) - || alwaysRemoveBrackets - ); - - if (removeRight) { - omega.goLeft(rightLength, true); - omega.setString(""); - } - - if (removeLeft) { - alpha.goRight(leftLength, true); - alpha.setString(""); - } - } - - private static XTextCursor - getFillCursorForCitationGroup( - DocumentConnection documentConnection, - String name // Identifies group - ) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - final boolean debugThisFun = false; - final String left = REFERENCE_MARK_LEFT_BRACKET; - final String right = REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); - - XTextCursor full = null; - String fullText = null; - for (int i = 1; i <= 2; i++) { - XTextContent markAsTextContent = - documentConnection.getReferenceMarkAsTextContentOrNull(name); - - if (markAsTextContent == null) { - throw new RuntimeException( - String.format( - "getFillCursorForCitationGroup: markAsTextContent(%s) == null (attempt %d)", - name, i - )); - } - full = - DocumentConnection.getTextCursorOfTextContent( - markAsTextContent); - if (full == null) { - throw new RuntimeException( - String.format( - "getFillCursorForCitationGroup: full == null (attempt %d)", i - ) - ); + String uniqueLetterForKey = cits.get(j).uniqueLetter.orElse(""); + uniqueLetterForCitedEntry[j] = uniqueLetterForKey; } - fullText = full.getString(); - if (debugThisFun) { - System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); + // TODO: Cannot pass unresolved keys to style.getCitationMarker + // fall back to ungrouped citations if there is + // any unresolved. + boolean hasUnresolved = false; + for (int j = 0; j < nCitedEntries; j++) { + //String currentKey = cits.get(j).citationKey; + if (cits.get(j).db.isEmpty()) { + hasUnresolved = true; + break; + } } - if (fullText.length() >= 2) { - break; - } else { - // (fullText.length() < 2) - if (i == 2) { - throw new RuntimeException( - String.format( - "getFillCursorForCitationGroup:" - + " (fullText.length() < 2) (attempt %d)", i - ) - ); - } - // too short, recreate - if (debugThisFun) { - System.out.println("getFillCursor: too short, recreate"); + if ( hasUnresolved ) { + /* + * Some entries are unresolved. + */ + String s = ""; + for (int j = 0; j < nCitedEntries; j++) { + List cEntries = new ArrayList<>(); + Map entries = new HashMap<>(); + int[] firstLimAuthors2 = new int[1]; + String[] uniqueLetterForCitedEntry2 = new String[1]; + + String currentKey = cits.get(j).citationKey; + if (!cits.get(j).db.isEmpty()) { + BibEntry e = cits.get(j).db.get().entry; + BibDatabase d = cits.get(j).db.get().database; + cEntries.add(e); + entries.put(e,d); + firstLimAuthors2[0] = firstLimAuthors[j]; + uniqueLetterForCitedEntry2[0] = uniqueLetterForCitedEntry[j]; + s = (s + + style.getCitationMarker( + cEntries, + entries, + cg.itcType == OOBibBase.AUTHORYEAR_PAR, + uniqueLetterForCitedEntry2, + firstLimAuthors2 + )); + } else { + s = s + String.format("(Unresolved(%s))", currentKey); + } } - full.setString(""); - try { - documentConnection.removeReferenceMark(name); - } catch (NoSuchElementException ex) { - LOGGER.warn(String.format( - "getFillCursorForCitationGroup got NoSuchElementException" - + " for '%s'", name)); + citMarkers.put( cgid, s ); + } else { + /* + * All entries are resolved. + */ + List cEntries = new ArrayList<>(); + //Arrays.stream(cEntriesForAll[i]) + // .map(OOBibBase::undefinedBibEntryToNull) + // .collect(Collectors.toList()); + Map entries = new HashMap<>(); + for (int j = 0; j < nCitedEntries; j++) { + // String currentKey = cits.get(j).citationKey + BibEntry e = cits.get(j).db.get().entry; + BibDatabase d = cits.get(j).db.get().database; + cEntries.add(e); + entries.put(e,d); } - createReferenceMarkForCitationGroup( - documentConnection, - name, - full, - false, // insertSpaceAfter - false // withoutBrackets + + citMarkers.put( cgid, + style.getCitationMarker( + cEntries, + entries, + cg.itcType == OOBibBase.AUTHORYEAR_PAR, + uniqueLetterForCitedEntry, + firstLimAuthors + ) ); } } - if (full == null) { - throw new RuntimeException( - "getFillCursorForCitationGroup: full == null (after loop)" - ); - } - if (fullText == null) { - throw new RuntimeException( - "getFillCursorForCitationGroup: fullText == null (after loop)" - ); - } - - // we have at least two characters inside - XTextCursor alpha = full.getText().createTextCursorByRange(full); - alpha.collapseToStart(); - XTextCursor omega = full.getText().createTextCursorByRange(full); - omega.collapseToEnd(); - - XTextCursor beta = full.getText().createTextCursorByRange(full); - beta.collapseToStart(); - beta.goRight((short) 1, false); - beta.goRight((short) (fullText.length() - 2), true); - beta.setString(left + right); - beta.collapseToEnd(); - beta.goLeft(rightLength, false); - // drop the initial character - alpha.goRight((short) 1, true); - alpha.setString(""); - // drop the last character - omega.goLeft((short) 1, true); - omega.setString(""); - return beta; + return citMarkers; } + private static void fillCitationMarkInCursor( DocumentConnection documentConnection, - String name, // citationGroup + CitationGroupsV001 cgs, + CitationGroupsV001.CitationGroupID cgid, //String name, // citationGroup XTextCursor cursor, String citationText, boolean withText, @@ -2615,12 +1864,12 @@ static class CitationMarkersWithUniqueLetters { // when creating. String citText; - String pageInfo = - getPageInfoForReferenceMarkName(documentConnection, name); + // String pageInfo = getPageInfoForReferenceMarkName(documentConnection, name); + Optional pageInfo = cgs.getPageInfo(cgid); citText = pageInfo.isEmpty() ? citationText - : style.insertPageInfo(citationText, pageInfo); + : style.insertPageInfo(citationText, pageInfo.get()); if (withText) { // setString: All styles are removed when applying this method. @@ -2695,8 +1944,11 @@ static class CitationMarkersWithUniqueLetters { */ private void insertReferenceMark( + CitationGroupsV001 cgs, DocumentConnection documentConnection, - String name, + List citationKeys, + Optional pageInfo, + int itcType, String citationText, XTextCursor position, boolean withText, @@ -2712,27 +1964,36 @@ static class CitationMarkersWithUniqueLetters { CreationException, NoDocumentException { - createReferenceMarkForCitationGroup(documentConnection, - name, - position, - insertSpaceAfter, - !withText); + CitationGroupsV001.CitationGroupID cgid = + cgs.createCitationGroup( + documentConnection, + citationKeys, + pageInfo, + itcType, + position, + insertSpaceAfter, + !withText); if (withText) { - XTextCursor c2 = getFillCursorForCitationGroup(documentConnection, - name); - - fillCitationMarkInCursor(documentConnection, - name, - c2, - citationText, - withText, - style); - - cleanFillCursorForCitationGroup(documentConnection, - name, - !withText, - REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); + XTextCursor c2 = + cgs.getFillCursorForCitationGroup( + documentConnection, + cgid); + + fillCitationMarkInCursor( + documentConnection, + cgs, + cgid, + c2, + citationText, + withText, + style); + + cgs.cleanFillCursorForCitationGroup( + documentConnection, + cgid, + !withText, + cgs.REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); } position.collapseToEnd(); } @@ -2789,7 +2050,32 @@ void assertCitationCharacterFormatIsOK( } } + /* + * In insertCitation we receive BibEntry values from the GUI. + * + * In the document we store citations by their citation key. + * + * If the citation key is missing, the best we can do is to notify + * the user. Or the programmer, that we cannot accept such input. + * + */ + private static String insertCitationGetCitationKey(BibEntry entry) { + Optional key = entry.getCitationKey(); + if (key.isEmpty()) { + throw new RuntimeException( + "insertCitationGetCitationKey:" + + " cannot cite entries without citation key"); + } + return key.get(); + } + /** + * + * Creates a citation group from {@code entries} at the cursor, + * and (if sync is true) refreshes the citation markers and the + * bibliography. + * + * * Called from: OpenOfficePanel.pushEntries, a GUI action for * "Cite", "Cite in-text", "Cite special" and "Insert empty * citation". @@ -2799,10 +2085,6 @@ void assertCitationCharacterFormatIsOK( * Note: Undo does not remove custom properties. Presumably * neither does it reestablish them. * - * This method inserts a reference mark in the text (at the - * cursor) citing the entries, and (if sync is true) refreshes the - * citation markers and the bibliography. - * * @param entries The entries to cite. * * @param database The database the entries belong to (all of them). @@ -2812,6 +2094,7 @@ void assertCitationCharacterFormatIsOK( * we may need to refresh the document. * * @param style The bibliography style we are using. + * * @param inParenthesis Indicates whether it is an in-text * citation or a citation in parenthesis. * This is not relevant if @@ -2879,6 +2162,8 @@ void assertCitationCharacterFormatIsOK( } DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + // TODO: imposeLocalOrder boolean useUndoContext = true; @@ -2901,17 +2186,19 @@ void assertCitationCharacterFormatIsOK( sortBibEntryListForMulticite(entries, style); - String keyString = + /* + * String keyString = + * entries.stream() + * .map(entry -> entry.getCitationKey().orElse("")) + * .collect(Collectors.joining(",")); + */ + List citationKeys = entries.stream() - .map(entry -> entry.getCitationKey().orElse("")) - .collect(Collectors.joining(",")); + .map(OOBibBase::insertCitationGetCitationKey) + .collect(Collectors.toList()); + // Generate unique mark-name int itcType = citationTypeFromOptions(withText, inParenthesis); - String newName = - getUniqueReferenceMarkName( - documentConnection, - keyString, - itcType); // If we should store metadata for page info, do that now: // @@ -2924,10 +2211,12 @@ void assertCitationCharacterFormatIsOK( // sortBibEntryListForMulticite call; (2) On // "Separate" it belongs to nobody. // + /* if (pageInfo != null) { LOGGER.info("Storing page info: " + pageInfo); documentConnection.setCustomProperty(newName, pageInfo); } + */ // else: branch ??? // Note: if (pageInfo is null), we might inadvertently // pick up a pageInfo from an earlier citation. The user @@ -2960,9 +2249,13 @@ void assertCitationCharacterFormatIsOK( if (citeText.equals("")) { citeText = "[?]"; } + insertReferenceMark( + cgs, documentConnection, - newName, + citationKeys, + Optional.ofNullable(pageInfo), + itcType, citeText, cursor, withText, @@ -2980,8 +2273,10 @@ void assertCitationCharacterFormatIsOK( if (sync) { // To account for numbering and for uniqueLetters, we // must refresh the cite markers: + /* CitationGroupsV001 */ //cgs = new CitationGroupsV001(documentConnection); ProduceCitationMarkersResult x = produceCitationMarkers( + //cgs, documentConnection, allBases, style @@ -2992,18 +2287,20 @@ void assertCitationCharacterFormatIsOK( applyNewCitationMarkers( documentConnection, - x.jabRefReferenceMarkNamesSortedByPosition, + // x.jabRefReferenceMarkNamesSortedByPosition, + x.cgs, x.citMarkers, - x.itcTypes, + //x.itcTypes, style); // Insert it at the current position: rebuildBibTextSection( documentConnection, style, - x.jabRefReferenceMarkNamesSortedByPosition, - x.uniqueLetters, - x.fce + x.getBibliography() + // x.jabRefReferenceMarkNamesSortedByPosition, + // x.uniqueLetters, + // x.fce ); } finally { documentConnection.unlockControllers(); @@ -3039,61 +2336,16 @@ void assertCitationCharacterFormatIsOK( * * **************************************************/ - static class ExportCitedHelperResult { - /** - * null: not done; isempty: no unresolved - */ - List unresolvedKeys; - BibDatabase newDatabase; - } - - /** - * Helper for GUI action "Export cited" - * - * Refreshes citation markers, (although the user did not ask for that). - * Does not refresh the bibliography. - */ - public ExportCitedHelperResult exportCitedHelper( - List databases, - OOBibStyle style - ) - throws - WrappedTargetException, - NoSuchElementException, - NoDocumentException, - UndefinedCharacterFormatException, - UnknownPropertyException, - PropertyVetoException, - IOException, - CreationException, - BibEntryNotFoundException, - InvalidStateException { - - ExportCitedHelperResult res = new ExportCitedHelperResult(); - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - try { - documentConnection.enterUndoContext("Changes during \"Export cited\""); - - ProduceCitationMarkersResult x = - produceCitationMarkers( - documentConnection, - databases, - style); - res.unresolvedKeys = x.unresolvedKeys; - res.newDatabase = this.generateDatabase(databases); - } finally { - documentConnection.leaveUndoContext(); - } - return res; - } /** * Visit each reference mark in referenceMarkNames, overwrite its * text content. * - * After each insertReferenceMark call check if we lost the + * After each fillCitationMarkInCursor call check if we lost the * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. * + * + * * @param referenceMarkNames Reference mark names * * @param citMarkers Corresponding text for each reference mark, @@ -3107,9 +2359,8 @@ public ExportCitedHelperResult exportCitedHelper( private void applyNewCitationMarkers( DocumentConnection documentConnection, - List referenceMarkNames, - String[] citMarkers, - int[] types, + CitationGroupsV001 cgs, + Map citMarkers, OOBibStyle style ) throws @@ -3120,9 +2371,12 @@ public ExportCitedHelperResult exportCitedHelper( WrappedTargetException, PropertyVetoException { - final int nRefMarks = referenceMarkNames.size(); - assert (citMarkers.length == nRefMarks); - assert (types.length == nRefMarks); + // CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + // CitationGroupsV001 cgs = x.cgs; + + // final int nRefMarks = referenceMarkNames.size(); + // assert (citMarkers.length == nRefMarks); + // assert (types.length == nRefMarks); final boolean hadBibSection = (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) != null); @@ -3135,16 +2389,20 @@ public ExportCitedHelperResult exportCitedHelper( // catastrophic consequences for the user. boolean mustTestCharFormat = style.isFormatCitations(); - for (int i = 0; i < nRefMarks; i++) { + for (CitationGroupsV001.CitationGroupID cgid : cgs.getCitationGroupIDs() ) { - final String name = referenceMarkNames.get(i); + CitationGroupsV001.CitationGroup cg = + cgs.getCitationGroup(cgid) + .orElseThrow(IllegalStateException::new) + ; - boolean withText = (types[i] != OOBibBase.INVISIBLE_CIT); + boolean withText = (cg.itcType != OOBibBase.INVISIBLE_CIT); if (withText) { + XTextCursor cursor = - getFillCursorForCitationGroup( + cgs.getFillCursorForCitationGroup( documentConnection, - name // Identifies group + cgid // Identifies group ); if (mustTestCharFormat) { @@ -3154,36 +2412,28 @@ public ExportCitedHelperResult exportCitedHelper( fillCitationMarkInCursor( documentConnection, - name, // citationGroup + cgs, + cgid, cursor, - citMarkers[i], // citationText, + citMarkers.get(cgid), // citationText withText, style ); - cleanFillCursorForCitationGroup(documentConnection, - name, - !withText, - REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); + cgs.cleanFillCursorForCitationGroup( + documentConnection, + cgid, + !withText, + cgs.REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); } if (hadBibSection && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { - // if (true) { - // Overwriting text already there is too harsh. - // I am making it an error, to see if we ever get here. - throw new RuntimeException( - "OOBibBase.applyNewCitationMarkers:" - + " just overwrote the bibliography section marker. Sorry."); - // } else { - // We have overwritten the marker for the start of the reference list. - // We need to add it again. - // --- - // cursor.collapseToEnd(); - // OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - // documentConnection.insertBookmark(OOBibBase.BIB_SECTION_NAME, cursor, true); - // cursor.collapseToEnd(); - // } + // Overwriting text already there is too harsh. + // I am making it an error, to see if we ever get here. + throw new RuntimeException( + "OOBibBase.applyNewCitationMarkers:" + + " just overwrote the bibliography section marker. Sorry."); } } } @@ -3192,37 +2442,42 @@ public ExportCitedHelperResult exportCitedHelper( * The main field is citMarkers, the rest is for reuse in caller. */ static class ProduceCitationMarkersResult { - /** JabRef reference mark names, sorted by position */ - List jabRefReferenceMarkNamesSortedByPosition; - /** AUTHORYEAR_PAR, AUTHORYEAR_INTEXT or INVISIBLE_CIT */ - int[] itcTypes; - /** citation keys */ - String[][] bibtexKeys; + + CitationGroupsV001 cgs; + /** citation markers */ - String[] citMarkers; - /** Letters making cited sources unique. */ - Map uniqueLetters; - /** Results from findCitedEntries */ - FindCitedEntriesResult fce; - /** Citation keys not found in databases */ - List unresolvedKeys; + Map citMarkers; ProduceCitationMarkersResult( - List jabRefReferenceMarkNamesSortedByPosition, - int[] itcTypes, - String[][] bibtexKeys, - String[] citMarkers, - Map uniqueLetters, - FindCitedEntriesResult fce, - List unresolvedKeys + CitationGroupsV001 cgs, + Map citMarkers ) { - this.jabRefReferenceMarkNamesSortedByPosition = jabRefReferenceMarkNamesSortedByPosition; - this.itcTypes = itcTypes; - this.bibtexKeys = bibtexKeys; + this.cgs = cgs; this.citMarkers = citMarkers; - this.uniqueLetters = uniqueLetters; - this.fce = fce; - this.unresolvedKeys = unresolvedKeys; + if ( cgs.getBibliography().isEmpty() ) { + throw new RuntimeException( + "ProduceCitationMarkersResult.constructor: cgs does not have a bibliography"); + } + } + + public CitationGroupsV001.CitedKeys + getBibliography() { + if ( cgs.getBibliography().isEmpty() ) { + throw new RuntimeException( + "ProduceCitationMarkersResult.getBibliography: cgs does not have a bibliography"); + } + return cgs.getBibliography().get(); + } + + public List getUnresolvedKeys() { + CitationGroupsV001.CitedKeys bib = getBibliography(); + List unresolvedKeys = new ArrayList<>(); + for (CitationGroupsV001.CitedKey ck : bib.values()) { + if ( ck.db.isEmpty() ) { + unresolvedKeys.add(ck.key); + } + } + return unresolvedKeys; } } @@ -3237,31 +2492,50 @@ static class ProduceCitationMarkersResult { IllegalArgumentException, NoSuchElementException, BibEntryNotFoundException, - NoDocumentException { + NoDocumentException, + UnknownPropertyException { - // Normally we sort the reference marks according to their - // order of appearance: + CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); - List jabRefReferenceMarkNamesSortedByPosition = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - List referenceMarkNames = jabRefReferenceMarkNamesSortedByPosition; + //final int nRefMarks = sortedCitationGroupIDs.size(); - final int nRefMarks = referenceMarkNames.size(); + cgs.lookupEntriesInDatabases( databases ); - int[] itcTypes = new int[nRefMarks]; - String[][] bibtexKeys = new String[nRefMarks][]; - parseRefMarkNamesToArrays(referenceMarkNames, itcTypes, bibtexKeys); + // requires cgs.lookupEntryInDatabases: needs BibEntry data + cgs.imposeLocalOrderByComparator( comparatorForMulticite(style) ); + + // Normally we sort the reference marks according to their + // order of appearance. + // + // This only depends on location of ranges and footnote marks + // in the text. Does not touch localOrder, only order between + // reference marks. + // + // Question: is there a case when we do not need order-of-appearance? + // + // style.isCitationKeyCiteMarkers() : ??? + // style.isNumberEntries() && style.isSortByPosition() : needs order-of-appearance for numbering + // style.isNumberEntries() && !style.isSortByPosition() : ??? + // produceCitationMarkersForNormalStyle : needs order-of-appearance for uniqueLetters + // + { + boolean mapFootnotesToFootnoteMarks = true; + List + sortedCitationGroupIDs = + getVisuallySortedCitationGroupIDs( + cgs, + documentConnection, + mapFootnotesToFootnoteMarks + ); + cgs.setGlobalOrder( sortedCitationGroupIDs ); + } + // localOrder and globalOrder together gives us order-of-appearance of citations - FindCitedEntriesResult fce = - findCitedEntries( - findCitedKeys(documentConnection), - databases - ); - // fce.entries are in same order as returned by findCitedKeys // citMarkers[i] = what goes in the text at referenceMark[i] - String[] citMarkers; + // String[] citMarkers; + Map citMarkers; // fill citMarkers Map uniqueLetters = new HashMap<>(); @@ -3269,47 +2543,38 @@ static class ProduceCitationMarkersResult { if (style.isCitationKeyCiteMarkers()) { citMarkers = produceCitationMarkersForIsCitationKeyCiteMarkers( - referenceMarkNames, - bibtexKeys, - fce.citeKeyToBibEntry, - style); + cgs, + //sortedCitationGroupIDs, + style + ); } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { citMarkers = produceCitationMarkersForIsNumberEntriesIsSortByPosition( - referenceMarkNames, - bibtexKeys, - fce.citeKeyToBibEntry, + cgs, + //sortedCitationGroupIDs, style); } else { citMarkers = produceCitationMarkersForIsNumberEntriesNotSortByPosition( - referenceMarkNames, - bibtexKeys, - fce.entries, + cgs, style); } } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { - CitationMarkersWithUniqueLetters x = + citMarkers = produceCitationMarkersForNormalStyle( - referenceMarkNames, - bibtexKeys, - fce.citeKeyToBibEntry, - itcTypes, - fce.entries, + cgs, + // referenceMarkNames, + // bibtexKeys, + // fce.citeKeyToBibEntry, + // itcTypes, + // fce.entries, style); - citMarkers = x.citMarkers; - uniqueLetters = x.uniqueLetters; } return new ProduceCitationMarkersResult( - jabRefReferenceMarkNamesSortedByPosition, - itcTypes, - bibtexKeys, - citMarkers, - uniqueLetters, - fce, - unresolvedKeysFromEntries(fce.entries) + cgs, // has bibliography as a side effect + citMarkers ); } @@ -3319,6 +2584,43 @@ static class ProduceCitationMarkersResult { * * **************************************************/ + /** + * Return bibliography entries sorted according to the order of + * first appearance in referenceMarkNames. + * + * @param referenceMarkNames Names of reference marks. + * @param citeKeyToBibEntry Helps to find the entries + * @return LinkedHashMap from BibEntry to BibDatabase with + * iteration order as first appearance in referenceMarkNames. + * + * Note: Within citation group (a reference mark) the order is + * as appears there. + * + * Used by rebuildBibTextSection + */ + private //Map + List + sortEntriesByRefMarkNames( + CitationGroupsV001 cgs + ) { + Set seen = new HashSet<>(); + + List res = new ArrayList<>(); + for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + List cits = cgs.getSortedCitations(cgid); + + // no need to look in the database again + for (CitationGroupsV001.Citation cit : cgs.getSortedCitations(cgid)) { + String key = cit.citationKey; + if (!seen.contains(key)) { + res.add(cit); + seen.add(key); + } + } + } + return res; + } + /** * Rebuilds the bibliography. * @@ -3329,9 +2631,10 @@ static class ProduceCitationMarkersResult { rebuildBibTextSection( DocumentConnection documentConnection, OOBibStyle style, - List jabRefReferenceMarkNamesSortedByPosition, - final Map uniqueLetters, - FindCitedEntriesResult fce + CitationGroupsV001.CitedKeys bibliography + // List jabRefReferenceMarkNamesSortedByPosition, + // final Map uniqueLetters, + // FindCitedEntriesResult fce ) throws NoSuchElementException, @@ -3342,27 +2645,30 @@ static class ProduceCitationMarkersResult { UnknownPropertyException, UndefinedParagraphFormatException { - Map entries; - - if (style.isSortByPosition()) { - // We need to sort the entries according to their order of appearance: - entries = - sortEntriesByRefMarkNames( - jabRefReferenceMarkNamesSortedByPosition, - fce.citeKeyToBibEntry, - fce.entries - ); - } else { - entries = sortEntriesByComparator(fce.entries, entryComparator); - } - + /* + * Map entries; + * + * if (style.isSortByPosition()) { + * // We need to sort the entries according to their order of appearance: + * entries = + * sortEntriesByRefMarkNames( + * jabRefReferenceMarkNamesSortedByPosition, + * fce.citeKeyToBibEntry, + * fce.entries + * ); + * } else { + * entries = sortEntriesByComparator(fce.entries, entryComparator); + * } + */ clearBibTextSectionContent2(documentConnection); populateBibTextSection( documentConnection, - entries, - style, - uniqueLetters); + bibliography, + // entries, + style + // uniqueLetters + ); } /** @@ -3381,11 +2687,9 @@ static class ProduceCitationMarkersResult { insertFullReferenceAtCursor( DocumentConnection documentConnection, XTextCursor cursor, - Map entries, + CitationGroupsV001.CitedKeys bibliography, OOBibStyle style, - String parFormat, - final Map uniqueLetters - ) + String parFormat) throws UndefinedParagraphFormatException, IllegalArgumentException, @@ -3393,51 +2697,83 @@ static class ProduceCitationMarkersResult { PropertyVetoException, WrappedTargetException { - int number = 1; - for (Map.Entry entry : entries.entrySet()) { + for (CitationGroupsV001.CitedKey ck : bibliography.values()) { - // skip unresolved entries - if (entry.getKey() instanceof UndefinedBibtexEntry) { + int number = 1; + int nUnresolved = 0; + + // for (Map.Entry entry : entries.entrySet()) { + // + // Optional db = ck.db; + // + // BibEntry bibentry = entry.getKey(); + // BibDatabase database = entry.getValue(); + // // skip unresolved entries + // if (bibentry instanceof UndefinedBibtexEntry) { + // continue; + // } + + if ( ck.db.isEmpty() ) { + // skip unresolved entries + nUnresolved++; continue; - } + } else { + + BibEntry bibentry = ck.db.get().entry; + BibDatabase database = ck.db.get().database; + + OOUtil.insertParagraphBreak(documentConnection.xText, cursor); + + // insert marker + if (style.isNumberEntries()) { + + if ( ck.number.isEmpty() ) { + throw new RuntimeException( + "insertFullReferenceAtCursor: numbered style, but found unnumbered entry" + ); + } else { + if ( ck.number.get() != (number + nUnresolved) ) { + throw new RuntimeException( + "insertFullReferenceAtCursor: numbering is not in sync" + ); + } + } + + // Note: minGroupingCount is pointless here, we are + // formatting a single entry. + // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + int minGroupingCount = 2; + List numbers = Collections.singletonList(number++); + String marker = + style.getNumCitationMarker( + numbers, + minGroupingCount, + true); + + OOUtil.insertTextAtCurrentLocation( + documentConnection.xText, + cursor, + marker, + Collections.emptyList() + ); + } - OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - - // insert marker - if (style.isNumberEntries()) { - // Note: minGroupingCount is pointless here, we are - // formatting a single entry. - // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - int minGroupingCount = 2; - List numbers = Collections.singletonList(number++); - String marker = - style.getNumCitationMarker( - numbers, - minGroupingCount, - true); - - OOUtil.insertTextAtCurrentLocation( + // insert the actual details. + Layout layout = style.getReferenceFormat(bibentry.getType()); + layout.setPostFormatter(POSTFORMATTER); + OOUtil.insertFullReferenceAtCurrentLocation( documentConnection.xText, cursor, - marker, - Collections.emptyList() + layout, + parFormat, + bibentry, + database, + ck.uniqueLetter.orElse(null) + // uniqueLetters.get(bibentry + // .getCitationKey() + // .orElse(null)) ); } - - // insert the actual details. - Layout layout = style.getReferenceFormat(entry.getKey().getType()); - layout.setPostFormatter(POSTFORMATTER); - OOUtil.insertFullReferenceAtCurrentLocation( - documentConnection.xText, - cursor, - layout, - parFormat, - entry.getKey(), - entry.getValue(), - uniqueLetters.get(entry.getKey() - .getCitationKey() - .orElse(null)) - ); } } @@ -3518,9 +2854,11 @@ static class ProduceCitationMarkersResult { private void populateBibTextSection( DocumentConnection documentConnection, - Map entries, - OOBibStyle style, - final Map uniqueLetters) + CitationGroupsV001.CitedKeys bibliography, + // Map entries, + OOBibStyle style + // final Map uniqueLetters + ) throws NoSuchElementException, WrappedTargetException, @@ -3550,10 +2888,11 @@ static class ProduceCitationMarkersResult { insertFullReferenceAtCursor( documentConnection, cursor, - entries, + bibliography, + // entries, style, - refParaFormat, - uniqueLetters + refParaFormat + // uniqueLetters ); documentConnection.insertBookmark( @@ -3567,9 +2906,11 @@ static class ProduceCitationMarkersResult { * * GUI level * - **************************/ + * *************************/ - /* GUI: Manage citations */ + /* + * GUI: Manage citations + */ /** * GUI action "Merge citations" @@ -3601,28 +2942,35 @@ static class ProduceCitationMarkersResult { final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + try { documentConnection.enterUndoContext("Merge citations"); - boolean madeModifications = false; - - // The testing for whitespace-only between (pivot) and (pivot+1) assumes that - // referenceMarkNames are in textual order: textually consecutive pairs - // must appear as neighbours (and in textual order). - // We have a bit of a clash here: referenceMarkNames is sorted by visual position, - // but we are testing if they are textually neighbours. - // In a two-column layout - // | a | c | - // | b | d | - // abcd is the textual order, but the visual order is acbd. - // So we will not find out that a and b are only separated by white space. - List referenceMarkNames = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - - final int nRefMarks = referenceMarkNames.size(); - int[] itcTypes = new int[nRefMarks]; - String[][] bibtexKeys = new String[nRefMarks][]; - parseRefMarkNamesToArrays(referenceMarkNames, itcTypes, bibtexKeys); + boolean madeModifications = false; + + // The testing for whitespace-only between (pivot) and (pivot+1) assumes that + // referenceMarkNames are in textual order: textually consecutive pairs + // must appear as neighbours (and in textual order). + // We have a bit of a clash here: referenceMarkNames is sorted by visual position, + // but we are testing if they are textually neighbours. + // In a two-column layout + // | a | c | + // | b | d | + // abcd is the textual order, but the visual order is acbd. + // So we will not find out that a and b are only separated by white space. + + boolean mapFootnotesToFootnoteMarks = false; + List referenceMarkNames = + // TODO: we probably want textually sorted partions here + getVisuallySortedCitationGroupIDs(cgs, + documentConnection, + mapFootnotesToFootnoteMarks); + + final int nRefMarks = referenceMarkNames.size(); + // int[] itcTypes = new int[nRefMarks]; + // String[][] bibtexKeys = new String[nRefMarks][]; + // parseRefMarkNamesToArrays(referenceMarkNames, itcTypes, bibtexKeys); try { @@ -3631,34 +2979,47 @@ static class ProduceCitationMarkersResult { } /* - * joinableGroups collects lists of indices of referenceMarkNames + * joinableGroups collects lists of CitationGroup values * that we think are joinable. * * joinableGroupsCursors provides the range for each group */ - List> joinableGroups = new ArrayList<>(); + List> joinableGroups = new ArrayList<>(); List joinableGroupsCursors = new ArrayList<>(); + // Since we only join groups with identical itcTypes, we + // can get itcType from the first element of each + // joinableGroup. + // + // List itcTypes = new ArrayList<>(); + if (referenceMarkNames.size() > 0) { - // current group - List currentGroup = new ArrayList<>(); + // current group of CitationGroup values + List currentGroup = new ArrayList<>(); XTextCursor currentGroupCursor = null; XTextCursor cursorBetween = null; - Integer prev = null; + // Integer prev = null; + CitationGroupsV001.CitationGroup prev = null; XTextRange prevRange = null; - for (int i = 0; i < referenceMarkNames.size(); i++) { - final String name = referenceMarkNames.get(i); - XTextRange currentRange = documentConnection.getReferenceMarkRangeOrNull(name); + for (CitationGroupsV001.CitationGroupID cgid : referenceMarkNames) { + CitationGroupsV001.CitationGroup cg = + cgs.getCitationGroup(cgid) + .orElseThrow( IllegalStateException::new ); + + // for (int i = 0; i < referenceMarkNames.size(); i++) { + // final String name = referenceMarkNames.get(i); + + XTextRange currentRange = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); Objects.requireNonNull(currentRange); boolean addToGroup = true; /* - * Decide if we add name to the group + * Decide if we add cg to the group */ // Only combine (Author 2000) type citations - if (itcTypes[i] != OOBibBase.AUTHORYEAR_PAR + if (cg.itcType != OOBibBase.AUTHORYEAR_PAR // allow "Author (2000)" // && itcTypes[i] != OOBibBase.AUTHORYEAR_INTEXT ) { @@ -3668,7 +3029,7 @@ static class ProduceCitationMarkersResult { // Even if we combine AUTHORYEAR_INTEXT citations, we // would not mix them with AUTHORYEAR_PAR if (addToGroup && (prev != null)) { - if (itcTypes[i] != itcTypes[prev]) { + if (cg.itcType != prev.itcType) { addToGroup = false; } } @@ -3749,7 +3110,7 @@ static class ProduceCitationMarkersResult { * * Can it start a new group? */ - boolean canStartGroup = (itcTypes[i] == OOBibBase.AUTHORYEAR_PAR); + boolean canStartGroup = (cg.itcType == OOBibBase.AUTHORYEAR_PAR); if (!addToGroup) { // close currentGroup @@ -3767,7 +3128,7 @@ static class ProduceCitationMarkersResult { if (addToGroup || canStartGroup) { // Add the current entry to a group. - currentGroup.add(i); + currentGroup.add(cg); // ... and start new cursorBetween // Set up cursorBetween // @@ -3819,7 +3180,7 @@ static class ProduceCitationMarkersResult { : "") ); } - prev = i; + prev = cg; prevRange = currentRange; } } @@ -3841,75 +3202,66 @@ static class ProduceCitationMarkersResult { */ for (int gi = 0; gi < joinableGroups.size(); gi++) { - List allKeys = new ArrayList<>(); + /* + * Join those in joinableGroups.get(gi) + */ + + // + // Note: we are taking ownership of the citations (by + // adding to newGroupCitations, then removing + // the original CitationGroup values) + // + // pageInfos currently belong to the CitationGroup, + // but it is not clear how should handle them here. + // + List newGroupCitations = new ArrayList<>(); + List> pageInfos = new ArrayList<>(); + int itcType = joinableGroups.get(gi).get(0).itcType; + for (int gj = 0; gj < joinableGroups.get(gi).size(); gj++) { - int rk = joinableGroups.get(gi).get(gj); - allKeys.addAll(Arrays.asList(bibtexKeys[rk])); + CitationGroupsV001.CitationGroup rk = joinableGroups.get(gi).get(gj); + //newGroupCitations.addAll(Arrays.asList(bibtexKeys[rk])); + newGroupCitations.addAll( rk.citations); + pageInfos.add( rk.pageInfo ); } - // Note: silently drops duplicate keys. - // What if they have different pageInfo fields? + // Try to do something of the pageInfo values. + // + String pageInfo = ""; + pageInfos.stream() + .filter(pi -> pi.isPresent()) + .map(pi -> pi.get()) + .distinct() + .collect(Collectors.joining("; ")); - // combineCiteMarkers: merging for same citation keys, - // but different pageInfo looses information. - List uniqueKeys = - (allKeys.stream() - .distinct() - .collect(Collectors.toList())); + /* + * joinGroups( documentConnection, oldGroups, cursor, removeOldGroups ) + */ // Remove the old referenceMarkNames from the document. // We might want to do this via backends. for (int gj = 0; gj < joinableGroups.get(gi).size(); gj++) { - int rk = joinableGroups.get(gi).get(gj); - documentConnection.removeReferenceMark(referenceMarkNames.get(rk)); + // int rk = joinableGroups.get(gi).get(gj); + // documentConnection.removeReferenceMark(referenceMarkNames.get(rk)); + cgs.removeCitationGroups( joinableGroups.get(gi), documentConnection ); } XTextCursor textCursor = joinableGroupsCursors.get(gi); // Also remove the spaces between. textCursor.setString(""); - boolean oldStrategy = false; - List entries; - String keyString; - if (oldStrategy) { - // Note: citation keys not found are silently left - // out from the combined reference mark - // name. Losing information. - entries = lookupEntriesInDatabasesSkipMissing(uniqueKeys, databases); - entries.sort(new FieldComparator(StandardField.YEAR)); - keyString = - entries.stream() - .map(c -> c.getCitationKey().orElse("")) - .collect(Collectors.joining(",")); - } else { - FindCitedEntriesResult fcr = findCitedEntries(uniqueKeys, databases); - // entries contains UndefinedBibtexEntry for keys not found in databases - entries = new ArrayList<>(); - for (Map.Entry kv : fcr.entries.entrySet()) { - entries.add(kv.getKey()); - } - // Now we do not sort the entries here. - // - // TODO: the sorting skipped here should be done - // when creating the presentation. Check if it is there. - // - // entries.sort(new FieldComparator(StandardField.YEAR)); - keyString = - entries.stream() - .map(OOBibBase::recoverCitationKeyFromPossiblyUndefinedBibEntry) - .collect(Collectors.joining(",")); - } + List citationKeys = + newGroupCitations.stream() + .map(cit -> cit.citationKey) + .collect(Collectors.toList()); // Insert reference mark: - String newName = - getUniqueReferenceMarkName( - documentConnection, - keyString, - OOBibBase.AUTHORYEAR_PAR); - insertReferenceMark( + cgs, documentConnection, - newName, + citationKeys, + Optional.ofNullable(pageInfo == "" ? null : pageInfo), + itcType, // OOBibBase.AUTHORYEAR_PAR, // itcType "tmp", textCursor, true, // withText @@ -3927,10 +3279,9 @@ static class ProduceCitationMarkersResult { } if (madeModifications) { - // List jabRefReferenceMarkNamesSortedByPosition = - // getJabRefReferenceMarkNamesSortedByPosition(documentConnection); ProduceCitationMarkersResult x = produceCitationMarkers( + // cgs, documentConnection, databases, style @@ -3939,12 +3290,12 @@ static class ProduceCitationMarkersResult { if (useLockControllers) { documentConnection.lockControllers(); } - // refreshCiteMarkers(databases, style, jabRefReferenceMarkNamesSortedByPosition); applyNewCitationMarkers( documentConnection, - x.jabRefReferenceMarkNamesSortedByPosition, + //x.jabRefReferenceMarkNamesSortedByPosition, + x.cgs, x.citMarkers, - x.itcTypes, + //x.itcTypes, style); } finally { if (useLockControllers) { @@ -3988,90 +3339,133 @@ static class ProduceCitationMarkersResult { final boolean useLockControllers = true; DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + try { documentConnection.enterUndoContext("Separate citations"); - boolean madeModifications = false; - List names = - getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - try { - if (useLockControllers) { - documentConnection.lockControllers(); - } + boolean madeModifications = false; - int pivot = 0; - boolean setCharStyleTested = false; - XNameAccess nameAccess = documentConnection.getReferenceMarks(); - - while (pivot < (names.size())) { - XTextRange range1 = - DocumentConnection.asTextContent( - nameAccess.getByName(names.get(pivot))) - .getAnchor(); - - XTextCursor textCursor = - range1.getText().createTextCursorByRange(range1); - - // If we are supposed to set character format for - // citations, test this before making any changes. This - // way we can throw an exception before any reference - // marks are removed, preventing damage to the user's - // document: - if (!setCharStyleTested) { - assertCitationCharacterFormatIsOK(textCursor, style); - setCharStyleTested = true; - } + // boolean mapFootnotesToFootnoteMarks = true; + // List names = + // getVisuallySortedCitationGroupIDs(cgs, documentConnection, mapFootnotesToFootnoteMarks); + // + // {@code names} does not need to be sorted. + List names = new ArrayList<>(cgs.getCitationGroupIDs()); - List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); - if (keys.size() <= 1) { - pivot++; - continue; + try { + if (useLockControllers) { + documentConnection.lockControllers(); } - documentConnection.removeReferenceMark(names.get(pivot)); + int pivot = 0; + boolean setCharStyleTested = false; + // XNameAccess nameAccess = documentConnection.getReferenceMarks(); - // Insert bookmark for each key - int last = keys.size() - 1; - int i = 0; - for (String key : keys) { - // Note: instead of generating a new name, we should explicitly - // recover the original. Otherwise ... - String newName = getUniqueReferenceMarkName( - documentConnection, - key, - OOBibBase.AUTHORYEAR_PAR); + while (pivot < (names.size())) { + CitationGroupsV001.CitationGroupID cgid = names.get(pivot); + CitationGroupsV001.CitationGroup cg = + cgs.getCitationGroup(cgid) + .orElseThrow(IllegalStateException::new); - boolean insertSpaceAfter = (i != last); - insertReferenceMark( - documentConnection, - newName, - "tmp", - textCursor, - /* withText should be itcType != OOBibBase.INVISIBLE_CIT */ - true, - style, - insertSpaceAfter - ); - textCursor.collapseToEnd(); - i++; - } - madeModifications = true; + /* XTextRange range1 = + * DocumentConnection.asTextContent( + * nameAccess.getByName(names.get(pivot))) + * .getAnchor(); + */ + XTextRange range1 = cgs.getReferenceMarkRangeOrNull(documentConnection,cgid); + + XTextCursor textCursor = + range1.getText().createTextCursorByRange(range1); + + // If we are supposed to set character format for + // citations, test this before making any changes. This + // way we can throw an exception before any reference + // marks are removed, preventing damage to the user's + // document: + if (!setCharStyleTested) { + assertCitationCharacterFormatIsOK(textCursor, style); + setCharStyleTested = true; + } - pivot++; - } - } finally { - if (useLockControllers) { - documentConnection.unlockControllers(); + Optional oldPageInfo = cg.pageInfo; + List cits=cg.citations; + if ( cits.size() <= 1 ) { + pivot++; + continue; + } + + List keys = + cits.stream().map(cit -> cit.citationKey).collect(Collectors.toList()); + + /* + List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); + if (keys.size() <= 1) { + pivot++; + continue; + } + */ + + cgs.removeCitationGroup( cg, documentConnection ); + // documentConnection.removeReferenceMark(names.get(pivot)); + + // Now we own the content of cits + + // Insert bookmark for each key + int last = keys.size() - 1; + int i = 0; + for (String key : keys) { + // Note: instead of generating a new name, we should explicitly + // recover the original. Otherwise ... + /* + String newName = getUniqueReferenceMarkName( + documentConnection, + key, + OOBibBase.AUTHORYEAR_PAR); + */ + + // Note: by using insertReferenceMark (and not something + // that accepts List, we lose the extra + // info stored in teh citations. + // We just reread below. + List citationKeys = new ArrayList<>(1); + citationKeys.add( key ); + boolean insertSpaceAfter = (i != last); + insertReferenceMark( + cgs, + documentConnection, + citationKeys, + ((i==last) ? oldPageInfo : Optional.empty()), // put into the last one + OOBibBase.AUTHORYEAR_PAR, // itcType, + //newName, + "tmp", + textCursor, + /* withText should be itcType != OOBibBase.INVISIBLE_CIT */ + true, + style, + insertSpaceAfter + ); + textCursor.collapseToEnd(); + i++; + } + madeModifications = true; + + pivot++; + } + } finally { + if (useLockControllers) { + documentConnection.unlockControllers(); + } } - } - if (madeModifications) { - // List jabRefReferenceMarkNamesSortedByPosition = - // getJabRefReferenceMarkNamesSortedByPosition(documentConnection); - ProduceCitationMarkersResult x = - produceCitationMarkers( - documentConnection, - databases, - style - ); + + if (madeModifications) { + // List jabRefReferenceMarkNamesSortedByPosition = + // getJabRefReferenceMarkNamesSortedByPosition(documentConnection); + ProduceCitationMarkersResult x = + produceCitationMarkers( + documentConnection, + databases, + style + ); try { if (useLockControllers) { documentConnection.lockControllers(); @@ -4079,9 +3473,10 @@ static class ProduceCitationMarkersResult { // refreshCiteMarkers(databases, style, jabRefReferenceMarkNamesSortedByPosition); applyNewCitationMarkers( documentConnection, - x.jabRefReferenceMarkNamesSortedByPosition, + //x.jabRefReferenceMarkNamesSortedByPosition, + x.cgs, x.citMarkers, - x.itcTypes, + //x.itcTypes, style); } finally { if (useLockControllers) { @@ -4094,6 +3489,69 @@ static class ProduceCitationMarkersResult { } } + + static class ExportCitedHelperResult { + /** + * null: not done; isempty: no unresolved + */ + List unresolvedKeys; + BibDatabase newDatabase; + ExportCitedHelperResult( + List unresolvedKeys, + BibDatabase newDatabase + ) { + this.unresolvedKeys = unresolvedKeys; + this.newDatabase = newDatabase; + } + } + + /** + * Helper for GUI action "Export cited" + * + * Refreshes citation markers, (although the user did not ask for that). + * Actually, we only call produceCitationMarkers to get x.unresolvedKeys + * + * Does not refresh the bibliography. + */ + public ExportCitedHelperResult exportCitedHelper( + List databases, + OOBibStyle style + ) + throws + WrappedTargetException, + NoSuchElementException, + NoDocumentException, + UndefinedCharacterFormatException, + UnknownPropertyException, + PropertyVetoException, + IOException, + CreationException, + BibEntryNotFoundException, + InvalidStateException { + + // ExportCitedHelperResult res = new ExportCitedHelperResult(); + DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + try { + documentConnection.enterUndoContext("Changes during \"Export cited\""); + + // CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + /* + ProduceCitationMarkersResult x = + produceCitationMarkers( + // cgs, + documentConnection, + databases, + style); + res.unresolvedKeys = x.unresolvedKeys; + res.newDatabase = this.generateDatabase(databases, documentConnection); + */ + return this.generateDatabase(databases, documentConnection); + } finally { + documentConnection.leaveUndoContext(); + } + //return res; + } + /** * Used from GUI: "Export cited" * @@ -4106,19 +3564,76 @@ static class ProduceCitationMarkersResult { * if the referenced entry is found, it is included in the result. * If it is not found, it is silently ignored. */ - public BibDatabase - generateDatabase(List databases) + private ExportCitedHelperResult // BibDatabase + generateDatabase(List databases, DocumentConnection documentConnection) throws NoSuchElementException, WrappedTargetException, - NoDocumentException { + NoDocumentException, + UnknownPropertyException { - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + // DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + + CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + CitationGroupsV001.CitedKeys cks = cgs.getCitedKeys(); + cks.lookupInDatabases( databases ); + + List unresolvedKeys = new ArrayList<>(); BibDatabase resultDatabase = new BibDatabase(); - List cited = findCitedKeys(documentConnection); + // List cited = findCitedKeys(documentConnection); + List entriesToInsert = new ArrayList<>(); + Set seen = new HashSet<>(); + + for (CitationGroupsV001.CitedKey ck : cks.values()) { + if ( ck.db.isEmpty() ) { + unresolvedKeys.add(ck.key); + continue; + } else { + BibEntry entry = ck.db.get().entry; + BibDatabase loopDatabase = ck.db.get().database; + + // If entry found + BibEntry clonedEntry = (BibEntry) entry.clone(); + + // Insert a copy of the entry + entriesToInsert.add(clonedEntry); + + // Check if the cloned entry has a cross-reference field + clonedEntry + .getField(StandardField.CROSSREF) + .ifPresent(crossReference -> { + // If the crossReference entry is not already in the database + + // broken logic here: + + // we just created resultDatabase, and + // added nothing yet. + + // Question: why do we use + // entriesToInsert instead of directly adding to resultDatabase? + // And why do we not look for it in entriesToInsert? + // With the present code we are always adding it. + // How does BibDatabase handle this situation? + /* + boolean isNew = (resultDatabase + .getEntryByCitationKey(crossReference) + .isEmpty()); + */ + boolean isNew = !seen.contains( crossReference ); + if (isNew) { + // Add it if it is in the current library + loopDatabase + .getEntryByCitationKey(crossReference) + .ifPresent(entriesToInsert::add); + seen.add(crossReference); + } + }); + } + } + /* // For each cited key for (String key : cited) { // Loop through the available databases @@ -4129,6 +3644,7 @@ static class ProduceCitationMarkersResult { } // If entry found BibEntry clonedEntry = (BibEntry) entry.get().clone(); + // Insert a copy of the entry entriesToInsert.add(clonedEntry); @@ -4164,9 +3680,10 @@ static class ProduceCitationMarkersResult { } // key not found here. No action. } + */ resultDatabase.insertEntries(entriesToInsert); - return resultDatabase; + return new ExportCitedHelperResult( unresolvedKeys, resultDatabase ); } void styleIsRequired(OOBibStyle style) @@ -4215,7 +3732,7 @@ void styleIsRequired(OOBibStyle style) documentConnection.enterUndoContext("Refresh bibliography"); boolean requireSeparation = false; // may loose citation without requireSeparation=true - CitationGroups cgs = new CitationGroups(documentConnection); + CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); int maxReportedOverlaps = 10; checkRangeOverlaps(cgs, this.xDocumentConnection, requireSeparation, maxReportedOverlaps); final boolean useLockControllers = true; @@ -4232,18 +3749,20 @@ void styleIsRequired(OOBibStyle style) } applyNewCitationMarkers( documentConnection, - x.jabRefReferenceMarkNamesSortedByPosition, + // x.jabRefReferenceMarkNamesSortedByPosition, + x.cgs, x.citMarkers, - x.itcTypes, + // x.itcTypes, style); rebuildBibTextSection( documentConnection, style, - x.jabRefReferenceMarkNamesSortedByPosition, - x.uniqueLetters, - x.fce + x.getBibliography() + // x.jabRefReferenceMarkNamesSortedByPosition, + // x.uniqueLetters, + // x.fce ); - return x.unresolvedKeys; + return x.getUnresolvedKeys(); } finally { if (useLockControllers) { documentConnection.unlockControllers(); diff --git a/src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java b/src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java index 8771c8fec67..b54d0a59ac3 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java @@ -16,16 +16,16 @@ * corresponding tables. * */ -class RangeForOverlapCheck { +class RangeForOverlapCheck { final static int REFERENCE_MARK_KIND = 0; final static int FOOTNOTE_MARK_KIND = 1; XTextRange range; int kind; - int i; + T i; // TODO: rename to content if identifier or cgid String description; - RangeForOverlapCheck(XTextRange range, int i, int kind, String description) { + RangeForOverlapCheck(XTextRange range, T i, int kind, String description) { this.range = range; this.kind = kind; this.i = i; diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java index 3fea1a993f6..cb9de128247 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java @@ -64,6 +64,9 @@ class RangeKeyedMap { return xs.put( r, value ); } + /** + * @return A list of the partitions. + */ public List> partitionValues() { return new ArrayList(xxs.values()); diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java index 196e6615d37..817ef9ba1c5 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java @@ -59,6 +59,14 @@ class RangeOverlap { this.kind = kind; this.vs = vs; } + }; + + /** + * @return A list of the partitions. + */ + public List>> + partitionValues() { + return this.xxs.partitionValues(); } /** diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index cb8c7231075..b7cd618ea5a 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1020,6 +1020,7 @@ Cite\ special=Cite special Extra\ information\ (e.g.\ page\ number)=Extra information (e.g. page number) Manage\ citations=Manage citations Problem\ modifying\ citation=Problem modifying citation +Problem\ collecting\ citations=Problem collecting citations Citation=Citation Connecting...=Connecting... Could\ not\ resolve\ BibTeX\ entry\ for\ citation\ marker\ '%0'.=Could not resolve BibTeX entry for citation marker '%0'. From 124a14f5e29e840295815d65650a1f4f9f4bfd32 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Mar 2021 00:41:51 +0100 Subject: [PATCH 0491/1068] refactor: started to cleanup, test, debug --- .../gui/openoffice/CitationGroupsV001.java | 64 +- .../org/jabref/gui/openoffice/OOBibBase.java | 1243 +++++------------ .../jabref/gui/openoffice/RangeKeyedMap.java | 4 +- 3 files changed, 402 insertions(+), 909 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 896beeb1511..b415ea2661a 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -10,6 +10,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; @@ -229,6 +230,16 @@ public int compare(CitationAndIndex a, CitationAndIndex b) { */ private Optional bibliography; + public void show() { + System.out.printf("CitationGroupsV001%n"); + System.out.printf(" citationGroups.size: %d%n", citationGroups.size()); + System.out.printf(" pageInfoThrash.size: %d%n", pageInfoThrash.size()); + System.out.printf(" globalOrder: %s%n", + globalOrder.isEmpty() + ? "isEmpty" + : String.format( "%d", globalOrder.get().size() ) + ); + } /** * Constructor @@ -275,6 +286,7 @@ public CitationGroupsV001(DocumentConnection documentConnection) // What is left out: the ranges controlled by the reference marks. // But (I guess) those change too easily, so we only ask when actually needed. + this.globalOrder = Optional.empty(); this.citedKeysAfterDatabaseLookup = Optional.empty(); this.bibliography = Optional.empty(); } @@ -332,12 +344,12 @@ class DatabaseLookupResult { } class CitedKey { - String key; + String key; // TODO: rename to citationKey LinkedHashSet where; Optional db; - Optional number; - Optional uniqueLetter; - Optional normCitMarker; + Optional number; // For Numbered citation styles. + Optional uniqueLetter; // For AuthorYear citation styles. + Optional normCitMarker; // For AuthorYear citation styles. CitedKey( String key, CitationPath p, Citation cit ) { this.key = key; @@ -390,6 +402,9 @@ void distributeUniqueLetter(CitationGroupsV001 cgs) { class CitedKeys { + /** + * Order-preserving map from citation keys to associated data. + */ LinkedHashMap data; CitedKeys(LinkedHashMap data) { @@ -647,37 +662,48 @@ Optional getBibliography() { public void setGlobalOrder( List globalOrder ) { + Objects.requireNonNull(globalOrder); + if (globalOrder.size() != citationGroups.size() ){ + throw new RuntimeException( + "CitationGroupsV001.setGlobalOrder: globalOrder.size() != citationGroups.size()" + ); + } this.globalOrder = Optional.of(globalOrder); } - public Optional - getCitationGroup(CitationGroupID cgid) { + public Optional getCitationGroup(CitationGroupID cgid) { CitationGroup e = citationGroups.get(cgid); return Optional.ofNullable(e); } - private Optional - getReferenceMarkName(CitationGroupID cgid) { + /** + * Call this when the citation group is unquestionably there. + */ + public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { + CitationGroup e = citationGroups.get(cgid); + if (e == null) { + throw new RuntimeException("CitationGroupsV001.getCitationGroupOrThrow:" + + " the requested CitationGroup is not available"); + } + return e; + } + + private Optional getReferenceMarkName(CitationGroupID cgid) { return getCitationGroup(cgid).map(cg -> cg.referenceMarkName); } - private Optional - getItcType(CitationGroupID cgid) { + private Optional getItcType(CitationGroupID cgid) { return getCitationGroup(cgid).map(cg -> cg.itcType); } - public int - numberOfCitationGroups() { + public int numberOfCitationGroups() { return citationGroups.size(); } - public Optional - getPageInfo(CitationGroupID cgid) { - return ( - getCitationGroup(cgid) - .map(cg -> cg.pageInfo) - .flatMap(x -> x) - ); + public Optional getPageInfo(CitationGroupID cgid) { + return (getCitationGroup(cgid) + .map(cg -> cg.pageInfo) + .flatMap(x -> x)); } public Optional> diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 036e4605bbb..4176552ba73 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -248,10 +248,8 @@ class OOBibBase { * document selected. * */ - private static XTextDocument - selectDocumentDialog( - List list, - DialogService dialogService) { + private static XTextDocument selectDocumentDialog(List list, + DialogService dialogService) { class DocumentTitleViewModel { @@ -273,27 +271,24 @@ public String toString() { } } - List viewModel = - list.stream() - .map(DocumentTitleViewModel::new) - .collect(Collectors.toList()); + List viewModel = (list.stream() + .map(DocumentTitleViewModel::new) + .collect(Collectors.toList())); // This whole method is part of a background task when // auto-detecting instances, so we need to show dialog in FX // thread Optional selectedDocument = - dialogService - .showChoiceDialogAndWait( - Localization.lang("Select document"), - Localization.lang("Found documents:"), - Localization.lang("Use selected document"), - viewModel - ); + (dialogService + .showChoiceDialogAndWait( + Localization.lang("Select document"), + Localization.lang("Found documents:"), + Localization.lang("Use selected document"), + viewModel)); - return - selectedDocument - .map(DocumentTitleViewModel::getXtextDocument) - .orElse(null); + return (selectedDocument + .map(DocumentTitleViewModel::getXtextDocument) + .orElse(null)); } /** @@ -313,8 +308,7 @@ public String toString() { * document and parts extracted. * */ - public void - selectDocument() + public void selectDocument() throws NoDocumentException, NoSuchElementException, @@ -325,14 +319,10 @@ public String toString() { if (textDocumentList.isEmpty()) { throw new NoDocumentException("No Writer documents found"); } else if (textDocumentList.size() == 1) { - // Get the only one - selected = textDocumentList.get(0); - } else { - // Bring up a dialog - selected = - OOBibBase.selectDocumentDialog( - textDocumentList, - this.dialogService); + selected = textDocumentList.get(0); // Get the only one + } else { // Bring up a dialog + selected = OOBibBase.selectDocumentDialog(textDocumentList, + this.dialogService); } if (selected == null) { @@ -340,15 +330,13 @@ public String toString() { } this.xDocumentConnection = new DocumentConnection(selected); - } /** * Mark the current document as missing. * */ - private void - forgetDocument() { + private void forgetDocument() { this.xDocumentConnection = null; } @@ -381,9 +369,9 @@ public boolean documentConnectionMissing() { * Either return a valid DocumentConnection or throw * NoDocumentException. */ - private DocumentConnection - getDocumentConnectionOrThrow() - throws NoDocumentException { + private DocumentConnection getDocumentConnectionOrThrow() + throws + NoDocumentException { if (documentConnectionMissing()) { throw new NoDocumentException("Not connected to document"); } @@ -393,8 +381,7 @@ public boolean documentConnectionMissing() { /** * The title of the current document, or Optional.empty() */ - public Optional - getCurrentDocumentTitle() { + public Optional getCurrentDocumentTitle() { if (documentConnectionMissing()) { return Optional.empty(); } else { @@ -411,13 +398,11 @@ public boolean documentConnectionMissing() { /** * unoQI : short for UnoRuntime.queryInterface * - * @return A reference to the requested UNO interface type if available, - * otherwise null + * @return A reference to the requested UNO interface type if + * available, otherwise null. */ - private static T - unoQI( - Class zInterface, - Object object) { + private static T unoQI(Class zInterface, + Object object) { return UnoRuntime.queryInterface(zInterface, object); } @@ -467,21 +452,14 @@ public boolean documentConnectionMissing() { * * **************************************/ - - - - /** * @param requireSeparation Report range pairs that only share a boundary. - * @param atMost Limit number of overlaps reported (0 for no limit) + * @param reportAtMost Limit number of overlaps reported (0 for no limit) */ - public void - checkRangeOverlaps( - CitationGroupsV001 cgs, - DocumentConnection documentConnection, - boolean requireSeparation, - int atMost - ) + public void checkRangeOverlaps(CitationGroupsV001 cgs, + DocumentConnection documentConnection, + boolean requireSeparation, + int reportAtMost) throws NoDocumentException, WrappedTargetException, @@ -499,35 +477,25 @@ public boolean documentConnectionMissing() { } List.RangeOverlap> ovs = - xall.findOverlappingRanges(atMost, requireSeparation); + xall.findOverlappingRanges(reportAtMost, requireSeparation); //checkSortedPartitionForOverlap(requireSeparation, oxs); if (ovs.size() > 0) { String msg = ""; for (RangeKeyedMapList.RangeOverlap e : ovs) { - String l = - (": " - + (e.vs.stream() - .map(v -> String.format("'%s'", v.format())) - .collect(Collectors.joining(", "))) - + "\n"); + String l = (": " + + (e.vs.stream() + .map(v -> String.format("'%s'", v.format())) + .collect(Collectors.joining(", "))) + + "\n"); switch (e.kind) { - case EQUAL_RANGE: - msg = msg + Localization.lang("Found identical ranges") + l; - break; - case OVERLAP: - msg = msg + Localization.lang("Found overlapping ranges") + l; - break; - case TOUCH: - msg = msg + Localization.lang("Found touching ranges") + l; - break; + case EQUAL_RANGE: msg = msg + Localization.lang("Found identical ranges") + l; break; + case OVERLAP: msg = msg + Localization.lang("Found overlapping ranges") + l; break; + case TOUCH: msg = msg + Localization.lang("Found touching ranges") + l; break; } } - throw new JabRefException( - "Found overlapping or touching ranges", - msg - ); + throw new JabRefException("Found overlapping or touching ranges", msg); } } @@ -565,8 +533,7 @@ public boolean documentConnectionMissing() { * the GUI could move the cursor in the document to * the entry. */ - public List - getCitationEntries() + public List getCitationEntries() throws UnknownPropertyException, WrappedTargetException, @@ -576,8 +543,6 @@ public boolean documentConnectionMissing() { DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); - // List names = this.getJabRefReferenceMarkNames(documentConnection); - int n = cgs.numberOfCitationGroups(); List citations = new ArrayList<>(n); for (CitationGroupsV001.CitationGroupID cgid : cgs.getCitationGroupIDs()) { @@ -586,8 +551,7 @@ public boolean documentConnectionMissing() { new CitationEntry( name, this.getCitationContext(cgs, cgid, documentConnection, 30, 30, true), - cgs.getPageInfo(cgid) //documentConnection.getCustomProperty(name) - ); + cgs.getPageInfo(cgid)); citations.add(entry); } return citations; @@ -605,15 +569,12 @@ public boolean documentConnectionMissing() { * @param htmlMarkup If true, the text belonging to the * reference mark is surrounded by bold html tag. */ - private String - getCitationContext( - CitationGroupsV001 cgs, - CitationGroupsV001.CitationGroupID cgid, - DocumentConnection documentConnection, - int charBefore, - int charAfter, - boolean htmlMarkup - ) + private String getCitationContext(CitationGroupsV001 cgs, + CitationGroupsV001.CitationGroupID cgid, + DocumentConnection documentConnection, + int charBefore, + int charAfter, + boolean htmlMarkup) throws WrappedTargetException, NoDocumentException, @@ -706,8 +667,7 @@ public boolean documentConnectionMissing() { * citation from the text). * */ - public void - applyCitationEntries( + public void applyCitationEntries( List citationEntries) throws UnknownPropertyException, @@ -722,9 +682,8 @@ public boolean documentConnectionMissing() { for (CitationEntry entry : citationEntries) { Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { - documentConnection.setCustomProperty( - entry.getRefMarkName(), - pageInfo.get()); + documentConnection.setCustomProperty(entry.getRefMarkName(), + pageInfo.get()); } } } @@ -735,168 +694,6 @@ public boolean documentConnectionMissing() { * * *************************************/ - /** - * The collection of data returned by findCitedKeys. - */ - private static class FindCitedEntriesResult { - /** - * entries : LinkedHashMap with iteration order as the - * citedKeys parameter of findCitedEntries - */ - Map entries; - - /** - * citeKeyToBibEntry : HashMap (no order) - */ - Map citeKeyToBibEntry; - - FindCitedEntriesResult( - Map entries, - Map citeKeyToBibEntry - ) { - this.entries = entries; - this.citeKeyToBibEntry = citeKeyToBibEntry; - } - } - - /** - * Look up a single citation key in a list of databases. - * - * @param key Citation key to look up. - * @param databases Key is looked up in these, in this order. - * @return The BibEntry at the first match, or Optional.empty(). - */ - Optional - lookupEntryInDatabases(String key, List databases) { - for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(key); - if (entry.isPresent()) { - return entry; - } - } - return Optional.empty(); - } - - /** - * Look up a list of citation keys in a list of databases. - * - * @param keys Citation keys to look up. - * @param databases Keys are looked up in these, in this order. - * @return The BibEntry objects found. - * - * The order of keys is kept in the result, but unresolved keys - * have no representation in the result, so result.get(i) does not - * necessarily belong to keys.get(i) - * - */ - List - lookupEntriesInDatabasesSkipMissing( - List keys, - List databases - ) { - List entries = new ArrayList<>(); - for (String key : keys) { - lookupEntryInDatabases(key, databases).ifPresent(entries::add); - } - return entries; - } - - /** - * @return A FindCitedEntriesResult containing - * - * entries: A LinkedHashMap, from BibEntry to BibDatabase with - * iteration order as the citedKeys parameter. - * - * Stores: in which database was the entry found. - * - * citeKeyToBibEntry: - * A HashMap from citation key to BibEntry. - * Stores: result of lookup. - * - * For citation keys not found, a new - * UndefinedBibtexEntry(citedKey) is created and added to both - * maps, with a null BibDatabase. - * - * How is the result used? - * - * entries : Allows to recover the list of keys in original - * order, and finding the corresponding databases. - * - * Well, it does, but not by a simple - * entry.getCitationKey(), because - * UndefinedBibtexEntry.getCitationKey() returns - * Optional.empty(). - * - * For UndefinedBibtexEntry, - * UndefinedBibtexEntry.getKey() returns the - * original key we stored. - * - * citeKeyToBibEntry: - * - * Caches the result of lookup performed here, with "not - * found" encoded as an instance of UndefinedBibtexEntry. - * - */ - private FindCitedEntriesResult - findCitedEntries( - List citedKeys, - List databases - ) { - Map citeKeyToBibEntry = new HashMap<>(); - - // LinkedHashMap, iteration order as in citedKeys - Map entries = new LinkedHashMap<>(); - for (String citedKey : citedKeys) { - boolean found = false; - for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(citedKey); - if (entry.isPresent()) { - entries.put(entry.get(), database); - citeKeyToBibEntry.put(citedKey, entry.get()); - found = true; - break; - } - } - - if (!found) { - BibEntry x = new UndefinedBibtexEntry(citedKey); - entries.put(x, null); - citeKeyToBibEntry.put(citedKey, x); - } - } - return new FindCitedEntriesResult(entries, citeKeyToBibEntry); - } - - static String - recoverCitationKeyFromPossiblyUndefinedBibEntry(BibEntry entry) { - if (entry instanceof UndefinedBibtexEntry) { - return ((UndefinedBibtexEntry) entry).getKey(); - } else { - Optional optKey = entry.getCitationKey(); - return optKey.get(); // may throw, but should not happen - } - } - - /** - * @return The list of citation keys from `instanceof - * UndefinedBibtexEntry` elements of (keys of) `entries`. - * - * Intent: Get list of unresolved citation keys. - */ - private static List - unresolvedKeysFromEntries(Map entries) { - // Collect and return unresolved citation keys. - List unresolvedKeys = new ArrayList<>(); - for (BibEntry entry : entries.keySet()) { - if (entry instanceof UndefinedBibtexEntry) { - String key = ((UndefinedBibtexEntry) entry).getKey(); - if (!unresolvedKeys.contains(key)) { - unresolvedKeys.add(key); - } - } - } - return unresolvedKeys; - } /* *************************************** * @@ -936,30 +733,6 @@ private static class FindCitedEntriesResult { entries.sort(comparatorForMulticite(style)); } - /** - * Look up citation keys from a map caching earlier look up, sort result within - * each reference mark. - * - * @param bibtexKeys Citation keys, bibtexKeys[i][j] is for the ith reference mark. - * @param citeKeyToBibEntry Cached lookup from keys to entries. - */ - private BibEntry[][] - getBibEntriesSortedWithinReferenceMarks( - String[][] bibtexKeys, - Map citeKeyToBibEntry, - OOBibStyle style - ) { - return - Arrays.stream(bibtexKeys) - .map(bibtexKeysOfAReferenceMark -> - Arrays.stream(bibtexKeysOfAReferenceMark) - .map(citeKeyToBibEntry::get) - .sorted(comparatorForMulticite(style)) // sort within referenceMark - .toArray(BibEntry[]::new) - ) - .toArray(BibEntry[][]::new); - } - /* *************************************** * * Global order: by first appearance or by bibliography order @@ -968,32 +741,6 @@ private static class FindCitedEntriesResult { /* bibliography order */ - /** - * @return Citation keys from `entries`, ordered as in the bibliography. - */ - private List - citationKeysOrNullInBibliographyOrderFromEntries( - Map entries - ) { - - // Sort entries to order in bibliography - // Belongs to global order. - Map sortedEntries = - sortEntriesByComparator(entries, entryComparator); - - // Citation keys, in the same order as sortedEntries - return - sortedEntries.keySet().stream() - .map( - entry -> - entry.getCitationKey() - // entries came from looking up by citation key, - // so Optional.empty() is only possible here for UndefinedBibtexEntry. - .orElse(null) - ) - .collect(Collectors.toList()); - } - /** * Return a TreeMap(entryComparator) copy of entries. * @@ -1163,8 +910,7 @@ public T getContent() { boolean mapFootnotesToFootnoteMarks) throws NoDocumentException, - WrappedTargetException - { + WrappedTargetException { // final int nMarks = cgs.numberOfCitationGroups(); @@ -1210,13 +956,16 @@ public T getContent() { // build final list List> res = new ArrayList<>(); + for (TreeMap>> xs : xxs.partitionValues()) { + List oxs = new ArrayList<>(xs.keySet()); + for (int i = 0; i < oxs.size(); i++) { XTextRange a = oxs.get(i); List> avs = xs.get(a); - for (int j=0; j v = avs.get(j); v.indexInPosition = j; if ( mapFootnotesToFootnoteMarks ) { @@ -1232,6 +981,10 @@ public T getContent() { } } } + // convert + // List> + // to + // List> return res.stream().map(e -> e).collect(Collectors.toList()); } @@ -1300,45 +1053,35 @@ public T getContent() { private List getVisuallySortedCitationGroupIDs( - // getJabRefReferenceMarkNamesSortedByPosition( CitationGroupsV001 cgs, - // List vses, DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks - ) + boolean mapFootnotesToFootnoteMarks ) throws WrappedTargetException, NoDocumentException { - List> vses = + List> vses = createVisualSortInput( cgs, documentConnection, mapFootnotesToFootnoteMarks); - List> sorted = visualSort( vses, documentConnection ); - return - sorted.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList()) - ; + return (sorted.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList())); } - /* *************************************** * * Make them unique: uniqueLetters or numbers * * **************************************/ - private String - normalizedCitationMarkerForNormalStyle( - CitationGroupsV001.CitedKey ck, - OOBibStyle style - ) { + private String normalizedCitationMarkerForNormalStyle(CitationGroupsV001.CitedKey ck, + OOBibStyle style) { if (ck.db.isEmpty()){ return String.format("(Unresolved(%s))", ck.key); } @@ -1347,31 +1090,23 @@ public T getContent() { entries.put( ce, ck.db.get().database ); // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: - return - style.getCitationMarker( - Collections.singletonList(ce), - entries, - true, - null, - new int[] {-1} // no limit on authors - ); + return style.getCitationMarker(Collections.singletonList(ce), + entries, + true, + null, + new int[] {-1} /* no limit on authors */); } /** - * Fills + * Fills {@code sortedCitedKeys//normCitMarker} */ private void - normalizedCitationMarkersForNormalStyle( - CitationGroupsV001.CitedKeys sortedCitedKeys, - OOBibStyle style - ) { + createNormalizedCitationMarkersForNormalStyle(CitationGroupsV001.CitedKeys sortedCitedKeys, + OOBibStyle style) { for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.data.values()) { - ck.normCitMarker = Optional.of( - normalizedCitationMarkerForNormalStyle( ck, style ) - ); + ck.normCitMarker = Optional.of(normalizedCitationMarkerForNormalStyle(ck, style)); } - // return normCitMarkers; } /** @@ -1391,65 +1126,56 @@ public T getContent() { * * Depends on: style, citations and their order. */ - void - createUniqueLetters( - CitationGroupsV001.CitedKeys sortedCitedKeys, - CitationGroupsV001 cgs - ) { - - //final int nRefMarks = bibtexKeys.length; - //assert nRefMarks == normCitMarkers.length; + void createUniqueLetters(CitationGroupsV001.CitedKeys sortedCitedKeys, + CitationGroupsV001 cgs) { - // refKeys: (normCitMarker) to (list of citation keys sharing it). - // The entries in the lists are ordered as in - // normCitMarkers[i][j] - Map> refKeys = new HashMap<>(); - for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.data.values()) { - String marker = ck.normCitMarker.get(); - String currentKey = ck.key; - - if (refKeys.containsKey(marker)) { - // Ok, we have seen this exact marker before. - if (!refKeys.get(marker).contains(currentKey)) { - // ... but not for this entry. - refKeys.get(marker).add(currentKey); - } + // ncm2clks: ncm (normCitMarker) to clks (clashing keys : list of citation keys fighting for it). + // + // The entries in the clks lists preserve firstAppearance order + // from sortedCitedKeys.data.values(). + // + // The index of the citationKey in this order will decide which + // unique letter it receives. + // + Map> ncm2clks = new HashMap<>(); + for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.values()) { + String ncm = ck.normCitMarker.get(); + String citationKey = ck.key; + + if (!ncm2clks.containsKey(ncm)) { + // Found new normCitMarker + List clks = new ArrayList<>(1); + ncm2clks.put(ncm, clks); + clks.add(citationKey); } else { - // add as new entry - List l = new ArrayList<>(1); - l.add(currentKey); - refKeys.put(marker, l); + List clks = ncm2clks.get(ncm); + if (!clks.contains(citationKey)) { + // First appearance of citationKey, add to list. + clks.add(citationKey); + } } } - Map uniqueLetters = new HashMap<>(); + // Map uniqueLetters = new HashMap<>(); // uniqueLetters.clear(); for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.data.values()) { ck.uniqueLetter = Optional.empty(); } - // Go through the collected lists and see where we need to + // For sets of citation keys figthing for a normCitMarker // add unique letters to the year. - for (Map.Entry> stringListEntry : refKeys.entrySet()) { - List clashingKeys = stringListEntry.getValue(); - if (clashingKeys.size() > 1) { - // This marker appears for more than one unique entry: - int nextUniqueLetter = 'a'; - for (String key : clashingKeys) { - // Update the map of uniqueLetters for the - // benefit of both the following generation of - // new citation markers, and for the method - // that builds the bibliography: - uniqueLetters.put(key, String.valueOf((char) nextUniqueLetter)); - nextUniqueLetter++; - } + for (List clks : ncm2clks.values()) { + if (clks.size() <= 1) { + continue; // No fight, no letters. + } + // Multiple citation keys: they get their letters according to their order in clks. + int nextUniqueLetter = 'a'; + for (String citationKey : clks) { + // uniqueLetters.put(citationKey, String.valueOf((char) nextUniqueLetter)); + String ul = String.valueOf((char) nextUniqueLetter); + sortedCitedKeys.data.get(citationKey).uniqueLetter = Optional.of(ul); + nextUniqueLetter++; } - } - // return uniqueLetters; - for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.data.values()) { - String key = ck.key; - Optional ul = Optional.ofNullable(key); - ck.uniqueLetter = ul; } sortedCitedKeys.distributeUniqueLetters(cgs); } @@ -1470,8 +1196,7 @@ public T getContent() { * @param inParenthesis True means "(Au and Thor 2000)". * False means "Au and Thor (2000)". */ - private static int - citationTypeFromOptions(boolean withText, boolean inParenthesis) { + private static int citationTypeFromOptions(boolean withText, boolean inParenthesis) { if (!withText) { return OOBibBase.INVISIBLE_CIT; } @@ -1480,130 +1205,29 @@ public T getContent() { : OOBibBase.AUTHORYEAR_INTEXT); } - /** - * @return Null if cEntry is an UndefinedBibtexEntry, - * otherwise return cEntry itself. - */ - private static BibEntry - undefinedBibEntryToNull(BibEntry cEntry) { - if (cEntry instanceof UndefinedBibtexEntry) { - return null; - } - return cEntry; - } - - /** - * result[i][j] = cEntriesForAll[i][j].getCitationKey() - */ - private String[][] - mapBibEntriesToCitationKeysOrNullForAll(BibEntry[][] cEntriesForAll) { - return - Arrays.stream(cEntriesForAll) - .map(cEntries -> - Arrays.stream(cEntries) - .map(ce -> ce.getCitationKey().orElse(null)) - .toArray(String[]::new) - ) - .toArray(String[][]::new); - } - - /** - * Checks that every element of `keys` can be found in `citeKeyToBibEntry`. - * - * Collects the missing keys, and if there is any, throws - * BibEntryNotFoundException (currently mentioning only the first - * missing key). - * - * @param keys An array of citation keys, we expect to appear as - * keys in citeKeyToBibEntry. - * - * @param citeKeyToBibEntry Should map each key in keys to a BibEntry. - * @param referenceMarkName The reference mark these keys belong to. - * Mentioned in the exception. - */ - private static void - assertKeysInCiteKeyToBibEntry( - String[] keys, // citeKeys - Map citeKeyToBibEntry, - String referenceMarkName, // for reporting - String where - ) - throws BibEntryNotFoundException { - - // check keys - List unresolvedKeys = - Arrays.stream(keys) - .filter(key -> null == citeKeyToBibEntry.get(key)) - .collect(Collectors.toList()); - - for (String key : unresolvedKeys) { - LOGGER.info("assertKeysInCiteKeyToBibEntry: Citation key not found: '" + key + '\''); - LOGGER.info("Problem with reference mark: '" + referenceMarkName + "' " + where); - String msg = - Localization.lang( - "Could not resolve BibTeX entry" - + " for citation marker '%0'.", - referenceMarkName); - throw new BibEntryNotFoundException(referenceMarkName, msg); - } - } - - /** - * For each reference mark name: check the corresponding element of - * bibtexKeys with assertKeysInCiteKeyToBibEntry. - */ - private static void - assertAllKeysInCiteKeyToBibEntry( - List referenceMarkNames, - String[][] bibtexKeys, - Map citeKeyToBibEntry, - String where - ) - throws BibEntryNotFoundException { - - final int nRefMarks = referenceMarkNames.size(); - assert (nRefMarks == bibtexKeys.length); - - for (int i = 0; i < nRefMarks; i++) { - assertKeysInCiteKeyToBibEntry( - bibtexKeys[i], - citeKeyToBibEntry, - referenceMarkNames.get(i), - where - ); - } - } - /** * Produce citation markers for the case when the citation * markers are the citation keys themselves, separated by commas. */ private static Map - produceCitationMarkersForIsCitationKeyCiteMarkers( - CitationGroupsV001 cgs, - // List sortedCitationGroupIDs, - OOBibStyle style - ) - throws BibEntryNotFoundException { + produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroupsV001 cgs, + OOBibStyle style) + throws + BibEntryNotFoundException { assert style.isCitationKeyCiteMarkers(); - cgs.createPlainBibliogaphySortedByComparator( OOBibBase.entryComparator ); - - //final int nRefMarks = sortedCitationGroupIDs.size(); + cgs.createPlainBibliogaphySortedByComparator(OOBibBase.entryComparator); - //String[] citMarkers = new String[nRefMarks]; Map citMarkers = new HashMap<>(); for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { List cits = cgs.getSortedCitations(cgid); - String citMarker = - cits.stream() - .map(cit -> cit.citationKey) - .collect(Collectors.joining(",")); + String citMarker = (cits.stream() + .map(cit -> cit.citationKey) + .collect(Collectors.joining(","))); citMarkers.put(cgid, citMarker); } - // Finally: return citMarkers; } @@ -1626,33 +1250,25 @@ public T getContent() { * */ private static Map - produceCitationMarkersForIsNumberEntriesIsSortByPosition( - CitationGroupsV001 cgs, - OOBibStyle style - ) - throws BibEntryNotFoundException { + produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroupsV001 cgs, + OOBibStyle style) + throws + BibEntryNotFoundException { assert style.isNumberEntries(); assert style.isSortByPosition(); - cgs.createNumberedBibliogaphySortedInOrderOfAppearance(); - final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); Map citMarkers = new HashMap<>(); for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroupsV001.CitationGroup cg = - cgs.getCitationGroup(cgid) - .orElseThrow( IllegalStateException::new ) - ; + CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); - citMarkers.put( - cgid, - style.getNumCitationMarker(numbers, minGroupingCount, false) - ); + citMarkers.put(cgid, + style.getNumCitationMarker(numbers, minGroupingCount, false)); } return citMarkers; @@ -1663,10 +1279,8 @@ public T getContent() { * when the bibliography is not sorted by position. */ private Map - produceCitationMarkersForIsNumberEntriesNotSortByPosition( - CitationGroupsV001 cgs, - OOBibStyle style - ) { + produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroupsV001 cgs, + OOBibStyle style) { assert style.isNumberEntries(); assert !style.isSortByPosition(); @@ -1678,20 +1292,14 @@ public T getContent() { Map citMarkers = new HashMap<>(); for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroupsV001.CitationGroup cg = - cgs.getCitationGroup(cgid) - .orElseThrow( IllegalStateException::new ) - ; + CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); - citMarkers.put( - cgid, - style.getNumCitationMarker(numbers, minGroupingCount, false) - ); + citMarkers.put(cgid, + style.getNumCitationMarker(numbers, minGroupingCount, false)); } return citMarkers; } - /** * Produce citMarkers for normal * (!isCitationKeyCiteMarkers && !isNumberEntries) styles. @@ -1704,38 +1312,30 @@ public T getContent() { * @param style Bibliography style. */ private Map - produceCitationMarkersForNormalStyle( - CitationGroupsV001 cgs, - OOBibStyle style - ) - throws BibEntryNotFoundException { + produceCitationMarkersForNormalStyle(CitationGroupsV001 cgs, + OOBibStyle style) + throws + BibEntryNotFoundException { assert !style.isCitationKeyCiteMarkers(); assert !style.isNumberEntries(); // Citations in (Au1, Au2 2000) form - CitationGroupsV001.CitedKeys sortedCitedKeys = - cgs.getCitedKeysSortedInOrderOfAppearance(); - - normalizedCitationMarkersForNormalStyle( sortedCitedKeys, style ); - createUniqueLetters( sortedCitedKeys, cgs ); // calls distributeUniqueLetters(cgs) - cgs.createPlainBibliogaphySortedByComparator( entryComparator ); + CitationGroupsV001.CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); + createNormalizedCitationMarkersForNormalStyle(sortedCitedKeys, style); + createUniqueLetters(sortedCitedKeys, cgs); // calls distributeUniqueLetters(cgs) + cgs.createPlainBibliogaphySortedByComparator(entryComparator); // Finally, go through all citation markers, and update // those referring to entries in our current list: final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); - //String[] citMarkers = new String[nRefMarks]; Map citMarkers = new HashMap<>(); for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - // for (int i = 0; i < nRefMarks; i++) { - CitationGroupsV001.CitationGroup cg = - cgs.getCitationGroup(cgid) - .orElseThrow( IllegalStateException::new ) - ; + CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List cits = cg.getSortedCitations(); final int nCitedEntries = cits.size(); int[] firstLimAuthors = new int[nCitedEntries]; @@ -1814,9 +1414,6 @@ public T getContent() { * All entries are resolved. */ List cEntries = new ArrayList<>(); - //Arrays.stream(cEntriesForAll[i]) - // .map(OOBibBase::undefinedBibEntryToNull) - // .collect(Collectors.toList()); Map entries = new HashMap<>(); for (int j = 0; j < nCitedEntries; j++) { // String currentKey = cits.get(j).citationKey @@ -1841,17 +1438,13 @@ public T getContent() { return citMarkers; } - - private static void - fillCitationMarkInCursor( - DocumentConnection documentConnection, - CitationGroupsV001 cgs, - CitationGroupsV001.CitationGroupID cgid, //String name, // citationGroup - XTextCursor cursor, - String citationText, - boolean withText, - OOBibStyle style - ) + private static void fillCitationMarkInCursor(DocumentConnection documentConnection, + CitationGroupsV001 cgs, + CitationGroupsV001.CitationGroupID cgid, + XTextCursor cursor, + String citationText, + boolean withText, + OOBibStyle style) throws UnknownPropertyException, WrappedTargetException, @@ -1859,6 +1452,13 @@ public T getContent() { IllegalArgumentException, UndefinedCharacterFormatException { + Objects.requireNonNull(documentConnection); + Objects.requireNonNull(cgs); + Objects.requireNonNull(cgid); + Objects.requireNonNull(cursor); + Objects.requireNonNull(citationText); + Objects.requireNonNull(style); + // Last minute editing: If there is "page info" for this // citation mark, we should inject it into the citation marker // when creating. @@ -1866,10 +1466,9 @@ public T getContent() { String citText; // String pageInfo = getPageInfoForReferenceMarkName(documentConnection, name); Optional pageInfo = cgs.getPageInfo(cgid); - citText = - pageInfo.isEmpty() - ? citationText - : style.insertPageInfo(citationText, pageInfo.get()); + citText = (pageInfo.isEmpty() + ? citationText + : style.insertPageInfo(citationText, pageInfo.get())); if (withText) { // setString: All styles are removed when applying this method. @@ -1892,6 +1491,8 @@ public T getContent() { boolean italicize = style.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); if (italicize) { String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); + Objects.requireNonNull(etAlString); + Objects.requireNonNull(citText); for (int index = citText.indexOf(etAlString); index >= 0; index = citText.indexOf(etAlString, index + 1)) { @@ -1910,12 +1511,9 @@ public T getContent() { * Why this API? This is used after finding "et al." string in a * citation marker. */ - private static void - italicizeRangeFromPosition( - XTextCursor position, - int start, - int end - ) + private static void italicizeRangeFromPosition(XTextCursor position, + int start, + int end) throws UnknownPropertyException, PropertyVetoException, @@ -1931,7 +1529,6 @@ public T getContent() { } /** - * * Insert a reference mark: creates and fills it. * * @param documentConnection Connection to a document. @@ -1942,19 +1539,16 @@ public T getContent() { * @param position OUT: left collapsed, just after the space inserted, * or after the reference mark inserted. */ - private void - insertReferenceMark( - CitationGroupsV001 cgs, - DocumentConnection documentConnection, - List citationKeys, - Optional pageInfo, - int itcType, - String citationText, - XTextCursor position, - boolean withText, - OOBibStyle style, - boolean insertSpaceAfter - ) + private void insertReferenceMark(CitationGroupsV001 cgs, + DocumentConnection documentConnection, + List citationKeys, + Optional pageInfo, + int itcType, + String citationText, + XTextCursor position, + boolean withText, + OOBibStyle style, + boolean insertSpaceAfter) throws UnknownPropertyException, WrappedTargetException, @@ -1965,35 +1559,31 @@ public T getContent() { NoDocumentException { CitationGroupsV001.CitationGroupID cgid = - cgs.createCitationGroup( - documentConnection, - citationKeys, - pageInfo, - itcType, - position, - insertSpaceAfter, - !withText); + cgs.createCitationGroup(documentConnection, + citationKeys, + pageInfo, + itcType, + position, + insertSpaceAfter, + !withText); if (withText) { XTextCursor c2 = - cgs.getFillCursorForCitationGroup( - documentConnection, - cgid); - - fillCitationMarkInCursor( - documentConnection, - cgs, - cgid, - c2, - citationText, - withText, - style); - - cgs.cleanFillCursorForCitationGroup( - documentConnection, - cgid, - !withText, - cgs.REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); + cgs.getFillCursorForCitationGroup(documentConnection, + cgid); + + fillCitationMarkInCursor(documentConnection, + cgs, + cgid, + c2, + citationText, + withText, + style); + + cgs.cleanFillCursorForCitationGroup(documentConnection, + cgid, + !withText, + cgs.REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); } position.collapseToEnd(); } @@ -2050,7 +1640,7 @@ void assertCitationCharacterFormatIsOK( } } - /* + /** * In insertCitation we receive BibEntry values from the GUI. * * In the document we store citations by their citation key. @@ -2119,17 +1709,14 @@ private static String insertCitationGetCitationKey(BibEntry entry) { * * */ - public void - insertCitation( - List entries, - BibDatabase database, - List allBases, - OOBibStyle style, - boolean inParenthesis, - boolean withText, - String pageInfo, - boolean sync - ) + public void insertCitation(List entries, + BibDatabase database, + List allBases, + OOBibStyle style, + boolean inParenthesis, + boolean withText, + String pageInfo, + boolean sync) throws JabRefException, IllegalArgumentException, @@ -2151,7 +1738,6 @@ private static String insertCitationGetCitationKey(BibEntry entry) { styleIsRequired(style); if (entries == null || entries.size() == 0) { - // System.out.println("insertCitation: throwing JabRefException"); throw new JabRefException( "No bibliography entries selected", Localization.lang( @@ -2246,78 +1832,61 @@ private static String insertCitationGetCitationKey(BibEntry entry) { inParenthesis, null, null); + if (citeText.equals("")) { citeText = "[?]"; } - insertReferenceMark( - cgs, - documentConnection, - citationKeys, - Optional.ofNullable(pageInfo), - itcType, - citeText, - cursor, - withText, - style, - true // insertSpaceAfter - ); + insertReferenceMark(cgs, + documentConnection, + citationKeys, + Optional.ofNullable(pageInfo), + itcType, + citeText, + cursor, + withText, + style, + true /* insertSpaceAfter */); // } // end of scope for databaseMap, citeText // Move to the right of the space and remember this // position: we will come back here in the end. // cursor.collapseToEnd(); // cursor.goRight((short) 1, false); - XTextRange position = cursor.getEnd(); - - if (sync) { - // To account for numbering and for uniqueLetters, we - // must refresh the cite markers: - /* CitationGroupsV001 */ //cgs = new CitationGroupsV001(documentConnection); - ProduceCitationMarkersResult x = - produceCitationMarkers( - //cgs, - documentConnection, - allBases, - style - ); - - try { - documentConnection.lockControllers(); - - applyNewCitationMarkers( - documentConnection, - // x.jabRefReferenceMarkNamesSortedByPosition, - x.cgs, - x.citMarkers, - //x.itcTypes, - style); - - // Insert it at the current position: - rebuildBibTextSection( - documentConnection, - style, - x.getBibliography() - // x.jabRefReferenceMarkNamesSortedByPosition, - // x.uniqueLetters, - // x.fce - ); - } finally { - documentConnection.unlockControllers(); - } + XTextRange position = cursor.getEnd(); + + if (sync) { + // To account for numbering and for uniqueLetters, we + // must refresh the cite markers: + ProduceCitationMarkersResult x = produceCitationMarkers(documentConnection, + allBases, + style); + try { + documentConnection.lockControllers(); + applyNewCitationMarkers(documentConnection, + x.cgs, + x.citMarkers, + style); + // Insert it at the current position: + rebuildBibTextSection(documentConnection, + style, + x.getBibliography()); + } finally { + documentConnection.unlockControllers(); + } - /* - * Problem: insertEntry in bibliography - * Reference is destroyed when we want to get there. - */ - // Go back to the relevant position: - try { - cursor.gotoRange(position, false); - } catch (com.sun.star.uno.RuntimeException ex) { - LOGGER.warn("OOBibBase.insertEntry:" - + " Could not go back to end of in-text citation", ex); + /* + * Problem: insertEntry in bibliography + * Reference is destroyed when we want to get there. + */ + // Go back to the relevant position: + try { + cursor.gotoRange(position, false); + } catch (com.sun.star.uno.RuntimeException ex) { + LOGGER.warn("OOBibBase.insertEntry:" + + " Could not go back to end of in-text citation", ex); + } } - } } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference @@ -2344,8 +1913,6 @@ private static String insertCitationGetCitationKey(BibEntry entry) { * After each fillCitationMarkInCursor call check if we lost the * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. * - * - * * @param referenceMarkNames Reference mark names * * @param citMarkers Corresponding text for each reference mark, @@ -2356,13 +1923,10 @@ private static String insertCitationGetCitationKey(BibEntry entry) { * @param style Bibliography style to use. * */ - private void - applyNewCitationMarkers( - DocumentConnection documentConnection, - CitationGroupsV001 cgs, - Map citMarkers, - OOBibStyle style - ) + private void applyNewCitationMarkers(DocumentConnection documentConnection, + CitationGroupsV001 cgs, + Map citMarkers, + OOBibStyle style) throws NoDocumentException, UndefinedCharacterFormatException, @@ -2389,42 +1953,42 @@ private static String insertCitationGetCitationKey(BibEntry entry) { // catastrophic consequences for the user. boolean mustTestCharFormat = style.isFormatCitations(); - for (CitationGroupsV001.CitationGroupID cgid : cgs.getCitationGroupIDs() ) { + for (Map.Entry kv : citMarkers.entrySet() ) { + + CitationGroupsV001.CitationGroupID cgid = kv.getKey(); + Objects.requireNonNull(cgid); + + String citationText = kv.getValue(); + Objects.requireNonNull(citationText); - CitationGroupsV001.CitationGroup cg = - cgs.getCitationGroup(cgid) - .orElseThrow(IllegalStateException::new) - ; + CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); boolean withText = (cg.itcType != OOBibBase.INVISIBLE_CIT); + if (withText) { XTextCursor cursor = cgs.getFillCursorForCitationGroup( documentConnection, - cgid // Identifies group - ); + cgid /* Identifies group */); if (mustTestCharFormat) { assertCitationCharacterFormatIsOK(cursor, style); mustTestCharFormat = false; } - fillCitationMarkInCursor( - documentConnection, - cgs, - cgid, - cursor, - citMarkers.get(cgid), // citationText - withText, - style - ); - - cgs.cleanFillCursorForCitationGroup( - documentConnection, - cgid, - !withText, - cgs.REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); + fillCitationMarkInCursor(documentConnection, + cgs, + cgid, + cursor, + citationText, + withText, + style); + + cgs.cleanFillCursorForCitationGroup(documentConnection, + cgid, + !withText, + cgs.REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); } if (hadBibSection @@ -2448,10 +2012,8 @@ static class ProduceCitationMarkersResult { /** citation markers */ Map citMarkers; - ProduceCitationMarkersResult( - CitationGroupsV001 cgs, - Map citMarkers - ) { + ProduceCitationMarkersResult(CitationGroupsV001 cgs, + Map citMarkers) { this.cgs = cgs; this.citMarkers = citMarkers; if ( cgs.getBibliography().isEmpty() ) { @@ -2481,12 +2043,9 @@ public List getUnresolvedKeys() { } } - private ProduceCitationMarkersResult - produceCitationMarkers( - DocumentConnection documentConnection, - List databases, - OOBibStyle style - ) + private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection documentConnection, + List databases, + OOBibStyle style) throws WrappedTargetException, IllegalArgumentException, @@ -2497,9 +2056,6 @@ public List getUnresolvedKeys() { CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); - - //final int nRefMarks = sortedCitationGroupIDs.size(); - cgs.lookupEntriesInDatabases( databases ); // requires cgs.lookupEntryInDatabases: needs BibEntry data @@ -2521,18 +2077,14 @@ public List getUnresolvedKeys() { // { boolean mapFootnotesToFootnoteMarks = true; - List - sortedCitationGroupIDs = - getVisuallySortedCitationGroupIDs( - cgs, - documentConnection, - mapFootnotesToFootnoteMarks - ); - cgs.setGlobalOrder( sortedCitationGroupIDs ); + List sortedCitationGroupIDs = + getVisuallySortedCitationGroupIDs(cgs, + documentConnection, + mapFootnotesToFootnoteMarks); + cgs.setGlobalOrder(sortedCitationGroupIDs); } // localOrder and globalOrder together gives us order-of-appearance of citations - // citMarkers[i] = what goes in the text at referenceMark[i] // String[] citMarkers; Map citMarkers; @@ -2542,40 +2094,21 @@ public List getUnresolvedKeys() { if (style.isCitationKeyCiteMarkers()) { citMarkers = - produceCitationMarkersForIsCitationKeyCiteMarkers( - cgs, - //sortedCitationGroupIDs, - style - ); + produceCitationMarkersForIsCitationKeyCiteMarkers(cgs, style); } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { citMarkers = - produceCitationMarkersForIsNumberEntriesIsSortByPosition( - cgs, - //sortedCitationGroupIDs, - style); + produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); } else { citMarkers = - produceCitationMarkersForIsNumberEntriesNotSortByPosition( - cgs, - style); + produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); } } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { - citMarkers = - produceCitationMarkersForNormalStyle( - cgs, - // referenceMarkNames, - // bibtexKeys, - // fce.citeKeyToBibEntry, - // itcTypes, - // fce.entries, - style); + citMarkers = produceCitationMarkersForNormalStyle(cgs, style); } - return new ProduceCitationMarkersResult( - cgs, // has bibliography as a side effect - citMarkers - ); + return new ProduceCitationMarkersResult(cgs, /* has bibliography as a side effect */ + citMarkers); } /* ************************************************** @@ -2598,13 +2131,8 @@ public List getUnresolvedKeys() { * * Used by rebuildBibTextSection */ - private //Map - List - sortEntriesByRefMarkNames( - CitationGroupsV001 cgs - ) { + private List sortEntriesByRefMarkNames(CitationGroupsV001 cgs) { Set seen = new HashSet<>(); - List res = new ArrayList<>(); for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { List cits = cgs.getSortedCitations(cgid); @@ -2628,14 +2156,9 @@ public List getUnresolvedKeys() { * if `style.isSortByPosition()` */ private void - rebuildBibTextSection( - DocumentConnection documentConnection, - OOBibStyle style, - CitationGroupsV001.CitedKeys bibliography - // List jabRefReferenceMarkNamesSortedByPosition, - // final Map uniqueLetters, - // FindCitedEntriesResult fce - ) + rebuildBibTextSection(DocumentConnection documentConnection, + OOBibStyle style, + CitationGroupsV001.CitedKeys bibliography) throws NoSuchElementException, WrappedTargetException, @@ -2662,13 +2185,9 @@ public List getUnresolvedKeys() { */ clearBibTextSectionContent2(documentConnection); - populateBibTextSection( - documentConnection, - bibliography, - // entries, - style - // uniqueLetters - ); + populateBibTextSection(documentConnection, + bibliography, + style); } /** @@ -2684,12 +2203,11 @@ public List getUnresolvedKeys() { * Only called from populateBibTextSection (and that from rebuildBibTextSection) */ private void - insertFullReferenceAtCursor( - DocumentConnection documentConnection, - XTextCursor cursor, - CitationGroupsV001.CitedKeys bibliography, - OOBibStyle style, - String parFormat) + insertFullReferenceAtCursor(DocumentConnection documentConnection, + XTextCursor cursor, + CitationGroupsV001.CitedKeys bibliography, + OOBibStyle style, + String parFormat) throws UndefinedParagraphFormatException, IllegalArgumentException, @@ -2769,9 +2287,6 @@ public List getUnresolvedKeys() { bibentry, database, ck.uniqueLetter.orElse(null) - // uniqueLetters.get(bibentry - // .getCitationKey() - // .orElse(null)) ); } } @@ -2998,17 +2513,11 @@ public List getUnresolvedKeys() { List currentGroup = new ArrayList<>(); XTextCursor currentGroupCursor = null; XTextCursor cursorBetween = null; - // Integer prev = null; CitationGroupsV001.CitationGroup prev = null; XTextRange prevRange = null; for (CitationGroupsV001.CitationGroupID cgid : referenceMarkNames) { - CitationGroupsV001.CitationGroup cg = - cgs.getCitationGroup(cgid) - .orElseThrow( IllegalStateException::new ); - - // for (int i = 0; i < referenceMarkNames.size(); i++) { - // final String name = referenceMarkNames.get(i); + CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); XTextRange currentRange = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); Objects.requireNonNull(currentRange); @@ -3314,11 +2823,8 @@ public List getUnresolvedKeys() { * Do the opposite of combineCiteMarkers. * Combined markers are split, with a space inserted between. */ - public void - unCombineCiteMarkers( - List databases, - OOBibStyle style - ) + public void unCombineCiteMarkers(List databases, + OOBibStyle style) throws IOException, WrappedTargetException, @@ -3359,23 +2865,12 @@ public List getUnresolvedKeys() { int pivot = 0; boolean setCharStyleTested = false; - // XNameAccess nameAccess = documentConnection.getReferenceMarks(); while (pivot < (names.size())) { CitationGroupsV001.CitationGroupID cgid = names.get(pivot); - CitationGroupsV001.CitationGroup cg = - cgs.getCitationGroup(cgid) - .orElseThrow(IllegalStateException::new); - - /* XTextRange range1 = - * DocumentConnection.asTextContent( - * nameAccess.getByName(names.get(pivot))) - * .getAnchor(); - */ + CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); XTextRange range1 = cgs.getReferenceMarkRangeOrNull(documentConnection,cgid); - - XTextCursor textCursor = - range1.getText().createTextCursorByRange(range1); + XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); // If we are supposed to set character format for // citations, test this before making any changes. This @@ -3397,14 +2892,6 @@ public List getUnresolvedKeys() { List keys = cits.stream().map(cit -> cit.citationKey).collect(Collectors.toList()); - /* - List keys = parseRefMarkNameToUniqueCitationKeys(names.get(pivot)); - if (keys.size() <= 1) { - pivot++; - continue; - } - */ - cgs.removeCitationGroup( cg, documentConnection ); // documentConnection.removeReferenceMark(names.get(pivot)); @@ -3458,32 +2945,24 @@ public List getUnresolvedKeys() { } if (madeModifications) { - // List jabRefReferenceMarkNamesSortedByPosition = - // getJabRefReferenceMarkNamesSortedByPosition(documentConnection); ProduceCitationMarkersResult x = - produceCitationMarkers( - documentConnection, - databases, - style - ); - try { - if (useLockControllers) { - documentConnection.lockControllers(); - } - // refreshCiteMarkers(databases, style, jabRefReferenceMarkNamesSortedByPosition); - applyNewCitationMarkers( - documentConnection, - //x.jabRefReferenceMarkNamesSortedByPosition, - x.cgs, - x.citMarkers, - //x.itcTypes, - style); - } finally { - if (useLockControllers) { - documentConnection.unlockControllers(); + produceCitationMarkers(documentConnection, + databases, + style); + try { + if (useLockControllers) { + documentConnection.lockControllers(); + } + applyNewCitationMarkers(documentConnection, + x.cgs, + x.citMarkers, + style); + } finally { + if (useLockControllers) { + documentConnection.unlockControllers(); + } } } - } } finally { documentConnection.leaveUndoContext(); } @@ -3706,10 +3185,8 @@ void styleIsRequired(OOBibStyle style) * @return List of unresolved citation keys. * */ - public List - updateDocumentActionHelper( - List databases, - OOBibStyle style) + public List updateDocumentActionHelper(List databases, + OOBibStyle style) throws NoSuchElementException, WrappedTargetException, @@ -3731,43 +3208,31 @@ void styleIsRequired(OOBibStyle style) try { documentConnection.enterUndoContext("Refresh bibliography"); - boolean requireSeparation = false; // may loose citation without requireSeparation=true - CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); - int maxReportedOverlaps = 10; - checkRangeOverlaps(cgs, this.xDocumentConnection, requireSeparation, maxReportedOverlaps); - final boolean useLockControllers = true; - try { - ProduceCitationMarkersResult x = - produceCitationMarkers( - documentConnection, - databases, - style - ); - - if (useLockControllers) { - documentConnection.lockControllers(); - } - applyNewCitationMarkers( - documentConnection, - // x.jabRefReferenceMarkNamesSortedByPosition, - x.cgs, - x.citMarkers, - // x.itcTypes, - style); - rebuildBibTextSection( - documentConnection, - style, - x.getBibliography() - // x.jabRefReferenceMarkNamesSortedByPosition, - // x.uniqueLetters, - // x.fce - ); - return x.getUnresolvedKeys(); - } finally { - if (useLockControllers) { - documentConnection.unlockControllers(); + boolean requireSeparation = false; + CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + int maxReportedOverlaps = 10; + checkRangeOverlaps(cgs, this.xDocumentConnection, requireSeparation, maxReportedOverlaps); + final boolean useLockControllers = true; + try { + ProduceCitationMarkersResult x = produceCitationMarkers(documentConnection, + databases, + style); + if (useLockControllers) { + documentConnection.lockControllers(); + } + applyNewCitationMarkers(documentConnection, + x.cgs, + x.citMarkers, + style); + rebuildBibTextSection(documentConnection, + style, + x.getBibliography()); + return x.getUnresolvedKeys(); + } finally { + if (useLockControllers) { + documentConnection.unlockControllers(); + } } - } } finally { documentConnection.leaveUndoContext(); } diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java index cb9de128247..8a28dcb2a95 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java @@ -34,7 +34,8 @@ class RangeKeyedMap { public boolean containsKey(XTextRange r) { - return xxs.containsKey( r.getText() ) && xxs.get(r).containsKey(r); + return xxs.containsKey( r.getText() ) + && xxs.get(r).containsKey(r); } public V @@ -60,6 +61,7 @@ class RangeKeyedMap { TreeMap xs = xxs.get(r.getText()); if ( xs == null ){ xs = new TreeMap<>( RangeKeyedMap::comparator ); + xxs.put( r.getText(), xs ); } return xs.put( r, value ); } From 6c44ca4379ff94434b69d6d7ed78d2b91f77a31e Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Mar 2021 15:46:57 +0100 Subject: [PATCH 0492/1068] Do emit unresolved citations As first in citation group. As first in AuthorYear style. For numbered styles it is still mixed in. --- .../gui/openoffice/CitationGroupsV001.java | 37 +++-- .../org/jabref/gui/openoffice/OOBibBase.java | 154 ++++++++++-------- .../gui/openoffice/OpenOfficePanel.java | 38 +++-- src/main/resources/l10n/JabRef_en.properties | 2 +- 4 files changed, 136 insertions(+), 95 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index b415ea2661a..e5bba06d1a4 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -164,6 +164,9 @@ class CitationAndIndex { } } + /** + * Sort citations for presentation within a CitationGroup. + */ class SortCitations implements Comparator { Comparator entryComparator; @@ -174,17 +177,21 @@ class SortCitations implements Comparator { public int compare(CitationAndIndex a, CitationAndIndex b) { if ( a.c.db.isEmpty() && b.c.db.isEmpty() ){ - // compare by citation key + // Both are unresolved: compare them by citation key. String ack = a.c.citationKey; String bck = b.c.citationKey; return ack.compareTo(bck); } + // Comparing unresolved and real entry + final boolean unresolvedComesFirst = true; + final int mul = unresolvedComesFirst ? (+1) : (-1); if ( a.c.db.isEmpty() ){ - return 1; + return -1*mul; } if ( b.c.db.isEmpty() ){ - return -1; + return +1*mul; } + // Proper comparison of entries return entryComparator.compare( a.c.db.get().entry, b.c.db.get().entry @@ -419,6 +426,9 @@ class CitedKeys { return new ArrayList<>(data.values()); } + /** + * Sort entries for the bibliography. + */ class SortCitedKeys implements Comparator { Comparator entryComparator; @@ -429,14 +439,19 @@ class SortCitedKeys implements Comparator { public int compare(CitedKey a, CitedKey b) { if (a.db.isEmpty() && b.db.isEmpty()) { + // Both are unresolved: compare them by citation key. return a.key.compareTo(b.key); } + // Comparing unresolved and real entry + final boolean unresolvedComesFirst = true; + final int mul = unresolvedComesFirst ? (+1) : (-1); if (a.db.isEmpty()){ - return 1; + return -1*mul; } if (b.db.isEmpty()){ - return -1; + return +1*mul; } + // Proper comparison of entries return entryComparator.compare(a.db.get().entry, b.db.get().entry); } @@ -603,11 +618,11 @@ Optional getBibliography() { } public void - createNumberedBibliogaphySortedInOrderOfAppearance() { + createNumberedBibliographySortedInOrderOfAppearance() { CitationGroupsV001 cgs = this; if (!cgs.bibliography.isEmpty()) { throw new RuntimeException( - "createNumberedBibliogaphySortedInOrderOfAppearance: already have a bibliography" + "createNumberedBibliographySortedInOrderOfAppearance: already have a bibliography" ); } CitationGroupsV001.CitedKeys sortedCitedKeys = @@ -618,11 +633,11 @@ Optional getBibliography() { } public void - createNumberedBibliogaphySortedByComparator( Comparator entryComparator ) { + createNumberedBibliographySortedByComparator( Comparator entryComparator ) { CitationGroupsV001 cgs = this; if (!cgs.bibliography.isEmpty()) { throw new RuntimeException( - "createNumberedBibliogaphySortedByComparator: already have a bibliography" + "createNumberedBibliographySortedByComparator: already have a bibliography" ); } CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); @@ -633,11 +648,11 @@ Optional getBibliography() { } public void - createPlainBibliogaphySortedByComparator( Comparator entryComparator ) { + createPlainBibliographySortedByComparator( Comparator entryComparator ) { CitationGroupsV001 cgs = this; if (!this.bibliography.isEmpty()) { throw new RuntimeException( - "createPlainBibliogaphySortedByComparator: already have a bibliography" + "createPlainBibliographySortedByComparator: already have a bibliography" ); } CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4176552ba73..e835a3ec68a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1217,7 +1217,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes assert style.isCitationKeyCiteMarkers(); - cgs.createPlainBibliogaphySortedByComparator(OOBibBase.entryComparator); + cgs.createPlainBibliographySortedByComparator(OOBibBase.entryComparator); Map citMarkers = new HashMap<>(); @@ -1258,7 +1258,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes assert style.isNumberEntries(); assert style.isSortByPosition(); - cgs.createNumberedBibliogaphySortedInOrderOfAppearance(); + cgs.createNumberedBibliographySortedInOrderOfAppearance(); final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); @@ -1284,7 +1284,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes assert style.isNumberEntries(); assert !style.isSortByPosition(); - cgs.createNumberedBibliogaphySortedByComparator( entryComparator ); + cgs.createNumberedBibliographySortedByComparator( entryComparator ); final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); @@ -1325,7 +1325,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes createNormalizedCitationMarkersForNormalStyle(sortedCitedKeys, style); createUniqueLetters(sortedCitedKeys, cgs); // calls distributeUniqueLetters(cgs) - cgs.createPlainBibliogaphySortedByComparator(entryComparator); + cgs.createPlainBibliographySortedByComparator(entryComparator); // Finally, go through all citation markers, and update // those referring to entries in our current list: @@ -2168,21 +2168,6 @@ private List sortEntriesByRefMarkNames(CitationGrou UnknownPropertyException, UndefinedParagraphFormatException { - /* - * Map entries; - * - * if (style.isSortByPosition()) { - * // We need to sort the entries according to their order of appearance: - * entries = - * sortEntriesByRefMarkNames( - * jabRefReferenceMarkNamesSortedByPosition, - * fce.citeKeyToBibEntry, - * fce.entries - * ); - * } else { - * entries = sortEntriesByComparator(fce.entries, entryComparator); - * } - */ clearBibTextSectionContent2(documentConnection); populateBibTextSection(documentConnection, @@ -2190,6 +2175,22 @@ private List sortEntriesByRefMarkNames(CitationGrou style); } + /* + enum BibliographyOrder { + Unspecified, + ByFirstAppearanceInTheText, + ByEntryComparator + } + + BibliographyOrder bibliographyOrderOfStyle( OOBibStyle style ) { + if (style.isSortByPosition()) { + return ByFirstAppearanceInTheText; + } else { + return ByEntryComparator; + } + } + */ + /** * Insert body of bibliography at `cursor`. * @@ -2215,66 +2216,77 @@ private List sortEntriesByRefMarkNames(CitationGrou PropertyVetoException, WrappedTargetException { + final boolean debugThisFun = false; + /* + * Map entries; + * + * if (style.isSortByPosition()) { + * // We need to sort the entries according to their order of appearance: + * entries = + * sortEntriesByRefMarkNames( + * jabRefReferenceMarkNamesSortedByPosition, + * fce.citeKeyToBibEntry, + * fce.entries + * ); + * } else { + * entries = sortEntriesByComparator(fce.entries, entryComparator); + * } + */ + + if (debugThisFun) { + System.out.printf("Ref isSortByPosition %s\n", style.isSortByPosition()); + System.out.printf("Ref isNumberEntries %s\n", style.isNumberEntries()); + } + for (CitationGroupsV001.CitedKey ck : bibliography.values()) { - int number = 1; - int nUnresolved = 0; - // for (Map.Entry entry : entries.entrySet()) { - // - // Optional db = ck.db; - // - // BibEntry bibentry = entry.getKey(); - // BibDatabase database = entry.getValue(); - // // skip unresolved entries - // if (bibentry instanceof UndefinedBibtexEntry) { - // continue; - // } + if (debugThisFun) { + System.out.printf("Ref cit %-20s ck.number %7s%n", + String.format("'%s'",ck.key), + (ck.number.isEmpty() + ? "(empty)" + : String.format("%02d",ck.number.get()))); + } - if ( ck.db.isEmpty() ) { - // skip unresolved entries - nUnresolved++; - continue; - } else { + OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - BibEntry bibentry = ck.db.get().entry; - BibDatabase database = ck.db.get().database; + // insert marker "[1]" + if (style.isNumberEntries()) { - OOUtil.insertParagraphBreak(documentConnection.xText, cursor); + if ( ck.number.isEmpty() ) { + throw new RuntimeException( + "insertFullReferenceAtCursor: numbered style, but found unnumbered entry"); + } - // insert marker - if (style.isNumberEntries()) { + // Note: minGroupingCount is pointless here, we are + // formatting a single entry. + // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + int minGroupingCount = 2; + List numbers = Collections.singletonList(ck.number.get()); + String marker = style.getNumCitationMarker(numbers, + minGroupingCount, + true); + + OOUtil.insertTextAtCurrentLocation(documentConnection.xText, + cursor, + marker, + Collections.emptyList()); + } else { + // !style.isNumberEntries() : emit no prefix + // TODO: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); + } - if ( ck.number.isEmpty() ) { - throw new RuntimeException( - "insertFullReferenceAtCursor: numbered style, but found unnumbered entry" - ); - } else { - if ( ck.number.get() != (number + nUnresolved) ) { - throw new RuntimeException( - "insertFullReferenceAtCursor: numbering is not in sync" - ); - } - } + if ( ck.db.isEmpty() ) { + // skip unresolved entries + OOUtil.insertTextAtCurrentLocation(documentConnection.xText, + cursor, + String.format("Unresolved(%s)", ck.key), + Collections.emptyList()); + // continue; + } else { - // Note: minGroupingCount is pointless here, we are - // formatting a single entry. - // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - int minGroupingCount = 2; - List numbers = Collections.singletonList(number++); - String marker = - style.getNumCitationMarker( - numbers, - minGroupingCount, - true); - - OOUtil.insertTextAtCurrentLocation( - documentConnection.xText, - cursor, - marker, - Collections.emptyList() - ); - } + BibEntry bibentry = ck.db.get().entry; // insert the actual details. Layout layout = style.getReferenceFormat(bibentry.getType()); @@ -2285,7 +2297,7 @@ private List sortEntriesByRefMarkNames(CitationGrou layout, parFormat, bibentry, - database, + ck.db.get().database, ck.uniqueLetter.orElse(null) ); } diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 8eae192e84b..914710ebc15 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -205,9 +205,10 @@ private void initPanel() { dialogService .showErrorDialogAndWait( Localization.lang("Unable to synchronize bibliography"), - Localization.lang("Your OpenOffice/LibreOffice document references" - + " citation keys which could not be found" - + " in your current library.") + Localization.lang( + "Your OpenOffice/LibreOffice document references" + + " citation keys which could not be found" + + " in your current library.") + "\n" + String.join(" ", unresolvedKeys)); } @@ -226,22 +227,35 @@ private void initPanel() { showNoDocumentErrorMessage(); } catch (IOException ex) { LOGGER.warn("Problem with style file", ex); - dialogService.showErrorDialogAndWait(Localization.lang("No valid style file defined"), - Localization.lang("You must select either a valid style file, or use one of the default styles.")); + dialogService.showErrorDialogAndWait( + Localization.lang("No valid style file defined"), + Localization.lang("You must select either a valid style file," + + " or use one of the default styles.")); } catch (BibEntryNotFoundException ex) { LOGGER.debug("BibEntry not found", ex); - dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), Localization.lang( - "Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - ex.getCitationKey())); - } catch (com.sun.star.lang.IllegalArgumentException | PropertyVetoException | UnknownPropertyException | WrappedTargetException | NoSuchElementException | - InvalidStateException | - CreationException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("Unable to synchronize bibliography"), + Localization.lang("Your OpenOffice/LibreOffice document" + + " references the citation key '%0'," + + " which could not be found in your current library.", + ex.getCitationKey())); + } catch (com.sun.star.lang.IllegalArgumentException + | PropertyVetoException + | UnknownPropertyException + | WrappedTargetException + | NoSuchElementException + | InvalidStateException + | CreationException ex) { LOGGER.warn("Could not update bibliography", ex); } }); merge.setMaxWidth(Double.MAX_VALUE); - merge.setTooltip(new Tooltip(Localization.lang("Combine pairs of citations that are separated by spaces only"))); + merge.setTooltip( + new Tooltip( + Localization.lang( + "Combine pairs of citations" + + " that are separated by spaces only"))); merge.setOnAction(e -> { try { ooBase.combineCiteMarkers(getBaseList(), style); diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index b7cd618ea5a..ad5a9eb2fdd 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1023,7 +1023,7 @@ Problem\ modifying\ citation=Problem modifying citation Problem\ collecting\ citations=Problem collecting citations Citation=Citation Connecting...=Connecting... -Could\ not\ resolve\ BibTeX\ entry\ for\ citation\ marker\ '%0'.=Could not resolve BibTeX entry for citation marker '%0'. + Select\ style=Select style Journals=Journals Cite=Cite From 5e4c4cdd84117e2f85004415a0b0d5cee49a9995 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 21 Mar 2021 22:46:46 +0100 Subject: [PATCH 0493/1068] Add "Cited on pages" for Unresolved() entries in bibliography --- .../gui/openoffice/DocumentConnection.java | 72 ++++++ .../org/jabref/gui/openoffice/OOBibBase.java | 235 ++++++++++++++++-- src/main/resources/l10n/JabRef_en.properties | 4 + 3 files changed, 295 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java index 6091ff1689c..035103c736c 100644 --- a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java @@ -69,6 +69,8 @@ import com.sun.star.lang.XComponent; // import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.text.ReferenceFieldSource; +import com.sun.star.text.ReferenceFieldPart; import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XFootnote; import com.sun.star.text.XReferenceMarksSupplier; @@ -87,6 +89,7 @@ import com.sun.star.uno.UnoRuntime; // import com.sun.star.uno.XComponentContext; import com.sun.star.util.InvalidStateException; +import com.sun.star.util.XRefreshable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -681,6 +684,75 @@ class DocumentConnection { ); } + /** + * Insert a clickable cross-reference to a reference mark, + * with a label containing the target's page number. + * + * May need a documentConnection.refresh() after, to update + * the text shown. + */ + public void + insertGetreferenceToPageNumberOfReferenceMark( + String referenceMarkName, + XTextRange cursor + ) + throws + CreationException, + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + + DocumentConnection documentConnection = this; + // based on: https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Reference_Marks + + // Create a 'GetReference' text field to refer to the reference mark we just inserted, + // and get it's XPropertySet interface + XPropertySet xFieldProps; + try { + xFieldProps = + (XPropertySet) unoQI(XPropertySet.class, + this.mxDocFactory.createInstance( + "com.sun.star.text.textfield.GetReference")); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + + // Set the SourceName of the GetReference text field to the referenceMarkName + xFieldProps.setPropertyValue("SourceName", referenceMarkName); + + // specify that the source is a reference mark (could also be a footnote, + // bookmark or sequence field) + xFieldProps.setPropertyValue ("ReferenceFieldSource", + new Short(ReferenceFieldSource.REFERENCE_MARK)); + + // We want the reference displayed as page number + xFieldProps.setPropertyValue("ReferenceFieldPart", + new Short (ReferenceFieldPart.PAGE)); + + // Get the XTextContent interface of the GetReference text field + XTextContent xRefContent = (XTextContent) unoQI(XTextContent.class, xFieldProps); + + // Make some text to precede the reference + // this.xText.insertString(cursor.getEnd(), "Page ", false); + + // Insert the text field + this.xText.insertTextContent(cursor.getEnd(), xRefContent, false); + + this.refresh(); + } + + /** + * Update TextFields, etc. + */ + public void + refresh() { + // Refresh the document + XRefreshable xRefresh = + (XRefreshable) unoQI(XRefreshable.class, + this.mxDoc); + xRefresh.refresh(); + } + /** * Create a text section with the provided name and insert it at * the provided cursor. diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e835a3ec68a..fd93431b21e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -71,6 +71,8 @@ import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.text.ReferenceFieldSource; +import com.sun.star.text.ReferenceFieldPart; import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XFootnote; import com.sun.star.text.XReferenceMarksSupplier; @@ -84,11 +86,14 @@ import com.sun.star.text.XTextSectionsSupplier; import com.sun.star.text.XTextViewCursor; import com.sun.star.text.XTextViewCursorSupplier; +//import com.sun.star.text.textfield.GetReference; +//import com.sun.star.text.GetReference; import com.sun.star.uno.Any; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; import com.sun.star.util.InvalidStateException; +import com.sun.star.util.XRefreshable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -1870,6 +1875,7 @@ public void insertCitation(List entries, // Insert it at the current position: rebuildBibTextSection(documentConnection, style, + x.cgs, x.getBibliography()); } finally { documentConnection.unlockControllers(); @@ -2158,6 +2164,7 @@ private List sortEntriesByRefMarkNames(CitationGrou private void rebuildBibTextSection(DocumentConnection documentConnection, OOBibStyle style, + CitationGroupsV001 cgs, CitationGroupsV001.CitedKeys bibliography) throws NoSuchElementException, @@ -2171,6 +2178,7 @@ private List sortEntriesByRefMarkNames(CitationGrou clearBibTextSectionContent2(documentConnection); populateBibTextSection(documentConnection, + cgs, bibliography, style); } @@ -2206,6 +2214,7 @@ BibliographyOrder bibliographyOrderOfStyle( OOBibStyle style ) { private void insertFullReferenceAtCursor(DocumentConnection documentConnection, XTextCursor cursor, + CitationGroupsV001 cgs, CitationGroupsV001.CitedKeys bibliography, OOBibStyle style, String parFormat) @@ -2214,9 +2223,181 @@ BibliographyOrder bibliographyOrderOfStyle( OOBibStyle style ) { IllegalArgumentException, UnknownPropertyException, PropertyVetoException, - WrappedTargetException { + WrappedTargetException, + CreationException { final boolean debugThisFun = false; + + + + /* + List ss = + Arrays.asList(documentConnection.mxDocFactory.getAvailableServiceNames()); + for ( String s : ss ) { + System.out.printf("%s\n", s); + } + /* + + +------- + com.sun.star.form.component.TextField + com.sun.star.text.TextEmbeddedObject + com.sun.star.text.Bookmark + com.sun.star.text.Footnote + com.sun.star.text.Endnote + com.sun.star.text.ReferenceMark +com.sun.star.style.CharacterStyle +com.sun.star.style.ParagraphStyle +com.sun.star.style.FrameStyle +com.sun.star.style.PageStyle +com.sun.star.style.NumberingStyle +com.sun.star.text.ContentIndexMark +com.sun.star.text.ContentIndex +com.sun.star.text.UserIndexMark +com.sun.star.text.UserIndex +com.sun.star.text.TextSection +com.sun.star.text.TextField.DateTime +com.sun.star.text.TextField.User +com.sun.star.text.TextField.SetExpression +com.sun.star.text.TextField.GetExpression +com.sun.star.text.TextField.FileName +com.sun.star.text.TextField.PageNumber +com.sun.star.text.TextField.Author +com.sun.star.text.TextField.Chapter +com.sun.star.text.TextField.GetReference +com.sun.star.text.TextField.ConditionalText +com.sun.star.text.TextField.Annotation +com.sun.star.text.TextField.Input +com.sun.star.text.TextField.Macro +com.sun.star.text.TextField.DDE +com.sun.star.text.TextField.HiddenParagraph +com.sun.star.text.TextField.TemplateName +com.sun.star.text.TextField.ExtendedUser +com.sun.star.text.TextField.ReferencePageSet +com.sun.star.text.TextField.ReferencePageGet +com.sun.star.text.TextField.JumpEdit +com.sun.star.text.TextField.Script +com.sun.star.text.TextField.DatabaseNextSet +com.sun.star.text.TextField.DatabaseNumberOfSet +com.sun.star.text.TextField.DatabaseSetNumber +com.sun.star.text.TextField.Database +com.sun.star.text.TextField.DatabaseName +com.sun.star.text.TextField.TableFormula +com.sun.star.text.TextField.PageCount +com.sun.star.text.TextField.ParagraphCount +com.sun.star.text.TextField.WordCount +com.sun.star.text.TextField.CharacterCount +com.sun.star.text.TextField.TableCount +com.sun.star.text.TextField.GraphicObjectCount +com.sun.star.text.TextField.EmbeddedObjectCount +com.sun.star.text.TextField.DocInfo.ChangeAuthor +com.sun.star.text.TextField.DocInfo.ChangeDateTime +com.sun.star.text.TextField.DocInfo.EditTime +com.sun.star.text.TextField.DocInfo.Description +com.sun.star.text.TextField.DocInfo.CreateAuthor +com.sun.star.text.TextField.DocInfo.CreateDateTime +com.sun.star.text.TextField.DocInfo.Custom +com.sun.star.text.TextField.DocInfo.PrintAuthor +com.sun.star.text.TextField.DocInfo.PrintDateTime +com.sun.star.text.TextField.DocInfo.KeyWords +com.sun.star.text.TextField.DocInfo.Subject +com.sun.star.text.TextField.DocInfo.Title +com.sun.star.text.TextField.DocInfo.Revision +com.sun.star.text.TextField.Bibliography +com.sun.star.text.TextField.CombinedCharacters +com.sun.star.text.TextField.DropDown +com.sun.star.text.textfield.MetadataField +com.sun.star.text.FieldMaster.User +com.sun.star.text.FieldMaster.DDE +com.sun.star.text.FieldMaster.SetExpression +com.sun.star.text.FieldMaster.Database +com.sun.star.text.FieldMaster.Bibliography +com.sun.star.text.IllustrationsIndex +com.sun.star.text.ObjectIndex +com.sun.star.text.TableIndex +com.sun.star.text.Bibliography +com.sun.star.text.Paragraph +com.sun.star.text.TextField.InputUser +com.sun.star.text.TextField.HiddenText +com.sun.star.style.ConditionalParagraphStyle +com.sun.star.text.NumberingRules +com.sun.star.text.TextColumns +com.sun.star.text.IndexHeaderSection +com.sun.star.text.Defaults +com.sun.star.image.ImageMapRectangleObject +com.sun.star.image.ImageMapCircleObject +com.sun.star.image.ImageMapPolygonObject +com.sun.star.text.TextGraphicObject +com.sun.star.chart2.data.DataProvider +com.sun.star.text.Fieldmark +com.sun.star.text.FormFieldmark +com.sun.star.text.InContentMetadata +ooo.vba.VBAObjectModuleObjectProvider +ooo.vba.VBACodeNameProvider +ooo.vba.VBAProjectNameProvider +ooo.vba.VBAGlobals +com.sun.star.text.textfield.DateTime +com.sun.star.text.textfield.User +com.sun.star.text.textfield.SetExpression +com.sun.star.text.textfield.GetExpression +com.sun.star.text.textfield.FileName +com.sun.star.text.textfield.PageNumber +com.sun.star.text.textfield.Author +com.sun.star.text.textfield.Chapter +com.sun.star.text.textfield.GetReference +com.sun.star.text.textfield.ConditionalText +com.sun.star.text.textfield.Annotation +com.sun.star.text.textfield.Input +com.sun.star.text.textfield.Macro +com.sun.star.text.textfield.DDE +com.sun.star.text.textfield.HiddenParagraph +com.sun.star.text.textfield.TemplateName +com.sun.star.text.textfield.ExtendedUser +com.sun.star.text.textfield.ReferencePageSet +com.sun.star.text.textfield.ReferencePageGet +com.sun.star.text.textfield.JumpEdit +com.sun.star.text.textfield.Script +com.sun.star.text.textfield.DatabaseNextSet +com.sun.star.text.textfield.DatabaseNumberOfSet +com.sun.star.text.textfield.DatabaseSetNumber +com.sun.star.text.textfield.Database +com.sun.star.text.textfield.DatabaseName +com.sun.star.text.textfield.TableFormula +com.sun.star.text.textfield.PageCount +com.sun.star.text.textfield.ParagraphCount +com.sun.star.text.textfield.WordCount +com.sun.star.text.textfield.CharacterCount +com.sun.star.text.textfield.TableCount +com.sun.star.text.textfield.GraphicObjectCount +com.sun.star.text.textfield.EmbeddedObjectCount +com.sun.star.text.textfield.docinfo.ChangeAuthor +com.sun.star.text.textfield.docinfo.ChangeDateTime +com.sun.star.text.textfield.docinfo.EditTime +com.sun.star.text.textfield.docinfo.Description +com.sun.star.text.textfield.docinfo.CreateAuthor +com.sun.star.text.textfield.docinfo.CreateDateTime +com.sun.star.text.textfield.docinfo.PrintAuthor +com.sun.star.text.textfield.docinfo.PrintDateTime +com.sun.star.text.textfield.docinfo.KeyWords +com.sun.star.text.textfield.docinfo.Subject +com.sun.star.text.textfield.docinfo.Title +com.sun.star.text.textfield.docinfo.Revision +com.sun.star.text.textfield.docinfo.Custom +com.sun.star.text.textfield.Bibliography +com.sun.star.text.textfield.CombinedCharacters +com.sun.star.text.textfield.DropDown +com.sun.star.text.textfield.InputUser +com.sun.star.text.textfield.HiddenText +com.sun.star.text.fieldmaster.User +com.sun.star.text.fieldmaster.DDE +com.sun.star.text.fieldmaster.SetExpression +com.sun.star.text.fieldmaster.Database +com.sun.star.text.fieldmaster.Bibliography +com.sun.star.style.TableStyle +com.sun.star.style.CellStyle + + */ + /* * Map entries; * @@ -2283,7 +2464,40 @@ BibliographyOrder bibliographyOrderOfStyle( OOBibStyle style ) { cursor, String.format("Unresolved(%s)", ck.key), Collections.emptyList()); - // continue; + // Try to list citations: + if (true) { + + OOUtil.insertTextAtCurrentLocation( + documentConnection.xText, + cursor, + String.format(" %s ", Localization.lang("CitedOnPagesPrefix")), + Collections.emptyList()); + + int last = ck.where.size(); + int i=0; + for (CitationGroupsV001.CitationPath p : ck.where) { + CitationGroupsV001.CitationGroupID cgid = p.group; + CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + String refMarkName = cg.referenceMarkName; + + if (i > 0) { + OOUtil.insertTextAtCurrentLocation(documentConnection.xText, + cursor, + String.format(", "), + Collections.emptyList()); + } + documentConnection + .insertGetreferenceToPageNumberOfReferenceMark(refMarkName,cursor); + i++; + } + documentConnection.refresh(); + + OOUtil.insertTextAtCurrentLocation( + documentConnection.xText, + cursor, + String.format("%s", Localization.lang("CitedOnPagesSuffix")), + Collections.emptyList()); + } } else { BibEntry bibentry = ck.db.get().entry; @@ -2381,6 +2595,7 @@ BibliographyOrder bibliographyOrderOfStyle( OOBibStyle style ) { private void populateBibTextSection( DocumentConnection documentConnection, + CitationGroupsV001 cgs, CitationGroupsV001.CitedKeys bibliography, // Map entries, OOBibStyle style @@ -2415,6 +2630,7 @@ BibliographyOrder bibliographyOrderOfStyle( OOBibStyle style ) { insertFullReferenceAtCursor( documentConnection, cursor, + cgs, bibliography, // entries, style, @@ -3020,27 +3236,13 @@ public ExportCitedHelperResult exportCitedHelper( BibEntryNotFoundException, InvalidStateException { - // ExportCitedHelperResult res = new ExportCitedHelperResult(); DocumentConnection documentConnection = getDocumentConnectionOrThrow(); try { documentConnection.enterUndoContext("Changes during \"Export cited\""); - - // CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); - /* - ProduceCitationMarkersResult x = - produceCitationMarkers( - // cgs, - documentConnection, - databases, - style); - res.unresolvedKeys = x.unresolvedKeys; - res.newDatabase = this.generateDatabase(databases, documentConnection); - */ return this.generateDatabase(databases, documentConnection); } finally { documentConnection.leaveUndoContext(); } - //return res; } /** @@ -3238,6 +3440,7 @@ public List updateDocumentActionHelper(List databases, style); rebuildBibTextSection(documentConnection, style, + x.cgs, x.getBibliography()); return x.getUnresolvedKeys(); } finally { diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index ad5a9eb2fdd..eabcef860ac 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -2314,11 +2314,15 @@ Unprotect\ terms=Unprotect terms Error\ connecting\ to\ Writer\ document=Error connecting to Writer document You\ need\ to\ open\ Writer\ with\ a\ document\ before\ connecting=You need to open Writer with a document before connecting + Generate\ a\ new\ key\ for\ imported\ entries\ (overwriting\ their\ default)=Generate a new key for imported entries (overwriting their default) Import\ settings=Import settings Custom\ DOI\ URI=Custom DOI URI Customization=Customization Use\ custom\ DOI\ base\ URI\ for\ article\ access=Use custom DOI base URI for article access +CitedOnPagesPrefix=(Cited on pages: +CitedOnPagesSuffix=) + Unable\ to\ find\ valid\ certification\ path\ to\ requested\ target(%0),\ download\ anyway?=Unable to find valid certification path to requested target(%0), download anyway? Download\ operation\ canceled.=Download operation canceled. From a166c1f4d2986e942b9072723e98ce8dcf39beeb Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Mar 2021 08:01:14 +0100 Subject: [PATCH 0494/1068] bug: "Separate" with multiple citations in same footnote --- .../gui/openoffice/CitationGroupsV001.java | 25 +- .../org/jabref/gui/openoffice/OOBibBase.java | 227 ++++-------------- .../jabref/gui/openoffice/RangeKeyedMap.java | 9 +- src/main/resources/l10n/JabRef_en.properties | 4 +- 4 files changed, 66 insertions(+), 199 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index e5bba06d1a4..397353fa284 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -1554,17 +1554,20 @@ private static class ParsedRefMark { XTextRange footnoteMarkRange = DocumentConnection.getFootnoteMarkRangeOrNull(r); - if (footnoteMarkRange != null) { - boolean seenContains = seen.containsKey( footnoteMarkRange ); - if (!seenContains) { - seen.put(footnoteMarkRange, true); - xs.add(new RangeForOverlapCheck( - footnoteMarkRange, - base.i, // cgid :: identifies of citation group - RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + base.description - )); - } + if (footnoteMarkRange == null) { + // not in footnote + continue; + } + + boolean seenContains = seen.containsKey( footnoteMarkRange ); + if (!seenContains) { + seen.put(footnoteMarkRange, true); + xs.add(new RangeForOverlapCheck( + footnoteMarkRange, + base.i, // cgid :: identifies of citation group + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + base.description + )); } } return xs; diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index fd93431b21e..1b57686c7f0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -851,7 +851,7 @@ public T getContent() { @Override public int hashCode() { - return Objects.hash(position, content); + return Objects.hash(position, indexInPosition, content); } } @@ -967,12 +967,13 @@ public T getContent() { List oxs = new ArrayList<>(xs.keySet()); + int indexInPartition = 0; for (int i = 0; i < oxs.size(); i++) { XTextRange a = oxs.get(i); List> avs = xs.get(a); for (int j = 0; j < avs.size(); j++){ VisualSortEntry v = avs.get(j); - v.indexInPosition = j; + v.indexInPosition = indexInPartition++; if ( mapFootnotesToFootnoteMarks ) { // Adjust range if we are inside a footnote: if (unoQI(XFootnote.class, v.range.getText()) != null) { @@ -1005,6 +1006,8 @@ public T getContent() { WrappedTargetException, NoDocumentException { + final int nCitationGroups = vses.size(); + if (documentConnection.hasControllersLocked()) { LOGGER.warn( "visualSort:" @@ -1035,6 +1038,10 @@ public T getContent() { // restore cursor position viewCursor.gotoRange(initialPos, false); + if ( positions.size() != nCitationGroups ) { + throw new RuntimeException("visualSort: positions.size() != nCitationGroups"); + } + // order by position Set>> set = new TreeSet<>(); for (int i = 0; i < vses.size(); i++) { @@ -1047,11 +1054,21 @@ public T getContent() { ); } + if ( set.size() != nCitationGroups ) { + // *** Fired *** + throw new RuntimeException("visualSort: set.size() != nCitationGroups"); + } + // collect CitationGroupIDs in order List> result = new ArrayList<>(set.size()); for (ComparableMark> mark : set) { result.add(mark.getContent()); } + + if ( result.size() != nCitationGroups ) { + throw new RuntimeException("visualSort: result.size() != nCitationGroups"); + } + return result; } @@ -1071,12 +1088,23 @@ public T getContent() { documentConnection, mapFootnotesToFootnoteMarks); - List> sorted = - visualSort( vses, documentConnection ); + if ( vses.size() != cgs.citationGroups.size() ) { + throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + + " vses.size() != cgs.citationGroups.size()"); + } + + List> sorted = + visualSort( vses, documentConnection ); + + if ( sorted.size() != cgs.citationGroups.size() ) { + // This Fired + throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + + " sorted.size() != cgs.citationGroups.size()"); + } - return (sorted.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList())); + return (sorted.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList())); } /* *************************************** @@ -2228,176 +2256,6 @@ BibliographyOrder bibliographyOrderOfStyle( OOBibStyle style ) { final boolean debugThisFun = false; - - - /* - List ss = - Arrays.asList(documentConnection.mxDocFactory.getAvailableServiceNames()); - for ( String s : ss ) { - System.out.printf("%s\n", s); - } - /* - - -------- - com.sun.star.form.component.TextField - com.sun.star.text.TextEmbeddedObject - com.sun.star.text.Bookmark - com.sun.star.text.Footnote - com.sun.star.text.Endnote - com.sun.star.text.ReferenceMark -com.sun.star.style.CharacterStyle -com.sun.star.style.ParagraphStyle -com.sun.star.style.FrameStyle -com.sun.star.style.PageStyle -com.sun.star.style.NumberingStyle -com.sun.star.text.ContentIndexMark -com.sun.star.text.ContentIndex -com.sun.star.text.UserIndexMark -com.sun.star.text.UserIndex -com.sun.star.text.TextSection -com.sun.star.text.TextField.DateTime -com.sun.star.text.TextField.User -com.sun.star.text.TextField.SetExpression -com.sun.star.text.TextField.GetExpression -com.sun.star.text.TextField.FileName -com.sun.star.text.TextField.PageNumber -com.sun.star.text.TextField.Author -com.sun.star.text.TextField.Chapter -com.sun.star.text.TextField.GetReference -com.sun.star.text.TextField.ConditionalText -com.sun.star.text.TextField.Annotation -com.sun.star.text.TextField.Input -com.sun.star.text.TextField.Macro -com.sun.star.text.TextField.DDE -com.sun.star.text.TextField.HiddenParagraph -com.sun.star.text.TextField.TemplateName -com.sun.star.text.TextField.ExtendedUser -com.sun.star.text.TextField.ReferencePageSet -com.sun.star.text.TextField.ReferencePageGet -com.sun.star.text.TextField.JumpEdit -com.sun.star.text.TextField.Script -com.sun.star.text.TextField.DatabaseNextSet -com.sun.star.text.TextField.DatabaseNumberOfSet -com.sun.star.text.TextField.DatabaseSetNumber -com.sun.star.text.TextField.Database -com.sun.star.text.TextField.DatabaseName -com.sun.star.text.TextField.TableFormula -com.sun.star.text.TextField.PageCount -com.sun.star.text.TextField.ParagraphCount -com.sun.star.text.TextField.WordCount -com.sun.star.text.TextField.CharacterCount -com.sun.star.text.TextField.TableCount -com.sun.star.text.TextField.GraphicObjectCount -com.sun.star.text.TextField.EmbeddedObjectCount -com.sun.star.text.TextField.DocInfo.ChangeAuthor -com.sun.star.text.TextField.DocInfo.ChangeDateTime -com.sun.star.text.TextField.DocInfo.EditTime -com.sun.star.text.TextField.DocInfo.Description -com.sun.star.text.TextField.DocInfo.CreateAuthor -com.sun.star.text.TextField.DocInfo.CreateDateTime -com.sun.star.text.TextField.DocInfo.Custom -com.sun.star.text.TextField.DocInfo.PrintAuthor -com.sun.star.text.TextField.DocInfo.PrintDateTime -com.sun.star.text.TextField.DocInfo.KeyWords -com.sun.star.text.TextField.DocInfo.Subject -com.sun.star.text.TextField.DocInfo.Title -com.sun.star.text.TextField.DocInfo.Revision -com.sun.star.text.TextField.Bibliography -com.sun.star.text.TextField.CombinedCharacters -com.sun.star.text.TextField.DropDown -com.sun.star.text.textfield.MetadataField -com.sun.star.text.FieldMaster.User -com.sun.star.text.FieldMaster.DDE -com.sun.star.text.FieldMaster.SetExpression -com.sun.star.text.FieldMaster.Database -com.sun.star.text.FieldMaster.Bibliography -com.sun.star.text.IllustrationsIndex -com.sun.star.text.ObjectIndex -com.sun.star.text.TableIndex -com.sun.star.text.Bibliography -com.sun.star.text.Paragraph -com.sun.star.text.TextField.InputUser -com.sun.star.text.TextField.HiddenText -com.sun.star.style.ConditionalParagraphStyle -com.sun.star.text.NumberingRules -com.sun.star.text.TextColumns -com.sun.star.text.IndexHeaderSection -com.sun.star.text.Defaults -com.sun.star.image.ImageMapRectangleObject -com.sun.star.image.ImageMapCircleObject -com.sun.star.image.ImageMapPolygonObject -com.sun.star.text.TextGraphicObject -com.sun.star.chart2.data.DataProvider -com.sun.star.text.Fieldmark -com.sun.star.text.FormFieldmark -com.sun.star.text.InContentMetadata -ooo.vba.VBAObjectModuleObjectProvider -ooo.vba.VBACodeNameProvider -ooo.vba.VBAProjectNameProvider -ooo.vba.VBAGlobals -com.sun.star.text.textfield.DateTime -com.sun.star.text.textfield.User -com.sun.star.text.textfield.SetExpression -com.sun.star.text.textfield.GetExpression -com.sun.star.text.textfield.FileName -com.sun.star.text.textfield.PageNumber -com.sun.star.text.textfield.Author -com.sun.star.text.textfield.Chapter -com.sun.star.text.textfield.GetReference -com.sun.star.text.textfield.ConditionalText -com.sun.star.text.textfield.Annotation -com.sun.star.text.textfield.Input -com.sun.star.text.textfield.Macro -com.sun.star.text.textfield.DDE -com.sun.star.text.textfield.HiddenParagraph -com.sun.star.text.textfield.TemplateName -com.sun.star.text.textfield.ExtendedUser -com.sun.star.text.textfield.ReferencePageSet -com.sun.star.text.textfield.ReferencePageGet -com.sun.star.text.textfield.JumpEdit -com.sun.star.text.textfield.Script -com.sun.star.text.textfield.DatabaseNextSet -com.sun.star.text.textfield.DatabaseNumberOfSet -com.sun.star.text.textfield.DatabaseSetNumber -com.sun.star.text.textfield.Database -com.sun.star.text.textfield.DatabaseName -com.sun.star.text.textfield.TableFormula -com.sun.star.text.textfield.PageCount -com.sun.star.text.textfield.ParagraphCount -com.sun.star.text.textfield.WordCount -com.sun.star.text.textfield.CharacterCount -com.sun.star.text.textfield.TableCount -com.sun.star.text.textfield.GraphicObjectCount -com.sun.star.text.textfield.EmbeddedObjectCount -com.sun.star.text.textfield.docinfo.ChangeAuthor -com.sun.star.text.textfield.docinfo.ChangeDateTime -com.sun.star.text.textfield.docinfo.EditTime -com.sun.star.text.textfield.docinfo.Description -com.sun.star.text.textfield.docinfo.CreateAuthor -com.sun.star.text.textfield.docinfo.CreateDateTime -com.sun.star.text.textfield.docinfo.PrintAuthor -com.sun.star.text.textfield.docinfo.PrintDateTime -com.sun.star.text.textfield.docinfo.KeyWords -com.sun.star.text.textfield.docinfo.Subject -com.sun.star.text.textfield.docinfo.Title -com.sun.star.text.textfield.docinfo.Revision -com.sun.star.text.textfield.docinfo.Custom -com.sun.star.text.textfield.Bibliography -com.sun.star.text.textfield.CombinedCharacters -com.sun.star.text.textfield.DropDown -com.sun.star.text.textfield.InputUser -com.sun.star.text.textfield.HiddenText -com.sun.star.text.fieldmaster.User -com.sun.star.text.fieldmaster.DDE -com.sun.star.text.fieldmaster.SetExpression -com.sun.star.text.fieldmaster.Database -com.sun.star.text.fieldmaster.Bibliography -com.sun.star.style.TableStyle -com.sun.star.style.CellStyle - - */ - /* * Map entries; * @@ -2466,11 +2324,10 @@ BibliographyOrder bibliographyOrderOfStyle( OOBibStyle style ) { Collections.emptyList()); // Try to list citations: if (true) { - OOUtil.insertTextAtCurrentLocation( documentConnection.xText, cursor, - String.format(" %s ", Localization.lang("CitedOnPagesPrefix")), + String.format(" (%s: ", Localization.lang("Cited on pages")), Collections.emptyList()); int last = ck.where.size(); @@ -2495,7 +2352,7 @@ BibliographyOrder bibliographyOrderOfStyle( OOBibStyle style ) { OOUtil.insertTextAtCurrentLocation( documentConnection.xText, cursor, - String.format("%s", Localization.lang("CitedOnPagesSuffix")), + ")", Collections.emptyList()); } } else { @@ -3427,10 +3284,10 @@ public List updateDocumentActionHelper(List databases, int maxReportedOverlaps = 10; checkRangeOverlaps(cgs, this.xDocumentConnection, requireSeparation, maxReportedOverlaps); final boolean useLockControllers = true; + ProduceCitationMarkersResult x = produceCitationMarkers(documentConnection, + databases, + style); try { - ProduceCitationMarkersResult x = produceCitationMarkers(documentConnection, - databases, - style); if (useLockControllers) { documentConnection.lockControllers(); } @@ -3444,7 +3301,9 @@ public List updateDocumentActionHelper(List databases, x.getBibliography()); return x.getUnresolvedKeys(); } finally { - if (useLockControllers) { + if (useLockControllers + // && documentConnection.hasControllersLocked() + ) { documentConnection.unlockControllers(); } } diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java index 8a28dcb2a95..0898ed223b4 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java @@ -5,6 +5,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.TreeMap; import com.sun.star.text.XText; @@ -34,8 +35,12 @@ class RangeKeyedMap { public boolean containsKey(XTextRange r) { - return xxs.containsKey( r.getText() ) - && xxs.get(r).containsKey(r); + Objects.requireNonNull(r); + XText partitionKey = r.getText(); + if ( !xxs.containsKey(partitionKey)) { + return false; + } + return xxs.get(partitionKey).containsKey(r); } public V diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index eabcef860ac..fcd3d93d534 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -2315,14 +2315,14 @@ Error\ connecting\ to\ Writer\ document=Error connecting to Writer document You\ need\ to\ open\ Writer\ with\ a\ document\ before\ connecting=You need to open Writer with a document before connecting + Generate\ a\ new\ key\ for\ imported\ entries\ (overwriting\ their\ default)=Generate a new key for imported entries (overwriting their default) Import\ settings=Import settings Custom\ DOI\ URI=Custom DOI URI Customization=Customization Use\ custom\ DOI\ base\ URI\ for\ article\ access=Use custom DOI base URI for article access -CitedOnPagesPrefix=(Cited on pages: -CitedOnPagesSuffix=) +Cited\ on\ pages=Cited on pages Unable\ to\ find\ valid\ certification\ path\ to\ requested\ target(%0),\ download\ anyway?=Unable to find valid certification path to requested target(%0), download anyway? Download\ operation\ canceled.=Download operation canceled. From 88d77a9131c66b580f7dc7a8ee5407976b9161d9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 22 Mar 2021 23:34:33 +0100 Subject: [PATCH 0495/1068] visualSort asks for cursor placement, but handles some cases insertCitation asks cursor placement --- .../gui/openoffice/DocumentConnection.java | 134 ++++++++++++- .../org/jabref/gui/openoffice/OOBibBase.java | 177 ++++++++++++------ src/main/resources/l10n/JabRef_en.properties | 6 + 3 files changed, 261 insertions(+), 56 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java index 035103c736c..e13f33aaa9d 100644 --- a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java @@ -69,6 +69,7 @@ import com.sun.star.lang.XComponent; // import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XServiceInfo; import com.sun.star.text.ReferenceFieldSource; import com.sun.star.text.ReferenceFieldPart; import com.sun.star.text.XBookmarksSupplier; @@ -90,6 +91,7 @@ // import com.sun.star.uno.XComponentContext; import com.sun.star.util.InvalidStateException; import com.sun.star.util.XRefreshable; +import com.sun.star.view.XSelectionSupplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -107,9 +109,19 @@ class DocumentConnection { public XTextDocument mxDoc; + + // unoQI(XComponent.class, mxDoc); public XComponent xCurrentComponent; + + // unoQI(XMultiServiceFactory.class, mxDoc); public XMultiServiceFactory mxDocFactory; + + // XModel mo = unoQI(XModel.class, this.xCurrentComponent); + // XController co = mo.getCurrentController(); + public XText xText; + + // xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); public XTextViewCursorSupplier xViewCursorSupplier; public XPropertyContainer userProperties; public XPropertySet propertySet; @@ -137,6 +149,126 @@ class DocumentConnection { this.propertySet = unoQI(XPropertySet.class, userProperties); } + /** + * @param An uno object, hopefully implementing XServiceInfo + */ + public static void + printServiceInfo(Object o) { + XServiceInfo xserviceinfo = unoQI(XServiceInfo.class, o ); + System.out.printf("*** xserviceinfo%n"); + System.out.printf(" object is %s%n", o == null ? "null" : "OK"); + System.out.printf(" xserviceinfo is %s%n", xserviceinfo == null ? "null" : "OK"); + if ( xserviceinfo != null ){ + System.out.printf(" .getImplementationName: \"%s\"%n", + xserviceinfo.getImplementationName()); + System.out.printf(" .getSupportedServiceNames:%n"); + for ( String s : xserviceinfo.getSupportedServiceNames() ) { + System.out.printf(" \"%s\"%n", s); + } + } + } + + public XModel + getModel() { + return unoQI(XModel.class, this.xCurrentComponent); + } + + public XController + getCurrentController() { + return this.getModel().getCurrentController(); + } + + public XSelectionSupplier + getSelectionSupplier() { + return unoQI(XSelectionSupplier.class, + this.getCurrentController()); + } + + /** + * @return may be null, or some type supporting XServiceInfo + * + * Experiments using printServiceInfo with cursor in various + * positions in the document: + * + * With cursor within the frame, in text: + * *** xserviceinfo.getImplementationName: "SwXTextRanges" + * "com.sun.star.text.TextRanges" + * + * With cursor somewehe else in text: + * *** xserviceinfo.getImplementationName: "SwXTextRanges" + * "com.sun.star.text.TextRanges" + * + * With cursor in comment (AKA annotation): + * *** XSelectionSupplier is OK + * *** Object initialSelection is null + * *** xserviceinfo is null + * + * 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" + * + * 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 Object + getSelectionAsObject() { + XSelectionSupplier xss = this.getSelectionSupplier(); + return xss.getSelection(); + } + + /** + * So far it seems teh first thing we have to do + * with a selection is to decide what do we have. + * + * One way to do that is accessing its XServiceInfo interface. + * + * Note: may return null. + */ + public XServiceInfo + getSelectionAsServiceInfo() { + Object o = getSelectionAsObject(); + if (o == null) { + return null; + } + XServiceInfo xserviceinfo = unoQI(XServiceInfo.class, o ); + if (xserviceinfo == null) { + // I do not know if this is possible: make a note + // if it is. + LOGGER.warn("DocumentConnection.getSelectionAsObject:" + + " XServiceInfo is null when Object is not"); + } + return xserviceinfo; + } + + /** + * Select the object represented by {@code newSelection} if it is + * known and selectable in this {@code XSelectionSupplier} object. + * + * Presumably result from {@code XSelectionSupplier.getSelection()} is + * usually OK. It also accepted + * {@code XTextRange newSelection = documentConnection.xText.getStart();} + * + * @return Apparently always returns true. + * + */ + public boolean + select(Object newSelection) { + XSelectionSupplier xss = this.getSelectionSupplier(); + return xss.select(newSelection); + } + /** * unoQI : short for UnoRuntime.queryInterface * @@ -172,7 +304,7 @@ class DocumentConnection { um.leaveUndoContext(); } - /* + /** * Disable screen refresh. * * Must be paired with unlockControllers() diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1b57686c7f0..8eac20ba450 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -42,6 +42,8 @@ import org.jabref.model.entry.field.StandardField; import com.sun.star.awt.Point; +import com.sun.star.awt.Selection; +import com.sun.star.awt.XTextComponent; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.Property; @@ -71,8 +73,10 @@ import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XServiceInfo; import com.sun.star.text.ReferenceFieldSource; import com.sun.star.text.ReferenceFieldPart; +// import com.sun.star.text.TextRanges; import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XFootnote; import com.sun.star.text.XReferenceMarksSupplier; @@ -92,8 +96,10 @@ import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; +import com.sun.star.uno.XInterface; import com.sun.star.util.InvalidStateException; import com.sun.star.util.XRefreshable; +import com.sun.star.view.XSelectionSupplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -585,20 +591,6 @@ private String getCitationContext(CitationGroupsV001 cgs, NoDocumentException, CreationException { - /* - XNameAccess nameAccess = documentConnection.getReferenceMarks(); - XTextContent mark = - DocumentConnection.nameAccessGetTextContentByNameOrNull(nameAccess, refMarkName); - if (null == mark) { - LOGGER.warn(String.format( - "OOBibBase.getCitationContext:" - + " lost reference mark: '%s'", - refMarkName - )); - return String.format("(Could not retrieve context for %s)", refMarkName); - } - XTextCursor cursor = DocumentConnection.getTextCursorOfTextContent(mark); - */ XTextCursor cursor = cgs.getRawCursorForCitationGroup(cgid, documentConnection); String citPart = cursor.getString(); @@ -909,6 +901,21 @@ public T getContent() { } } + /** + * Creates a list of {@code XTextRange} values for our {@code + * CitationGroup} values, to be passed to {@code visualSort} + * + * The elements of the returned list are actually of type {@code + * VisualSortEntry} + * + * @param cgs The source of CitationGroup values. + * @param documentConnection Connection to the document. + * @param mapFootnotesToFootnoteMarks If true, replace ranges in + * footnotes with the range of the corresponding footnote + * mark. This is used for numbering the citations. + * + * + */ List> createVisualSortInput(CitationGroupsV001 cgs, DocumentConnection documentConnection, @@ -917,8 +924,6 @@ public T getContent() { NoDocumentException, WrappedTargetException { - // final int nMarks = cgs.numberOfCitationGroups(); - List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); @@ -994,17 +999,12 @@ public T getContent() { return res.stream().map(e -> e).collect(Collectors.toList()); } - private List> - visualSort( - // getJabRefReferenceMarkNamesSortedByPosition( - // CitationGroupsV001 cgs, - List> vses, - DocumentConnection documentConnection - //boolean mapFootnotesToFootnoteMarks - ) + private List> visualSort(List> vses, + DocumentConnection documentConnection) throws WrappedTargetException, - NoDocumentException { + NoDocumentException, + JabRefException { final int nCitationGroups = vses.size(); @@ -1016,27 +1016,96 @@ public T getContent() { ); } - XTextViewCursor viewCursor = documentConnection.getViewCursor(); - // initialPos: to be restored before return - XTextRange initialPos = viewCursor.getStart(); - // for (String name : names) { + /* + * A problem with XTextViewCursor: if it is not in text, + * then we get a crippled version that does not support + * viewCursor.getStart() or viewCursor.gotoRange(range,false), + * and will throw an exception instead. + * + * Our hope is that either we can move the cursor with a + * page- or scrolling-based method that does not throw, (see + * https://docs.libreoffice.org/sw/html/unotxvw_8cxx_source.html#l00896 + * ) or that we can manipulate the cursor via getSelection and + * select (of XSelectionSupplier). + * + * Here we implemented the second, selection-based method. + * Seems to work when the user selected a frame or image. + * In these cases restoring the selection works, too. + * + * Still, we have a problem when the cursor is in a comment + * (referred to as "annotation" in OO API): in this case + * initialSelection is null, and documentConnection.select() + * does not help to get a function viewCursor. Having no + * better idea, we ask the user to move the cursor into the + * document. + */ + /* + * Selection-based + */ + final boolean debugThisFun = false; - //final int nMarks = vses.size(); + XServiceInfo initialSelection = documentConnection.getSelectionAsServiceInfo(); + + if (initialSelection != null) { + if (Arrays.stream(initialSelection.getSupportedServiceNames()) + .anyMatch("com.sun.star.text.TextRanges"::equals)) { + // we are probably OK with the viewCursor + if (debugThisFun) { + LOGGER.info("visualSort: initialSelection supports TextRanges: no action needed."); + } + } else { + if (debugThisFun) { + LOGGER.info("visualSort: initialSelection does not support TextRanges." + + " We need to change the viewCursor."); + } + XTextRange newSelection = documentConnection.xText.getStart(); + documentConnection.select( newSelection ); + } + } else { + if (debugThisFun) { + LOGGER.info("visualSort: initialSelection is null: no idea what to do."); + } + /* + * XTextRange newSelection = documentConnection.xText.getStart(); + * boolean res = documentConnection.select( newSelection ); + * XServiceInfo sel2 = documentConnection.getSelectionAsServiceInfo(); + * LOGGER.info( + * String.format("visualSort: initialSelection is null: result of select: %s, isNull: %s%n", + * res, + * sel2 == null)); + * // ^^^ prints true, true + */ + } + + XTextViewCursor viewCursor = documentConnection.getViewCursor(); + Objects.requireNonNull(viewCursor); + try { + viewCursor.getStart(); + } catch (com.sun.star.uno.RuntimeException ex) { + throw new JabRefException( + Localization.lang("Please move the cursor into the document text.") + + "\n" + + Localization.lang("To get the visual positions of your citations" + + " I need to move the cursor around," + + " but could not get it."), + ex); + } // find coordinates List positions = new ArrayList<>(vses.size()); for (VisualSortable v : vses) { - positions.add( - findPositionOfTextRange( - v.getRange(), - viewCursor) - ); + positions.add(findPositionOfTextRange(v.getRange(), + viewCursor)); } - // restore cursor position - viewCursor.gotoRange(initialPos, false); + /* + * Restore initial state of selection (and thus viewCursor) + */ + if (initialSelection != null) { + documentConnection.select(initialSelection); + } if ( positions.size() != nCitationGroups ) { throw new RuntimeException("visualSort: positions.size() != nCitationGroups"); @@ -1055,7 +1124,6 @@ public T getContent() { } if ( set.size() != nCitationGroups ) { - // *** Fired *** throw new RuntimeException("visualSort: set.size() != nCitationGroups"); } @@ -1080,7 +1148,8 @@ public T getContent() { boolean mapFootnotesToFootnoteMarks ) throws WrappedTargetException, - NoDocumentException { + NoDocumentException, + JabRefException { List> vses = createVisualSortInput( @@ -1803,6 +1872,18 @@ public void insertCitation(List entries, ); } + // Check for crippled XTextViewCursor + Objects.requireNonNull(cursor); + try { + cursor.getStart(); + } catch (com.sun.star.uno.RuntimeException ex) { + throw new JabRefException( + Localization.lang("Please move the cursor to the location for the new citation.") + + "\n" + + Localization.lang("I cannot insert to the cursors current location."), + ex); + } + sortBibEntryListForMulticite(entries, style); /* @@ -2086,7 +2167,8 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d NoSuchElementException, BibEntryNotFoundException, NoDocumentException, - UnknownPropertyException { + UnknownPropertyException, + JabRefException { CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); @@ -2211,21 +2293,6 @@ private List sortEntriesByRefMarkNames(CitationGrou style); } - /* - enum BibliographyOrder { - Unspecified, - ByFirstAppearanceInTheText, - ByEntryComparator - } - - BibliographyOrder bibliographyOrderOfStyle( OOBibStyle style ) { - if (style.isSortByPosition()) { - return ByFirstAppearanceInTheText; - } else { - return ByEntryComparator; - } - } - */ /** * Insert body of bibliography at `cursor`. diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index fcd3d93d534..260bf1ba070 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -2323,6 +2323,12 @@ Customization=Customization Use\ custom\ DOI\ base\ URI\ for\ article\ access=Use custom DOI base URI for article access Cited\ on\ pages=Cited on pages +Please\ move\ the\ cursor\ into\ the\ document\ text.=Please\ move\ the\ cursor\ into\ the\ document\ text. +To\ get\ the\ visual\ positions\ of\ your\ citations\ I\ need\ to\ move\ the\ cursor\ around,\ but\ could\ not\ get\ it.=To\ get\ the\ visual\ positions\ of\ your\ citations\ I\ need\ to\ move\ the\ cursor\ around,\ but\ could\ not\ get\ it. + +I\ cannot\ insert\ to\ the\ cursors\ current\ location.=I\ cannot\ insert\ to\ the\ cursors\ current\ location. + +Please\ move\ the\ cursor\ to\ the\ location\ for\ the\ new\ citation.=Please\ move\ the\ cursor\ to\ the\ location\ for\ the\ new\ citation. Unable\ to\ find\ valid\ certification\ path\ to\ requested\ target(%0),\ download\ anyway?=Unable to find valid certification path to requested target(%0), download anyway? Download\ operation\ canceled.=Download operation canceled. From 485f60e91c4f49a34e7f9ab0a42a1577d180f243 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Mar 2021 09:07:35 +0100 Subject: [PATCH 0496/1068] pageInfo.get().equals("") is shown as pageInfo.isEmpty() --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8eac20ba450..d8bf196765f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1568,7 +1568,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti String citText; // String pageInfo = getPageInfoForReferenceMarkName(documentConnection, name); Optional pageInfo = cgs.getPageInfo(cgid); - citText = (pageInfo.isEmpty() + citText = ((pageInfo.isEmpty() || pageInfo.get().equals("")) ? citationText : style.insertPageInfo(citationText, pageInfo.get())); From d179f1e8236ff5bad37afda9bdf781b6ef2dcd9b Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 23 Mar 2021 11:11:35 +0100 Subject: [PATCH 0497/1068] insertCitation does not sort the entries --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d8bf196765f..416b8f7054a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1884,7 +1884,7 @@ public void insertCitation(List entries, ex); } - sortBibEntryListForMulticite(entries, style); + // sortBibEntryListForMulticite(entries, style); /* * String keyString = From db988b4585d22ea2f629cd610482f48330025968 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Mar 2021 18:22:48 +0100 Subject: [PATCH 0498/1068] refactor: format --- .../org/jabref/gui/openoffice/OOBibBase.java | 63 ++++++++----------- .../gui/openoffice/RangeKeyedMapList.java | 19 ++---- 2 files changed, 31 insertions(+), 51 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 416b8f7054a..44f8d79f4af 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1142,20 +1142,18 @@ private List> visualSort(List> vses, private List - getVisuallySortedCitationGroupIDs( - CitationGroupsV001 cgs, - DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks ) + getVisuallySortedCitationGroupIDs(CitationGroupsV001 cgs, + DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) throws WrappedTargetException, NoDocumentException, JabRefException { List> vses = - createVisualSortInput( - cgs, - documentConnection, - mapFootnotesToFootnoteMarks); + createVisualSortInput(cgs, + documentConnection, + mapFootnotesToFootnoteMarks); if ( vses.size() != cgs.citationGroups.size() ) { throw new RuntimeException("getVisuallySortedCitationGroupIDs:" @@ -2271,11 +2269,10 @@ private List sortEntriesByRefMarkNames(CitationGrou * Note: assumes fresh `jabRefReferenceMarkNamesSortedByPosition` * if `style.isSortByPosition()` */ - private void - rebuildBibTextSection(DocumentConnection documentConnection, - OOBibStyle style, - CitationGroupsV001 cgs, - CitationGroupsV001.CitedKeys bibliography) + private void rebuildBibTextSection(DocumentConnection documentConnection, + OOBibStyle style, + CitationGroupsV001 cgs, + CitationGroupsV001.CitedKeys bibliography) throws NoSuchElementException, WrappedTargetException, @@ -2306,13 +2303,12 @@ private List sortEntriesByRefMarkNames(CitationGrou * * Only called from populateBibTextSection (and that from rebuildBibTextSection) */ - private void - insertFullReferenceAtCursor(DocumentConnection documentConnection, - XTextCursor cursor, - CitationGroupsV001 cgs, - CitationGroupsV001.CitedKeys bibliography, - OOBibStyle style, - String parFormat) + private void insertFullReferenceAtCursor(DocumentConnection documentConnection, + XTextCursor cursor, + CitationGroupsV001 cgs, + CitationGroupsV001.CitedKeys bibliography, + OOBibStyle style, + String parFormat) throws UndefinedParagraphFormatException, IllegalArgumentException, @@ -2447,8 +2443,7 @@ private List sortEntriesByRefMarkNames(CitationGrou * * Only called from `clearBibTextSectionContent2` */ - private void - createBibTextSection2(DocumentConnection documentConnection) + private void createBibTextSection2(DocumentConnection documentConnection) throws IllegalArgumentException, CreationException { @@ -2474,8 +2469,7 @@ private List sortEntriesByRefMarkNames(CitationGrou * Only called from: `rebuildBibTextSection` * */ - private void - clearBibTextSectionContent2(DocumentConnection documentConnection) + private void clearBibTextSectionContent2(DocumentConnection documentConnection) throws WrappedTargetException, IllegalArgumentException, @@ -2516,15 +2510,10 @@ private List sortEntriesByRefMarkNames(CitationGrou * * Assumes the section named `OOBibBase.BIB_SECTION_NAME` exists. */ - private void - populateBibTextSection( - DocumentConnection documentConnection, - CitationGroupsV001 cgs, - CitationGroupsV001.CitedKeys bibliography, - // Map entries, - OOBibStyle style - // final Map uniqueLetters - ) + private void populateBibTextSection(DocumentConnection documentConnection, + CitationGroupsV001 cgs, + CitationGroupsV001.CitedKeys bibliography, + OOBibStyle style) throws NoSuchElementException, WrappedTargetException, @@ -2583,11 +2572,8 @@ private List sortEntriesByRefMarkNames(CitationGrou * GUI action "Merge citations" * */ - public void - combineCiteMarkers( - List databases, - OOBibStyle style - ) + public void combineCiteMarkers(List databases, + OOBibStyle style) throws IOException, WrappedTargetException, @@ -2619,6 +2605,7 @@ private List sortEntriesByRefMarkNames(CitationGrou // The testing for whitespace-only between (pivot) and (pivot+1) assumes that // referenceMarkNames are in textual order: textually consecutive pairs // must appear as neighbours (and in textual order). + // // We have a bit of a clash here: referenceMarkNames is sorted by visual position, // but we are testing if they are textually neighbours. // In a two-column layout diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java index 817ef9ba1c5..c4bca41e1ea 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java @@ -11,23 +11,19 @@ class RangeKeyedMapList { RangeKeyedMap> xxs; - public - RangeKeyedMapList() { + public RangeKeyedMapList() { this.xxs = new RangeKeyedMap<>(); } - public boolean - containsKey(XTextRange r) { + public boolean containsKey(XTextRange r) { return xxs.containsKey(r); } - public List - get(XTextRange r) { + public List get(XTextRange r) { return xxs.get(r); } - public void - add( XTextRange r, V value) { + public void add(XTextRange r, V value) { List vs = xxs.get(r); if (vs == null){ vs = new ArrayList<>(); @@ -54,8 +50,7 @@ class RangeOverlap { OverlapKind kind; List vs; - public - RangeOverlap( OverlapKind kind, List vs ) { + public RangeOverlap( OverlapKind kind, List vs ) { this.kind = kind; this.vs = vs; } @@ -78,8 +73,7 @@ class RangeOverlap { * @param atMost Limit the number of records returneed to atMost. * Zero or negative {@code atMost} means no limit. */ - List - findOverlappingRanges(int atMost, boolean includeTouching) { + List findOverlappingRanges(int atMost, boolean includeTouching) { List res = new ArrayList<>(); for (TreeMap> xs : xxs.partitionValues()) { List oxs = new ArrayList<>(xs.keySet()); @@ -121,5 +115,4 @@ class RangeOverlap { } return res; } - } From 539b2294c972b9cd1fc16dd20bb25fb7371d1413 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Mar 2021 18:23:34 +0100 Subject: [PATCH 0499/1068] refactor: move partitionValues forward --- .../jabref/gui/openoffice/RangeKeyedMapList.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java index c4bca41e1ea..4adae8ce39a 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java @@ -34,6 +34,12 @@ public void add(XTextRange r, V value) { } } + /** + * @return A list of the partitions. + */ + public List>> partitionValues() { + return this.xxs.partitionValues(); + } enum OverlapKind { TOUCH, OVERLAP, @@ -56,14 +62,6 @@ public RangeOverlap( OverlapKind kind, List vs ) { } }; - /** - * @return A list of the partitions. - */ - public List>> - partitionValues() { - return this.xxs.partitionValues(); - } - /** * Report identical, overlapping or touching ranges. * From b599be8618375023d8713da2054ddbb096187a5d Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Mar 2021 18:50:48 +0100 Subject: [PATCH 0500/1068] flatListOfValues --- .../jabref/gui/openoffice/RangeKeyedMapList.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java index 4adae8ce39a..c0cb7aebf3d 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java @@ -40,6 +40,22 @@ public void add(XTextRange r, V value) { public List>> partitionValues() { return this.xxs.partitionValues(); } + + /** + * Lis of all values: partitions in arbitrary order, ranges are + * sorted within partitions, values under the same range are in + * the order they were added. + */ + public List flatListOfValues() { + List result = new ArrayList<>(); + for (TreeMap> partition : partitionValues() ) { + for (List valuesUnderARange : partition.values() ) { + result.addAll(valuesUnderARange); + } + } + return result; + } + enum OverlapKind { TOUCH, OVERLAP, From ac8120013e3871b060473029fd183422819ac531 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Mar 2021 20:14:55 +0100 Subject: [PATCH 0501/1068] refactor: add RangeSortVisual.java, move getVisuallySortedCitationGroupIDs --- .../gui/openoffice/CitationGroupsV001.java | 208 ++++++++ .../org/jabref/gui/openoffice/OOBibBase.java | 465 +----------------- .../gui/openoffice/RangeSortVisual.java | 346 +++++++++++++ 3 files changed, 570 insertions(+), 449 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 397353fa284..5a705efc50e 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -13,6 +13,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -22,12 +23,16 @@ import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XFootnote; import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; import com.sun.star.util.InvalidStateException; +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.slf4j.Logger; @@ -67,6 +72,17 @@ class CitationGroupsV001 { public static final boolean REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS = true; + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if + * available, otherwise null. + */ + private static T unoQI(Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + class CitationGroupID { String id; CitationGroupID(String id){ @@ -667,6 +683,198 @@ Optional getBibliography() { return citationGroups.keySet(); } + /** + * Read reference mark names from the document, keep only those + * with JabRef naming convention, get their visual positions, + * + * @return JabRef reference mark names sorted by these positions. + * + * Limitation: for two column layout visual (top-down, + * left-right) order does not match the expected (textual) + * order. + * + * TODO: refmarks in the same footnote get the same position. + * After sorting, they may get the wrong order. + * + */ + + /** + * Creates a list of {@code + * VisualSortable} values for + * our {@code CitationGroup} values. Originally designed to be + * passed to {@code visualSort}. + * + * The elements of the returned list are actually of type {@code + * VisualSortEntry}. + * + * The result is sorted within {@code XTextRange.getText()} + * partitions of the citation groups according to their {@code + * XTextRange} (before mapping to footnote marks). + * + * In the result, VisualSortable.getIndexInPosition() contains + * unique indexes within the original partition (not after + * mapFootnotesToFootnoteMarks). + * + * @param cgs The source of CitationGroup values. + * @param documentConnection Connection to the document. + * @param mapFootnotesToFootnoteMarks If true, replace ranges in + * footnotes with the range of the corresponding footnote + * mark. This is used for numbering the citations. + * + */ + private static List> + createVisualSortInput(CitationGroupsV001 cgs, + DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + NoDocumentException, + WrappedTargetException { + + List cgids = + new ArrayList<>(cgs.getCitationGroupIDs()); + + List vses = new ArrayList<>(); + for (CitationGroupsV001.CitationGroupID cgid : cgids) { + XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); + if (range == null) { + throw new RuntimeException( "getReferenceMarkRangeOrNull returned null" ); + } + vses.add( new RangeSortVisual.VisualSortEntry(range, 0, cgid) ); + } + + /* + * At this point we are almost ready to return vses. + * + * For example we may want to number citations in a footnote + * as if it appeared where the footnote mark is. + * + * The following code replaces ranges within footnotes with + * the range for the corresponding footnote mark. + * + * This brings further ambiguity if we have multiple + * citations within the same footnote: for the comparison + * they become indistinguishable. Numbering between them is + * not controlled. Also combineCiteMarkers will see them in + * the wrong order (if we use this comparison), and will not + * be able to merge. To avoid these, we sort textually within + * each .getText() partition and add indexInPosition + * accordingly. + * + */ + + // Sort within partitions + RangeKeyedMapList> xxs + = new RangeKeyedMapList<>(); + + for (RangeSortVisual.VisualSortEntry v : vses) { + xxs.add( v.getRange(), v ); + } + + // build final list + List> res = new ArrayList<>(); + + for (TreeMap>> + xs : xxs.partitionValues()) { + + List oxs = new ArrayList<>(xs.keySet()); + + int indexInPartition = 0; + for (int i = 0; i < oxs.size(); i++) { + XTextRange a = oxs.get(i); + List> avs = xs.get(a); + for (int j = 0; j < avs.size(); j++){ + RangeSortVisual.VisualSortEntry v = avs.get(j); + v.indexInPosition = indexInPartition++; + if ( mapFootnotesToFootnoteMarks ) { + // Adjust range if we are inside a footnote: + if (unoQI(XFootnote.class, v.range.getText()) != null) { + // Find the linking footnote marker: + XFootnote footer = unoQI(XFootnote.class, v.range.getText()); + // The footnote's anchor gives the correct position in the text: + v.range = footer.getAnchor(); + } + } + res.add(v); + } + } + } + // convert + // List> + // to + // List> + return res.stream().map(e -> e).collect(Collectors.toList()); + } + + public List + getVisuallySortedCitationGroupIDs(DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + WrappedTargetException, + NoDocumentException, + JabRefException { + CitationGroupsV001 cgs = this; + List> vses = + createVisualSortInput(cgs, + documentConnection, + mapFootnotesToFootnoteMarks); + + if ( vses.size() != cgs.citationGroups.size() ) { + throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + + " vses.size() != cgs.citationGroups.size()"); + } + + String messageOnFailureToObtainAFunctionalXTextViewCursor = + Localization.lang("Please move the cursor into the document text.") + + "\n" + + Localization.lang("To get the visual positions of your citations" + + " I need to move the cursor around," + + " but could not get it."); + List> sorted = + RangeSortVisual.visualSort( vses, + documentConnection, + messageOnFailureToObtainAFunctionalXTextViewCursor ); + + if ( sorted.size() != cgs.citationGroups.size() ) { + // This Fired + throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + + " sorted.size() != cgs.citationGroups.size()"); + } + + return (sorted.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList())); + } + + /** + * Calculate and return citation group IDs in visual order. + */ + public List + getCitationGroupIDsSortedWithinPartitions(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException + { + // This is like getVisuallySortedCitationGroupIDs, + // but we skip the visualSort part. + CitationGroupsV001 cgs = this; + boolean mapFootnotesToFootnoteMarks = false; + List> vses = + CitationGroupsV001.createVisualSortInput(cgs, + documentConnection, + mapFootnotesToFootnoteMarks); + + if ( vses.size() != cgs.citationGroups.size() ) { + throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" + + " vses.size() != cgs.citationGroups.size()"); + } + return (vses.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList())); + } + + /** + * Citation group IDs in {@code globalOrder} + */ public List getSortedCitationGroupIDs() { if ( globalOrder.isEmpty() ) { diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 44f8d79f4af..4505cf56da7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -26,6 +26,7 @@ import org.jabref.architecture.AllowedToUseAwt; import org.jabref.gui.DialogService; +import org.jabref.gui.openoffice.RangeSortVisual; import org.jabref.logic.JabRefException; import org.jabref.logic.bibtex.comparator.FieldComparator; import org.jabref.logic.bibtex.comparator.FieldComparatorStack; @@ -757,422 +758,6 @@ public void applyCitationEntries( return newMap; } - /* first appearance order, based on visual order */ - - /** - * Given a location, return its position: coordinates relative to - * the top left position of the first page of the document. - * - * Note: for text layouts with two or more columns, this gives the - * wrong order: top-down/left-to-right does not match - * reading order. - * - * Note: The "relative to the top left position of the first page" - * is meant "as it appears on the screen". - * - * In particular: when viewing pages side-by-side, the top - * half of the right page is higher than the lower half of - * the left page. Again, top-down/left-to-right does not - * match reading order. - * - * @param range Location. - * @param cursor To get the position, we need az XTextViewCursor. - * It will be moved to the range. - */ - private static Point - findPositionOfTextRange(XTextRange range, XTextViewCursor cursor) { - cursor.gotoRange(range, false); - return cursor.getPosition(); - } - - /** - * A reference mark name paired with its visual position. - * - * Comparison is based on (Y,X,indexInPosition): vertical compared - * first, horizontal second, indexInPosition third. - * - * Used for sorting reference marks by their visual positions. - * - * - * - */ - private static class ComparableMark implements Comparable> { - - private final Point position; - private final int indexInPosition; - private final T content; - - public ComparableMark(Point position, int indexInPosition, T content) { - this.position = position; - this.indexInPosition = indexInPosition; - this.content = content; - } - - @Override - public int compareTo(ComparableMark other) { - - if (position.Y != other.position.Y) { - return position.Y - other.position.Y; - } - if (position.X != other.position.X) { - return position.X - other.position.X; - } - return indexInPosition - other.indexInPosition; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (o instanceof ComparableMark) { - ComparableMark other = (ComparableMark) o; - return ((this.position.X == other.position.X) - && (this.position.Y == other.position.Y) - && (this.indexInPosition == other.indexInPosition) - && Objects.equals(this.content, other.content) - ); - } - return false; - } - - public T getContent() { - return content; - } - - @Override - public int hashCode() { - return Objects.hash(position, indexInPosition, content); - } - } - - /** - * - */ - interface VisualSortable { - public XTextRange getRange(); - public int getIndexInPosition(); - public T getContent(); - } - - /** - * Read reference mark names from the document, keep only those - * with JabRef naming convention, get their visual positions, - * - * @return JabRef reference mark names sorted by these positions. - * - * Limitation: for two column layout visual (top-down, - * left-right) order does not match the expected (textual) - * order. - * - * TODO: refmarks in the same footnote get the same position. - * After sorting, they may get the wrong order. - * - */ - class VisualSortEntry implements VisualSortable { - public XTextRange range; - public int indexInPosition; - public T content; - - VisualSortEntry( - XTextRange range, - int indexInPosition, - T content - ) { - this.range = range; - this.indexInPosition = indexInPosition; - this.content = content; - } - - @Override - public XTextRange getRange() { - return range; - } - - @Override - public int getIndexInPosition() { - return indexInPosition; - } - - @Override - public T getContent() { - return content; - } - } - - /** - * Creates a list of {@code XTextRange} values for our {@code - * CitationGroup} values, to be passed to {@code visualSort} - * - * The elements of the returned list are actually of type {@code - * VisualSortEntry} - * - * @param cgs The source of CitationGroup values. - * @param documentConnection Connection to the document. - * @param mapFootnotesToFootnoteMarks If true, replace ranges in - * footnotes with the range of the corresponding footnote - * mark. This is used for numbering the citations. - * - * - */ - List> - createVisualSortInput(CitationGroupsV001 cgs, - DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - NoDocumentException, - WrappedTargetException { - - List cgids = - new ArrayList<>(cgs.getCitationGroupIDs()); - - List vses = new ArrayList<>(); - for (CitationGroupsV001.CitationGroupID cgid : cgids) { - XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); - if (range == null) { - throw new RuntimeException( "getReferenceMarkRangeOrNull returned null" ); - } - vses.add( new VisualSortEntry(range, 0, cgid) ); - } - - /* - * At this point we are almost ready to return vses. - * - * For example we may want to number citations in a footnote - * as if it appeared where the footnote mark is. - * - * The following code replaces ranges within footnotes with - * the range for the corresponding footnote mark. - * - * This brings further ambiguity if we have multiple - * citations within the same footnote: for the comparison - * they become indistinguishable. Numbering between them is - * not controlled. Also combineCiteMarkers will see them in - * the wrong order (if we use this comparison), and will not - * be able to merge. To avoid these, we sort textually within - * each .getText() partition and add indexInPosition - * accordingly. - * - */ - - // Sort within partitions - RangeKeyedMapList> xxs - = new RangeKeyedMapList<>(); - - for (VisualSortEntry v : vses) { - xxs.add( v.getRange(), v ); - } - - // build final list - List> res = new ArrayList<>(); - - for (TreeMap>> - xs : xxs.partitionValues()) { - - List oxs = new ArrayList<>(xs.keySet()); - - int indexInPartition = 0; - for (int i = 0; i < oxs.size(); i++) { - XTextRange a = oxs.get(i); - List> avs = xs.get(a); - for (int j = 0; j < avs.size(); j++){ - VisualSortEntry v = avs.get(j); - v.indexInPosition = indexInPartition++; - if ( mapFootnotesToFootnoteMarks ) { - // Adjust range if we are inside a footnote: - if (unoQI(XFootnote.class, v.range.getText()) != null) { - // Find the linking footnote marker: - XFootnote footer = unoQI(XFootnote.class, v.range.getText()); - // The footnote's anchor gives the correct position in the text: - v.range = footer.getAnchor(); - } - } - res.add(v); - } - } - } - // convert - // List> - // to - // List> - return res.stream().map(e -> e).collect(Collectors.toList()); - } - - private List> visualSort(List> vses, - DocumentConnection documentConnection) - throws - WrappedTargetException, - NoDocumentException, - JabRefException { - - final int nCitationGroups = vses.size(); - - if (documentConnection.hasControllersLocked()) { - LOGGER.warn( - "visualSort:" - + " with ControllersLocked, viewCursor.gotoRange" - + " is probably useless" - ); - } - - /* - * A problem with XTextViewCursor: if it is not in text, - * then we get a crippled version that does not support - * viewCursor.getStart() or viewCursor.gotoRange(range,false), - * and will throw an exception instead. - * - * Our hope is that either we can move the cursor with a - * page- or scrolling-based method that does not throw, (see - * https://docs.libreoffice.org/sw/html/unotxvw_8cxx_source.html#l00896 - * ) or that we can manipulate the cursor via getSelection and - * select (of XSelectionSupplier). - * - * Here we implemented the second, selection-based method. - * Seems to work when the user selected a frame or image. - * In these cases restoring the selection works, too. - * - * Still, we have a problem when the cursor is in a comment - * (referred to as "annotation" in OO API): in this case - * initialSelection is null, and documentConnection.select() - * does not help to get a function viewCursor. Having no - * better idea, we ask the user to move the cursor into the - * document. - */ - - /* - * Selection-based - */ - final boolean debugThisFun = false; - - XServiceInfo initialSelection = documentConnection.getSelectionAsServiceInfo(); - - if (initialSelection != null) { - if (Arrays.stream(initialSelection.getSupportedServiceNames()) - .anyMatch("com.sun.star.text.TextRanges"::equals)) { - // we are probably OK with the viewCursor - if (debugThisFun) { - LOGGER.info("visualSort: initialSelection supports TextRanges: no action needed."); - } - } else { - if (debugThisFun) { - LOGGER.info("visualSort: initialSelection does not support TextRanges." - + " We need to change the viewCursor."); - } - XTextRange newSelection = documentConnection.xText.getStart(); - documentConnection.select( newSelection ); - } - } else { - if (debugThisFun) { - LOGGER.info("visualSort: initialSelection is null: no idea what to do."); - } - /* - * XTextRange newSelection = documentConnection.xText.getStart(); - * boolean res = documentConnection.select( newSelection ); - * XServiceInfo sel2 = documentConnection.getSelectionAsServiceInfo(); - * LOGGER.info( - * String.format("visualSort: initialSelection is null: result of select: %s, isNull: %s%n", - * res, - * sel2 == null)); - * // ^^^ prints true, true - */ - } - - XTextViewCursor viewCursor = documentConnection.getViewCursor(); - Objects.requireNonNull(viewCursor); - try { - viewCursor.getStart(); - } catch (com.sun.star.uno.RuntimeException ex) { - throw new JabRefException( - Localization.lang("Please move the cursor into the document text.") - + "\n" - + Localization.lang("To get the visual positions of your citations" - + " I need to move the cursor around," - + " but could not get it."), - ex); - } - - // find coordinates - List positions = new ArrayList<>(vses.size()); - - for (VisualSortable v : vses) { - positions.add(findPositionOfTextRange(v.getRange(), - viewCursor)); - } - - /* - * Restore initial state of selection (and thus viewCursor) - */ - if (initialSelection != null) { - documentConnection.select(initialSelection); - } - - if ( positions.size() != nCitationGroups ) { - throw new RuntimeException("visualSort: positions.size() != nCitationGroups"); - } - - // order by position - Set>> set = new TreeSet<>(); - for (int i = 0; i < vses.size(); i++) { - set.add( - new ComparableMark<>( - positions.get(i), - vses.get(i).getIndexInPosition(), - vses.get(i) - ) - ); - } - - if ( set.size() != nCitationGroups ) { - throw new RuntimeException("visualSort: set.size() != nCitationGroups"); - } - - // collect CitationGroupIDs in order - List> result = new ArrayList<>(set.size()); - for (ComparableMark> mark : set) { - result.add(mark.getContent()); - } - - if ( result.size() != nCitationGroups ) { - throw new RuntimeException("visualSort: result.size() != nCitationGroups"); - } - - return result; - } - - - private List - getVisuallySortedCitationGroupIDs(CitationGroupsV001 cgs, - DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - WrappedTargetException, - NoDocumentException, - JabRefException { - - List> vses = - createVisualSortInput(cgs, - documentConnection, - mapFootnotesToFootnoteMarks); - - if ( vses.size() != cgs.citationGroups.size() ) { - throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " vses.size() != cgs.citationGroups.size()"); - } - - List> sorted = - visualSort( vses, documentConnection ); - - if ( sorted.size() != cgs.citationGroups.size() ) { - // This Fired - throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " sorted.size() != cgs.citationGroups.size()"); - } - - return (sorted.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList())); - } /* *************************************** * @@ -2192,9 +1777,8 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d { boolean mapFootnotesToFootnoteMarks = true; List sortedCitationGroupIDs = - getVisuallySortedCitationGroupIDs(cgs, - documentConnection, - mapFootnotesToFootnoteMarks); + cgs.getVisuallySortedCitationGroupIDs(documentConnection, + mapFootnotesToFootnoteMarks); cgs.setGlobalOrder(sortedCitationGroupIDs); } // localOrder and globalOrder together gives us order-of-appearance of citations @@ -2602,29 +2186,11 @@ public void combineCiteMarkers(List databases, boolean madeModifications = false; - // The testing for whitespace-only between (pivot) and (pivot+1) assumes that - // referenceMarkNames are in textual order: textually consecutive pairs - // must appear as neighbours (and in textual order). - // - // We have a bit of a clash here: referenceMarkNames is sorted by visual position, - // but we are testing if they are textually neighbours. - // In a two-column layout - // | a | c | - // | b | d | - // abcd is the textual order, but the visual order is acbd. - // So we will not find out that a and b are only separated by white space. - - boolean mapFootnotesToFootnoteMarks = false; - List referenceMarkNames = - // TODO: we probably want textually sorted partions here - getVisuallySortedCitationGroupIDs(cgs, - documentConnection, - mapFootnotesToFootnoteMarks); + + List + referenceMarkNames = cgs.getCitationGroupIDsSortedWithinPartitions(documentConnection); final int nRefMarks = referenceMarkNames.size(); - // int[] itcTypes = new int[nRefMarks]; - // String[][] bibtexKeys = new String[nRefMarks][]; - // parseRefMarkNamesToArrays(referenceMarkNames, itcTypes, bibtexKeys); try { @@ -2796,17 +2362,18 @@ public void combineCiteMarkers(List databases, if (DocumentConnection.javaCompareRegionEnds( cursorBetween, currentGroupCursor) != 0) { /* - * A problem discovered using this check: when - * viewing the document in + * A problem discovered using this check: + * when viewing the document in * two-pages-side-by-side mode, our visual * firstAppearanceOrder follows the visual - * ordering on the screen. The problem this - * caused: it sees a citation on the 2nd line - * of the 1st page as appearing after one at - * the 1st line of 2nd page. Since we create - * cursorBetween at the end of range1Full (on - * 1st page), it is now BEFORE - * currentGroupCursor (on 2nd page). + * ordering on the screen. The problem + * this caused: it sees a citation on the + * 2nd line of the 1st page as appearing + * after one at the 1st line of 2nd + * page. Since we create cursorBetween at + * the end of range1Full (on 1st page), it + * is now BEFORE currentGroupCursor (on + * 2nd page). */ throw new RuntimeException( "combineCiteMarkers: " diff --git a/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java new file mode 100644 index 00000000000..e4add04c2c6 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java @@ -0,0 +1,346 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Collections; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Selection; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.text.XText; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextRange; +import com.sun.star.text.XTextRangeCompare; +import com.sun.star.text.XTextViewCursor; +import com.sun.star.text.XTextViewCursorSupplier; +import com.sun.star.util.InvalidStateException; + +import org.jabref.logic.JabRefException; +// import org.jabref.model.database.BibDatabase; +// import org.jabref.model.entry.BibEntry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class RangeSortVisual { + + private static final Logger LOGGER = + LoggerFactory.getLogger(RangeSortVisual.class); + + /* first appearance order, based on visual order */ + + /** + * Given a location, return its position: coordinates relative to + * the top left position of the first page of the document. + * + * Note: for text layouts with two or more columns, this gives the + * wrong order: top-down/left-to-right does not match + * reading order. + * + * Note: The "relative to the top left position of the first page" + * is meant "as it appears on the screen". + * + * In particular: when viewing pages side-by-side, the top + * half of the right page is higher than the lower half of + * the left page. Again, top-down/left-to-right does not + * match reading order. + * + * @param range Location. + * @param cursor To get the position, we need az XTextViewCursor. + * It will be moved to the range. + */ + private static Point + findPositionOfTextRange(XTextRange range, XTextViewCursor cursor) { + cursor.gotoRange(range, false); + return cursor.getPosition(); + } + + /** + * A reference mark name paired with its visual position. + * + * Comparison is based on (Y,X,indexInPosition): vertical compared + * first, horizontal second, indexInPosition third. + * + * Used for sorting reference marks by their visual positions. + * + * + * + */ + private static class ComparableMark implements Comparable> { + + private final Point position; + private final int indexInPosition; + private final T content; + + public ComparableMark(Point position, int indexInPosition, T content) { + this.position = position; + this.indexInPosition = indexInPosition; + this.content = content; + } + + @Override + public int compareTo(ComparableMark other) { + + if (position.Y != other.position.Y) { + return position.Y - other.position.Y; + } + if (position.X != other.position.X) { + return position.X - other.position.X; + } + return indexInPosition - other.indexInPosition; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (o instanceof ComparableMark) { + ComparableMark other = (ComparableMark) o; + return ((this.position.X == other.position.X) + && (this.position.Y == other.position.Y) + && (this.indexInPosition == other.indexInPosition) + && Objects.equals(this.content, other.content) + ); + } + return false; + } + + public T getContent() { + return content; + } + + @Override + public int hashCode() { + return Objects.hash(position, indexInPosition, content); + } + } + + /** + * This is what {@code visualSort} needs in its input. + */ + public interface VisualSortable { + public XTextRange getRange(); + public int getIndexInPosition(); + public T getContent(); + } + + /** + * A simple implementation of {@code VisualSortable} + */ + public static class VisualSortEntry implements VisualSortable { + public XTextRange range; + public int indexInPosition; + public T content; + + VisualSortEntry( + XTextRange range, + int indexInPosition, + T content + ) { + this.range = range; + this.indexInPosition = indexInPosition; + this.content = content; + } + + @Override + public XTextRange getRange() { + return range; + } + + @Override + public int getIndexInPosition() { + return indexInPosition; + } + + @Override + public T getContent() { + return content; + } + } + + /** + * Sort its input {@code vses} visually. + * + * Requires a functional {@code XTextViewCursor}. + * In case the user selected a frame, it can get one, + * but not if the cursor is in a comment. In the latter case + * it throws a JabRefException asking the user to move the cursor. + * + * @param messageOnFailureToObtainAFunctionalXTextViewCursor + * A localized message to the user, asking to move the cursor + * into the document. + * + * @return The input, sorted by the elements XTextRange and + * getIndexInPosition. + */ + public static List> + visualSort(List> vses, + DocumentConnection documentConnection, + String messageOnFailureToObtainAFunctionalXTextViewCursor) + throws + WrappedTargetException, + NoDocumentException, + JabRefException { + + final int nCitationGroups = vses.size(); + + // if ( messageOnFailureToObtainAFunctionalXTextViewCursor == null ) { + // messageOnFailureToObtainAFunctionalXTextViewCursor = + // Localization.lang("Please move the cursor into the document text.") + // + "\n" + // + Localization.lang("To get the visual positions of your citations" + // + " I need to move the cursor around," + // + " but could not get it."); + // } + + if (documentConnection.hasControllersLocked()) { + LOGGER.warn( + "visualSort:" + + " with ControllersLocked, viewCursor.gotoRange" + + " is probably useless" + ); + } + + /* + * A problem with XTextViewCursor: if it is not in text, + * then we get a crippled version that does not support + * viewCursor.getStart() or viewCursor.gotoRange(range,false), + * and will throw an exception instead. + * + * Our hope is that either we can move the cursor with a + * page- or scrolling-based method that does not throw, (see + * https://docs.libreoffice.org/sw/html/unotxvw_8cxx_source.html#l00896 + * ) or that we can manipulate the cursor via getSelection and + * select (of XSelectionSupplier). + * + * Here we implemented the second, selection-based method. + * Seems to work when the user selected a frame or image. + * In these cases restoring the selection works, too. + * + * Still, we have a problem when the cursor is in a comment + * (referred to as "annotation" in OO API): in this case + * initialSelection is null, and documentConnection.select() + * does not help to get a function viewCursor. Having no + * better idea, we ask the user to move the cursor into the + * document. + */ + + /* + * Selection-based + */ + final boolean debugThisFun = false; + + XServiceInfo initialSelection = documentConnection.getSelectionAsServiceInfo(); + + if (initialSelection != null) { + if (Arrays.stream(initialSelection.getSupportedServiceNames()) + .anyMatch("com.sun.star.text.TextRanges"::equals)) { + // we are probably OK with the viewCursor + if (debugThisFun) { + LOGGER.info("visualSort: initialSelection supports TextRanges: no action needed."); + } + } else { + if (debugThisFun) { + LOGGER.info("visualSort: initialSelection does not support TextRanges." + + " We need to change the viewCursor."); + } + XTextRange newSelection = documentConnection.xText.getStart(); + documentConnection.select( newSelection ); + } + } else { + if (debugThisFun) { + LOGGER.info("visualSort: initialSelection is null: no idea what to do."); + } + /* + * XTextRange newSelection = documentConnection.xText.getStart(); + * boolean res = documentConnection.select( newSelection ); + * XServiceInfo sel2 = documentConnection.getSelectionAsServiceInfo(); + * LOGGER.info( + * String.format("visualSort: initialSelection is null: result of select: %s, isNull: %s%n", + * res, + * sel2 == null)); + * // ^^^ prints true, true + */ + } + + + XTextViewCursor viewCursor = documentConnection.getViewCursor(); + Objects.requireNonNull(viewCursor); + try { + viewCursor.getStart(); + } catch (com.sun.star.uno.RuntimeException ex) { + throw new JabRefException( + messageOnFailureToObtainAFunctionalXTextViewCursor, + ex); + } + + // find coordinates + List positions = new ArrayList<>(vses.size()); + + for (VisualSortable v : vses) { + positions.add(findPositionOfTextRange(v.getRange(), + viewCursor)); + } + + /* + * Restore initial state of selection (and thus viewCursor) + */ + if (initialSelection != null) { + documentConnection.select(initialSelection); + } + + if ( positions.size() != nCitationGroups ) { + throw new RuntimeException("visualSort: positions.size() != nCitationGroups"); + } + + // order by position + Set>> set = new TreeSet<>(); + for (int i = 0; i < vses.size(); i++) { + set.add( + new ComparableMark<>( + positions.get(i), + vses.get(i).getIndexInPosition(), + vses.get(i) + ) + ); + } + + if ( set.size() != nCitationGroups ) { + throw new RuntimeException("visualSort: set.size() != nCitationGroups"); + } + + // collect CitationGroupIDs in order + List> result = new ArrayList<>(set.size()); + for (ComparableMark> mark : set) { + result.add(mark.getContent()); + } + + if ( result.size() != nCitationGroups ) { + throw new RuntimeException("visualSort: result.size() != nCitationGroups"); + } + + return result; + } + +} From 6a4b86ae2769f5eb7bee73d9d388aa40aa9b1cd0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Mar 2021 20:22:48 +0100 Subject: [PATCH 0502/1068] refactor: describe RangeSortVisual --- .../gui/openoffice/RangeSortVisual.java | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java index e4add04c2c6..d7ee52842ae 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java @@ -41,6 +41,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * Sort XTextRange values visually (top-down,left-to-right). + * + * Requires functional XTextViewCursor. + * + * Problem: for multicolumn layout and view pages side-by-side mode of + * LO, the (top-down,left-to-right) order interpreted + * as-on-the-screen: an XTextRange at the top of the second + * column or second page is sorted before one at the bottom + * of the first column of the first page. + * + */ class RangeSortVisual { private static final Logger LOGGER = @@ -203,7 +215,7 @@ public T getContent() { NoDocumentException, JabRefException { - final int nCitationGroups = vses.size(); + final int inputSize = vses.size(); // if ( messageOnFailureToObtainAFunctionalXTextViewCursor == null ) { // messageOnFailureToObtainAFunctionalXTextViewCursor = @@ -310,8 +322,8 @@ public T getContent() { documentConnection.select(initialSelection); } - if ( positions.size() != nCitationGroups ) { - throw new RuntimeException("visualSort: positions.size() != nCitationGroups"); + if ( positions.size() != inputSize ) { + throw new RuntimeException("visualSort: positions.size() != inputSize"); } // order by position @@ -326,8 +338,8 @@ public T getContent() { ); } - if ( set.size() != nCitationGroups ) { - throw new RuntimeException("visualSort: set.size() != nCitationGroups"); + if ( set.size() != inputSize ) { + throw new RuntimeException("visualSort: set.size() != inputSize"); } // collect CitationGroupIDs in order @@ -336,8 +348,8 @@ public T getContent() { result.add(mark.getContent()); } - if ( result.size() != nCitationGroups ) { - throw new RuntimeException("visualSort: result.size() != nCitationGroups"); + if ( result.size() != inputSize ) { + throw new RuntimeException("visualSort: result.size() != inputSize"); } return result; From 4f01243c201d5b5d594474de63363ccf2cf7ddd1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 27 Mar 2021 21:10:28 +0100 Subject: [PATCH 0503/1068] refactor: separate RangeSort, non-visual parts from RangeSortVisual --- .../gui/openoffice/CitationGroupsV001.java | 34 +++---- .../org/jabref/gui/openoffice/RangeSort.java | 93 +++++++++++++++++++ .../gui/openoffice/RangeSortVisual.java | 55 ++--------- 3 files changed, 117 insertions(+), 65 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/RangeSort.java diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 5a705efc50e..0f76fec5627 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -700,18 +700,18 @@ Optional getBibliography() { /** * Creates a list of {@code - * VisualSortable} values for + * RangeSortable} values for * our {@code CitationGroup} values. Originally designed to be * passed to {@code visualSort}. * * The elements of the returned list are actually of type {@code - * VisualSortEntry}. + * RangeSortEntry}. * * The result is sorted within {@code XTextRange.getText()} * partitions of the citation groups according to their {@code * XTextRange} (before mapping to footnote marks). * - * In the result, VisualSortable.getIndexInPosition() contains + * In the result, RangeSortable.getIndexInPosition() contains * unique indexes within the original partition (not after * mapFootnotesToFootnoteMarks). * @@ -722,7 +722,7 @@ Optional getBibliography() { * mark. This is used for numbering the citations. * */ - private static List> + private static List> createVisualSortInput(CitationGroupsV001 cgs, DocumentConnection documentConnection, boolean mapFootnotesToFootnoteMarks) @@ -733,13 +733,13 @@ Optional getBibliography() { List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); - List vses = new ArrayList<>(); + List vses = new ArrayList<>(); for (CitationGroupsV001.CitationGroupID cgid : cgids) { XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); if (range == null) { throw new RuntimeException( "getReferenceMarkRangeOrNull returned null" ); } - vses.add( new RangeSortVisual.VisualSortEntry(range, 0, cgid) ); + vses.add( new RangeSort.RangeSortEntry(range, 0, cgid) ); } /* @@ -763,17 +763,17 @@ Optional getBibliography() { */ // Sort within partitions - RangeKeyedMapList> xxs + RangeKeyedMapList> xxs = new RangeKeyedMapList<>(); - for (RangeSortVisual.VisualSortEntry v : vses) { + for (RangeSort.RangeSortEntry v : vses) { xxs.add( v.getRange(), v ); } // build final list - List> res = new ArrayList<>(); + List> res = new ArrayList<>(); - for (TreeMap>> + for (TreeMap>> xs : xxs.partitionValues()) { List oxs = new ArrayList<>(xs.keySet()); @@ -781,9 +781,9 @@ Optional getBibliography() { int indexInPartition = 0; for (int i = 0; i < oxs.size(); i++) { XTextRange a = oxs.get(i); - List> avs = xs.get(a); + List> avs = xs.get(a); for (int j = 0; j < avs.size(); j++){ - RangeSortVisual.VisualSortEntry v = avs.get(j); + RangeSort.RangeSortEntry v = avs.get(j); v.indexInPosition = indexInPartition++; if ( mapFootnotesToFootnoteMarks ) { // Adjust range if we are inside a footnote: @@ -799,9 +799,9 @@ Optional getBibliography() { } } // convert - // List> + // List> // to - // List> + // List> return res.stream().map(e -> e).collect(Collectors.toList()); } @@ -813,7 +813,7 @@ Optional getBibliography() { NoDocumentException, JabRefException { CitationGroupsV001 cgs = this; - List> vses = + List> vses = createVisualSortInput(cgs, documentConnection, mapFootnotesToFootnoteMarks); @@ -829,7 +829,7 @@ Optional getBibliography() { + Localization.lang("To get the visual positions of your citations" + " I need to move the cursor around," + " but could not get it."); - List> sorted = + List> sorted = RangeSortVisual.visualSort( vses, documentConnection, messageOnFailureToObtainAFunctionalXTextViewCursor ); @@ -858,7 +858,7 @@ Optional getBibliography() { // but we skip the visualSort part. CitationGroupsV001 cgs = this; boolean mapFootnotesToFootnoteMarks = false; - List> vses = + List> vses = CitationGroupsV001.createVisualSortInput(cgs, documentConnection, mapFootnotesToFootnoteMarks); diff --git a/src/main/java/org/jabref/gui/openoffice/RangeSort.java b/src/main/java/org/jabref/gui/openoffice/RangeSort.java new file mode 100644 index 00000000000..29b91097d27 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/RangeSort.java @@ -0,0 +1,93 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Collections; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Selection; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.text.XText; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextRange; +import com.sun.star.text.XTextRangeCompare; +import com.sun.star.text.XTextViewCursor; +import com.sun.star.text.XTextViewCursorSupplier; +import com.sun.star.util.InvalidStateException; + +// import org.jabref.logic.JabRefException; +// import org.jabref.model.database.BibDatabase; +// import org.jabref.model.entry.BibEntry; +// import org.slf4j.Logger; +// import org.slf4j.LoggerFactory; + +class RangeSort { + + /** + * This is what {@code visualSort} needs in its input. + * + * But actually there is nothing visual in it. + * Maybe we could reuse it for other sorters. + * + */ + public interface RangeSortable { + public XTextRange getRange(); + public int getIndexInPosition(); + public T getContent(); + } + + /** + * A simple implementation of {@code RangeSortable} + */ + public static class RangeSortEntry implements RangeSortable { + public XTextRange range; + public int indexInPosition; + public T content; + + RangeSortEntry( + XTextRange range, + int indexInPosition, + T content + ) { + this.range = range; + this.indexInPosition = indexInPosition; + this.content = content; + } + + @Override + public XTextRange getRange() { + return range; + } + + @Override + public int getIndexInPosition() { + return indexInPosition; + } + + @Override + public T getContent() { + return content; + } + } + +} diff --git a/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java index d7ee52842ae..a3c6867bc62 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java @@ -36,6 +36,7 @@ import com.sun.star.util.InvalidStateException; import org.jabref.logic.JabRefException; +import org.jabref.gui.openoffice.RangeSort; // import org.jabref.model.database.BibDatabase; // import org.jabref.model.entry.BibEntry; import org.slf4j.Logger; @@ -148,48 +149,6 @@ public int hashCode() { } } - /** - * This is what {@code visualSort} needs in its input. - */ - public interface VisualSortable { - public XTextRange getRange(); - public int getIndexInPosition(); - public T getContent(); - } - - /** - * A simple implementation of {@code VisualSortable} - */ - public static class VisualSortEntry implements VisualSortable { - public XTextRange range; - public int indexInPosition; - public T content; - - VisualSortEntry( - XTextRange range, - int indexInPosition, - T content - ) { - this.range = range; - this.indexInPosition = indexInPosition; - this.content = content; - } - - @Override - public XTextRange getRange() { - return range; - } - - @Override - public int getIndexInPosition() { - return indexInPosition; - } - - @Override - public T getContent() { - return content; - } - } /** * Sort its input {@code vses} visually. @@ -206,8 +165,8 @@ public T getContent() { * @return The input, sorted by the elements XTextRange and * getIndexInPosition. */ - public static List> - visualSort(List> vses, + public static List> + visualSort(List> vses, DocumentConnection documentConnection, String messageOnFailureToObtainAFunctionalXTextViewCursor) throws @@ -310,7 +269,7 @@ public T getContent() { // find coordinates List positions = new ArrayList<>(vses.size()); - for (VisualSortable v : vses) { + for (RangeSort.RangeSortable v : vses) { positions.add(findPositionOfTextRange(v.getRange(), viewCursor)); } @@ -327,7 +286,7 @@ public T getContent() { } // order by position - Set>> set = new TreeSet<>(); + Set>> set = new TreeSet<>(); for (int i = 0; i < vses.size(); i++) { set.add( new ComparableMark<>( @@ -343,8 +302,8 @@ public T getContent() { } // collect CitationGroupIDs in order - List> result = new ArrayList<>(set.size()); - for (ComparableMark> mark : set) { + List> result = new ArrayList<>(set.size()); + for (ComparableMark> mark : set) { result.add(mark.getContent()); } From 3da232d9ed13b3d733f8642378c903c7570bfd69 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 10:10:33 +0200 Subject: [PATCH 0504/1068] drop REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4505cf56da7..5d78373cd0f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1267,8 +1267,7 @@ private void insertReferenceMark(CitationGroupsV001 cgs, cgs.cleanFillCursorForCitationGroup(documentConnection, cgid, - !withText, - cgs.REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); + !withText); } position.collapseToEnd(); } @@ -1685,8 +1684,7 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, cgs.cleanFillCursorForCitationGroup(documentConnection, cgid, - !withText, - cgs.REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS); + !withText); } if (hadBibSection @@ -2188,7 +2186,9 @@ public void combineCiteMarkers(List databases, List - referenceMarkNames = cgs.getCitationGroupIDsSortedWithinPartitions(documentConnection); + referenceMarkNames = + cgs.getCitationGroupIDsSortedWithinPartitions(documentConnection, + false /* mapFootnotesToFootnoteMarks */); final int nRefMarks = referenceMarkNames.size(); From a7e0dc4e8590e195324c6e38bab72d3924513e0f Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 10:11:20 +0200 Subject: [PATCH 0505/1068] refactor: checkstyle, CitationComparator --- .../gui/openoffice/CitationGroupsV001.java | 1009 ++++++++--------- 1 file changed, 491 insertions(+), 518 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 0f76fec5627..b9d357619fc 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -2,12 +2,11 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.Collections; -import java.util.Collection; import java.util.Comparator; import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -19,27 +18,25 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XFootnote; import com.sun.star.text.XText; -import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextRange; import com.sun.star.uno.UnoRuntime; -import com.sun.star.util.InvalidStateException; - -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -/* +/** * At the start of GUI actions we may want to check the state of the document. * * Operations: @@ -68,174 +65,11 @@ class CitationGroupsV001 { private static final String REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; - /** Should we always fully remove reference mark brackets? */ - public static final boolean - REFERENCE_MARK_ALWAYS_REMOVE_BRACKETS = true; - - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if - * available, otherwise null. - */ - private static T unoQI(Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - - class CitationGroupID { - String id; - CitationGroupID(String id){ - this.id = id; - } - - /** - * CitationEntry needs refMark or other identifying string - */ - String asString() { - return id; - } - - CitationGroupID fromString(String s) { - return new CitationGroupID(s); - } - } - - - class Citation { - - /** key in database */ - String citationKey; - Optional db; - Optional number; - Optional uniqueLetter; - - /* missing: something that differentiates this from other - * citations of the same citationKey - */ - - Citation( String citationKey ) { - this.citationKey = citationKey; - this.db = Optional.empty(); - this.number = Optional.empty(); - this.uniqueLetter = Optional.empty(); - } - } - - List makeIndices( int n ) { - return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); - } - - class CitationGroup { - CitationGroupID cgid; - int itcType; - List citations; - List localOrder; - // Currently pageInfo belongs to the group - Optional pageInfo; - /** - * Locator in document - */ - String referenceMarkName; - - CitationGroup( - CitationGroupID cgid, - int itcType, - List citations, - Optional pageInfo, - String referenceMarkName) { - this.cgid = cgid; - this.itcType = itcType; - this.citations = citations; - this.pageInfo = pageInfo; - this.referenceMarkName = referenceMarkName; - this.localOrder = makeIndices( citations.size() ); - } - - List - getSortedCitations() { - List res = new ArrayList<>(citations.size()); - for (int i : localOrder) { - res.add(citations.get(i)); - } - return res; - } - - List - getSortedNumbers() { - List cits = getSortedCitations(); - List numbers = - cits.stream() - .map( cit -> cit.number.get() ) - .collect(Collectors.toList()); - return numbers; - } - - class CitationAndIndex { - Citation c; - int i; - CitationAndIndex( Citation c, int i ){ - this.c = c; - this.i = i; - } - } - - /** - * Sort citations for presentation within a CitationGroup. - */ - class SortCitations implements Comparator { - - Comparator entryComparator; - - SortCitations(Comparator entryComparator) { - this.entryComparator = entryComparator; - } - - public int compare(CitationAndIndex a, CitationAndIndex b) { - if ( a.c.db.isEmpty() && b.c.db.isEmpty() ){ - // Both are unresolved: compare them by citation key. - String ack = a.c.citationKey; - String bck = b.c.citationKey; - return ack.compareTo(bck); - } - // Comparing unresolved and real entry - final boolean unresolvedComesFirst = true; - final int mul = unresolvedComesFirst ? (+1) : (-1); - if ( a.c.db.isEmpty() ){ - return -1*mul; - } - if ( b.c.db.isEmpty() ){ - return +1*mul; - } - // Proper comparison of entries - return entryComparator.compare( - a.c.db.get().entry, - b.c.db.get().entry - ); - } - } - - void - imposeLocalOrderByComparator(Comparator entryComparator) { - List cks = new ArrayList<>(); - for (int i = 0; i < citations.size(); i++) { - Citation c = citations.get(i); - cks.add( new CitationAndIndex(c,i) ); - } - Collections.sort(cks, new SortCitations(entryComparator)); - - List o = new ArrayList<>(); - for (CitationAndIndex ck : cks) { - o.add(ck.i); - } - this.localOrder = o; - } - } /** * Original CitationGroups Data */ - Map citationGroups; + Map citationGroups; /** * Extra Data @@ -253,17 +87,6 @@ public int compare(CitationAndIndex a, CitationAndIndex b) { */ private Optional bibliography; - public void show() { - System.out.printf("CitationGroupsV001%n"); - System.out.printf(" citationGroups.size: %d%n", citationGroups.size()); - System.out.printf(" pageInfoThrash.size: %d%n", pageInfoThrash.size()); - System.out.printf(" globalOrder: %s%n", - globalOrder.isEmpty() - ? "isEmpty" - : String.format( "%d", globalOrder.get().size() ) - ); - } - /** * Constructor */ @@ -273,38 +96,14 @@ public CitationGroupsV001(DocumentConnection documentConnection) WrappedTargetException { // Get the citationGroupNames - List citationGroupNames = - getJabRefReferenceMarkNames(documentConnection); + List citationGroupNames = getJabRefReferenceMarkNames(documentConnection); - { - // Collect unused jabrefPropertyNames - Set citationGroupNamesSet = - citationGroupNames.stream().collect(Collectors.toSet()); + this.pageInfoThrash = findUnusedJabrefPropertyNames(documentConnection, + citationGroupNames); - List pageInfoThrash = new ArrayList<>(); - List jabrefPropertyNames = - documentConnection.getCustomPropertyNames() - .stream() - .filter(CitationGroupsV001::isJabRefReferenceMarkName) - .collect(Collectors.toList()); - for (String pn : jabrefPropertyNames) { - if (!citationGroupNamesSet.contains(pn)) { - pageInfoThrash.add(pn); - } - } - this.pageInfoThrash = pageInfoThrash; - } + this.citationGroups = readCitationGroupsFromDocument(documentConnection, + citationGroupNames); - { - Map citationGroups = new HashMap<>(); - for (int i = 0; i < citationGroupNames.size(); i++) { - final String name = citationGroupNames.get(i); - CitationGroup cg = - readCitationGroupFromDocumentOrThrow(documentConnection, name); - citationGroups.put(cg.cgid, cg); - } - this.citationGroups = citationGroups; - } // Now we have almost every information from the document about citations. // What is left out: the ranges controlled by the reference marks. // But (I guess) those change too easily, so we only ask when actually needed. @@ -314,7 +113,43 @@ public CitationGroupsV001(DocumentConnection documentConnection) this.bibliography = Optional.empty(); } - private CitationGroup + private static List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, + List citationGroupNames) { + // Collect unused jabrefPropertyNames + Set citationGroupNamesSet = + citationGroupNames.stream().collect(Collectors.toSet()); + + List pageInfoThrash = new ArrayList<>(); + List jabrefPropertyNames = + documentConnection.getCustomPropertyNames() + .stream() + .filter(CitationGroupsV001::isJabRefReferenceMarkName) + .collect(Collectors.toList()); + for (String pn : jabrefPropertyNames) { + if (!citationGroupNamesSet.contains(pn)) { + pageInfoThrash.add(pn); + } + } + return pageInfoThrash; + } + + private static Map + readCitationGroupsFromDocument(DocumentConnection documentConnection, + List citationGroupNames) + throws + WrappedTargetException { + + Map citationGroups = new HashMap<>(); + for (int i = 0; i < citationGroupNames.size(); i++) { + final String name = citationGroupNames.get(i); + CitationGroup cg = + readCitationGroupFromDocumentOrThrow(documentConnection, name); + citationGroups.put(cg.cgid, cg); + } + return citationGroups; + } + + private static CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection documentConnection, String refMarkName) throws @@ -360,13 +195,13 @@ class CitationPath { class DatabaseLookupResult { BibEntry entry; BibDatabase database; - DatabaseLookupResult( BibEntry entry, BibDatabase database ) { + DatabaseLookupResult(BibEntry entry, BibDatabase database) { this.entry = entry; this.database = database; } } - class CitedKey { + class CitedKey implements SortableCitation { String key; // TODO: rename to citationKey LinkedHashSet where; Optional db; @@ -374,7 +209,7 @@ class CitedKey { Optional uniqueLetter; // For AuthorYear citation styles. Optional normCitMarker; // For AuthorYear citation styles. - CitedKey( String key, CitationPath p, Citation cit ) { + CitedKey(String key, CitationPath p, Citation cit) { this.key = key; this.where = new LinkedHashSet<>(); // remember order this.where.add(p); @@ -384,7 +219,19 @@ class CitedKey { this.normCitMarker = Optional.empty(); } - void addPath( CitationPath p, Citation cit ) { + @Override + public String getCitationKey(){ + return key; + } + + @Override + public Optional getBibEntry(){ + return (db.isPresent() + ? Optional.of(db.get().entry) + : Optional.empty()); + } + + void addPath(CitationPath p, Citation cit) { this.where.add(p); if (cit.db != this.db) { throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); @@ -423,12 +270,53 @@ void distributeUniqueLetter(CitationGroupsV001 cgs) { } } + interface SortableCitation { + public String getCitationKey(); + public Optional getBibEntry(); + } + + static class CitationComparator implements Comparator { + + Comparator entryComparator; + boolean unresolvedComesFirst; + + CitationComparator(Comparator entryComparator, + boolean unresolvedComesFirst) { + this.entryComparator = entryComparator; + this.unresolvedComesFirst = unresolvedComesFirst; + } + + public int compare(SortableCitation a, SortableCitation b) { + Optional abe = a.getBibEntry(); + Optional bbe = b.getBibEntry(); + + if (abe.isEmpty() && bbe.isEmpty()) { + // Both are unresolved: compare them by citation key. + String ack = a.getCitationKey(); + String bck = b.getCitationKey(); + return ack.compareTo(bck); + } + // Comparing unresolved and real entry + + final int mul = unresolvedComesFirst ? (+1) : (-1); + if (abe.isEmpty()) { + return -mul; + } + if (bbe.isEmpty()) { + return mul; + } + // Proper comparison of entries + return entryComparator.compare(abe.get(), + bbe.get()); + } + } + class CitedKeys { /** * Order-preserving map from citation keys to associated data. */ - LinkedHashMap data; + LinkedHashMap data; CitedKeys(LinkedHashMap data) { this.data = data; @@ -437,64 +325,64 @@ class CitedKeys { /** * The cited keys in sorted order. */ - public List - values() { + public List values() { return new ArrayList<>(data.values()); } /** * Sort entries for the bibliography. */ - class SortCitedKeys implements Comparator { + /* + class SortCitedKeys implements Comparator { Comparator entryComparator; + boolean unresolvedComesFirst; - SortCitedKeys(Comparator entryComparator) { + SortCitedKeys(Comparator entryComparator, + boolean unresolvedComesFirst) { this.entryComparator = entryComparator; + this.unresolvedComesFirst = unresolvedComesFirst; } public int compare(CitedKey a, CitedKey b) { - if (a.db.isEmpty() && b.db.isEmpty()) { + if (a.db.isEmpty() && b.db.isEmpty()) { // Both are unresolved: compare them by citation key. return a.key.compareTo(b.key); } // Comparing unresolved and real entry - final boolean unresolvedComesFirst = true; final int mul = unresolvedComesFirst ? (+1) : (-1); - if (a.db.isEmpty()){ - return -1*mul; + if (a.db.isEmpty()) { + return -mul; } - if (b.db.isEmpty()){ - return +1*mul; + if (b.db.isEmpty()) { + return mul; } // Proper comparison of entries return entryComparator.compare(a.db.get().entry, b.db.get().entry); } } + */ - void - sortByComparator(Comparator entryComparator) { - List cks = new ArrayList(data.values()); - Collections.sort(cks, new SortCitedKeys(entryComparator)); - LinkedHashMap newData = new LinkedHashMap<>(); + void sortByComparator(Comparator entryComparator) { + List cks = new ArrayList<>(data.values()); + cks.sort(new CitationComparator(entryComparator, true)); + LinkedHashMap newData = new LinkedHashMap<>(); for (CitedKey ck : cks) { newData.put(ck.key, ck); } data = newData; } - void - numberCitedKeysInCurrentOrder() { - int i=1; + void numberCitedKeysInCurrentOrder() { + int i = 1; for (CitedKey ck : data.values()) { ck.number = Optional.of(i); // was: -1 for UndefinedBibtexEntry i++; } } - void - lookupInDatabases(List databases) { + void lookupInDatabases(List databases) { for (CitedKey ck : this.data.values()) { ck.lookupInDatabases(databases); } @@ -520,12 +408,11 @@ void distributeUniqueLetters(CitationGroupsV001 cgs) { } - public void - setDatabaseLookupResults(Set where, - Optional db) { + public void setDatabaseLookupResults(Set where, + Optional db) { for (CitationPath p : where) { CitationGroup cg = this.citationGroups.get(p.group); - if (cg == null){ + if (cg == null) { LOGGER.warn("CitationGroups.setDatabaseLookupResult: group missing"); continue; } @@ -534,8 +421,7 @@ void distributeUniqueLetters(CitationGroupsV001 cgs) { } } - public CitationGroupsV001.CitedKeys - lookupEntriesInDatabases(List databases) { + public CitationGroupsV001.CitedKeys lookupEntriesInDatabases(List databases) { CitationGroupsV001 cgs = this; CitationGroupsV001.CitedKeys cks = cgs.getCitedKeys(); @@ -548,12 +434,11 @@ void distributeUniqueLetters(CitationGroupsV001 cgs) { return cks; } - public void - setNumbers(Set where, - Optional number) { + public void setNumbers(Set where, + Optional number) { for (CitationPath p : where) { CitationGroup cg = this.citationGroups.get(p.group); - if (cg == null){ + if (cg == null) { LOGGER.warn("CitationGroups.setNumbers: group missing"); continue; } @@ -562,9 +447,8 @@ void distributeUniqueLetters(CitationGroupsV001 cgs) { } } - public void - setUniqueLetters(Set where, - Optional uniqueLetter) { + public void setUniqueLetters(Set where, + Optional uniqueLetter) { for (CitationPath p : where) { CitationGroup cg = this.citationGroups.get(p.group); if (cg == null) { @@ -576,25 +460,23 @@ void distributeUniqueLetters(CitationGroupsV001 cgs) { } } - public void - imposeLocalOrderByComparator(Comparator entryComparator) { + public void imposeLocalOrderByComparator(Comparator entryComparator) { for (CitationGroup cg : citationGroups.values()) { cg.imposeLocalOrderByComparator(entryComparator); } } - public CitedKeys - getCitedKeys() { - LinkedHashMap res = new LinkedHashMap<>(); + public CitedKeys getCitedKeys() { + LinkedHashMap res = new LinkedHashMap<>(); for (CitationGroup cg : citationGroups.values()) { int storageIndexInGroup = 0; for (Citation cit : cg.citations) { String key = cit.citationKey; CitationPath p = new CitationPath(cg.cgid, storageIndexInGroup); - if ( res.containsKey(key) ) { - res.get(key).addPath(p,cit); + if (res.containsKey(key)) { + res.get(key).addPath(p, cit); } else { - res.put(key, new CitedKey( key, p, cit )); + res.put(key, new CitedKey(key, p, cit)); } storageIndexInGroup++; } @@ -602,13 +484,11 @@ void distributeUniqueLetters(CitationGroupsV001 cgs) { return new CitedKeys(res); } - /** * CitedKeys created iterating citations in (globalOrder,localOrder) */ - public CitedKeys - getCitedKeysSortedInOrderOfAppearance() { - LinkedHashMap res = new LinkedHashMap<>(); + public CitedKeys getCitedKeysSortedInOrderOfAppearance() { + LinkedHashMap res = new LinkedHashMap<>(); if (globalOrder.isEmpty()) { throw new RuntimeException("getSortedCitedKeys: no globalOrder"); } @@ -618,9 +498,9 @@ void distributeUniqueLetters(CitationGroupsV001 cgs) { for (int i : cg.localOrder) { Citation cit = cg.citations.get(i); String citationKey = cit.citationKey; - CitationPath p = new CitationPath(cgid,i); + CitationPath p = new CitationPath(cgid, i); if (res.containsKey(citationKey)) { - res.get(citationKey).addPath(p,cit); + res.get(citationKey).addPath(p, cit); } else { res.put(citationKey, new CitedKey(citationKey, p, cit)); } @@ -633,13 +513,11 @@ Optional getBibliography() { return bibliography; } - public void - createNumberedBibliographySortedInOrderOfAppearance() { + public void createNumberedBibliographySortedInOrderOfAppearance() { CitationGroupsV001 cgs = this; if (!cgs.bibliography.isEmpty()) { throw new RuntimeException( - "createNumberedBibliographySortedInOrderOfAppearance: already have a bibliography" - ); + "createNumberedBibliographySortedInOrderOfAppearance: already have a bibliography"); } CitationGroupsV001.CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); @@ -648,56 +526,38 @@ Optional getBibliography() { cgs.bibliography = Optional.of(sortedCitedKeys); } - public void - createNumberedBibliographySortedByComparator( Comparator entryComparator ) { + public void createNumberedBibliographySortedByComparator(Comparator entryComparator) { CitationGroupsV001 cgs = this; if (!cgs.bibliography.isEmpty()) { throw new RuntimeException( - "createNumberedBibliographySortedByComparator: already have a bibliography" - ); + "createNumberedBibliographySortedByComparator: already have a bibliography"); } CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); - citedKeys.sortByComparator( entryComparator ); // TODO: must be after database lookup + citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup citedKeys.numberCitedKeysInCurrentOrder(); citedKeys.distributeNumbers(cgs); this.bibliography = Optional.of(citedKeys); } public void - createPlainBibliographySortedByComparator( Comparator entryComparator ) { + createPlainBibliographySortedByComparator(Comparator entryComparator) { CitationGroupsV001 cgs = this; if (!this.bibliography.isEmpty()) { throw new RuntimeException( - "createPlainBibliographySortedByComparator: already have a bibliography" - ); + "createPlainBibliographySortedByComparator: already have a bibliography"); } CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); - citedKeys.sortByComparator( entryComparator ); // TODO: must be after database lookup + citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup // citedKeys.numberCitedKeysInCurrentOrder(); // citedKeys.distributeNumbers(); this.bibliography = Optional.of(citedKeys); } - + public Set getCitationGroupIDs() { return citationGroups.keySet(); } - /** - * Read reference mark names from the document, keep only those - * with JabRef naming convention, get their visual positions, - * - * @return JabRef reference mark names sorted by these positions. - * - * Limitation: for two column layout visual (top-down, - * left-right) order does not match the expected (textual) - * order. - * - * TODO: refmarks in the same footnote get the same position. - * After sorting, they may get the wrong order. - * - */ - /** * Creates a list of {@code * RangeSortable} values for @@ -737,9 +597,9 @@ Optional getBibliography() { for (CitationGroupsV001.CitationGroupID cgid : cgids) { XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); if (range == null) { - throw new RuntimeException( "getReferenceMarkRangeOrNull returned null" ); + throw new RuntimeException("getReferenceMarkRangeOrNull returned null"); } - vses.add( new RangeSort.RangeSortEntry(range, 0, cgid) ); + vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); } /* @@ -767,13 +627,13 @@ Optional getBibliography() { = new RangeKeyedMapList<>(); for (RangeSort.RangeSortEntry v : vses) { - xxs.add( v.getRange(), v ); + xxs.add(v.getRange(), v); } // build final list List> res = new ArrayList<>(); - for (TreeMap>> + for (TreeMap>> xs : xxs.partitionValues()) { List oxs = new ArrayList<>(xs.keySet()); @@ -782,10 +642,10 @@ Optional getBibliography() { for (int i = 0; i < oxs.size(); i++) { XTextRange a = oxs.get(i); List> avs = xs.get(a); - for (int j = 0; j < avs.size(); j++){ + for (int j = 0; j < avs.size(); j++) { RangeSort.RangeSortEntry v = avs.get(j); v.indexInPosition = indexInPartition++; - if ( mapFootnotesToFootnoteMarks ) { + if (mapFootnotesToFootnoteMarks) { // Adjust range if we are inside a footnote: if (unoQI(XFootnote.class, v.range.getText()) != null) { // Find the linking footnote marker: @@ -805,6 +665,20 @@ Optional getBibliography() { return res.stream().map(e -> e).collect(Collectors.toList()); } + /** + * Return JabRef reference mark names sorted by their visual positions. + * + * @param mapFootnotesToFootnoteMarks If true, sort reference + * marks in footnotes as if they appeared at the + * corresponding footnote mark. + * + * @return JabRef reference mark names sorted by these positions. + * + * Limitation: for two column layout visual (top-down, + * left-right) order does not match the expected (textual) + * order. + * + */ public List getVisuallySortedCitationGroupIDs(DocumentConnection documentConnection, boolean mapFootnotesToFootnoteMarks) @@ -818,7 +692,7 @@ Optional getBibliography() { documentConnection, mapFootnotesToFootnoteMarks); - if ( vses.size() != cgs.citationGroups.size() ) { + if (vses.size() != cgs.citationGroups.size()) { throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + " vses.size() != cgs.citationGroups.size()"); } @@ -830,11 +704,11 @@ Optional getBibliography() { + " I need to move the cursor around," + " but could not get it."); List> sorted = - RangeSortVisual.visualSort( vses, - documentConnection, - messageOnFailureToObtainAFunctionalXTextViewCursor ); + RangeSortVisual.visualSort(vses, + documentConnection, + messageOnFailureToObtainAFunctionalXTextViewCursor); - if ( sorted.size() != cgs.citationGroups.size() ) { + if (sorted.size() != cgs.citationGroups.size()) { // This Fired throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + " sorted.size() != cgs.citationGroups.size()"); @@ -849,21 +723,21 @@ Optional getBibliography() { * Calculate and return citation group IDs in visual order. */ public List - getCitationGroupIDsSortedWithinPartitions(DocumentConnection documentConnection) + getCitationGroupIDsSortedWithinPartitions(DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) throws NoDocumentException, - WrappedTargetException - { + WrappedTargetException { // This is like getVisuallySortedCitationGroupIDs, // but we skip the visualSort part. CitationGroupsV001 cgs = this; - boolean mapFootnotesToFootnoteMarks = false; + // boolean mapFootnotesToFootnoteMarks = false; List> vses = CitationGroupsV001.createVisualSortInput(cgs, documentConnection, mapFootnotesToFootnoteMarks); - if ( vses.size() != cgs.citationGroups.size() ) { + if (vses.size() != cgs.citationGroups.size()) { throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" + " vses.size() != cgs.citationGroups.size()"); } @@ -877,19 +751,18 @@ Optional getBibliography() { */ public List getSortedCitationGroupIDs() { - if ( globalOrder.isEmpty() ) { + if (globalOrder.isEmpty()) { throw new RuntimeException("getSortedCitationGroupIDs: not ordered yet"); } return globalOrder.get(); } public void - setGlobalOrder( List globalOrder ) { + setGlobalOrder(List globalOrder) { Objects.requireNonNull(globalOrder); - if (globalOrder.size() != citationGroups.size() ){ + if (globalOrder.size() != citationGroups.size()) { throw new RuntimeException( - "CitationGroupsV001.setGlobalOrder: globalOrder.size() != citationGroups.size()" - ); + "CitationGroupsV001.setGlobalOrder: globalOrder.size() != citationGroups.size()"); } this.globalOrder = Optional.of(globalOrder); } @@ -937,13 +810,12 @@ public Optional getPageInfo(CitationGroupID cgid) { public List getSortedCitations(CitationGroupID cgid) { Optional cg = getCitationGroup(cgid); - if ( cg.isEmpty() ) { - throw new RuntimeException( "getSortedCitations: invalid cgid" ); + if (cg.isEmpty()) { + throw new RuntimeException("getSortedCitations: invalid cgid"); } return cg.get().getSortedCitations(); } - /* *********************************** * * modifies both storage and presentation @@ -1023,7 +895,6 @@ public Optional getPageInfo(CitationGroupID cgid) { * inserted space, or at the end of the reference mark. * * @param documentConnection Connection to document. - * @param name For the reference mark. * @param position Collapsed to its end. * @param insertSpaceAfter We insert a space after the mark, that * carries on format of characters from @@ -1033,16 +904,13 @@ public Optional getPageInfo(CitationGroupID cgid) { * For use with INVISIBLE_CIT. * */ - public CitationGroupID - createCitationGroup( - DocumentConnection documentConnection, - List citationKeys, - Optional pageInfo, - int itcType, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets - ) + public CitationGroupID createCitationGroup(DocumentConnection documentConnection, + List citationKeys, + Optional pageInfo, + int itcType, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException, NoDocumentException, @@ -1053,11 +921,9 @@ public Optional getPageInfo(CitationGroupID cgid) { .collect(Collectors.joining(",")); String refMarkName = - getUniqueReferenceMarkName( - documentConnection, - xkey, - itcType - ); + getUniqueReferenceMarkName(documentConnection, + xkey, + itcType); CitationGroupID cgid = new CitationGroupID(refMarkName); @@ -1069,7 +935,7 @@ public Optional getPageInfo(CitationGroupID cgid) { /* new ArrayList<>(citationKeys.size()); for (int j = 0; j < ov.citationKeys.size(); j++) { - citatitons.add( new Citation( citationKeys.get(j) ) ); + citatitons.add(new Citation(citationKeys.get(j))); } */ @@ -1080,7 +946,7 @@ public Optional getPageInfo(CitationGroupID cgid) { refMarkName); // add to our data - this.citationGroups.put( cgid, cg ); + this.citationGroups.put(cgid, cg); // invalidate globalOrder. // TODO: look out for localOrder! this.globalOrder = Optional.empty(); @@ -1098,14 +964,11 @@ public Optional getPageInfo(CitationGroupID cgid) { return cgid; } - private static void - createReferenceMarkForCitationGroup( - DocumentConnection documentConnection, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets - ) + private static void createReferenceMarkForCitationGroup(DocumentConnection documentConnection, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException { @@ -1137,11 +1000,9 @@ public Optional getPageInfo(CitationGroupID cgid) { bracketedContent, true); - /* XNamed mark = */ documentConnection.insertReferenceMark( - refMarkName, - cursor, - true // absorb - ); + documentConnection.insertReferenceMark(refMarkName, + cursor, + true /* absorb */); cursorBefore.goRight((short) 1, true); cursorBefore.setString(""); @@ -1159,8 +1020,7 @@ public Optional getPageInfo(CitationGroupID cgid) { * not know how the bibliography was generated: it was partially done * outside CitationGroupsV001, and we did not store how. */ - public void - removeCitationGroups( List cgs, DocumentConnection documentConnection ) + public void removeCitationGroups(List cgs, DocumentConnection documentConnection) throws WrappedTargetException, NoDocumentException, @@ -1175,20 +1035,19 @@ public Optional getPageInfo(CitationGroupID cgid) { this.citedKeysAfterDatabaseLookup = Optional.empty(); this.bibliography = Optional.empty(); /* - * this.citedKeysAfterDatabaseLookup.map(cks -> cks.forgetCitationGroup(cg.cgid) ); + * this.citedKeysAfterDatabaseLookup.map(cks -> cks.forgetCitationGroup(cg.cgid)); * this.bibliography.map(cks -> cks.forgetCitationGroup(cg.cgid)); */ } } - public void - removeCitationGroup( CitationGroup cg, DocumentConnection documentConnection ) + public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) throws WrappedTargetException, NoDocumentException, NoSuchElementException { - removeCitationGroups( Collections.singletonList(cg), documentConnection ); + removeCitationGroups(Collections.singletonList(cg), documentConnection); } /** @@ -1198,44 +1057,21 @@ public Optional getPageInfo(CitationGroupID cgid) { * @param removeBracketsFromEmpty is intended to force removal if * we are working on an "Empty citation" (INVISIBLE_CIT). */ - public void - cleanFillCursorForCitationGroup( - DocumentConnection documentConnection, - CitationGroupID cgid, // String name, // Identifies group - boolean removeBracketsFromEmpty, - boolean alwaysRemoveBrackets - ) + public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, + CitationGroupID cgid, + boolean removeBracketsFromEmpty) throws NoDocumentException, WrappedTargetException, CreationException { + boolean alwaysRemoveBrackets = true; final String left = REFERENCE_MARK_LEFT_BRACKET; final String right = REFERENCE_MARK_RIGHT_BRACKET; final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); CitationGroupsV001 cgs = this; - /* - // XTextContent markAsTextContent = documentConnection.getReferenceMarkAsTextContentOrNull(name); - XTextContent markAsTextContent = cgs.getReferenceMarkRangeOrNull(cgid,documentConnection); - - if (markAsTextContent == null) { - throw new RuntimeException( - String.format( - "cleanFillCursorForCitationGroup: markAsTextContent(%s) == null", - name - )); - } - XTextCursor full = - DocumentConnection.getTextCursorOfTextContent( - markAsTextContent); - if (full == null) { - throw new RuntimeException( - "cleanFillCursorForCitationGroup: full == null" - ); - } - */ String name = cgs.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); XTextCursor full = cgs.getRawCursorForCitationGroup(cgid, documentConnection); @@ -1254,43 +1090,32 @@ public Optional getPageInfo(CitationGroupID cgid) { if (!fullText.startsWith(left)) { throw new RuntimeException( - String.format( - "cleanFillCursorForCitationGroup:" - + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", - name - )); + String.format("cleanFillCursorForCitationGroup:" + + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", + name)); } if (!fullText.endsWith(right)) { throw new RuntimeException( - String.format( - "cleanFillCursorForCitationGroup:" - + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", - name - )); + String.format("cleanFillCursorForCitationGroup:" + + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", + name)); } final int contentLength = (fullTextLength - (leftLength + rightLength)); if (contentLength < 0) { throw new RuntimeException( - String.format( - "cleanFillCursorForCitationGroup: length(%s) < 0", - name - )); - } - - boolean removeRight = ( - // have at least 1 character content - (contentLength >= 1) - || ((contentLength == 0) && removeBracketsFromEmpty) - || alwaysRemoveBrackets - ); - boolean removeLeft = ( - // have at least 2 character content - (contentLength >= 2) - || ((contentLength == 0) && removeBracketsFromEmpty) - || alwaysRemoveBrackets - ); + String.format("cleanFillCursorForCitationGroup: length(%s) < 0", + name)); + } + + boolean removeRight = ((contentLength >= 1) + || ((contentLength == 0) && removeBracketsFromEmpty) + || alwaysRemoveBrackets); + + boolean removeLeft = ((contentLength >= 2) + || ((contentLength == 0) && removeBracketsFromEmpty) + || alwaysRemoveBrackets); if (removeRight) { omega.goLeft(rightLength, true); @@ -1307,11 +1132,8 @@ public Optional getPageInfo(CitationGroupID cgid) { * Cursor for the reference marks as is, not prepared for filling, * but does not need cleanFillCursorForCitationGroup either. */ - public XTextCursor - getRawCursorForCitationGroup( - CitationGroupID cgid, // Identifies group - DocumentConnection documentConnection - ) + public XTextCursor getRawCursorForCitationGroup(CitationGroupID cgid, + DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException, @@ -1327,25 +1149,18 @@ public Optional getPageInfo(CitationGroupID cgid) { throw new RuntimeException( String.format( "getRawCursorForCitationGroup: markAsTextContent(%s) == null", - name - )); + name)); } - full = - DocumentConnection.getTextCursorOfTextContent( - markAsTextContent); + + full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); if (full == null) { - throw new RuntimeException( - "getRawCursorForCitationGroup: full == null" - ); + throw new RuntimeException("getRawCursorForCitationGroup: full == null"); } return full; } - public XTextCursor - getFillCursorForCitationGroup( - DocumentConnection documentConnection, - CitationGroupID cgid // Identifies group - ) + public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, + CitationGroupID cgid) throws NoDocumentException, WrappedTargetException, @@ -1367,23 +1182,20 @@ public Optional getPageInfo(CitationGroupID cgid) { if (markAsTextContent == null) { throw new RuntimeException( - String.format( - "getFillCursorForCitationGroup: markAsTextContent(%s) == null (attempt %d)", - name, i - )); + String.format("getFillCursorForCitationGroup:" + + " markAsTextContent(%s) == null (attempt %d)", + name, + i)); } - full = - DocumentConnection.getTextCursorOfTextContent( - markAsTextContent); + + full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); if (full == null) { throw new RuntimeException( - String.format( - "getFillCursorForCitationGroup: full == null (attempt %d)", i - ) - ); + String.format("getFillCursorForCitationGroup: full == null (attempt %d)", i)); } fullText = full.getString(); + if (debugThisFun) { System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); } @@ -1394,11 +1206,9 @@ public Optional getPageInfo(CitationGroupID cgid) { // (fullText.length() < 2) if (i == 2) { throw new RuntimeException( - String.format( - "getFillCursorForCitationGroup:" - + " (fullText.length() < 2) (attempt %d)", i - ) - ); + String.format("getFillCursorForCitationGroup:" + + " (fullText.length() < 2) (attempt %d)", + i)); } // too short, recreate if (debugThisFun) { @@ -1408,29 +1218,25 @@ public Optional getPageInfo(CitationGroupID cgid) { try { documentConnection.removeReferenceMark(name); } catch (NoSuchElementException ex) { - LOGGER.warn(String.format( - "getFillCursorForCitationGroup got NoSuchElementException" - + " for '%s'", name)); + LOGGER.warn( + String.format("getFillCursorForCitationGroup got NoSuchElementException" + + " for '%s'", + name)); } createReferenceMarkForCitationGroup( documentConnection, name, full, - false, // insertSpaceAfter - false // withoutBrackets - ); + false, /* insertSpaceAfter */ + false /* withoutBrackets */); } } if (full == null) { - throw new RuntimeException( - "getFillCursorForCitationGroup: full == null (after loop)" - ); + throw new RuntimeException("getFillCursorForCitationGroup: full == null (after loop)"); } if (fullText == null) { - throw new RuntimeException( - "getFillCursorForCitationGroup: fullText == null (after loop)" - ); + throw new RuntimeException("getFillCursorForCitationGroup: fullText == null (after loop)"); } // we have at least two characters inside @@ -1454,7 +1260,7 @@ public Optional getPageInfo(CitationGroupID cgid) { omega.setString(""); return beta; } - + /** * Produce a reference mark name for JabRef for the given citation * key and itcType that does not yet appear among the reference @@ -1469,11 +1275,9 @@ public Optional getPageInfo(CitationGroupID cgid) { * * Or the first unused in this series, after removals. */ - private String - getUniqueReferenceMarkName( - DocumentConnection documentConnection, - String bibtexKey, - int itcType) + private String getUniqueReferenceMarkName(DocumentConnection documentConnection, + String bibtexKey, + int itcType) throws NoDocumentException { XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); @@ -1511,8 +1315,7 @@ private static class ParsedRefMark { * @return Optional.empty() on failure. * */ - private static Optional - parseRefMarkName(String refMarkName) { + private static Optional parseRefMarkName(String refMarkName) { Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); if (!citeMatcher.find()) { @@ -1538,25 +1341,20 @@ private static class ParsedRefMark { * If name does not match CITE_PATTERN, * an empty list of strings is returned. */ - private List - parseRefMarkNameToUniqueCitationKeys(String name) { + private List parseRefMarkNameToUniqueCitationKeys(String name) { Optional op = parseRefMarkName(name); - return - op.map( - parsedRefMark -> - parsedRefMark.citationKeys.stream() - .distinct() - .collect(Collectors.toList()) - ) - .orElseGet(ArrayList::new); + return (op.map(parsedRefMark -> + parsedRefMark.citationKeys.stream() + .distinct() + .collect(Collectors.toList())) + .orElseGet(ArrayList::new)); } /** * @return true if name matches the pattern used for JabRef * reference mark names. */ - private static boolean - isJabRefReferenceMarkName(String name) { + private static boolean isJabRefReferenceMarkName(String name) { return (CITE_PATTERN.matcher(name).find()); } @@ -1565,13 +1363,11 @@ private static class ParsedRefMark { * * @param names The list to be filtered. */ - private static List - filterIsJabRefReferenceMarkName(List names) { + private static List filterIsJabRefReferenceMarkName(List names) { return (names .stream() .filter(CitationGroupsV001::isJabRefReferenceMarkName) - .collect(Collectors.toList()) - ); + .collect(Collectors.toList())); } /** @@ -1583,9 +1379,9 @@ private static class ParsedRefMark { * * */ - private List - getJabRefReferenceMarkNames(DocumentConnection documentConnection) - throws NoDocumentException { + private List getJabRefReferenceMarkNames(DocumentConnection documentConnection) + throws + NoDocumentException { List allNames = documentConnection.getReferenceMarkNames(); return filterIsJabRefReferenceMarkName(allNames); } @@ -1598,12 +1394,10 @@ private static class ParsedRefMark { * @param types OUT Must be same length as referenceMarkNames. * @param bibtexKeys OUT First level must be same length as referenceMarkNames. */ - private static void - parseRefMarkNamesToArrays( - List referenceMarkNames, - int[] types, - String[][] bibtexKeys - ) { + private static void parseRefMarkNamesToArrays(List referenceMarkNames, + int[] types, + String[][] bibtexKeys) { + final int nRefMarks = referenceMarkNames.size(); assert (types.length == nRefMarks); assert (bibtexKeys.length == nRefMarks); @@ -1616,8 +1410,7 @@ private static class ParsedRefMark { // And do not want null in bibtexKeys (or error code in types) // on return. throw new IllegalArgumentException( - "parseRefMarkNamesToArrays expects parsable referenceMarkNames" - ); + "parseRefMarkNamesToArrays expects parsable referenceMarkNames"); } ParsedRefMark ov = op.get(); types[i] = ov.itcType; @@ -1633,8 +1426,7 @@ private static class ParsedRefMark { * * doc.referenceMarks.names.map(parse).flatten.unique */ - private List - findCitedKeys(DocumentConnection documentConnection) + private List findCitedKeys(DocumentConnection documentConnection) throws NoSuchElementException, WrappedTargetException, @@ -1663,8 +1455,6 @@ private static class ParsedRefMark { return keys; } - - /** * Given the name of a reference mark, get the corresponding * pageInfo text. @@ -1673,11 +1463,10 @@ private static class ParsedRefMark { * @param name Name of the custom property to query. * @return "" for missing or empty pageInfo */ - private static String - getPageInfoForReferenceMarkName( - DocumentConnection documentConnection, - String name) - throws WrappedTargetException, + private static String getPageInfoForReferenceMarkName(DocumentConnection documentConnection, + String name) + throws + WrappedTargetException, UnknownPropertyException { Optional pageInfo = documentConnection.getCustomProperty(name); @@ -1687,20 +1476,19 @@ private static class ParsedRefMark { return pageInfo.get(); } - /* * ranges controlled by citation groups should not overlap with each other. * * @param cgid : Must be known. * @return Null if the reference mark is missing. */ - public XTextRange - getReferenceMarkRangeOrNull(DocumentConnection documentConnection, CitationGroupID cgid) + public XTextRange getReferenceMarkRangeOrNull(DocumentConnection documentConnection, + CitationGroupID cgid) throws NoDocumentException, WrappedTargetException { - String name = this.getReferenceMarkName( cgid ) - .orElseThrow(RuntimeException::new); + String name = (this.getReferenceMarkName(cgid) + .orElseThrow(RuntimeException::new)); return documentConnection.getReferenceMarkRangeOrNull(name); } @@ -1709,8 +1497,7 @@ private static class ParsedRefMark { * * result.size() == nRefMarks */ - List - citationRanges(DocumentConnection documentConnection) + List citationRanges(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException { @@ -1726,8 +1513,7 @@ private static class ParsedRefMark { xs.add(new RangeForOverlapCheck( r, cgid, RangeForOverlapCheck.REFERENCE_MARK_KIND, - name - )); + name)); } return xs; } @@ -1742,8 +1528,7 @@ private static class ParsedRefMark { * reference marks in the footnote. * */ - List - footnoteMarkRanges(DocumentConnection documentConnection) + List footnoteMarkRanges(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException { @@ -1767,19 +1552,207 @@ private static class ParsedRefMark { continue; } - boolean seenContains = seen.containsKey( footnoteMarkRange ); + boolean seenContains = seen.containsKey(footnoteMarkRange); if (!seenContains) { seen.put(footnoteMarkRange, true); xs.add(new RangeForOverlapCheck( footnoteMarkRange, base.i, // cgid :: identifies of citation group RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + base.description - )); + "FootnoteMark for " + base.description)); } } return xs; } + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if + * available, otherwise null. + */ + private static T unoQI(Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + + static class CitationGroupID { + String id; + CitationGroupID(String id) { + this.id = id; + } + + /** + * CitationEntry needs refMark or other identifying string + */ + String asString() { + return id; + } + } + + static class Citation implements SortableCitation { + + /** key in database */ + String citationKey; + Optional db; + Optional number; + Optional uniqueLetter; + + /* missing: something that differentiates this from other + * citations of the same citationKey + */ + + Citation(String citationKey) { + this.citationKey = citationKey; + this.db = Optional.empty(); + this.number = Optional.empty(); + this.uniqueLetter = Optional.empty(); + } + + @Override + public String getCitationKey(){ + return citationKey; + } + + @Override + public Optional getBibEntry(){ + return (db.isPresent() + ? Optional.of(db.get().entry) + : Optional.empty()); + } + } + + static List makeIndices(int n) { + return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); + } + + static class CitationGroup { + CitationGroupID cgid; + int itcType; + List citations; + List localOrder; + // Currently pageInfo belongs to the group + Optional pageInfo; + + /** + * Locator in document + */ + String referenceMarkName; + + CitationGroup( + CitationGroupID cgid, + int itcType, + List citations, + Optional pageInfo, + String referenceMarkName) { + this.cgid = cgid; + this.itcType = itcType; + this.citations = citations; + this.pageInfo = pageInfo; + this.referenceMarkName = referenceMarkName; + this.localOrder = makeIndices(citations.size()); + } + + List + getSortedCitations() { + List res = new ArrayList<>(citations.size()); + for (int i : localOrder) { + res.add(citations.get(i)); + } + return res; + } + + List + getSortedNumbers() { + List cits = getSortedCitations(); + return (cits.stream() + .map(cit -> cit.number.orElseThrow(RuntimeException::new)) + .collect(Collectors.toList())); + } + + class CitationAndIndex implements SortableCitation { + Citation c; + int i; + CitationAndIndex(Citation c, int i) { + this.c = c; + this.i = i; + } + + @Override + public String getCitationKey(){ + return c.getCitationKey(); + } + + @Override + public Optional getBibEntry(){ + return c.getBibEntry(); + } + } + + /** + * Sort citations for presentation within a CitationGroup. + */ + /* + class SortCitations implements Comparator { + + Comparator entryComparator; + boolean unresolvedComesFirst; + + SortCitations(Comparator entryComparator, + boolean unresolvedComesFirst) { + this.entryComparator = entryComparator; + this.unresolvedComesFirst = unresolvedComesFirst; + } + + public int compare(CitationAndIndex a, CitationAndIndex b) { + if (a.c.db.isEmpty() && b.c.db.isEmpty()) { + // Both are unresolved: compare them by citation key. + String ack = a.c.citationKey; + String bck = b.c.citationKey; + return ack.compareTo(bck); + } + // Comparing unresolved and real entry + final boolean unresolvedComesFirst = true; + final int mul = unresolvedComesFirst ? (+1) : (-1); + if (a.c.db.isEmpty()) { + return -mul; + } + if (b.c.db.isEmpty()) { + return mul; + } + // Proper comparison of entries + return entryComparator.compare(a.c.db.get().entry, + b.c.db.get().entry); + } + } + */ + + void imposeLocalOrderByComparator(Comparator entryComparator) { + List cks = new ArrayList<>(); + for (int i = 0; i < citations.size(); i++) { + Citation c = citations.get(i); + cks.add(new CitationAndIndex(c, i)); + } + // Collections.sort(cks, new SortCitations(entryComparator, true)); + Collections.sort(cks, new CitationComparator(entryComparator, true)); + + List o = new ArrayList<>(); + for (CitationAndIndex ck : cks) { + o.add(ck.i); + } + this.localOrder = o; + } + } + + public void show() { + System.out.printf("CitationGroupsV001%n"); + System.out.printf(" citationGroups.size: %d%n", citationGroups.size()); + System.out.printf(" pageInfoThrash.size: %d%n", pageInfoThrash.size()); + System.out.printf(" globalOrder: %s%n", + (globalOrder.isEmpty() + ? "isEmpty" + : String.format("%d", globalOrder.get().size()))); + } + } // class citationGroups From 3b4942d9c52c4932c987e71829dacc31e7777b16 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 10:25:54 +0200 Subject: [PATCH 0506/1068] refactor: extract CitationSort --- .../gui/openoffice/CitationGroupsV001.java | 87 ++----------------- .../jabref/gui/openoffice/CitationSort.java | 51 +++++++++++ 2 files changed, 57 insertions(+), 81 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/CitationSort.java diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index b9d357619fc..e8c4b5be509 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -18,6 +18,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import org.jabref.gui.openoffice.CitationSort; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; @@ -201,7 +202,7 @@ class DatabaseLookupResult { } } - class CitedKey implements SortableCitation { + class CitedKey implements CitationSort.ComparableCitation { String key; // TODO: rename to citationKey LinkedHashSet where; Optional db; @@ -270,46 +271,6 @@ void distributeUniqueLetter(CitationGroupsV001 cgs) { } } - interface SortableCitation { - public String getCitationKey(); - public Optional getBibEntry(); - } - - static class CitationComparator implements Comparator { - - Comparator entryComparator; - boolean unresolvedComesFirst; - - CitationComparator(Comparator entryComparator, - boolean unresolvedComesFirst) { - this.entryComparator = entryComparator; - this.unresolvedComesFirst = unresolvedComesFirst; - } - - public int compare(SortableCitation a, SortableCitation b) { - Optional abe = a.getBibEntry(); - Optional bbe = b.getBibEntry(); - - if (abe.isEmpty() && bbe.isEmpty()) { - // Both are unresolved: compare them by citation key. - String ack = a.getCitationKey(); - String bck = b.getCitationKey(); - return ack.compareTo(bck); - } - // Comparing unresolved and real entry - - final int mul = unresolvedComesFirst ? (+1) : (-1); - if (abe.isEmpty()) { - return -mul; - } - if (bbe.isEmpty()) { - return mul; - } - // Proper comparison of entries - return entryComparator.compare(abe.get(), - bbe.get()); - } - } class CitedKeys { @@ -366,7 +327,7 @@ public int compare(CitedKey a, CitedKey b) { void sortByComparator(Comparator entryComparator) { List cks = new ArrayList<>(data.values()); - cks.sort(new CitationComparator(entryComparator, true)); + cks.sort(new CitationSort.CitationComparator(entryComparator, true)); LinkedHashMap newData = new LinkedHashMap<>(); for (CitedKey ck : cks) { newData.put(ck.key, ck); @@ -1590,7 +1551,7 @@ String asString() { } } - static class Citation implements SortableCitation { + static class Citation implements CitationSort.ComparableCitation { /** key in database */ String citationKey; @@ -1670,7 +1631,7 @@ static class CitationGroup { .collect(Collectors.toList())); } - class CitationAndIndex implements SortableCitation { + class CitationAndIndex implements CitationSort.ComparableCitation { Citation c; int i; CitationAndIndex(Citation c, int i) { @@ -1692,49 +1653,13 @@ public Optional getBibEntry(){ /** * Sort citations for presentation within a CitationGroup. */ - /* - class SortCitations implements Comparator { - - Comparator entryComparator; - boolean unresolvedComesFirst; - - SortCitations(Comparator entryComparator, - boolean unresolvedComesFirst) { - this.entryComparator = entryComparator; - this.unresolvedComesFirst = unresolvedComesFirst; - } - - public int compare(CitationAndIndex a, CitationAndIndex b) { - if (a.c.db.isEmpty() && b.c.db.isEmpty()) { - // Both are unresolved: compare them by citation key. - String ack = a.c.citationKey; - String bck = b.c.citationKey; - return ack.compareTo(bck); - } - // Comparing unresolved and real entry - final boolean unresolvedComesFirst = true; - final int mul = unresolvedComesFirst ? (+1) : (-1); - if (a.c.db.isEmpty()) { - return -mul; - } - if (b.c.db.isEmpty()) { - return mul; - } - // Proper comparison of entries - return entryComparator.compare(a.c.db.get().entry, - b.c.db.get().entry); - } - } - */ - void imposeLocalOrderByComparator(Comparator entryComparator) { List cks = new ArrayList<>(); for (int i = 0; i < citations.size(); i++) { Citation c = citations.get(i); cks.add(new CitationAndIndex(c, i)); } - // Collections.sort(cks, new SortCitations(entryComparator, true)); - Collections.sort(cks, new CitationComparator(entryComparator, true)); + Collections.sort(cks, new CitationSort.CitationComparator(entryComparator, true)); List o = new ArrayList<>(); for (CitationAndIndex ck : cks) { diff --git a/src/main/java/org/jabref/gui/openoffice/CitationSort.java b/src/main/java/org/jabref/gui/openoffice/CitationSort.java new file mode 100644 index 00000000000..5dad446cb6a --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/CitationSort.java @@ -0,0 +1,51 @@ +package org.jabref.gui.openoffice; + +import java.util.Comparator; +import java.util.Optional; + +import org.jabref.model.entry.BibEntry; + +class CitationSort { + + interface ComparableCitation { + public String getCitationKey(); + public Optional getBibEntry(); + } + + static class CitationComparator implements Comparator { + + Comparator entryComparator; + boolean unresolvedComesFirst; + + CitationComparator(Comparator entryComparator, + boolean unresolvedComesFirst) { + this.entryComparator = entryComparator; + this.unresolvedComesFirst = unresolvedComesFirst; + } + + public int compare(ComparableCitation a, ComparableCitation b) { + Optional abe = a.getBibEntry(); + Optional bbe = b.getBibEntry(); + + if (abe.isEmpty() && bbe.isEmpty()) { + // Both are unresolved: compare them by citation key. + String ack = a.getCitationKey(); + String bck = b.getCitationKey(); + return ack.compareTo(bck); + } + // Comparing unresolved and real entry + + final int mul = unresolvedComesFirst ? (+1) : (-1); + if (abe.isEmpty()) { + return -mul; + } + if (bbe.isEmpty()) { + return mul; + } + // Proper comparison of entries + return entryComparator.compare(abe.get(), + bbe.get()); + } + } + +} From 001b6d921d1fe1e896a71b9deaed00fcec2db473 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 10:27:57 +0200 Subject: [PATCH 0507/1068] refactor: cleanup --- .../gui/openoffice/CitationGroupsV001.java | 32 ------------------- 1 file changed, 32 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index e8c4b5be509..cdaa4b475d6 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -293,38 +293,6 @@ public List values() { /** * Sort entries for the bibliography. */ - /* - class SortCitedKeys implements Comparator { - - Comparator entryComparator; - boolean unresolvedComesFirst; - - SortCitedKeys(Comparator entryComparator, - boolean unresolvedComesFirst) { - this.entryComparator = entryComparator; - this.unresolvedComesFirst = unresolvedComesFirst; - } - - public int compare(CitedKey a, CitedKey b) { - if (a.db.isEmpty() && b.db.isEmpty()) { - // Both are unresolved: compare them by citation key. - return a.key.compareTo(b.key); - } - // Comparing unresolved and real entry - final int mul = unresolvedComesFirst ? (+1) : (-1); - if (a.db.isEmpty()) { - return -mul; - } - if (b.db.isEmpty()) { - return mul; - } - // Proper comparison of entries - return entryComparator.compare(a.db.get().entry, - b.db.get().entry); - } - } - */ - void sortByComparator(Comparator entryComparator) { List cks = new ArrayList<>(data.values()); cks.sort(new CitationSort.CitationComparator(entryComparator, true)); From 69c9c063a356251bde77654b877ba625b33430ca Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 11:50:34 +0200 Subject: [PATCH 0508/1068] refactor: CitationDatabaseLookup.java --- .../openoffice/CitationDatabaseLookup.java | 31 ++++++++++++++++ .../gui/openoffice/CitationGroupsV001.java | 36 +++++++------------ 2 files changed, 43 insertions(+), 24 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/CitationDatabaseLookup.java diff --git a/src/main/java/org/jabref/gui/openoffice/CitationDatabaseLookup.java b/src/main/java/org/jabref/gui/openoffice/CitationDatabaseLookup.java new file mode 100644 index 00000000000..a2b0af44e6b --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/CitationDatabaseLookup.java @@ -0,0 +1,31 @@ +package org.jabref.gui.openoffice; + +import java.util.List; +import java.util.Optional; + +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +class CitationDatabaseLookup { + + public static class Result { + BibEntry entry; + BibDatabase database; + Result(BibEntry entry, BibDatabase database) { + this.entry = entry; + this.database = database; + } + } + + public static Optional lookup(List databases, + String key) { + for (BibDatabase database : databases) { + Optional entry = database.getEntryByCitationKey(key); + if (entry.isPresent()) { + return Optional.of(new Result(entry.get(), database)); + } + } + return Optional.empty(); + } + +} diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index cdaa4b475d6..8b4cd16189a 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -18,7 +18,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import org.jabref.gui.openoffice.CitationSort; +//import org.jabref.gui.openoffice.CitationSort; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; @@ -70,7 +70,7 @@ class CitationGroupsV001 { /** * Original CitationGroups Data */ - Map citationGroups; + private Map citationGroups; /** * Extra Data @@ -83,6 +83,7 @@ class CitationGroupsV001 { private Optional> globalOrder; private Optional citedKeysAfterDatabaseLookup; + /** * This is going to be the bibliography */ @@ -183,6 +184,10 @@ private static List findUnusedJabrefPropertyNames(DocumentConnection doc return cg; } + /** + * Identifies a citation with the citation group containing it and + * its storage index within. + */ class CitationPath { CitationGroupID group; int storageIndexInGroup; @@ -193,19 +198,11 @@ class CitationPath { } } - class DatabaseLookupResult { - BibEntry entry; - BibDatabase database; - DatabaseLookupResult(BibEntry entry, BibDatabase database) { - this.entry = entry; - this.database = database; - } - } class CitedKey implements CitationSort.ComparableCitation { String key; // TODO: rename to citationKey LinkedHashSet where; - Optional db; + Optional db; Optional number; // For Numbered citation styles. Optional uniqueLetter; // For AuthorYear citation styles. Optional normCitMarker; // For AuthorYear citation styles. @@ -246,16 +243,7 @@ void addPath(CitationPath p, Citation cit) { } void lookupInDatabases(List databases) { - Optional res = Optional.empty(); - for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(key); - if (entry.isPresent()) { - res = Optional.of(new DatabaseLookupResult(entry.get(), database)); - break; - } - } - // store result - this.db = res; + this.db = CitationDatabaseLookup.lookup(databases, this.key); } void distributeDatabaseLookupResult(CitationGroupsV001 cgs) { @@ -338,7 +326,7 @@ void distributeUniqueLetters(CitationGroupsV001 cgs) { } public void setDatabaseLookupResults(Set where, - Optional db) { + Optional db) { for (CitationPath p : where) { CitationGroup cg = this.citationGroups.get(p.group); if (cg == null) { @@ -1523,7 +1511,7 @@ static class Citation implements CitationSort.ComparableCitation { /** key in database */ String citationKey; - Optional db; + Optional db; Optional number; Optional uniqueLetter; @@ -1627,7 +1615,7 @@ void imposeLocalOrderByComparator(Comparator entryComparator) { Citation c = citations.get(i); cks.add(new CitationAndIndex(c, i)); } - Collections.sort(cks, new CitationSort.CitationComparator(entryComparator, true)); + cks.sort(new CitationSort.CitationComparator(entryComparator, true)); List o = new ArrayList<>(); for (CitationAndIndex ck : cks) { From 163670bbb1b0b3275f74e40b962759c650d7a263 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 16:17:54 +0200 Subject: [PATCH 0509/1068] refactor: StorageBaseRefMark --- .../gui/openoffice/CitationGroupsV001.java | 31 +- .../org/jabref/gui/openoffice/OOBibBase.java | 10 +- .../jabref/gui/openoffice/StorageBase.java | 102 ++++ .../gui/openoffice/StorageBaseRefMark.java | 444 ++++++++++++++++++ 4 files changed, 560 insertions(+), 27 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/StorageBase.java create mode 100644 src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 8b4cd16189a..f53302d2017 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -54,18 +54,6 @@ class CitationGroupsV001 { private static final Pattern CITE_PATTERN = Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); - private static final String ZERO_WIDTH_SPACE = "\u200b"; - - // for debugging we may want visible bracket - private static final boolean - REFERENCE_MARK_USE_INVISIBLE_BRACKETS = true; // !debug; - - private static final String - REFERENCE_MARK_LEFT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<"; - - private static final String - REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; - /** * Original CitationGroups Data @@ -904,8 +892,8 @@ private static void createReferenceMarkForCitationGroup(DocumentConnection docum cursor.goRight((short) 1, false); // now we are between two spaces - final String left = REFERENCE_MARK_LEFT_BRACKET; - final String right = REFERENCE_MARK_RIGHT_BRACKET; + final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; + final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); String bracketedContent = (withoutBrackets @@ -975,16 +963,17 @@ public void removeCitationGroup(CitationGroup cg, DocumentConnection documentCon * we are working on an "Empty citation" (INVISIBLE_CIT). */ public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, - CitationGroupID cgid, - boolean removeBracketsFromEmpty) + CitationGroupID cgid) throws NoDocumentException, WrappedTargetException, CreationException { boolean alwaysRemoveBrackets = true; - final String left = REFERENCE_MARK_LEFT_BRACKET; - final String right = REFERENCE_MARK_RIGHT_BRACKET; + boolean removeBracketsFromEmpty = false; + + final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; + final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); @@ -1086,8 +1075,8 @@ public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConn String name = this.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); final boolean debugThisFun = false; - final String left = REFERENCE_MARK_LEFT_BRACKET; - final String right = REFERENCE_MARK_RIGHT_BRACKET; + final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; + final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); @@ -1398,6 +1387,8 @@ private static String getPageInfoForReferenceMarkName(DocumentConnection documen * * @param cgid : Must be known. * @return Null if the reference mark is missing. + * + * TODO: getReferenceMarkRangeOrNull vs getRawCursorForCitationGroup */ public XTextRange getReferenceMarkRangeOrNull(DocumentConnection documentConnection, CitationGroupID cgid) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5d78373cd0f..3d36da6c159 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1250,7 +1250,7 @@ private void insertReferenceMark(CitationGroupsV001 cgs, itcType, position, insertSpaceAfter, - !withText); + !withText /* withoutBrackets */); if (withText) { XTextCursor c2 = @@ -1265,9 +1265,7 @@ private void insertReferenceMark(CitationGroupsV001 cgs, withText, style); - cgs.cleanFillCursorForCitationGroup(documentConnection, - cgid, - !withText); + cgs.cleanFillCursorForCitationGroup(documentConnection, cgid); } position.collapseToEnd(); } @@ -1682,9 +1680,7 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, withText, style); - cgs.cleanFillCursorForCitationGroup(documentConnection, - cgid, - !withText); + cgs.cleanFillCursorForCitationGroup(documentConnection, cgid); } if (hadBibSection diff --git a/src/main/java/org/jabref/gui/openoffice/StorageBase.java b/src/main/java/org/jabref/gui/openoffice/StorageBase.java new file mode 100644 index 00000000000..a3b020548ac --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/StorageBase.java @@ -0,0 +1,102 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +//import org.jabref.gui.openoffice.CitationSort; +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +class StorageBase { + + interface HasName { + public String getName(); + } + + interface HasTextRange { + /** + * Cursor for the reference marks as is, not prepared for filling, + * but does not need cleanFillCursorForCitationGroup either. + */ + public XTextCursor getRawCursor(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException; + + /** + * Get a cursor for filling in text. + * + * Must be followed by cleanFillCursor() + */ + public XTextCursor getFillCursor(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException; + + /** + * Remove brackets, but if the result would become empty, leave + * them; if the result would be a single characer, leave the left bracket. + * + * @param removeBracketsFromEmpty is intended to force removal if + * we are working on an "Empty citation" (INVISIBLE_CIT). + */ + public void cleanFillCursor(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException ; + + // public void removeFromDocument(DocumentConnection documentConnection) + } + + interface NamedRange extends HasName, HasTextRange { + // nothing new here + } + + interface NamedRangeManager { + public NamedRange create( DocumentConnection documentConnection, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets ) + throws + CreationException; + + public List getUsedNames(DocumentConnection documentConnection) + throws + NoDocumentException; + } +} diff --git a/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java new file mode 100644 index 00000000000..297d6af3139 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java @@ -0,0 +1,444 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +//import org.jabref.gui.openoffice.CitationSort; +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +class StorageBaseRefMark implements StorageBase.NamedRange { + + private static final String ZERO_WIDTH_SPACE = "\u200b"; + + // for debugging we may want visible bracket + private static final boolean + REFERENCE_MARK_USE_INVISIBLE_BRACKETS = true; // !debug; + + public static final String + REFERENCE_MARK_LEFT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : "<"; + + public static final String + REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; + + private static final Logger LOGGER = + LoggerFactory.getLogger(StorageBaseRefMark.class); + + private String id; /* reference mark name */ + + private StorageBaseRefMark( String id ) { + this.id = id; + } + + String getId(){ return id; } + + /** + * Insert {@code n} spaces in a way that reference + * marks just before or just after the cursor are not affected. + * + * This is based on the observation, that starting two + * new paragraphs separates us from a reference mark on either side. + * + * The pattern used is: + * {@code safeInsertSpaces(n): para, para, left, space(n), right-delete, left(n), left-delete} + * + * @param position Where to insert (at position.getStart()) + * @param n Number of spaces to insert. + * + * @return a new cursor, covering the just-inserted spaces. + * + * This could be generalized to insert arbitrary text safely + * between two reference marks. But we do not need that now. + */ + private static XTextCursor + safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { + // Start with an empty cursor at position.getStart(); + XText text = position.getText(); + XTextCursor cursor = text.createTextCursorByRange(position.getStart()); + text.insertString(cursor, "\r\r", false); // para, para + cursor.goLeft((short) 1, false); // left + text.insertString(cursor, " ".repeat(n), false); // space(n) + cursor.goRight((short) 1, true); + cursor.setString(""); // right-delete + cursor.goLeft((short) n, false); // left(n) + cursor.goLeft((short) 1, true); + cursor.setString(""); // left-delete + cursor.goRight((short) n, true); + return cursor; + } + + private static void createReprInDocument(DocumentConnection documentConnection, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) + throws + CreationException { + // The cursor we received: we push it before us. + position.collapseToEnd(); + + XTextCursor cursor = safeInsertSpacesBetweenReferenceMarks(position.getEnd(), 2); + + // cursors before the first and after the last space + XTextCursor cursorBefore = cursor.getText().createTextCursorByRange(cursor.getStart()); + XTextCursor cursorAfter = cursor.getText().createTextCursorByRange(cursor.getEnd()); + + cursor.collapseToStart(); + cursor.goRight((short) 1, false); + // now we are between two spaces + + final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; + final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); + String bracketedContent = (withoutBrackets + ? "" + : left + right); + + cursor.getText().insertString( + cursor, + bracketedContent, + true); + + documentConnection.insertReferenceMark(refMarkName, + cursor, + true /* absorb */); + + cursorBefore.goRight((short) 1, true); + cursorBefore.setString(""); + if (!insertSpaceAfter) { + cursorAfter.goLeft((short) 1, true); + cursorAfter.setString(""); + } + } + + private static StorageBaseRefMark create(DocumentConnection documentConnection, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) + throws + CreationException { + createReprInDocument(documentConnection, + refMarkName, + position, + insertSpaceAfter, + withoutBrackets); + return new StorageBaseRefMark( refMarkName ); + } + + /* + * Remove it from the document. + * + * See: removeCitationGroups + */ + public void removeFromDocument(DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException { + documentConnection.removeReferenceMark(this.getName()); + } + + + @Override + public String getName(){ return id; } + + /* + * ranges controlled by citation groups should not overlap with each other. + * + * @return Null if the reference mark is missing. + * + * See: getReferenceMarkRangeOrNull + */ + public XTextRange getRangeOrNull(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + String name = this.getName(); + return documentConnection.getReferenceMarkRangeOrNull(name); + } + + /** + * Cursor for the reference marks as is, not prepared for filling, + * but does not need cleanFillCursorForCitationGroup either. + * + * See: getRawCursorForCitationGroup + */ + @Override + public XTextCursor getRawCursor(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + String name = this.getName(); + XTextCursor full = null; + + XTextContent markAsTextContent = + documentConnection.getReferenceMarkAsTextContentOrNull(name); + + if (markAsTextContent == null) { + throw new RuntimeException( + String.format( + "getRawCursor: markAsTextContent(%s) == null", + name)); + } + + full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); + if (full == null) { + throw new RuntimeException("getRawCursor: full == null"); + } + return full; + } + + /** + * See: getFillCursorForCitationGroup + */ + @Override + public XTextCursor getFillCursor(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + String name = this.getName(); + + final boolean debugThisFun = false; + final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; + final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); + + XTextCursor full = null; + String fullText = null; + for (int i = 1; i <= 2; i++) { + XTextContent markAsTextContent = + documentConnection.getReferenceMarkAsTextContentOrNull(name); + + if (markAsTextContent == null) { + throw new RuntimeException( + String.format("getFillCursor:" + + " markAsTextContent(%s) == null (attempt %d)", + name, + i)); + } + + full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); + if (full == null) { + throw new RuntimeException( + String.format("getFillCursor: full == null (attempt %d)", i)); + } + + fullText = full.getString(); + + if (debugThisFun) { + System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); + } + + if (fullText.length() >= 2) { + break; + } else { + // (fullText.length() < 2) + if (i == 2) { + throw new RuntimeException( + String.format("getFillCursor:" + + " (fullText.length() < 2) (attempt %d)", + i)); + } + // too short, recreate + if (debugThisFun) { + System.out.println("getFillCursor: too short, recreate"); + } + full.setString(""); + try { + documentConnection.removeReferenceMark(name); + } catch (NoSuchElementException ex) { + LOGGER.warn( + String.format("getFillCursor got NoSuchElementException" + + " for '%s'", + name)); + } + createReprInDocument( + documentConnection, + name, + full, + false, /* insertSpaceAfter */ + false /* withoutBrackets */); + } + } + + if (full == null) { + throw new RuntimeException("getFillCursorFor: full == null (after loop)"); + } + if (fullText == null) { + throw new RuntimeException("getFillCursor: fullText == null (after loop)"); + } + + // we have at least two characters inside + XTextCursor alpha = full.getText().createTextCursorByRange(full); + alpha.collapseToStart(); + XTextCursor omega = full.getText().createTextCursorByRange(full); + omega.collapseToEnd(); + + XTextCursor beta = full.getText().createTextCursorByRange(full); + beta.collapseToStart(); + beta.goRight((short) 1, false); + beta.goRight((short) (fullText.length() - 2), true); + beta.setString(left + right); + beta.collapseToEnd(); + beta.goLeft(rightLength, false); + // drop the initial character + alpha.goRight((short) 1, true); + alpha.setString(""); + // drop the last character + omega.goLeft((short) 1, true); + omega.setString(""); + return beta; + } + + /** + * Remove brackets, but if the result would become empty, leave + * them; if the result would be a single characer, leave the left bracket. + * + * See: cleanFillCursorForCitationGroup + */ + @Override + public void cleanFillCursor(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + // alwaysRemoveBrackets : full compatibility with JabRef 5.2: + // brackets are temporary, only exist between getFillCursor + // and cleanFillCursor. + final boolean alwaysRemoveBrackets = true; + // removeBracketsFromEmpty is intended to force removal if we + // are working on an "Empty citation" (INVISIBLE_CIT). + final boolean removeBracketsFromEmpty = false; + + final String left = REFERENCE_MARK_LEFT_BRACKET; + final String right = REFERENCE_MARK_RIGHT_BRACKET; + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); + + // CitationGroupsV001 cgs = this; + // String name = cgs.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); + String name = this.getName(); + + XTextCursor full = this.getRawCursor(documentConnection); + final String fullText = full.getString(); + final int fullTextLength = fullText.length(); + + XTextCursor alpha = full.getText().createTextCursorByRange(full); + alpha.collapseToStart(); + + XTextCursor beta = full.getText().createTextCursorByRange(full); + beta.collapseToStart(); + beta.goRight(leftLength, false); + + XTextCursor omega = full.getText().createTextCursorByRange(full); + omega.collapseToEnd(); + + if (!fullText.startsWith(left)) { + throw new RuntimeException( + String.format("cleanFillCursor:" + + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", + name)); + } + + if (!fullText.endsWith(right)) { + throw new RuntimeException( + String.format("cleanFillCursor:" + + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", + name)); + } + + final int contentLength = (fullTextLength - (leftLength + rightLength)); + if (contentLength < 0) { + throw new RuntimeException( + String.format("cleanFillCursor: length(%s) < 0", + name)); + } + + boolean removeRight = ((contentLength >= 1) + || ((contentLength == 0) && removeBracketsFromEmpty) + || alwaysRemoveBrackets); + + boolean removeLeft = ((contentLength >= 2) + || ((contentLength == 0) && removeBracketsFromEmpty) + || alwaysRemoveBrackets); + + if (removeRight) { + omega.goLeft(rightLength, true); + omega.setString(""); + } + + if (removeLeft) { + alpha.goRight(leftLength, true); + alpha.setString(""); + } + } + + private static List getUsedNames(DocumentConnection documentConnection) + throws + NoDocumentException { + return documentConnection.getReferenceMarkNames(); + } + + public static class Manager implements StorageBase.NamedRangeManager { + @Override + public StorageBase.NamedRange create( DocumentConnection documentConnection, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets ) + throws + CreationException { + return StorageBaseRefMark.create(documentConnection, + refMarkName, + position, + insertSpaceAfter, + withoutBrackets); + } + + @Override + public List getUsedNames(DocumentConnection documentConnection) + throws + NoDocumentException { + return StorageBaseRefMark.getUsedNames(documentConnection); + } + } +} From 933e807f3049fee859c7aab18b1cb19e800b9b05 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 17:15:50 +0200 Subject: [PATCH 0510/1068] use StorageBase.NamedRangeManager in CitationGroupsV001 --- .../gui/openoffice/CitationGroupsV001.java | 555 ++++++++++-------- .../jabref/gui/openoffice/StorageBase.java | 12 +- .../gui/openoffice/StorageBaseRefMark.java | 23 + 3 files changed, 330 insertions(+), 260 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index f53302d2017..b73628bc1db 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -54,6 +54,7 @@ class CitationGroupsV001 { private static final Pattern CITE_PATTERN = Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + private StorageBase.NamedRangeManager citationStorageManager; /** * Original CitationGroups Data @@ -85,13 +86,17 @@ public CitationGroupsV001(DocumentConnection documentConnection) NoDocumentException, WrappedTargetException { + this.citationStorageManager = new StorageBaseRefMark.Manager(); + // Get the citationGroupNames - List citationGroupNames = getJabRefReferenceMarkNames(documentConnection); + List citationGroupNames = getJabRefReferenceMarkNames(this.citationStorageManager, + documentConnection); this.pageInfoThrash = findUnusedJabrefPropertyNames(documentConnection, citationGroupNames); - this.citationGroups = readCitationGroupsFromDocument(documentConnection, + this.citationGroups = readCitationGroupsFromDocument(this.citationStorageManager, + documentConnection, citationGroupNames); // Now we have almost every information from the document about citations. @@ -124,26 +129,30 @@ private static List findUnusedJabrefPropertyNames(DocumentConnection doc } private static Map - readCitationGroupsFromDocument(DocumentConnection documentConnection, + readCitationGroupsFromDocument(StorageBase.NamedRangeManager citationStorageManager, + DocumentConnection documentConnection, List citationGroupNames) throws - WrappedTargetException { + WrappedTargetException, + NoDocumentException { Map citationGroups = new HashMap<>(); for (int i = 0; i < citationGroupNames.size(); i++) { final String name = citationGroupNames.get(i); CitationGroup cg = - readCitationGroupFromDocumentOrThrow(documentConnection, name); + readCitationGroupFromDocumentOrThrow(citationStorageManager, documentConnection, name); citationGroups.put(cg.cgid, cg); } return citationGroups; } private static CitationGroup - readCitationGroupFromDocumentOrThrow(DocumentConnection documentConnection, + readCitationGroupFromDocumentOrThrow(StorageBase.NamedRangeManager citationStorageManager, + DocumentConnection documentConnection, String refMarkName) throws - WrappedTargetException { + WrappedTargetException, + NoDocumentException { Optional op = parseRefMarkName(refMarkName); if (op.isEmpty()) { @@ -164,7 +173,16 @@ private static List findUnusedJabrefPropertyNames(DocumentConnection doc Optional pageInfo = documentConnection.getCustomProperty(refMarkName); + StorageBase.NamedRange sr = citationStorageManager.getFromDocumentOrNull(documentConnection, + refMarkName); + + if (sr == null) { + throw new IllegalArgumentException( + "readCitationGroupFromDocumentOrThrow: referenceMarkName is not in the document"); + } + CitationGroup cg = new CitationGroup(id, + sr, ov.itcType, citations, pageInfo, @@ -745,22 +763,22 @@ public Optional getPageInfo(CitationGroupID cgid) { * This could be generalized to insert arbitrary text safely * between two reference marks. But we do not need that now. */ - private static XTextCursor - safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { - // Start with an empty cursor at position.getStart(); - XText text = position.getText(); - XTextCursor cursor = text.createTextCursorByRange(position.getStart()); - text.insertString(cursor, "\r\r", false); // para, para - cursor.goLeft((short) 1, false); // left - text.insertString(cursor, " ".repeat(n), false); // space(n) - cursor.goRight((short) 1, true); - cursor.setString(""); // right-delete - cursor.goLeft((short) n, false); // left(n) - cursor.goLeft((short) 1, true); - cursor.setString(""); // left-delete - cursor.goRight((short) n, true); - return cursor; - } +// private static XTextCursor +// safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { +// // Start with an empty cursor at position.getStart(); +// XText text = position.getText(); +// XTextCursor cursor = text.createTextCursorByRange(position.getStart()); +// text.insertString(cursor, "\r\r", false); // para, para +// cursor.goLeft((short) 1, false); // left +// text.insertString(cursor, " ".repeat(n), false); // space(n) +// cursor.goRight((short) 1, true); +// cursor.setString(""); // right-delete +// cursor.goLeft((short) n, false); // left(n) +// cursor.goLeft((short) 1, true); +// cursor.setString(""); // left-delete +// cursor.goRight((short) n, true); +// return cursor; +// } /** * Create a reference mark with the given name, at the @@ -838,13 +856,19 @@ public CitationGroupID createCitationGroup(DocumentConnection documentConnection .collect(Collectors.toList()); /* - new ArrayList<>(citationKeys.size()); - for (int j = 0; j < ov.citationKeys.size(); j++) { - citatitons.add(new Citation(citationKeys.get(j))); - } - */ + * Apply to document + */ + + StorageBase.NamedRange sr = createReferenceMarkForCitationGroup( + this.citationStorageManager, + documentConnection, + refMarkName, + position, + insertSpaceAfter, + withoutBrackets); CitationGroup cg = new CitationGroup(cgid, + sr, itcType, citations, pageInfo, @@ -856,65 +880,63 @@ public CitationGroupID createCitationGroup(DocumentConnection documentConnection // TODO: look out for localOrder! this.globalOrder = Optional.empty(); - /* - * Apply to document - */ - - createReferenceMarkForCitationGroup( - documentConnection, - refMarkName, - position, - insertSpaceAfter, - withoutBrackets); return cgid; } - private static void createReferenceMarkForCitationGroup(DocumentConnection documentConnection, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) + private static StorageBase.NamedRange + createReferenceMarkForCitationGroup(StorageBase.NamedRangeManager manager, + DocumentConnection documentConnection, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException { - // The cursor we received: we push it before us. - position.collapseToEnd(); - - XTextCursor cursor = safeInsertSpacesBetweenReferenceMarks(position.getEnd(), 2); - - // cursors before the first and after the last space - XTextCursor cursorBefore = - cursor.getText().createTextCursorByRange(cursor.getStart()); - XTextCursor cursorAfter = - cursor.getText().createTextCursorByRange(cursor.getEnd()); - - cursor.collapseToStart(); - cursor.goRight((short) 1, false); - // now we are between two spaces - - final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; - final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); - String bracketedContent = (withoutBrackets - ? "" - : left + right); - - cursor.getText().insertString( - cursor, - bracketedContent, - true); - - documentConnection.insertReferenceMark(refMarkName, - cursor, - true /* absorb */); - - cursorBefore.goRight((short) 1, true); - cursorBefore.setString(""); - if (!insertSpaceAfter) { - cursorAfter.goLeft((short) 1, true); - cursorAfter.setString(""); - } + return manager.create(documentConnection, + refMarkName, + position, + insertSpaceAfter, + withoutBrackets); + +// // The cursor we received: we push it before us. +// position.collapseToEnd(); +// +// XTextCursor cursor = safeInsertSpacesBetweenReferenceMarks(position.getEnd(), 2); +// +// // cursors before the first and after the last space +// XTextCursor cursorBefore = +// cursor.getText().createTextCursorByRange(cursor.getStart()); +// XTextCursor cursorAfter = +// cursor.getText().createTextCursorByRange(cursor.getEnd()); +// +// cursor.collapseToStart(); +// cursor.goRight((short) 1, false); +// // now we are between two spaces +// +// final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; +// final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; +// final short leftLength = (short) left.length(); +// final short rightLength = (short) right.length(); +// String bracketedContent = (withoutBrackets +// ? "" +// : left + right); +// +// cursor.getText().insertString( +// cursor, +// bracketedContent, +// true); +// +// documentConnection.insertReferenceMark(refMarkName, +// cursor, +// true /* absorb */); +// +// cursorBefore.goRight((short) 1, true); +// cursorBefore.setString(""); +// if (!insertSpaceAfter) { +// cursorAfter.goLeft((short) 1, true); +// cursorAfter.setString(""); +// } } /* @@ -932,7 +954,8 @@ public void removeCitationGroups(List cgs, DocumentConnection doc NoSuchElementException { for (CitationGroup cg : cgs) { - documentConnection.removeReferenceMark(cg.referenceMarkName); + //documentConnection.removeReferenceMark(cg.referenceMarkName); + cg.cgRangeStorage.removeFromDocument(documentConnection); this.citationGroups.remove(cg.cgid); this.globalOrder.map(l -> l.remove(cg.cgid)); @@ -969,69 +992,72 @@ public void cleanFillCursorForCitationGroup(DocumentConnection documentConnectio WrappedTargetException, CreationException { - boolean alwaysRemoveBrackets = true; - boolean removeBracketsFromEmpty = false; - - final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; - final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); - - CitationGroupsV001 cgs = this; - String name = cgs.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); - - XTextCursor full = cgs.getRawCursorForCitationGroup(cgid, documentConnection); - final String fullText = full.getString(); - final int fullTextLength = fullText.length(); - - XTextCursor alpha = full.getText().createTextCursorByRange(full); - alpha.collapseToStart(); - - XTextCursor beta = full.getText().createTextCursorByRange(full); - beta.collapseToStart(); - beta.goRight(leftLength, false); - - XTextCursor omega = full.getText().createTextCursorByRange(full); - omega.collapseToEnd(); - - if (!fullText.startsWith(left)) { - throw new RuntimeException( - String.format("cleanFillCursorForCitationGroup:" - + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", - name)); - } - - if (!fullText.endsWith(right)) { - throw new RuntimeException( - String.format("cleanFillCursorForCitationGroup:" - + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", - name)); - } - - final int contentLength = (fullTextLength - (leftLength + rightLength)); - if (contentLength < 0) { - throw new RuntimeException( - String.format("cleanFillCursorForCitationGroup: length(%s) < 0", - name)); - } - - boolean removeRight = ((contentLength >= 1) - || ((contentLength == 0) && removeBracketsFromEmpty) - || alwaysRemoveBrackets); - - boolean removeLeft = ((contentLength >= 2) - || ((contentLength == 0) && removeBracketsFromEmpty) - || alwaysRemoveBrackets); - - if (removeRight) { - omega.goLeft(rightLength, true); - omega.setString(""); - } - - if (removeLeft) { - alpha.goRight(leftLength, true); - alpha.setString(""); - } + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + cg.cgRangeStorage.cleanFillCursor(documentConnection); + +// boolean alwaysRemoveBrackets = true; +// boolean removeBracketsFromEmpty = false; +// +// final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; +// final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; +// final short leftLength = (short) left.length(); +// final short rightLength = (short) right.length(); +// +// CitationGroupsV001 cgs = this; +// String name = cgs.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); +// +// XTextCursor full = cgs.getRawCursorForCitationGroup(cgid, documentConnection); +// final String fullText = full.getString(); +// final int fullTextLength = fullText.length(); +// +// XTextCursor alpha = full.getText().createTextCursorByRange(full); +// alpha.collapseToStart(); +// +// XTextCursor beta = full.getText().createTextCursorByRange(full); +// beta.collapseToStart(); +// beta.goRight(leftLength, false); +// +// XTextCursor omega = full.getText().createTextCursorByRange(full); +// omega.collapseToEnd(); +// +// if (!fullText.startsWith(left)) { +// throw new RuntimeException( +// String.format("cleanFillCursorForCitationGroup:" +// + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", +// name)); +// } +// +// if (!fullText.endsWith(right)) { +// throw new RuntimeException( +// String.format("cleanFillCursorForCitationGroup:" +// + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", +// name)); +// } +// +// final int contentLength = (fullTextLength - (leftLength + rightLength)); +// if (contentLength < 0) { +// throw new RuntimeException( +// String.format("cleanFillCursorForCitationGroup: length(%s) < 0", +// name)); +// } +// +// boolean removeRight = ((contentLength >= 1) +// || ((contentLength == 0) && removeBracketsFromEmpty) +// || alwaysRemoveBrackets); +// +// boolean removeLeft = ((contentLength >= 2) +// || ((contentLength == 0) && removeBracketsFromEmpty) +// || alwaysRemoveBrackets); +// +// if (removeRight) { +// omega.goLeft(rightLength, true); +// omega.setString(""); +// } +// +// if (removeLeft) { +// alpha.goRight(leftLength, true); +// alpha.setString(""); +// } } /** @@ -1045,24 +1071,27 @@ public XTextCursor getRawCursorForCitationGroup(CitationGroupID cgid, WrappedTargetException, CreationException { - String name = this.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); - XTextCursor full = null; - - XTextContent markAsTextContent = - documentConnection.getReferenceMarkAsTextContentOrNull(name); - - if (markAsTextContent == null) { - throw new RuntimeException( - String.format( - "getRawCursorForCitationGroup: markAsTextContent(%s) == null", - name)); - } - - full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); - if (full == null) { - throw new RuntimeException("getRawCursorForCitationGroup: full == null"); - } - return full; + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + return cg.cgRangeStorage.getRawCursor(documentConnection); + +// String name = this.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); +// XTextCursor full = null; +// +// XTextContent markAsTextContent = +// documentConnection.getReferenceMarkAsTextContentOrNull(name); +// +// if (markAsTextContent == null) { +// throw new RuntimeException( +// String.format( +// "getRawCursorForCitationGroup: markAsTextContent(%s) == null", +// name)); +// } +// +// full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); +// if (full == null) { +// throw new RuntimeException("getRawCursorForCitationGroup: full == null"); +// } +// return full; } public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, @@ -1072,99 +1101,102 @@ public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConn WrappedTargetException, CreationException { - String name = this.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); - - final boolean debugThisFun = false; - final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; - final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); - - XTextCursor full = null; - String fullText = null; - for (int i = 1; i <= 2; i++) { - XTextContent markAsTextContent = - documentConnection.getReferenceMarkAsTextContentOrNull(name); - - if (markAsTextContent == null) { - throw new RuntimeException( - String.format("getFillCursorForCitationGroup:" - + " markAsTextContent(%s) == null (attempt %d)", - name, - i)); - } - - full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); - if (full == null) { - throw new RuntimeException( - String.format("getFillCursorForCitationGroup: full == null (attempt %d)", i)); - } - - fullText = full.getString(); - - if (debugThisFun) { - System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); - } - - if (fullText.length() >= 2) { - break; - } else { - // (fullText.length() < 2) - if (i == 2) { - throw new RuntimeException( - String.format("getFillCursorForCitationGroup:" - + " (fullText.length() < 2) (attempt %d)", - i)); - } - // too short, recreate - if (debugThisFun) { - System.out.println("getFillCursor: too short, recreate"); - } - full.setString(""); - try { - documentConnection.removeReferenceMark(name); - } catch (NoSuchElementException ex) { - LOGGER.warn( - String.format("getFillCursorForCitationGroup got NoSuchElementException" - + " for '%s'", - name)); - } - createReferenceMarkForCitationGroup( - documentConnection, - name, - full, - false, /* insertSpaceAfter */ - false /* withoutBrackets */); - } - } - - if (full == null) { - throw new RuntimeException("getFillCursorForCitationGroup: full == null (after loop)"); - } - if (fullText == null) { - throw new RuntimeException("getFillCursorForCitationGroup: fullText == null (after loop)"); - } - - // we have at least two characters inside - XTextCursor alpha = full.getText().createTextCursorByRange(full); - alpha.collapseToStart(); - XTextCursor omega = full.getText().createTextCursorByRange(full); - omega.collapseToEnd(); - - XTextCursor beta = full.getText().createTextCursorByRange(full); - beta.collapseToStart(); - beta.goRight((short) 1, false); - beta.goRight((short) (fullText.length() - 2), true); - beta.setString(left + right); - beta.collapseToEnd(); - beta.goLeft(rightLength, false); - // drop the initial character - alpha.goRight((short) 1, true); - alpha.setString(""); - // drop the last character - omega.goLeft((short) 1, true); - omega.setString(""); - return beta; + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + return cg.cgRangeStorage.getFillCursor(documentConnection); + +// String name = this.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); +// +// final boolean debugThisFun = false; +// final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; +// final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; +// final short leftLength = (short) left.length(); +// final short rightLength = (short) right.length(); +// +// XTextCursor full = null; +// String fullText = null; +// for (int i = 1; i <= 2; i++) { +// XTextContent markAsTextContent = +// documentConnection.getReferenceMarkAsTextContentOrNull(name); +// +// if (markAsTextContent == null) { +// throw new RuntimeException( +// String.format("getFillCursorForCitationGroup:" +// + " markAsTextContent(%s) == null (attempt %d)", +// name, +// i)); +// } +// +// full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); +// if (full == null) { +// throw new RuntimeException( +// String.format("getFillCursorForCitationGroup: full == null (attempt %d)", i)); +// } +// +// fullText = full.getString(); +// +// if (debugThisFun) { +// System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); +// } +// +// if (fullText.length() >= 2) { +// break; +// } else { +// // (fullText.length() < 2) +// if (i == 2) { +// throw new RuntimeException( +// String.format("getFillCursorForCitationGroup:" +// + " (fullText.length() < 2) (attempt %d)", +// i)); +// } +// // too short, recreate +// if (debugThisFun) { +// System.out.println("getFillCursor: too short, recreate"); +// } +// full.setString(""); +// try { +// documentConnection.removeReferenceMark(name); +// } catch (NoSuchElementException ex) { +// LOGGER.warn( +// String.format("getFillCursorForCitationGroup got NoSuchElementException" +// + " for '%s'", +// name)); +// } +// createReferenceMarkForCitationGroup( +// documentConnection, +// name, +// full, +// false, /* insertSpaceAfter */ +// false /* withoutBrackets */); +// } +// } +// +// if (full == null) { +// throw new RuntimeException("getFillCursorForCitationGroup: full == null (after loop)"); +// } +// if (fullText == null) { +// throw new RuntimeException("getFillCursorForCitationGroup: fullText == null (after loop)"); +// } +// +// // we have at least two characters inside +// XTextCursor alpha = full.getText().createTextCursorByRange(full); +// alpha.collapseToStart(); +// XTextCursor omega = full.getText().createTextCursorByRange(full); +// omega.collapseToEnd(); +// +// XTextCursor beta = full.getText().createTextCursorByRange(full); +// beta.collapseToStart(); +// beta.goRight((short) 1, false); +// beta.goRight((short) (fullText.length() - 2), true); +// beta.setString(left + right); +// beta.collapseToEnd(); +// beta.goLeft(rightLength, false); +// // drop the initial character +// alpha.goRight((short) 1, true); +// alpha.setString(""); +// // drop the last character +// omega.goLeft((short) 1, true); +// omega.setString(""); +// return beta; } /** @@ -1285,10 +1317,11 @@ private static List filterIsJabRefReferenceMarkName(List names) * * */ - private List getJabRefReferenceMarkNames(DocumentConnection documentConnection) + private List getJabRefReferenceMarkNames(StorageBase.NamedRangeManager manager, + DocumentConnection documentConnection) throws NoDocumentException { - List allNames = documentConnection.getReferenceMarkNames(); + List allNames = manager.getUsedNames(documentConnection); return filterIsJabRefReferenceMarkName(allNames); } @@ -1338,7 +1371,8 @@ private List findCitedKeys(DocumentConnection documentConnection) WrappedTargetException, NoDocumentException { - List names = getJabRefReferenceMarkNames(documentConnection); + List names = getJabRefReferenceMarkNames(this.citationStorageManager, + documentConnection); // assert it supports XTextContent XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); @@ -1536,6 +1570,7 @@ static List makeIndices(int n) { static class CitationGroup { CitationGroupID cgid; + StorageBase.NamedRange cgRangeStorage; int itcType; List citations; List localOrder; @@ -1549,11 +1584,13 @@ static class CitationGroup { CitationGroup( CitationGroupID cgid, + StorageBase.NamedRange cgRangeStorage, int itcType, List citations, Optional pageInfo, String referenceMarkName) { this.cgid = cgid; + this.cgRangeStorage = cgRangeStorage; this.itcType = itcType; this.citations = citations; this.pageInfo = pageInfo; diff --git a/src/main/java/org/jabref/gui/openoffice/StorageBase.java b/src/main/java/org/jabref/gui/openoffice/StorageBase.java index a3b020548ac..eb0f7a3594f 100644 --- a/src/main/java/org/jabref/gui/openoffice/StorageBase.java +++ b/src/main/java/org/jabref/gui/openoffice/StorageBase.java @@ -79,7 +79,11 @@ public void cleanFillCursor(DocumentConnection documentConnection) WrappedTargetException, CreationException ; - // public void removeFromDocument(DocumentConnection documentConnection) + public void removeFromDocument(DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException; } interface NamedRange extends HasName, HasTextRange { @@ -98,5 +102,11 @@ public NamedRange create( DocumentConnection documentConnection, public List getUsedNames(DocumentConnection documentConnection) throws NoDocumentException; + + public NamedRange getFromDocumentOrNull(DocumentConnection documentConnection, + String refMarkName) + throws + NoDocumentException, + WrappedTargetException ; } } diff --git a/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java index 297d6af3139..9472bbf39bf 100644 --- a/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java @@ -158,11 +158,25 @@ private static StorageBaseRefMark create(DocumentConnection documentConnection, return new StorageBaseRefMark( refMarkName ); } + private static StorageBaseRefMark getFromDocumentOrNull(DocumentConnection documentConnection, + String refMarkName) + throws + NoDocumentException, + WrappedTargetException { + XTextRange r = documentConnection.getReferenceMarkRangeOrNull(refMarkName); + if (r == null) { + return null; + } else { + return new StorageBaseRefMark( refMarkName ); + } + } + /* * Remove it from the document. * * See: removeCitationGroups */ + @Override public void removeFromDocument(DocumentConnection documentConnection) throws WrappedTargetException, @@ -440,5 +454,14 @@ public List getUsedNames(DocumentConnection documentConnection) NoDocumentException { return StorageBaseRefMark.getUsedNames(documentConnection); } + + @Override + public StorageBase.NamedRange getFromDocumentOrNull(DocumentConnection documentConnection, + String refMarkName) + throws + NoDocumentException, + WrappedTargetException { + return StorageBaseRefMark.getFromDocumentOrNull(documentConnection, refMarkName); + } } } From 23b196368cc820b0d9153d9f32ca21c0b22383b2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 17:27:18 +0200 Subject: [PATCH 0511/1068] refactor: format --- .../org/jabref/gui/openoffice/CitationGroupsV001.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index b73628bc1db..25b2fdd7047 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -18,7 +18,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -//import org.jabref.gui.openoffice.CitationSort; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; @@ -160,8 +159,8 @@ private static List findUnusedJabrefPropertyNames(DocumentConnection doc // to correspond to referenceMarkNames.get(i). // And do not want null in bibtexKeys (or error code in types) // on return. - throw new IllegalArgumentException( - "citationGroups: found unparsable referenceMarkName"); + throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" + + " found unparsable referenceMarkName"); } ParsedRefMark ov = op.get(); CitationGroupID id = new CitationGroupID(refMarkName); @@ -235,6 +234,9 @@ public Optional getBibEntry(){ : Optional.empty()); } + /** + * Appends to end of {@code where} + */ void addPath(CitationPath p, Citation cit) { this.where.add(p); if (cit.db != this.db) { From 769ddd4dfe157fcda27898e41233ca12d6da30d1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 17:32:09 +0200 Subject: [PATCH 0512/1068] CitedKey.key rnamed to CitedKey.citationKey --- .../jabref/gui/openoffice/CitationGroupsV001.java | 12 ++++++------ .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 25b2fdd7047..6afd4545dcc 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -205,15 +205,15 @@ class CitationPath { class CitedKey implements CitationSort.ComparableCitation { - String key; // TODO: rename to citationKey + String citationKey; LinkedHashSet where; Optional db; Optional number; // For Numbered citation styles. Optional uniqueLetter; // For AuthorYear citation styles. Optional normCitMarker; // For AuthorYear citation styles. - CitedKey(String key, CitationPath p, Citation cit) { - this.key = key; + CitedKey(String citationKey, CitationPath p, Citation cit) { + this.citationKey = citationKey; this.where = new LinkedHashSet<>(); // remember order this.where.add(p); this.db = cit.db; @@ -224,7 +224,7 @@ class CitedKey implements CitationSort.ComparableCitation { @Override public String getCitationKey(){ - return key; + return citationKey; } @Override @@ -251,7 +251,7 @@ void addPath(CitationPath p, Citation cit) { } void lookupInDatabases(List databases) { - this.db = CitationDatabaseLookup.lookup(databases, this.key); + this.db = CitationDatabaseLookup.lookup(databases, this.citationKey); } void distributeDatabaseLookupResult(CitationGroupsV001 cgs) { @@ -294,7 +294,7 @@ void sortByComparator(Comparator entryComparator) { cks.sort(new CitationSort.CitationComparator(entryComparator, true)); LinkedHashMap newData = new LinkedHashMap<>(); for (CitedKey ck : cks) { - newData.put(ck.key, ck); + newData.put(ck.citationKey, ck); } data = newData; } diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3d36da6c159..d687c32dd49 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -768,7 +768,7 @@ public void applyCitationEntries( private String normalizedCitationMarkerForNormalStyle(CitationGroupsV001.CitedKey ck, OOBibStyle style) { if (ck.db.isEmpty()){ - return String.format("(Unresolved(%s))", ck.key); + return String.format("(Unresolved(%s))", ck.citationKey); } BibEntry ce = ck.db.get().entry; Map entries = new HashMap<>(); @@ -825,7 +825,7 @@ void createUniqueLetters(CitationGroupsV001.CitedKeys sortedCitedKeys, Map> ncm2clks = new HashMap<>(); for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.values()) { String ncm = ck.normCitMarker.get(); - String citationKey = ck.key; + String citationKey = ck.citationKey; if (!ncm2clks.containsKey(ncm)) { // Found new normCitMarker @@ -1728,7 +1728,7 @@ public List getUnresolvedKeys() { List unresolvedKeys = new ArrayList<>(); for (CitationGroupsV001.CitedKey ck : bib.values()) { if ( ck.db.isEmpty() ) { - unresolvedKeys.add(ck.key); + unresolvedKeys.add(ck.citationKey); } } return unresolvedKeys; @@ -1923,7 +1923,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, if (debugThisFun) { System.out.printf("Ref cit %-20s ck.number %7s%n", - String.format("'%s'",ck.key), + String.format("'%s'",ck.citationKey), (ck.number.isEmpty() ? "(empty)" : String.format("%02d",ck.number.get()))); @@ -1961,7 +1961,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // skip unresolved entries OOUtil.insertTextAtCurrentLocation(documentConnection.xText, cursor, - String.format("Unresolved(%s)", ck.key), + String.format("Unresolved(%s)", ck.citationKey), Collections.emptyList()); // Try to list citations: if (true) { @@ -2755,7 +2755,7 @@ public ExportCitedHelperResult exportCitedHelper( for (CitationGroupsV001.CitedKey ck : cks.values()) { if ( ck.db.isEmpty() ) { - unresolvedKeys.add(ck.key); + unresolvedKeys.add(ck.citationKey); continue; } else { BibEntry entry = ck.db.get().entry; From a7d379369025287e43957a3a1efaef3eb65da104 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 17:47:30 +0200 Subject: [PATCH 0513/1068] cleanup --- .../gui/openoffice/CitationGroupsV001.java | 267 +----------------- 1 file changed, 5 insertions(+), 262 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 6afd4545dcc..8384f763e39 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -464,8 +464,7 @@ public void createNumberedBibliographySortedByComparator(Comparator en this.bibliography = Optional.of(citedKeys); } - public void - createPlainBibliographySortedByComparator(Comparator entryComparator) { + public void createPlainBibliographySortedByComparator(Comparator entryComparator) { CitationGroupsV001 cgs = this; if (!this.bibliography.isEmpty()) { throw new RuntimeException( @@ -478,8 +477,7 @@ public void createNumberedBibliographySortedByComparator(Comparator en this.bibliography = Optional.of(citedKeys); } - public Set - getCitationGroupIDs() { + public Set getCitationGroupIDs() { return citationGroups.keySet(); } @@ -741,47 +739,6 @@ public Optional getPageInfo(CitationGroupID cgid) { return cg.get().getSortedCitations(); } - /* *********************************** - * - * modifies both storage and presentation - * - * ***********************************/ - - /** - * Insert {@code n} spaces in a way that reference - * marks just before or just after the cursor are not affected. - * - * This is based on the observation, that starting two - * new paragraphs separates us from a reference mark on either side. - * - * The pattern used is: - * {@code safeInsertSpaces(n): para, para, left, space(n), right-delete, left(n), left-delete} - * - * @param position Where to insert (at position.getStart()) - * @param n Number of spaces to insert. - * - * @return a new cursor, covering the just-inserted spaces. - * - * This could be generalized to insert arbitrary text safely - * between two reference marks. But we do not need that now. - */ -// private static XTextCursor -// safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { -// // Start with an empty cursor at position.getStart(); -// XText text = position.getText(); -// XTextCursor cursor = text.createTextCursorByRange(position.getStart()); -// text.insertString(cursor, "\r\r", false); // para, para -// cursor.goLeft((short) 1, false); // left -// text.insertString(cursor, " ".repeat(n), false); // space(n) -// cursor.goRight((short) 1, true); -// cursor.setString(""); // right-delete -// cursor.goLeft((short) n, false); // left(n) -// cursor.goLeft((short) 1, true); -// cursor.setString(""); // left-delete -// cursor.goRight((short) n, true); -// return cursor; -// } - /** * Create a reference mark with the given name, at the * end of position. @@ -900,45 +857,6 @@ public CitationGroupID createCitationGroup(DocumentConnection documentConnection position, insertSpaceAfter, withoutBrackets); - -// // The cursor we received: we push it before us. -// position.collapseToEnd(); -// -// XTextCursor cursor = safeInsertSpacesBetweenReferenceMarks(position.getEnd(), 2); -// -// // cursors before the first and after the last space -// XTextCursor cursorBefore = -// cursor.getText().createTextCursorByRange(cursor.getStart()); -// XTextCursor cursorAfter = -// cursor.getText().createTextCursorByRange(cursor.getEnd()); -// -// cursor.collapseToStart(); -// cursor.goRight((short) 1, false); -// // now we are between two spaces -// -// final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; -// final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; -// final short leftLength = (short) left.length(); -// final short rightLength = (short) right.length(); -// String bracketedContent = (withoutBrackets -// ? "" -// : left + right); -// -// cursor.getText().insertString( -// cursor, -// bracketedContent, -// true); -// -// documentConnection.insertReferenceMark(refMarkName, -// cursor, -// true /* absorb */); -// -// cursorBefore.goRight((short) 1, true); -// cursorBefore.setString(""); -// if (!insertSpaceAfter) { -// cursorAfter.goLeft((short) 1, true); -// cursorAfter.setString(""); -// } } /* @@ -996,70 +914,6 @@ public void cleanFillCursorForCitationGroup(DocumentConnection documentConnectio CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); cg.cgRangeStorage.cleanFillCursor(documentConnection); - -// boolean alwaysRemoveBrackets = true; -// boolean removeBracketsFromEmpty = false; -// -// final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; -// final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; -// final short leftLength = (short) left.length(); -// final short rightLength = (short) right.length(); -// -// CitationGroupsV001 cgs = this; -// String name = cgs.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); -// -// XTextCursor full = cgs.getRawCursorForCitationGroup(cgid, documentConnection); -// final String fullText = full.getString(); -// final int fullTextLength = fullText.length(); -// -// XTextCursor alpha = full.getText().createTextCursorByRange(full); -// alpha.collapseToStart(); -// -// XTextCursor beta = full.getText().createTextCursorByRange(full); -// beta.collapseToStart(); -// beta.goRight(leftLength, false); -// -// XTextCursor omega = full.getText().createTextCursorByRange(full); -// omega.collapseToEnd(); -// -// if (!fullText.startsWith(left)) { -// throw new RuntimeException( -// String.format("cleanFillCursorForCitationGroup:" -// + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", -// name)); -// } -// -// if (!fullText.endsWith(right)) { -// throw new RuntimeException( -// String.format("cleanFillCursorForCitationGroup:" -// + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", -// name)); -// } -// -// final int contentLength = (fullTextLength - (leftLength + rightLength)); -// if (contentLength < 0) { -// throw new RuntimeException( -// String.format("cleanFillCursorForCitationGroup: length(%s) < 0", -// name)); -// } -// -// boolean removeRight = ((contentLength >= 1) -// || ((contentLength == 0) && removeBracketsFromEmpty) -// || alwaysRemoveBrackets); -// -// boolean removeLeft = ((contentLength >= 2) -// || ((contentLength == 0) && removeBracketsFromEmpty) -// || alwaysRemoveBrackets); -// -// if (removeRight) { -// omega.goLeft(rightLength, true); -// omega.setString(""); -// } -// -// if (removeLeft) { -// alpha.goRight(leftLength, true); -// alpha.setString(""); -// } } /** @@ -1075,25 +929,6 @@ public XTextCursor getRawCursorForCitationGroup(CitationGroupID cgid, CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); return cg.cgRangeStorage.getRawCursor(documentConnection); - -// String name = this.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); -// XTextCursor full = null; -// -// XTextContent markAsTextContent = -// documentConnection.getReferenceMarkAsTextContentOrNull(name); -// -// if (markAsTextContent == null) { -// throw new RuntimeException( -// String.format( -// "getRawCursorForCitationGroup: markAsTextContent(%s) == null", -// name)); -// } -// -// full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); -// if (full == null) { -// throw new RuntimeException("getRawCursorForCitationGroup: full == null"); -// } -// return full; } public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, @@ -1105,100 +940,6 @@ public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConn CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); return cg.cgRangeStorage.getFillCursor(documentConnection); - -// String name = this.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); -// -// final boolean debugThisFun = false; -// final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; -// final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; -// final short leftLength = (short) left.length(); -// final short rightLength = (short) right.length(); -// -// XTextCursor full = null; -// String fullText = null; -// for (int i = 1; i <= 2; i++) { -// XTextContent markAsTextContent = -// documentConnection.getReferenceMarkAsTextContentOrNull(name); -// -// if (markAsTextContent == null) { -// throw new RuntimeException( -// String.format("getFillCursorForCitationGroup:" -// + " markAsTextContent(%s) == null (attempt %d)", -// name, -// i)); -// } -// -// full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); -// if (full == null) { -// throw new RuntimeException( -// String.format("getFillCursorForCitationGroup: full == null (attempt %d)", i)); -// } -// -// fullText = full.getString(); -// -// if (debugThisFun) { -// System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); -// } -// -// if (fullText.length() >= 2) { -// break; -// } else { -// // (fullText.length() < 2) -// if (i == 2) { -// throw new RuntimeException( -// String.format("getFillCursorForCitationGroup:" -// + " (fullText.length() < 2) (attempt %d)", -// i)); -// } -// // too short, recreate -// if (debugThisFun) { -// System.out.println("getFillCursor: too short, recreate"); -// } -// full.setString(""); -// try { -// documentConnection.removeReferenceMark(name); -// } catch (NoSuchElementException ex) { -// LOGGER.warn( -// String.format("getFillCursorForCitationGroup got NoSuchElementException" -// + " for '%s'", -// name)); -// } -// createReferenceMarkForCitationGroup( -// documentConnection, -// name, -// full, -// false, /* insertSpaceAfter */ -// false /* withoutBrackets */); -// } -// } -// -// if (full == null) { -// throw new RuntimeException("getFillCursorForCitationGroup: full == null (after loop)"); -// } -// if (fullText == null) { -// throw new RuntimeException("getFillCursorForCitationGroup: fullText == null (after loop)"); -// } -// -// // we have at least two characters inside -// XTextCursor alpha = full.getText().createTextCursorByRange(full); -// alpha.collapseToStart(); -// XTextCursor omega = full.getText().createTextCursorByRange(full); -// omega.collapseToEnd(); -// -// XTextCursor beta = full.getText().createTextCursorByRange(full); -// beta.collapseToStart(); -// beta.goRight((short) 1, false); -// beta.goRight((short) (fullText.length() - 2), true); -// beta.setString(left + right); -// beta.collapseToEnd(); -// beta.goLeft(rightLength, false); -// // drop the initial character -// alpha.goRight((short) 1, true); -// alpha.setString(""); -// // drop the last character -// omega.goLeft((short) 1, true); -// omega.setString(""); -// return beta; } /** @@ -1366,6 +1107,8 @@ private static void parseRefMarkNamesToArrays(List referenceMarkNames, * (in `names`, which itself is in arbitrary order) * * doc.referenceMarks.names.map(parse).flatten.unique + * + * TODO: avoid direct reference mark manipulation */ private List findCitedKeys(DocumentConnection documentConnection) throws @@ -1418,7 +1161,7 @@ private static String getPageInfoForReferenceMarkName(DocumentConnection documen return pageInfo.get(); } - /* + /** * ranges controlled by citation groups should not overlap with each other. * * @param cgid : Must be known. From 83199caf836c1d2095c92a9eabeae104e3151b6b Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 21:14:58 +0200 Subject: [PATCH 0514/1068] refactor: separate CitationGroups and Codec in CitationGroupsV001 --- .../gui/openoffice/CitationGroupsV001.java | 2041 +++++++++-------- .../org/jabref/gui/openoffice/OOBibBase.java | 54 +- 2 files changed, 1055 insertions(+), 1040 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 8384f763e39..7df060a7689 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -49,177 +49,43 @@ class CitationGroupsV001 { private static final Logger LOGGER = LoggerFactory.getLogger(CitedKeys.class); - private static final String BIB_CITATION = "JR_cite"; - private static final Pattern CITE_PATTERN = - Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); - - private StorageBase.NamedRangeManager citationStorageManager; - - /** - * Original CitationGroups Data - */ - private Map citationGroups; - - /** - * Extra Data - */ - // For custom properties belonging to us, but - // without a corresponding reference mark. - // These can be deleted. - private List pageInfoThrash; - - private Optional> globalOrder; - - private Optional citedKeysAfterDatabaseLookup; - - /** - * This is going to be the bibliography - */ - private Optional bibliography; - - /** - * Constructor - */ - public CitationGroupsV001(DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException { - - this.citationStorageManager = new StorageBaseRefMark.Manager(); - - // Get the citationGroupNames - List citationGroupNames = getJabRefReferenceMarkNames(this.citationStorageManager, - documentConnection); - - this.pageInfoThrash = findUnusedJabrefPropertyNames(documentConnection, - citationGroupNames); - - this.citationGroups = readCitationGroupsFromDocument(this.citationStorageManager, - documentConnection, - citationGroupNames); - - // Now we have almost every information from the document about citations. - // What is left out: the ranges controlled by the reference marks. - // But (I guess) those change too easily, so we only ask when actually needed. - - this.globalOrder = Optional.empty(); - this.citedKeysAfterDatabaseLookup = Optional.empty(); - this.bibliography = Optional.empty(); - } - - private static List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, - List citationGroupNames) { - // Collect unused jabrefPropertyNames - Set citationGroupNamesSet = - citationGroupNames.stream().collect(Collectors.toSet()); - - List pageInfoThrash = new ArrayList<>(); - List jabrefPropertyNames = - documentConnection.getCustomPropertyNames() - .stream() - .filter(CitationGroupsV001::isJabRefReferenceMarkName) - .collect(Collectors.toList()); - for (String pn : jabrefPropertyNames) { - if (!citationGroupNamesSet.contains(pn)) { - pageInfoThrash.add(pn); - } - } - return pageInfoThrash; - } - - private static Map - readCitationGroupsFromDocument(StorageBase.NamedRangeManager citationStorageManager, - DocumentConnection documentConnection, - List citationGroupNames) - throws - WrappedTargetException, - NoDocumentException { - - Map citationGroups = new HashMap<>(); - for (int i = 0; i < citationGroupNames.size(); i++) { - final String name = citationGroupNames.get(i); - CitationGroup cg = - readCitationGroupFromDocumentOrThrow(citationStorageManager, documentConnection, name); - citationGroups.put(cg.cgid, cg); + static class CitationGroupID { + String id; + CitationGroupID(String id) { + this.id = id; } - return citationGroups; - } - private static CitationGroup - readCitationGroupFromDocumentOrThrow(StorageBase.NamedRangeManager citationStorageManager, - DocumentConnection documentConnection, - String refMarkName) - throws - WrappedTargetException, - NoDocumentException { - - Optional op = parseRefMarkName(refMarkName); - if (op.isEmpty()) { - // We have a problem. We want types[i] and bibtexKeys[i] - // to correspond to referenceMarkNames.get(i). - // And do not want null in bibtexKeys (or error code in types) - // on return. - throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" - + " found unparsable referenceMarkName"); - } - ParsedRefMark ov = op.get(); - CitationGroupID id = new CitationGroupID(refMarkName); - List citations = ((ov.citationKeys == null) - ? new ArrayList<>() - : (ov.citationKeys.stream() - .map(Citation::new) - .collect(Collectors.toList()))); - - Optional pageInfo = documentConnection.getCustomProperty(refMarkName); - - StorageBase.NamedRange sr = citationStorageManager.getFromDocumentOrNull(documentConnection, - refMarkName); - - if (sr == null) { - throw new IllegalArgumentException( - "readCitationGroupFromDocumentOrThrow: referenceMarkName is not in the document"); - } - - CitationGroup cg = new CitationGroup(id, - sr, - ov.itcType, - citations, - pageInfo, - refMarkName); - return cg; - } - - /** - * Identifies a citation with the citation group containing it and - * its storage index within. - */ - class CitationPath { - CitationGroupID group; - int storageIndexInGroup; - CitationPath(CitationGroupID group, - int storageIndexInGroup) { - this.group = group; - this.storageIndexInGroup = storageIndexInGroup; + /** + * CitationEntry needs refMark or other identifying string + */ + String asString() { + return id; } } + static class Citation implements CitationSort.ComparableCitation { - class CitedKey implements CitationSort.ComparableCitation { + /** key in database */ String citationKey; - LinkedHashSet where; + /** Result from database lookup. Optional.empty() if not found. */ Optional db; - Optional number; // For Numbered citation styles. - Optional uniqueLetter; // For AuthorYear citation styles. - Optional normCitMarker; // For AuthorYear citation styles. + /** The number used for numbered citation styles . */ + Optional number; + /** Letter that makes the in-text citation unique. */ + Optional uniqueLetter; - CitedKey(String citationKey, CitationPath p, Citation cit) { + /* missing: something that differentiates this from other + * citations of the same citationKey. In particular, a + * CitationGroup may contain multiple citations of the same + * source. We use CitationPath.storageIndexInGroup to refer to + * citations. + */ + + Citation(String citationKey) { this.citationKey = citationKey; - this.where = new LinkedHashSet<>(); // remember order - this.where.add(p); - this.db = cit.db; - this.number = cit.number; - this.uniqueLetter = cit.uniqueLetter; - this.normCitMarker = Optional.empty(); + this.db = Optional.empty(); + this.number = Optional.empty(); + this.uniqueLetter = Optional.empty(); } @Override @@ -233,872 +99,844 @@ public Optional getBibEntry(){ ? Optional.of(db.get().entry) : Optional.empty()); } + } + + public static class CitationGroup { + CitationGroupID cgid; + StorageBase.NamedRange cgRangeStorage; + int itcType; + List citations; + List localOrder; + // Currently pageInfo belongs to the group + Optional pageInfo; /** - * Appends to end of {@code where} + * Locator in document */ - void addPath(CitationPath p, Citation cit) { - this.where.add(p); - if (cit.db != this.db) { - throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); - } - if (cit.number != this.number) { - throw new RuntimeException("CitedKey.addPath: mismatch on cit.number"); - } - if (cit.uniqueLetter != this.uniqueLetter) { - throw new RuntimeException("CitedKey.addPath: mismatch on cit.uniqueLetter"); - } - } + String referenceMarkName; - void lookupInDatabases(List databases) { - this.db = CitationDatabaseLookup.lookup(databases, this.citationKey); + CitationGroup( + CitationGroupID cgid, + StorageBase.NamedRange cgRangeStorage, + int itcType, + List citations, + Optional pageInfo, + String referenceMarkName) { + this.cgid = cgid; + this.cgRangeStorage = cgRangeStorage; + this.itcType = itcType; + this.citations = citations; + this.pageInfo = pageInfo; + this.referenceMarkName = referenceMarkName; + this.localOrder = makeIndices(citations.size()); } - void distributeDatabaseLookupResult(CitationGroupsV001 cgs) { - cgs.setDatabaseLookupResults(where, db); + /** Integers 0..(n-1) */ + static List makeIndices(int n) { + return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); } - void distributeNumber(CitationGroupsV001 cgs) { - cgs.setNumbers(where, number); + List + getSortedCitations() { + List res = new ArrayList<>(citations.size()); + for (int i : localOrder) { + res.add(citations.get(i)); + } + return res; } - void distributeUniqueLetter(CitationGroupsV001 cgs) { - cgs.setUniqueLetters(where, uniqueLetter); + List + getSortedNumbers() { + List cits = getSortedCitations(); + return (cits.stream() + .map(cit -> cit.number.orElseThrow(RuntimeException::new)) + .collect(Collectors.toList())); } - } + class CitationAndIndex implements CitationSort.ComparableCitation { + Citation c; + int i; + CitationAndIndex(Citation c, int i) { + this.c = c; + this.i = i; + } + + @Override + public String getCitationKey(){ + return c.getCitationKey(); + } - class CitedKeys { + @Override + public Optional getBibEntry(){ + return c.getBibEntry(); + } + } /** - * Order-preserving map from citation keys to associated data. + * Sort citations for presentation within a CitationGroup. */ - LinkedHashMap data; + void imposeLocalOrderByComparator(Comparator entryComparator) { + List cks = new ArrayList<>(); + for (int i = 0; i < citations.size(); i++) { + Citation c = citations.get(i); + cks.add(new CitationAndIndex(c, i)); + } + cks.sort(new CitationSort.CitationComparator(entryComparator, true)); - CitedKeys(LinkedHashMap data) { - this.data = data; + List o = new ArrayList<>(); + for (CitationAndIndex ck : cks) { + o.add(ck.i); + } + this.localOrder = o; } + } // class CitationGroup + + /** + * + */ + public static class CitationGroups { + private StorageBase.NamedRangeManager citationStorageManager; /** - * The cited keys in sorted order. + * Original CitationGroups Data */ - public List values() { - return new ArrayList<>(data.values()); - } + private Map citationGroups; /** - * Sort entries for the bibliography. + * Extra Data */ - void sortByComparator(Comparator entryComparator) { - List cks = new ArrayList<>(data.values()); - cks.sort(new CitationSort.CitationComparator(entryComparator, true)); - LinkedHashMap newData = new LinkedHashMap<>(); - for (CitedKey ck : cks) { - newData.put(ck.citationKey, ck); - } - data = newData; - } + // For custom properties belonging to us, but + // without a corresponding reference mark. + // These can be deleted. + private List pageInfoThrash; - void numberCitedKeysInCurrentOrder() { - int i = 1; - for (CitedKey ck : data.values()) { - ck.number = Optional.of(i); // was: -1 for UndefinedBibtexEntry - i++; - } - } + private Optional> globalOrder; - void lookupInDatabases(List databases) { - for (CitedKey ck : this.data.values()) { - ck.lookupInDatabases(databases); + private Optional citedKeysAfterDatabaseLookup; + + /** + * This is going to be the bibliography + */ + private Optional bibliography; + + /** + * Constructor + */ + public CitationGroups(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + this.citationStorageManager = new StorageBaseRefMark.Manager(); + + // Get the citationGroupNames + List citationGroupNames = + Codec.getJabRefReferenceMarkNames(this.citationStorageManager, + documentConnection); + + this.pageInfoThrash = findUnusedJabrefPropertyNames(documentConnection, + citationGroupNames); + + this.citationGroups = readCitationGroupsFromDocument(this.citationStorageManager, + documentConnection, + citationGroupNames); + + // Now we have almost every information from the document about citations. + // What is left out: the ranges controlled by the reference marks. + // But (I guess) those change too easily, so we only ask when actually needed. + + this.globalOrder = Optional.empty(); + this.citedKeysAfterDatabaseLookup = Optional.empty(); + this.bibliography = Optional.empty(); + } + + private static List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, + List citationGroupNames) { + // Collect unused jabrefPropertyNames + Set citationGroupNamesSet = + citationGroupNames.stream().collect(Collectors.toSet()); + + List pageInfoThrash = new ArrayList<>(); + List jabrefPropertyNames = + documentConnection.getCustomPropertyNames() + .stream() + .filter(CitationGroupsV001.Codec::isJabRefReferenceMarkName) + .collect(Collectors.toList()); + for (String pn : jabrefPropertyNames) { + if (!citationGroupNamesSet.contains(pn)) { + pageInfoThrash.add(pn); + } } + return pageInfoThrash; } - void distributeDatabaseLookupResults(CitationGroupsV001 cgs) { - for (CitedKey ck : this.data.values()) { - ck.distributeDatabaseLookupResult(cgs); + private static Map + readCitationGroupsFromDocument(StorageBase.NamedRangeManager citationStorageManager, + DocumentConnection documentConnection, + List citationGroupNames) + throws + WrappedTargetException, + NoDocumentException { + + Map citationGroups = new HashMap<>(); + for (int i = 0; i < citationGroupNames.size(); i++) { + final String name = citationGroupNames.get(i); + CitationGroup cg = + readCitationGroupFromDocumentOrThrow(citationStorageManager, documentConnection, name); + citationGroups.put(cg.cgid, cg); } + return citationGroups; } - void distributeNumbers(CitationGroupsV001 cgs) { - for (CitedKey ck : this.data.values()) { - ck.distributeNumber(cgs); + private static CitationGroup + readCitationGroupFromDocumentOrThrow(StorageBase.NamedRangeManager citationStorageManager, + DocumentConnection documentConnection, + String refMarkName) + throws + WrappedTargetException, + NoDocumentException { + + Optional op = Codec.parseRefMarkName(refMarkName); + if (op.isEmpty()) { + // We have a problem. We want types[i] and bibtexKeys[i] + // to correspond to referenceMarkNames.get(i). + // And do not want null in bibtexKeys (or error code in types) + // on return. + throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" + + " found unparsable referenceMarkName"); } - } + ParsedRefMark ov = op.get(); + CitationGroupID id = new CitationGroupID(refMarkName); + List citations = ((ov.citationKeys == null) + ? new ArrayList<>() + : (ov.citationKeys.stream() + .map(Citation::new) + .collect(Collectors.toList()))); - void distributeUniqueLetters(CitationGroupsV001 cgs) { - for (CitedKey ck : this.data.values()) { - ck.distributeUniqueLetter(cgs); + Optional pageInfo = documentConnection.getCustomProperty(refMarkName); + + StorageBase.NamedRange sr = citationStorageManager.getFromDocumentOrNull(documentConnection, + refMarkName); + + if (sr == null) { + throw new IllegalArgumentException( + "readCitationGroupFromDocumentOrThrow: referenceMarkName is not in the document"); } - } - } + CitationGroup cg = new CitationGroup(id, + sr, + ov.itcType, + citations, + pageInfo, + refMarkName); + return cg; + } - public void setDatabaseLookupResults(Set where, - Optional db) { - for (CitationPath p : where) { - CitationGroup cg = this.citationGroups.get(p.group); - if (cg == null) { - LOGGER.warn("CitationGroups.setDatabaseLookupResult: group missing"); - continue; + public void setDatabaseLookupResults(Set where, + Optional db) { + for (CitationPath p : where) { + CitationGroup cg = this.citationGroups.get(p.group); + if (cg == null) { + LOGGER.warn("CitationGroups.setDatabaseLookupResult: group missing"); + continue; + } + Citation cit = cg.citations.get(p.storageIndexInGroup); + cit.db = db; } - Citation cit = cg.citations.get(p.storageIndexInGroup); - cit.db = db; } - } - public CitationGroupsV001.CitedKeys lookupEntriesInDatabases(List databases) { - CitationGroupsV001 cgs = this; + public CitationGroupsV001.CitedKeys lookupEntriesInDatabases(List databases) { + CitationGroupsV001.CitationGroups cgs = this; - CitationGroupsV001.CitedKeys cks = cgs.getCitedKeys(); + CitationGroupsV001.CitedKeys cks = cgs.getCitedKeys(); - cks.lookupInDatabases(databases); - cks.distributeDatabaseLookupResults(cgs); - // record we did a database lookup - // and allow extracting unresolved keys. - this.citedKeysAfterDatabaseLookup = Optional.of(cks); - return cks; - } + cks.lookupInDatabases(databases); + cks.distributeDatabaseLookupResults(cgs); + // record we did a database lookup + // and allow extracting unresolved keys. + this.citedKeysAfterDatabaseLookup = Optional.of(cks); + return cks; + } - public void setNumbers(Set where, - Optional number) { - for (CitationPath p : where) { - CitationGroup cg = this.citationGroups.get(p.group); - if (cg == null) { - LOGGER.warn("CitationGroups.setNumbers: group missing"); - continue; + public void setNumbers(Set where, + Optional number) { + for (CitationPath p : where) { + CitationGroup cg = this.citationGroups.get(p.group); + if (cg == null) { + LOGGER.warn("CitationGroups.setNumbers: group missing"); + continue; + } + Citation cit = cg.citations.get(p.storageIndexInGroup); + cit.number = number; } - Citation cit = cg.citations.get(p.storageIndexInGroup); - cit.number = number; } - } - public void setUniqueLetters(Set where, - Optional uniqueLetter) { - for (CitationPath p : where) { - CitationGroup cg = this.citationGroups.get(p.group); - if (cg == null) { - LOGGER.warn("CitationGroups.setUniqueLetters: group missing"); - continue; + public void setUniqueLetters(Set where, + Optional uniqueLetter) { + for (CitationPath p : where) { + CitationGroup cg = this.citationGroups.get(p.group); + if (cg == null) { + LOGGER.warn("CitationGroups.setUniqueLetters: group missing"); + continue; + } + Citation cit = cg.citations.get(p.storageIndexInGroup); + cit.uniqueLetter = uniqueLetter; } - Citation cit = cg.citations.get(p.storageIndexInGroup); - cit.uniqueLetter = uniqueLetter; } - } - public void imposeLocalOrderByComparator(Comparator entryComparator) { - for (CitationGroup cg : citationGroups.values()) { - cg.imposeLocalOrderByComparator(entryComparator); + public void imposeLocalOrderByComparator(Comparator entryComparator) { + for (CitationGroup cg : citationGroups.values()) { + cg.imposeLocalOrderByComparator(entryComparator); + } } - } - public CitedKeys getCitedKeys() { - LinkedHashMap res = new LinkedHashMap<>(); - for (CitationGroup cg : citationGroups.values()) { - int storageIndexInGroup = 0; - for (Citation cit : cg.citations) { - String key = cit.citationKey; - CitationPath p = new CitationPath(cg.cgid, storageIndexInGroup); - if (res.containsKey(key)) { - res.get(key).addPath(p, cit); - } else { - res.put(key, new CitedKey(key, p, cit)); + public CitedKeys getCitedKeys() { + LinkedHashMap res = new LinkedHashMap<>(); + for (CitationGroup cg : citationGroups.values()) { + int storageIndexInGroup = 0; + for (Citation cit : cg.citations) { + String key = cit.citationKey; + CitationPath p = new CitationPath(cg.cgid, storageIndexInGroup); + if (res.containsKey(key)) { + res.get(key).addPath(p, cit); + } else { + res.put(key, new CitedKey(key, p, cit)); + } + storageIndexInGroup++; } - storageIndexInGroup++; } + return new CitedKeys(res); } - return new CitedKeys(res); - } - /** - * CitedKeys created iterating citations in (globalOrder,localOrder) - */ - public CitedKeys getCitedKeysSortedInOrderOfAppearance() { - LinkedHashMap res = new LinkedHashMap<>(); - if (globalOrder.isEmpty()) { - throw new RuntimeException("getSortedCitedKeys: no globalOrder"); - } - for (CitationGroupID cgid : globalOrder.get()) { - CitationGroup cg = getCitationGroup(cgid) - .orElseThrow(RuntimeException::new); - for (int i : cg.localOrder) { - Citation cit = cg.citations.get(i); - String citationKey = cit.citationKey; - CitationPath p = new CitationPath(cgid, i); - if (res.containsKey(citationKey)) { - res.get(citationKey).addPath(p, cit); - } else { - res.put(citationKey, new CitedKey(citationKey, p, cit)); + /** + * CitedKeys created iterating citations in (globalOrder,localOrder) + */ + public CitedKeys getCitedKeysSortedInOrderOfAppearance() { + LinkedHashMap res = new LinkedHashMap<>(); + if (globalOrder.isEmpty()) { + throw new RuntimeException("getSortedCitedKeys: no globalOrder"); + } + for (CitationGroupID cgid : globalOrder.get()) { + CitationGroup cg = getCitationGroup(cgid) + .orElseThrow(RuntimeException::new); + for (int i : cg.localOrder) { + Citation cit = cg.citations.get(i); + String citationKey = cit.citationKey; + CitationPath p = new CitationPath(cgid, i); + if (res.containsKey(citationKey)) { + res.get(citationKey).addPath(p, cit); + } else { + res.put(citationKey, new CitedKey(citationKey, p, cit)); + } } } + return new CitedKeys(res); } - return new CitedKeys(res); - } - Optional getBibliography() { - return bibliography; - } + Optional getBibliography() { + return bibliography; + } - public void createNumberedBibliographySortedInOrderOfAppearance() { - CitationGroupsV001 cgs = this; - if (!cgs.bibliography.isEmpty()) { - throw new RuntimeException( - "createNumberedBibliographySortedInOrderOfAppearance: already have a bibliography"); - } - CitationGroupsV001.CitedKeys sortedCitedKeys = - cgs.getCitedKeysSortedInOrderOfAppearance(); - sortedCitedKeys.numberCitedKeysInCurrentOrder(); - sortedCitedKeys.distributeNumbers(cgs); - cgs.bibliography = Optional.of(sortedCitedKeys); - } - - public void createNumberedBibliographySortedByComparator(Comparator entryComparator) { - CitationGroupsV001 cgs = this; - if (!cgs.bibliography.isEmpty()) { - throw new RuntimeException( - "createNumberedBibliographySortedByComparator: already have a bibliography"); - } - CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); - citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup - citedKeys.numberCitedKeysInCurrentOrder(); - citedKeys.distributeNumbers(cgs); - this.bibliography = Optional.of(citedKeys); - } - - public void createPlainBibliographySortedByComparator(Comparator entryComparator) { - CitationGroupsV001 cgs = this; - if (!this.bibliography.isEmpty()) { - throw new RuntimeException( - "createPlainBibliographySortedByComparator: already have a bibliography"); - } - CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); - citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup - // citedKeys.numberCitedKeysInCurrentOrder(); - // citedKeys.distributeNumbers(); - this.bibliography = Optional.of(citedKeys); - } - - public Set getCitationGroupIDs() { - return citationGroups.keySet(); - } - - /** - * Creates a list of {@code - * RangeSortable} values for - * our {@code CitationGroup} values. Originally designed to be - * passed to {@code visualSort}. - * - * The elements of the returned list are actually of type {@code - * RangeSortEntry}. - * - * The result is sorted within {@code XTextRange.getText()} - * partitions of the citation groups according to their {@code - * XTextRange} (before mapping to footnote marks). - * - * In the result, RangeSortable.getIndexInPosition() contains - * unique indexes within the original partition (not after - * mapFootnotesToFootnoteMarks). - * - * @param cgs The source of CitationGroup values. - * @param documentConnection Connection to the document. - * @param mapFootnotesToFootnoteMarks If true, replace ranges in - * footnotes with the range of the corresponding footnote - * mark. This is used for numbering the citations. - * - */ - private static List> - createVisualSortInput(CitationGroupsV001 cgs, - DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - NoDocumentException, - WrappedTargetException { + public void createNumberedBibliographySortedInOrderOfAppearance() { + CitationGroupsV001.CitationGroups cgs = this; + if (!cgs.bibliography.isEmpty()) { + throw new RuntimeException( + "createNumberedBibliographySortedInOrderOfAppearance: already have a bibliography"); + } + CitationGroupsV001.CitedKeys sortedCitedKeys = + cgs.getCitedKeysSortedInOrderOfAppearance(); + sortedCitedKeys.numberCitedKeysInCurrentOrder(); + sortedCitedKeys.distributeNumbers(cgs); + cgs.bibliography = Optional.of(sortedCitedKeys); + } - List cgids = - new ArrayList<>(cgs.getCitationGroupIDs()); + public void createNumberedBibliographySortedByComparator(Comparator entryComparator) { + CitationGroupsV001.CitationGroups cgs = this; + if (!cgs.bibliography.isEmpty()) { + throw new RuntimeException( + "createNumberedBibliographySortedByComparator: already have a bibliography"); + } + CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); + citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup + citedKeys.numberCitedKeysInCurrentOrder(); + citedKeys.distributeNumbers(cgs); + this.bibliography = Optional.of(citedKeys); + } - List vses = new ArrayList<>(); - for (CitationGroupsV001.CitationGroupID cgid : cgids) { - XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); - if (range == null) { - throw new RuntimeException("getReferenceMarkRangeOrNull returned null"); + public void createPlainBibliographySortedByComparator(Comparator entryComparator) { + CitationGroupsV001.CitationGroups cgs = this; + if (!this.bibliography.isEmpty()) { + throw new RuntimeException( + "createPlainBibliographySortedByComparator: already have a bibliography"); } - vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); + CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); + citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup + // citedKeys.numberCitedKeysInCurrentOrder(); + // citedKeys.distributeNumbers(); + this.bibliography = Optional.of(citedKeys); } - /* - * At this point we are almost ready to return vses. + public Set getCitationGroupIDs() { + return citationGroups.keySet(); + } + + /** + * Creates a list of {@code + * RangeSortable} values for + * our {@code CitationGroup} values. Originally designed to be + * passed to {@code visualSort}. + * + * The elements of the returned list are actually of type {@code + * RangeSortEntry}. * - * For example we may want to number citations in a footnote - * as if it appeared where the footnote mark is. + * The result is sorted within {@code XTextRange.getText()} + * partitions of the citation groups according to their {@code + * XTextRange} (before mapping to footnote marks). * - * The following code replaces ranges within footnotes with - * the range for the corresponding footnote mark. + * In the result, RangeSortable.getIndexInPosition() contains + * unique indexes within the original partition (not after + * mapFootnotesToFootnoteMarks). * - * This brings further ambiguity if we have multiple - * citations within the same footnote: for the comparison - * they become indistinguishable. Numbering between them is - * not controlled. Also combineCiteMarkers will see them in - * the wrong order (if we use this comparison), and will not - * be able to merge. To avoid these, we sort textually within - * each .getText() partition and add indexInPosition - * accordingly. + * @param cgs The source of CitationGroup values. + * @param documentConnection Connection to the document. + * @param mapFootnotesToFootnoteMarks If true, replace ranges in + * footnotes with the range of the corresponding footnote + * mark. This is used for numbering the citations. * */ + private static List> + createVisualSortInput(CitationGroupsV001.CitationGroups cgs, + DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + NoDocumentException, + WrappedTargetException { + + List cgids = + new ArrayList<>(cgs.getCitationGroupIDs()); + + List vses = new ArrayList<>(); + for (CitationGroupsV001.CitationGroupID cgid : cgids) { + XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); + if (range == null) { + throw new RuntimeException("getReferenceMarkRangeOrNull returned null"); + } + vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); + } - // Sort within partitions - RangeKeyedMapList> xxs - = new RangeKeyedMapList<>(); - - for (RangeSort.RangeSortEntry v : vses) { - xxs.add(v.getRange(), v); - } - - // build final list - List> res = new ArrayList<>(); + /* + * At this point we are almost ready to return vses. + * + * For example we may want to number citations in a footnote + * as if it appeared where the footnote mark is. + * + * The following code replaces ranges within footnotes with + * the range for the corresponding footnote mark. + * + * This brings further ambiguity if we have multiple + * citations within the same footnote: for the comparison + * they become indistinguishable. Numbering between them is + * not controlled. Also combineCiteMarkers will see them in + * the wrong order (if we use this comparison), and will not + * be able to merge. To avoid these, we sort textually within + * each .getText() partition and add indexInPosition + * accordingly. + * + */ - for (TreeMap>> - xs : xxs.partitionValues()) { + // Sort within partitions + RangeKeyedMapList> xxs + = new RangeKeyedMapList<>(); - List oxs = new ArrayList<>(xs.keySet()); + for (RangeSort.RangeSortEntry v : vses) { + xxs.add(v.getRange(), v); + } - int indexInPartition = 0; - for (int i = 0; i < oxs.size(); i++) { - XTextRange a = oxs.get(i); - List> avs = xs.get(a); - for (int j = 0; j < avs.size(); j++) { - RangeSort.RangeSortEntry v = avs.get(j); - v.indexInPosition = indexInPartition++; - if (mapFootnotesToFootnoteMarks) { - // Adjust range if we are inside a footnote: - if (unoQI(XFootnote.class, v.range.getText()) != null) { - // Find the linking footnote marker: - XFootnote footer = unoQI(XFootnote.class, v.range.getText()); - // The footnote's anchor gives the correct position in the text: - v.range = footer.getAnchor(); + // build final list + List> res = new ArrayList<>(); + + for (TreeMap>> + xs : xxs.partitionValues()) { + + List oxs = new ArrayList<>(xs.keySet()); + + int indexInPartition = 0; + for (int i = 0; i < oxs.size(); i++) { + XTextRange a = oxs.get(i); + List> avs = xs.get(a); + for (int j = 0; j < avs.size(); j++) { + RangeSort.RangeSortEntry v = avs.get(j); + v.indexInPosition = indexInPartition++; + if (mapFootnotesToFootnoteMarks) { + // Adjust range if we are inside a footnote: + if (unoQI(XFootnote.class, v.range.getText()) != null) { + // Find the linking footnote marker: + XFootnote footer = unoQI(XFootnote.class, v.range.getText()); + // The footnote's anchor gives the correct position in the text: + v.range = footer.getAnchor(); + } } + res.add(v); } - res.add(v); } } + // convert + // List> + // to + // List> + return res.stream().map(e -> e).collect(Collectors.toList()); } - // convert - // List> - // to - // List> - return res.stream().map(e -> e).collect(Collectors.toList()); - } - /** - * Return JabRef reference mark names sorted by their visual positions. - * - * @param mapFootnotesToFootnoteMarks If true, sort reference - * marks in footnotes as if they appeared at the - * corresponding footnote mark. - * - * @return JabRef reference mark names sorted by these positions. - * - * Limitation: for two column layout visual (top-down, - * left-right) order does not match the expected (textual) - * order. - * - */ - public List - getVisuallySortedCitationGroupIDs(DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - WrappedTargetException, - NoDocumentException, - JabRefException { - CitationGroupsV001 cgs = this; - List> vses = - createVisualSortInput(cgs, - documentConnection, - mapFootnotesToFootnoteMarks); - - if (vses.size() != cgs.citationGroups.size()) { - throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " vses.size() != cgs.citationGroups.size()"); - } - - String messageOnFailureToObtainAFunctionalXTextViewCursor = - Localization.lang("Please move the cursor into the document text.") - + "\n" - + Localization.lang("To get the visual positions of your citations" - + " I need to move the cursor around," - + " but could not get it."); - List> sorted = - RangeSortVisual.visualSort(vses, - documentConnection, - messageOnFailureToObtainAFunctionalXTextViewCursor); - - if (sorted.size() != cgs.citationGroups.size()) { - // This Fired - throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " sorted.size() != cgs.citationGroups.size()"); - } - - return (sorted.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList())); - } + /** + * Return JabRef reference mark names sorted by their visual positions. + * + * @param mapFootnotesToFootnoteMarks If true, sort reference + * marks in footnotes as if they appeared at the + * corresponding footnote mark. + * + * @return JabRef reference mark names sorted by these positions. + * + * Limitation: for two column layout visual (top-down, + * left-right) order does not match the expected (textual) + * order. + * + */ + public List + getVisuallySortedCitationGroupIDs(DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + WrappedTargetException, + NoDocumentException, + JabRefException { + CitationGroupsV001.CitationGroups cgs = this; + List> vses = + createVisualSortInput(cgs, + documentConnection, + mapFootnotesToFootnoteMarks); + + if (vses.size() != cgs.citationGroups.size()) { + throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + + " vses.size() != cgs.citationGroups.size()"); + } - /** - * Calculate and return citation group IDs in visual order. - */ - public List - getCitationGroupIDsSortedWithinPartitions(DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - NoDocumentException, - WrappedTargetException { - // This is like getVisuallySortedCitationGroupIDs, - // but we skip the visualSort part. - CitationGroupsV001 cgs = this; - // boolean mapFootnotesToFootnoteMarks = false; - List> vses = - CitationGroupsV001.createVisualSortInput(cgs, - documentConnection, - mapFootnotesToFootnoteMarks); - - if (vses.size() != cgs.citationGroups.size()) { - throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" - + " vses.size() != cgs.citationGroups.size()"); - } - return (vses.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList())); - } + String messageOnFailureToObtainAFunctionalXTextViewCursor = + Localization.lang("Please move the cursor into the document text.") + + "\n" + + Localization.lang("To get the visual positions of your citations" + + " I need to move the cursor around," + + " but could not get it."); + List> sorted = + RangeSortVisual.visualSort(vses, + documentConnection, + messageOnFailureToObtainAFunctionalXTextViewCursor); + + if (sorted.size() != cgs.citationGroups.size()) { + // This Fired + throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + + " sorted.size() != cgs.citationGroups.size()"); + } - /** - * Citation group IDs in {@code globalOrder} - */ - public List - getSortedCitationGroupIDs() { - if (globalOrder.isEmpty()) { - throw new RuntimeException("getSortedCitationGroupIDs: not ordered yet"); + return (sorted.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList())); } - return globalOrder.get(); - } - public void - setGlobalOrder(List globalOrder) { - Objects.requireNonNull(globalOrder); - if (globalOrder.size() != citationGroups.size()) { - throw new RuntimeException( - "CitationGroupsV001.setGlobalOrder: globalOrder.size() != citationGroups.size()"); + /** + * Calculate and return citation group IDs in visual order. + */ + public List + getCitationGroupIDsSortedWithinPartitions(DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + NoDocumentException, + WrappedTargetException { + // This is like getVisuallySortedCitationGroupIDs, + // but we skip the visualSort part. + CitationGroupsV001.CitationGroups cgs = this; + // boolean mapFootnotesToFootnoteMarks = false; + List> vses = + CitationGroupsV001.CitationGroups.createVisualSortInput(cgs, + documentConnection, + mapFootnotesToFootnoteMarks); + + if (vses.size() != cgs.citationGroups.size()) { + throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" + + " vses.size() != cgs.citationGroups.size()"); + } + return (vses.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList())); } - this.globalOrder = Optional.of(globalOrder); - } - - public Optional getCitationGroup(CitationGroupID cgid) { - CitationGroup e = citationGroups.get(cgid); - return Optional.ofNullable(e); - } - /** - * Call this when the citation group is unquestionably there. - */ - public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { - CitationGroup e = citationGroups.get(cgid); - if (e == null) { - throw new RuntimeException("CitationGroupsV001.getCitationGroupOrThrow:" - + " the requested CitationGroup is not available"); + /** + * Citation group IDs in {@code globalOrder} + */ + public List getSortedCitationGroupIDs() { + if (globalOrder.isEmpty()) { + throw new RuntimeException("getSortedCitationGroupIDs: not ordered yet"); + } + return globalOrder.get(); } - return e; - } - - private Optional getReferenceMarkName(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.referenceMarkName); - } - private Optional getItcType(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.itcType); - } - - public int numberOfCitationGroups() { - return citationGroups.size(); - } - - public Optional getPageInfo(CitationGroupID cgid) { - return (getCitationGroup(cgid) - .map(cg -> cg.pageInfo) - .flatMap(x -> x)); - } + public void setGlobalOrder(List globalOrder) { + Objects.requireNonNull(globalOrder); + if (globalOrder.size() != citationGroups.size()) { + throw new RuntimeException( + "CitationGroupsV001.setGlobalOrder: globalOrder.size() != citationGroups.size()"); + } + this.globalOrder = Optional.of(globalOrder); + } - public Optional> - getCitations(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.citations); - } + public Optional getCitationGroup(CitationGroupID cgid) { + CitationGroup e = citationGroups.get(cgid); + return Optional.ofNullable(e); + } - public List - getSortedCitations(CitationGroupID cgid) { - Optional cg = getCitationGroup(cgid); - if (cg.isEmpty()) { - throw new RuntimeException("getSortedCitations: invalid cgid"); + /** + * Call this when the citation group is unquestionably there. + */ + public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { + CitationGroup e = citationGroups.get(cgid); + if (e == null) { + throw new RuntimeException("CitationGroupsV001.getCitationGroupOrThrow:" + + " the requested CitationGroup is not available"); + } + return e; } - return cg.get().getSortedCitations(); - } - /** - * Create a reference mark with the given name, at the - * end of position. - * - * To reduce the difference from the original representation, we - * only insist on having at least two characters inside reference - * marks. These may be ZERO_WIDTH_SPACE characters or other - * placeholder not likely to appear in a citation mark. - * - * This placeholder is only needed if the citation mark is - * otherwise empty (e.g. when we just create it). - * - * getFillCursorForCitationGroup yields a bracketed cursor, that - * can be used to fill in / overwrite the value inside. - * - * After each getFillCursorForCitationGroup, we require a call to - * cleanFillCursorForCitationGroup, which removes the brackets, - * unless if it would make the content less than two - * characters. If we need only one placeholder, we keep the left - * bracket. If we need two, then the content is empty. The - * removeBracketsFromEmpty parameter of - * cleanFillCursorForCitationGroup overrides this, and for empty - * citations it will remove the brackets, leaving an empty - * reference mark. The idea behind this is that we do not need to - * refill empty marks (itcTypes INVISIBLE_CIT), and the caller - * can tell us that we are dealing with one of these. - * - * Thus the only user-visible difference in citation marks is - * that instead of empty marks we use two brackets, for - * single-character marks we add a left bracket before. - * - * Character-attribute inheritance: updates inherit from the - * first character inside, not from the left. - * - * On return {@code position} is collapsed, and is after the - * inserted space, or at the end of the reference mark. - * - * @param documentConnection Connection to document. - * @param position Collapsed to its end. - * @param insertSpaceAfter We insert a space after the mark, that - * carries on format of characters from - * the original position. - * - * @param withoutBrackets Force empty reference mark (no brackets). - * For use with INVISIBLE_CIT. - * - */ - public CitationGroupID createCitationGroup(DocumentConnection documentConnection, - List citationKeys, - Optional pageInfo, - int itcType, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) - throws - CreationException, - NoDocumentException, - WrappedTargetException { + private Optional getReferenceMarkName(CitationGroupID cgid) { + return getCitationGroup(cgid).map(cg -> cg.referenceMarkName); + } - String xkey = - citationKeys.stream() - .collect(Collectors.joining(",")); + private Optional getItcType(CitationGroupID cgid) { + return getCitationGroup(cgid).map(cg -> cg.itcType); + } - String refMarkName = - getUniqueReferenceMarkName(documentConnection, - xkey, - itcType); + public int numberOfCitationGroups() { + return citationGroups.size(); + } - CitationGroupID cgid = new CitationGroupID(refMarkName); + public Optional getPageInfo(CitationGroupID cgid) { + return (getCitationGroup(cgid) + .map(cg -> cg.pageInfo) + .flatMap(x -> x)); + } - List citations = - citationKeys.stream() - .map(Citation::new) - .collect(Collectors.toList()); + public Optional> getCitations(CitationGroupID cgid) { + return getCitationGroup(cgid).map(cg -> cg.citations); + } + + public List getSortedCitations(CitationGroupID cgid) { + Optional cg = getCitationGroup(cgid); + if (cg.isEmpty()) { + throw new RuntimeException("getSortedCitations: invalid cgid"); + } + return cg.get().getSortedCitations(); + } - /* - * Apply to document + /** + * Create a reference mark with the given name, at the + * end of position. + * + * To reduce the difference from the original representation, we + * only insist on having at least two characters inside reference + * marks. These may be ZERO_WIDTH_SPACE characters or other + * placeholder not likely to appear in a citation mark. + * + * This placeholder is only needed if the citation mark is + * otherwise empty (e.g. when we just create it). + * + * getFillCursorForCitationGroup yields a bracketed cursor, that + * can be used to fill in / overwrite the value inside. + * + * After each getFillCursorForCitationGroup, we require a call to + * cleanFillCursorForCitationGroup, which removes the brackets, + * unless if it would make the content less than two + * characters. If we need only one placeholder, we keep the left + * bracket. If we need two, then the content is empty. The + * removeBracketsFromEmpty parameter of + * cleanFillCursorForCitationGroup overrides this, and for empty + * citations it will remove the brackets, leaving an empty + * reference mark. The idea behind this is that we do not need to + * refill empty marks (itcTypes INVISIBLE_CIT), and the caller + * can tell us that we are dealing with one of these. + * + * Thus the only user-visible difference in citation marks is + * that instead of empty marks we use two brackets, for + * single-character marks we add a left bracket before. + * + * Character-attribute inheritance: updates inherit from the + * first character inside, not from the left. + * + * On return {@code position} is collapsed, and is after the + * inserted space, or at the end of the reference mark. + * + * @param documentConnection Connection to document. + * @param position Collapsed to its end. + * @param insertSpaceAfter We insert a space after the mark, that + * carries on format of characters from + * the original position. + * + * @param withoutBrackets Force empty reference mark (no brackets). + * For use with INVISIBLE_CIT. + * */ + public CitationGroupID createCitationGroup(DocumentConnection documentConnection, + List citationKeys, + Optional pageInfo, + int itcType, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) + throws + CreationException, + NoDocumentException, + WrappedTargetException { + + String xkey = + citationKeys.stream() + .collect(Collectors.joining(",")); + + String refMarkName = + Codec.getUniqueReferenceMarkName(documentConnection, + xkey, + itcType); + + CitationGroupID cgid = new CitationGroupID(refMarkName); + + List citations = + citationKeys.stream() + .map(Citation::new) + .collect(Collectors.toList()); - StorageBase.NamedRange sr = createReferenceMarkForCitationGroup( - this.citationStorageManager, - documentConnection, - refMarkName, - position, - insertSpaceAfter, - withoutBrackets); - - CitationGroup cg = new CitationGroup(cgid, - sr, - itcType, - citations, - pageInfo, - refMarkName); - - // add to our data - this.citationGroups.put(cgid, cg); - // invalidate globalOrder. - // TODO: look out for localOrder! - this.globalOrder = Optional.empty(); - - return cgid; - } - - private static StorageBase.NamedRange - createReferenceMarkForCitationGroup(StorageBase.NamedRangeManager manager, - DocumentConnection documentConnection, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) - throws - CreationException { - - return manager.create(documentConnection, - refMarkName, - position, - insertSpaceAfter, - withoutBrackets); - } - - /* - * Remove it from the {@code this} and the document. - * - * TODO: either invalidate or update the extra data we are storing - * (bibliography). Update may be complicated, since we do - * not know how the bibliography was generated: it was partially done - * outside CitationGroupsV001, and we did not store how. - */ - public void removeCitationGroups(List cgs, DocumentConnection documentConnection) - throws - WrappedTargetException, - NoDocumentException, - NoSuchElementException { - - for (CitationGroup cg : cgs) { - //documentConnection.removeReferenceMark(cg.referenceMarkName); - cg.cgRangeStorage.removeFromDocument(documentConnection); - this.citationGroups.remove(cg.cgid); - this.globalOrder.map(l -> l.remove(cg.cgid)); - - // Invalidate CitedKeys - this.citedKeysAfterDatabaseLookup = Optional.empty(); - this.bibliography = Optional.empty(); /* - * this.citedKeysAfterDatabaseLookup.map(cks -> cks.forgetCitationGroup(cg.cgid)); - * this.bibliography.map(cks -> cks.forgetCitationGroup(cg.cgid)); + * Apply to document */ + StorageBase.NamedRange sr = createReferenceMarkForCitationGroup( + this.citationStorageManager, + documentConnection, + refMarkName, + position, + insertSpaceAfter, + withoutBrackets); + + CitationGroup cg = new CitationGroup(cgid, + sr, + itcType, + citations, + pageInfo, + refMarkName); + + // add to our data + this.citationGroups.put(cgid, cg); + // invalidate globalOrder. + // TODO: look out for localOrder! + this.globalOrder = Optional.empty(); + + return cgid; } - } - - public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) - throws - WrappedTargetException, - NoDocumentException, - NoSuchElementException { - - removeCitationGroups(Collections.singletonList(cg), documentConnection); - } - - /** - * Remove brackets, but if the result would become empty, leave - * them; if the result would be a single characer, leave the left bracket. - * - * @param removeBracketsFromEmpty is intended to force removal if - * we are working on an "Empty citation" (INVISIBLE_CIT). - */ - public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, - CitationGroupID cgid) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - cg.cgRangeStorage.cleanFillCursor(documentConnection); - } - - /** - * Cursor for the reference marks as is, not prepared for filling, - * but does not need cleanFillCursorForCitationGroup either. - */ - public XTextCursor getRawCursorForCitationGroup(CitationGroupID cgid, - DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return cg.cgRangeStorage.getRawCursor(documentConnection); - } - - public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, - CitationGroupID cgid) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return cg.cgRangeStorage.getFillCursor(documentConnection); - } - - /** - * Produce a reference mark name for JabRef for the given citation - * key and itcType that does not yet appear among the reference - * marks of the document. - * - * @param bibtexKey The citation key. - * @param itcType Encodes the effect of withText and - * inParenthesis options. - * - * The first occurrence of bibtexKey gets no serial number, the - * second gets 0, the third 1 ... - * - * Or the first unused in this series, after removals. - */ - private String getUniqueReferenceMarkName(DocumentConnection documentConnection, - String bibtexKey, - int itcType) - throws NoDocumentException { - - XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); - int i = 0; - String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; - while (xNamedRefMarks.hasByName(name)) { - name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; - i++; - } - return name; - } - - /** - * This is what we get back from parsing a refMarkName. - * - */ - private static class ParsedRefMark { - /** "", "0", "1" ... */ - public String i; - /** in-text-citation type */ - public int itcType; - /** Citation keys embedded in the reference mark. */ - public List citationKeys; - ParsedRefMark(String i, int itcType, List citationKeys) { - this.i = i; - this.itcType = itcType; - this.citationKeys = citationKeys; + private static StorageBase.NamedRange + createReferenceMarkForCitationGroup(StorageBase.NamedRangeManager manager, + DocumentConnection documentConnection, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) + throws + CreationException { + + return manager.create(documentConnection, + refMarkName, + position, + insertSpaceAfter, + withoutBrackets); + } + + /* + * Remove it from the {@code this} and the document. + * + * TODO: either invalidate or update the extra data we are storing + * (bibliography). Update may be complicated, since we do + * not know how the bibliography was generated: it was partially done + * outside CitationGroupsV001, and we did not store how. + */ + public void removeCitationGroups(List cgs, DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException { + + for (CitationGroup cg : cgs) { + //documentConnection.removeReferenceMark(cg.referenceMarkName); + cg.cgRangeStorage.removeFromDocument(documentConnection); + this.citationGroups.remove(cg.cgid); + this.globalOrder.map(l -> l.remove(cg.cgid)); + + // Invalidate CitedKeys + this.citedKeysAfterDatabaseLookup = Optional.empty(); + this.bibliography = Optional.empty(); + /* + * this.citedKeysAfterDatabaseLookup.map(cks -> cks.forgetCitationGroup(cg.cgid)); + * this.bibliography.map(cks -> cks.forgetCitationGroup(cg.cgid)); + */ + } } - } - /** - * Parse a JabRef reference mark name. - * - * @return Optional.empty() on failure. - * - */ - private static Optional parseRefMarkName(String refMarkName) { + public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException { - Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); - if (!citeMatcher.find()) { - return Optional.empty(); + removeCitationGroups(Collections.singletonList(cg), documentConnection); } - List keys = Arrays.asList(citeMatcher.group(3).split(",")); - String i = citeMatcher.group(1); - int itcType = Integer.parseInt(citeMatcher.group(2)); - return (Optional.of(new CitationGroupsV001.ParsedRefMark(i, itcType, keys))); - } + /** + * Remove brackets, but if the result would become empty, leave + * them; if the result would be a single characer, leave the left bracket. + * + * @param removeBracketsFromEmpty is intended to force removal if + * we are working on an "Empty citation" (INVISIBLE_CIT). + */ + public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, + CitationGroupID cgid) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + cg.cgRangeStorage.cleanFillCursor(documentConnection); + } - /** - * Extract the list of citation keys from a reference mark name. - * - * @param name The reference mark name. - * @return The list of citation keys encoded in the name. - * - * In case of duplicated citation keys, - * only the first occurrence. - * Otherwise their order is preserved. - * - * If name does not match CITE_PATTERN, - * an empty list of strings is returned. - */ - private List parseRefMarkNameToUniqueCitationKeys(String name) { - Optional op = parseRefMarkName(name); - return (op.map(parsedRefMark -> - parsedRefMark.citationKeys.stream() - .distinct() - .collect(Collectors.toList())) - .orElseGet(ArrayList::new)); - } + /** + * Cursor for the reference marks as is, not prepared for filling, + * but does not need cleanFillCursorForCitationGroup either. + */ + public XTextCursor getRawCursorForCitationGroup(CitationGroupID cgid, + DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + return cg.cgRangeStorage.getRawCursor(documentConnection); + } - /** - * @return true if name matches the pattern used for JabRef - * reference mark names. - */ - private static boolean isJabRefReferenceMarkName(String name) { - return (CITE_PATTERN.matcher(name).find()); - } + public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, + CitationGroupID cgid) + throws + NoDocumentException, + WrappedTargetException, + CreationException { - /** - * Filter a list of reference mark names by `isJabRefReferenceMarkName` - * - * @param names The list to be filtered. - */ - private static List filterIsJabRefReferenceMarkName(List names) { - return (names - .stream() - .filter(CitationGroupsV001::isJabRefReferenceMarkName) - .collect(Collectors.toList())); - } + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + return cg.cgRangeStorage.getFillCursor(documentConnection); + } - /** - * Get reference mark names from the document matching the pattern - * used for JabRef reference mark names. - * - * Note: the names returned are in arbitrary order. - * - * - * - */ - private List getJabRefReferenceMarkNames(StorageBase.NamedRangeManager manager, - DocumentConnection documentConnection) - throws - NoDocumentException { - List allNames = manager.getUsedNames(documentConnection); - return filterIsJabRefReferenceMarkName(allNames); - } - /** - * For each name in referenceMarkNames set types[i] and - * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) - * - * @param referenceMarkNames Should only contain parsable names. - * @param types OUT Must be same length as referenceMarkNames. - * @param bibtexKeys OUT First level must be same length as referenceMarkNames. - */ - private static void parseRefMarkNamesToArrays(List referenceMarkNames, - int[] types, - String[][] bibtexKeys) { - - final int nRefMarks = referenceMarkNames.size(); - assert (types.length == nRefMarks); - assert (bibtexKeys.length == nRefMarks); - for (int i = 0; i < nRefMarks; i++) { - final String name = referenceMarkNames.get(i); - Optional op = parseRefMarkName(name); - if (op.isEmpty()) { - // We have a problem. We want types[i] and bibtexKeys[i] - // to correspond to referenceMarkNames.get(i). - // And do not want null in bibtexKeys (or error code in types) - // on return. - throw new IllegalArgumentException( - "parseRefMarkNamesToArrays expects parsable referenceMarkNames"); - } - ParsedRefMark ov = op.get(); - types[i] = ov.itcType; - bibtexKeys[i] = ov.citationKeys.toArray(String[]::new); - } - } /** * Extract citation keys from names of referenceMarks in the document. @@ -1116,8 +954,9 @@ private List findCitedKeys(DocumentConnection documentConnection) WrappedTargetException, NoDocumentException { - List names = getJabRefReferenceMarkNames(this.citationStorageManager, - documentConnection); + List names = + Codec.getJabRefReferenceMarkNames(this.citationStorageManager, + documentConnection); // assert it supports XTextContent XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); @@ -1129,7 +968,7 @@ private List findCitedKeys(DocumentConnection documentConnection) // Collect to a flat list while keep only the first appearance. List keys = new ArrayList<>(); for (String name1 : names) { - List newKeys = parseRefMarkNameToUniqueCitationKeys(name1); + List newKeys = Codec.parseRefMarkNameToUniqueCitationKeys(name1); for (String key : newKeys) { if (!keys.contains(key)) { keys.add(key); @@ -1252,6 +1091,17 @@ List footnoteMarkRanges(DocumentConnection documentConnect return xs; } + public void show() { + System.out.printf("CitationGroupsV001%n"); + System.out.printf(" citationGroups.size: %d%n", citationGroups.size()); + System.out.printf(" pageInfoThrash.size: %d%n", pageInfoThrash.size()); + System.out.printf(" globalOrder: %s%n", + (globalOrder.isEmpty() + ? "isEmpty" + : String.format("%d", globalOrder.get().size()))); + } +} + /** * unoQI : short for UnoRuntime.queryInterface * @@ -1263,37 +1113,39 @@ private static T unoQI(Class zInterface, return UnoRuntime.queryInterface(zInterface, object); } - static class CitationGroupID { - String id; - CitationGroupID(String id) { - this.id = id; - } - /** - * CitationEntry needs refMark or other identifying string - */ - String asString() { - return id; + + /** + * Identifies a citation with the citation group containing it and + * its storage index within. + */ + public static class CitationPath { + CitationGroupID group; + int storageIndexInGroup; + CitationPath(CitationGroupID group, + int storageIndexInGroup) { + this.group = group; + this.storageIndexInGroup = storageIndexInGroup; } } - static class Citation implements CitationSort.ComparableCitation { - /** key in database */ + public static class CitedKey implements CitationSort.ComparableCitation { String citationKey; + LinkedHashSet where; Optional db; - Optional number; - Optional uniqueLetter; - - /* missing: something that differentiates this from other - * citations of the same citationKey - */ + Optional number; // For Numbered citation styles. + Optional uniqueLetter; // For AuthorYear citation styles. + Optional normCitMarker; // For AuthorYear citation styles. - Citation(String citationKey) { + CitedKey(String citationKey, CitationPath p, Citation cit) { this.citationKey = citationKey; - this.db = Optional.empty(); - this.number = Optional.empty(); - this.uniqueLetter = Optional.empty(); + this.where = new LinkedHashSet<>(); // remember order + this.where.add(p); + this.db = cit.db; + this.number = cit.number; + this.uniqueLetter = cit.uniqueLetter; + this.normCitMarker = Optional.empty(); } @Override @@ -1307,106 +1159,269 @@ public Optional getBibEntry(){ ? Optional.of(db.get().entry) : Optional.empty()); } - } - static List makeIndices(int n) { - return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); - } + /** + * Appends to end of {@code where} + */ + void addPath(CitationPath p, Citation cit) { + this.where.add(p); + if (cit.db != this.db) { + throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); + } + if (cit.number != this.number) { + throw new RuntimeException("CitedKey.addPath: mismatch on cit.number"); + } + if (cit.uniqueLetter != this.uniqueLetter) { + throw new RuntimeException("CitedKey.addPath: mismatch on cit.uniqueLetter"); + } + } - static class CitationGroup { - CitationGroupID cgid; - StorageBase.NamedRange cgRangeStorage; - int itcType; - List citations; - List localOrder; - // Currently pageInfo belongs to the group - Optional pageInfo; + void lookupInDatabases(List databases) { + this.db = CitationDatabaseLookup.lookup(databases, this.citationKey); + } + + void distributeDatabaseLookupResult(CitationGroupsV001.CitationGroups cgs) { + cgs.setDatabaseLookupResults(where, db); + } + + void distributeNumber(CitationGroupsV001.CitationGroups cgs) { + cgs.setNumbers(where, number); + } + + void distributeUniqueLetter(CitationGroupsV001.CitationGroups cgs) { + cgs.setUniqueLetters(where, uniqueLetter); + } + } // class CitedKey + + public static class CitedKeys { /** - * Locator in document + * Order-preserving map from citation keys to associated data. */ - String referenceMarkName; + LinkedHashMap data; - CitationGroup( - CitationGroupID cgid, - StorageBase.NamedRange cgRangeStorage, - int itcType, - List citations, - Optional pageInfo, - String referenceMarkName) { - this.cgid = cgid; - this.cgRangeStorage = cgRangeStorage; - this.itcType = itcType; - this.citations = citations; - this.pageInfo = pageInfo; - this.referenceMarkName = referenceMarkName; - this.localOrder = makeIndices(citations.size()); + CitedKeys(LinkedHashMap data) { + this.data = data; } - List - getSortedCitations() { - List res = new ArrayList<>(citations.size()); - for (int i : localOrder) { - res.add(citations.get(i)); + /** + * The cited keys in sorted order. + */ + public List values() { + return new ArrayList<>(data.values()); + } + + /** + * Sort entries for the bibliography. + */ + void sortByComparator(Comparator entryComparator) { + List cks = new ArrayList<>(data.values()); + cks.sort(new CitationSort.CitationComparator(entryComparator, true)); + LinkedHashMap newData = new LinkedHashMap<>(); + for (CitedKey ck : cks) { + newData.put(ck.citationKey, ck); } - return res; + data = newData; } - List - getSortedNumbers() { - List cits = getSortedCitations(); - return (cits.stream() - .map(cit -> cit.number.orElseThrow(RuntimeException::new)) - .collect(Collectors.toList())); + void numberCitedKeysInCurrentOrder() { + int i = 1; + for (CitedKey ck : data.values()) { + ck.number = Optional.of(i); // was: -1 for UndefinedBibtexEntry + i++; + } } - class CitationAndIndex implements CitationSort.ComparableCitation { - Citation c; - int i; - CitationAndIndex(Citation c, int i) { - this.c = c; - this.i = i; + void lookupInDatabases(List databases) { + for (CitedKey ck : this.data.values()) { + ck.lookupInDatabases(databases); } + } - @Override - public String getCitationKey(){ - return c.getCitationKey(); + void distributeDatabaseLookupResults(CitationGroupsV001.CitationGroups cgs) { + for (CitedKey ck : this.data.values()) { + ck.distributeDatabaseLookupResult(cgs); } + } - @Override - public Optional getBibEntry(){ - return c.getBibEntry(); + void distributeNumbers(CitationGroupsV001.CitationGroups cgs) { + for (CitedKey ck : this.data.values()) { + ck.distributeNumber(cgs); + } + } + + void distributeUniqueLetters(CitationGroupsV001.CitationGroups cgs) { + for (CitedKey ck : this.data.values()) { + ck.distributeUniqueLetter(cgs); } } + } // class CitedKeys + + + /** + * This is what we get back from parsing a refMarkName. + * + */ + private static class ParsedRefMark { + /** "", "0", "1" ... */ + public String i; + /** in-text-citation type */ + public int itcType; + /** Citation keys embedded in the reference mark. */ + public List citationKeys; + + ParsedRefMark(String i, int itcType, List citationKeys) { + this.i = i; + this.itcType = itcType; + this.citationKeys = citationKeys; + } + } + + private static class Codec { + private static final String BIB_CITATION = "JR_cite"; + private static final Pattern CITE_PATTERN = + Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + + /** - * Sort citations for presentation within a CitationGroup. + * Produce a reference mark name for JabRef for the given citation + * key and itcType that does not yet appear among the reference + * marks of the document. + * + * @param bibtexKey The citation key. + * @param itcType Encodes the effect of withText and + * inParenthesis options. + * + * The first occurrence of bibtexKey gets no serial number, the + * second gets 0, the third 1 ... + * + * Or the first unused in this series, after removals. */ - void imposeLocalOrderByComparator(Comparator entryComparator) { - List cks = new ArrayList<>(); - for (int i = 0; i < citations.size(); i++) { - Citation c = citations.get(i); - cks.add(new CitationAndIndex(c, i)); + public static String getUniqueReferenceMarkName(DocumentConnection documentConnection, + String bibtexKey, + int itcType) + throws NoDocumentException { + + XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); + int i = 0; + String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; + while (xNamedRefMarks.hasByName(name)) { + name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; + i++; } - cks.sort(new CitationSort.CitationComparator(entryComparator, true)); + return name; + } - List o = new ArrayList<>(); - for (CitationAndIndex ck : cks) { - o.add(ck.i); + /** + * Parse a JabRef reference mark name. + * + * @return Optional.empty() on failure. + * + */ + private static Optional parseRefMarkName(String refMarkName) { + + Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); + if (!citeMatcher.find()) { + return Optional.empty(); } - this.localOrder = o; + + List keys = Arrays.asList(citeMatcher.group(3).split(",")); + String i = citeMatcher.group(1); + int itcType = Integer.parseInt(citeMatcher.group(2)); + return (Optional.of(new CitationGroupsV001.ParsedRefMark(i, itcType, keys))); } - } - public void show() { - System.out.printf("CitationGroupsV001%n"); - System.out.printf(" citationGroups.size: %d%n", citationGroups.size()); - System.out.printf(" pageInfoThrash.size: %d%n", pageInfoThrash.size()); - System.out.printf(" globalOrder: %s%n", - (globalOrder.isEmpty() - ? "isEmpty" - : String.format("%d", globalOrder.get().size()))); - } + /** + * Extract the list of citation keys from a reference mark name. + * + * @param name The reference mark name. + * @return The list of citation keys encoded in the name. + * + * In case of duplicated citation keys, + * only the first occurrence. + * Otherwise their order is preserved. + * + * If name does not match CITE_PATTERN, + * an empty list of strings is returned. + */ + private static List parseRefMarkNameToUniqueCitationKeys(String name) { + Optional op = parseRefMarkName(name); + return (op.map(parsedRefMark -> + parsedRefMark.citationKeys.stream() + .distinct() + .collect(Collectors.toList())) + .orElseGet(ArrayList::new)); + } + + /** + * @return true if name matches the pattern used for JabRef + * reference mark names. + */ + private static boolean isJabRefReferenceMarkName(String name) { + return (CITE_PATTERN.matcher(name).find()); + } -} // class citationGroups + /** + * Filter a list of reference mark names by `isJabRefReferenceMarkName` + * + * @param names The list to be filtered. + */ + private static List filterIsJabRefReferenceMarkName(List names) { + return (names + .stream() + .filter(CitationGroupsV001.Codec::isJabRefReferenceMarkName) + .collect(Collectors.toList())); + } + /** + * Get reference mark names from the document matching the pattern + * used for JabRef reference mark names. + * + * Note: the names returned are in arbitrary order. + * + * + * + */ + private static List getJabRefReferenceMarkNames(StorageBase.NamedRangeManager manager, + DocumentConnection documentConnection) + throws + NoDocumentException { + List allNames = manager.getUsedNames(documentConnection); + return filterIsJabRefReferenceMarkName(allNames); + } + + /** + * For each name in referenceMarkNames set types[i] and + * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) + * + * @param referenceMarkNames Should only contain parsable names. + * @param types OUT Must be same length as referenceMarkNames. + * @param bibtexKeys OUT First level must be same length as referenceMarkNames. + */ + private static void parseRefMarkNamesToArrays(List referenceMarkNames, + int[] types, + String[][] bibtexKeys) { + + final int nRefMarks = referenceMarkNames.size(); + assert (types.length == nRefMarks); + assert (bibtexKeys.length == nRefMarks); + for (int i = 0; i < nRefMarks; i++) { + final String name = referenceMarkNames.get(i); + Optional op = parseRefMarkName(name); + if (op.isEmpty()) { + // We have a problem. We want types[i] and bibtexKeys[i] + // to correspond to referenceMarkNames.get(i). + // And do not want null in bibtexKeys (or error code in types) + // on return. + throw new IllegalArgumentException( + "parseRefMarkNamesToArrays expects parsable referenceMarkNames"); + } + ParsedRefMark ov = op.get(); + types[i] = ov.itcType; + bibtexKeys[i] = ov.citationKeys.toArray(String[]::new); + } + } + + } +} // class CitationGroupsV001 diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d687c32dd49..0a523a95719 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -468,7 +468,7 @@ private static T unoQI(Class zInterface, * @param requireSeparation Report range pairs that only share a boundary. * @param reportAtMost Limit number of overlaps reported (0 for no limit) */ - public void checkRangeOverlaps(CitationGroupsV001 cgs, + public void checkRangeOverlaps(CitationGroupsV001.CitationGroups cgs, DocumentConnection documentConnection, boolean requireSeparation, int reportAtMost) @@ -553,7 +553,7 @@ public List getCitationEntries() CreationException { DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); int n = cgs.numberOfCitationGroups(); List citations = new ArrayList<>(n); @@ -581,7 +581,7 @@ public List getCitationEntries() * @param htmlMarkup If true, the text belonging to the * reference mark is surrounded by bold html tag. */ - private String getCitationContext(CitationGroupsV001 cgs, + private String getCitationContext(CitationGroupsV001.CitationGroups cgs, CitationGroupsV001.CitationGroupID cgid, DocumentConnection documentConnection, int charBefore, @@ -812,7 +812,7 @@ private String normalizedCitationMarkerForNormalStyle(CitationGroupsV001.CitedKe * Depends on: style, citations and their order. */ void createUniqueLetters(CitationGroupsV001.CitedKeys sortedCitedKeys, - CitationGroupsV001 cgs) { + CitationGroupsV001.CitationGroups cgs) { // ncm2clks: ncm (normCitMarker) to clks (clashing keys : list of citation keys fighting for it). // @@ -895,7 +895,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * markers are the citation keys themselves, separated by commas. */ private static Map - produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroupsV001 cgs, + produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroupsV001.CitationGroups cgs, OOBibStyle style) throws BibEntryNotFoundException { @@ -935,7 +935,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * */ private static Map - produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroupsV001 cgs, + produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroupsV001.CitationGroups cgs, OOBibStyle style) throws BibEntryNotFoundException { @@ -964,7 +964,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * when the bibliography is not sorted by position. */ private Map - produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroupsV001 cgs, + produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroupsV001.CitationGroups cgs, OOBibStyle style) { assert style.isNumberEntries(); assert !style.isSortByPosition(); @@ -997,7 +997,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * @param style Bibliography style. */ private Map - produceCitationMarkersForNormalStyle(CitationGroupsV001 cgs, + produceCitationMarkersForNormalStyle(CitationGroupsV001.CitationGroups cgs, OOBibStyle style) throws BibEntryNotFoundException { @@ -1124,7 +1124,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes } private static void fillCitationMarkInCursor(DocumentConnection documentConnection, - CitationGroupsV001 cgs, + CitationGroupsV001.CitationGroups cgs, CitationGroupsV001.CitationGroupID cgid, XTextCursor cursor, String citationText, @@ -1224,7 +1224,7 @@ private static void italicizeRangeFromPosition(XTextCursor position, * @param position OUT: left collapsed, just after the space inserted, * or after the reference mark inserted. */ - private void insertReferenceMark(CitationGroupsV001 cgs, + private void insertReferenceMark(CitationGroupsV001.CitationGroups cgs, DocumentConnection documentConnection, List citationKeys, Optional pageInfo, @@ -1430,7 +1430,7 @@ public void insertCitation(List entries, } DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); // TODO: imposeLocalOrder boolean useUndoContext = true; @@ -1619,7 +1619,7 @@ public void insertCitation(List entries, * */ private void applyNewCitationMarkers(DocumentConnection documentConnection, - CitationGroupsV001 cgs, + CitationGroupsV001.CitationGroups cgs, Map citMarkers, OOBibStyle style) throws @@ -1699,12 +1699,12 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, */ static class ProduceCitationMarkersResult { - CitationGroupsV001 cgs; + CitationGroupsV001.CitationGroups cgs; /** citation markers */ Map citMarkers; - ProduceCitationMarkersResult(CitationGroupsV001 cgs, + ProduceCitationMarkersResult(CitationGroupsV001.CitationGroups cgs, Map citMarkers) { this.cgs = cgs; this.citMarkers = citMarkers; @@ -1747,7 +1747,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d UnknownPropertyException, JabRefException { - CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); cgs.lookupEntriesInDatabases( databases ); @@ -1823,7 +1823,8 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d * * Used by rebuildBibTextSection */ - private List sortEntriesByRefMarkNames(CitationGroupsV001 cgs) { + private List + sortEntriesByRefMarkNames(CitationGroupsV001.CitationGroups cgs) { Set seen = new HashSet<>(); List res = new ArrayList<>(); for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { @@ -1849,7 +1850,7 @@ private List sortEntriesByRefMarkNames(CitationGrou */ private void rebuildBibTextSection(DocumentConnection documentConnection, OOBibStyle style, - CitationGroupsV001 cgs, + CitationGroupsV001.CitationGroups cgs, CitationGroupsV001.CitedKeys bibliography) throws NoSuchElementException, @@ -1883,7 +1884,7 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, */ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, XTextCursor cursor, - CitationGroupsV001 cgs, + CitationGroupsV001.CitationGroups cgs, CitationGroupsV001.CitedKeys bibliography, OOBibStyle style, String parFormat) @@ -2089,7 +2090,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) * Assumes the section named `OOBibBase.BIB_SECTION_NAME` exists. */ private void populateBibTextSection(DocumentConnection documentConnection, - CitationGroupsV001 cgs, + CitationGroupsV001.CitationGroups cgs, CitationGroupsV001.CitedKeys bibliography, OOBibStyle style) throws @@ -2173,7 +2174,7 @@ public void combineCiteMarkers(List databases, final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); try { documentConnection.enterUndoContext("Merge citations"); @@ -2547,7 +2548,7 @@ public void unCombineCiteMarkers(List databases, final boolean useLockControllers = true; DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); try { documentConnection.enterUndoContext("Separate citations"); @@ -2694,10 +2695,8 @@ static class ExportCitedHelperResult { * * Does not refresh the bibliography. */ - public ExportCitedHelperResult exportCitedHelper( - List databases, - OOBibStyle style - ) + public ExportCitedHelperResult exportCitedHelper(List databases, + OOBibStyle style) throws WrappedTargetException, NoSuchElementException, @@ -2741,7 +2740,7 @@ public ExportCitedHelperResult exportCitedHelper( // DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); CitationGroupsV001.CitedKeys cks = cgs.getCitedKeys(); cks.lookupInDatabases( databases ); @@ -2897,7 +2896,8 @@ public List updateDocumentActionHelper(List databases, documentConnection.enterUndoContext("Refresh bibliography"); boolean requireSeparation = false; - CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); + CitationGroupsV001.CitationGroups cgs = + new CitationGroupsV001.CitationGroups(documentConnection); int maxReportedOverlaps = 10; checkRangeOverlaps(cgs, this.xDocumentConnection, requireSeparation, maxReportedOverlaps); final boolean useLockControllers = true; From c9ce935c9037505be4ca1759a885404a0bc3adff Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 21:21:42 +0200 Subject: [PATCH 0515/1068] refactor: bring Codec forward --- .../gui/openoffice/CitationGroupsV001.java | 335 +++++++++--------- 1 file changed, 168 insertions(+), 167 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 7df060a7689..1af6a98a3b4 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -49,6 +49,171 @@ class CitationGroupsV001 { private static final Logger LOGGER = LoggerFactory.getLogger(CitedKeys.class); + /** + * This is what we get back from parsing a refMarkName. + * + */ + private static class ParsedRefMark { + /** "", "0", "1" ... */ + public String i; + /** in-text-citation type */ + public int itcType; + /** Citation keys embedded in the reference mark. */ + public List citationKeys; + + ParsedRefMark(String i, int itcType, List citationKeys) { + this.i = i; + this.itcType = itcType; + this.citationKeys = citationKeys; + } + } + + private static class Codec { + private static final String BIB_CITATION = "JR_cite"; + private static final Pattern CITE_PATTERN = + Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + + + /** + * Produce a reference mark name for JabRef for the given citation + * key and itcType that does not yet appear among the reference + * marks of the document. + * + * @param bibtexKey The citation key. + * @param itcType Encodes the effect of withText and + * inParenthesis options. + * + * The first occurrence of bibtexKey gets no serial number, the + * second gets 0, the third 1 ... + * + * Or the first unused in this series, after removals. + */ + public static String getUniqueReferenceMarkName(DocumentConnection documentConnection, + String bibtexKey, + int itcType) + throws NoDocumentException { + + XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); + int i = 0; + String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; + while (xNamedRefMarks.hasByName(name)) { + name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; + i++; + } + return name; + } + + /** + * Parse a JabRef reference mark name. + * + * @return Optional.empty() on failure. + * + */ + private static Optional parseRefMarkName(String refMarkName) { + + Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); + if (!citeMatcher.find()) { + return Optional.empty(); + } + + List keys = Arrays.asList(citeMatcher.group(3).split(",")); + String i = citeMatcher.group(1); + int itcType = Integer.parseInt(citeMatcher.group(2)); + return (Optional.of(new CitationGroupsV001.ParsedRefMark(i, itcType, keys))); + } + + /** + * Extract the list of citation keys from a reference mark name. + * + * @param name The reference mark name. + * @return The list of citation keys encoded in the name. + * + * In case of duplicated citation keys, + * only the first occurrence. + * Otherwise their order is preserved. + * + * If name does not match CITE_PATTERN, + * an empty list of strings is returned. + */ + private static List parseRefMarkNameToUniqueCitationKeys(String name) { + Optional op = parseRefMarkName(name); + return (op.map(parsedRefMark -> + parsedRefMark.citationKeys.stream() + .distinct() + .collect(Collectors.toList())) + .orElseGet(ArrayList::new)); + } + + /** + * @return true if name matches the pattern used for JabRef + * reference mark names. + */ + private static boolean isJabRefReferenceMarkName(String name) { + return (CITE_PATTERN.matcher(name).find()); + } + + /** + * Filter a list of reference mark names by `isJabRefReferenceMarkName` + * + * @param names The list to be filtered. + */ + private static List filterIsJabRefReferenceMarkName(List names) { + return (names + .stream() + .filter(CitationGroupsV001.Codec::isJabRefReferenceMarkName) + .collect(Collectors.toList())); + } + /** + * Get reference mark names from the document matching the pattern + * used for JabRef reference mark names. + * + * Note: the names returned are in arbitrary order. + * + * + * + */ + private static List getJabRefReferenceMarkNames(StorageBase.NamedRangeManager manager, + DocumentConnection documentConnection) + throws + NoDocumentException { + List allNames = manager.getUsedNames(documentConnection); + return filterIsJabRefReferenceMarkName(allNames); + } + + /** + * For each name in referenceMarkNames set types[i] and + * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) + * + * @param referenceMarkNames Should only contain parsable names. + * @param types OUT Must be same length as referenceMarkNames. + * @param bibtexKeys OUT First level must be same length as referenceMarkNames. + */ + private static void parseRefMarkNamesToArrays(List referenceMarkNames, + int[] types, + String[][] bibtexKeys) { + + final int nRefMarks = referenceMarkNames.size(); + assert (types.length == nRefMarks); + assert (bibtexKeys.length == nRefMarks); + for (int i = 0; i < nRefMarks; i++) { + final String name = referenceMarkNames.get(i); + Optional op = parseRefMarkName(name); + if (op.isEmpty()) { + // We have a problem. We want types[i] and bibtexKeys[i] + // to correspond to referenceMarkNames.get(i). + // And do not want null in bibtexKeys (or error code in types) + // on return. + throw new IllegalArgumentException( + "parseRefMarkNamesToArrays expects parsable referenceMarkNames"); + } + ParsedRefMark ov = op.get(); + types[i] = ov.itcType; + bibtexKeys[i] = ov.citationKeys.toArray(String[]::new); + } + } + + } + static class CitationGroupID { String id; CitationGroupID(String id) { @@ -244,12 +409,12 @@ public CitationGroups(DocumentConnection documentConnection) // Now we have almost every information from the document about citations. // What is left out: the ranges controlled by the reference marks. // But (I guess) those change too easily, so we only ask when actually needed. - + this.globalOrder = Optional.empty(); this.citedKeysAfterDatabaseLookup = Optional.empty(); this.bibliography = Optional.empty(); } - + private static List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, List citationGroupNames) { // Collect unused jabrefPropertyNames @@ -725,7 +890,7 @@ public Optional getPageInfo(CitationGroupID cgid) { public Optional> getCitations(CitationGroupID cgid) { return getCitationGroup(cgid).map(cg -> cg.citations); } - + public List getSortedCitations(CitationGroupID cgid) { Optional cg = getCitationGroup(cgid); if (cg.isEmpty()) { @@ -1259,169 +1424,5 @@ void distributeUniqueLetters(CitationGroupsV001.CitationGroups cgs) { } // class CitedKeys - /** - * This is what we get back from parsing a refMarkName. - * - */ - private static class ParsedRefMark { - /** "", "0", "1" ... */ - public String i; - /** in-text-citation type */ - public int itcType; - /** Citation keys embedded in the reference mark. */ - public List citationKeys; - - ParsedRefMark(String i, int itcType, List citationKeys) { - this.i = i; - this.itcType = itcType; - this.citationKeys = citationKeys; - } - } - - private static class Codec { - private static final String BIB_CITATION = "JR_cite"; - private static final Pattern CITE_PATTERN = - Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); - - - /** - * Produce a reference mark name for JabRef for the given citation - * key and itcType that does not yet appear among the reference - * marks of the document. - * - * @param bibtexKey The citation key. - * @param itcType Encodes the effect of withText and - * inParenthesis options. - * - * The first occurrence of bibtexKey gets no serial number, the - * second gets 0, the third 1 ... - * - * Or the first unused in this series, after removals. - */ - public static String getUniqueReferenceMarkName(DocumentConnection documentConnection, - String bibtexKey, - int itcType) - throws NoDocumentException { - - XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); - int i = 0; - String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; - while (xNamedRefMarks.hasByName(name)) { - name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; - i++; - } - return name; - } - - /** - * Parse a JabRef reference mark name. - * - * @return Optional.empty() on failure. - * - */ - private static Optional parseRefMarkName(String refMarkName) { - - Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); - if (!citeMatcher.find()) { - return Optional.empty(); - } - - List keys = Arrays.asList(citeMatcher.group(3).split(",")); - String i = citeMatcher.group(1); - int itcType = Integer.parseInt(citeMatcher.group(2)); - return (Optional.of(new CitationGroupsV001.ParsedRefMark(i, itcType, keys))); - } - - /** - * Extract the list of citation keys from a reference mark name. - * - * @param name The reference mark name. - * @return The list of citation keys encoded in the name. - * - * In case of duplicated citation keys, - * only the first occurrence. - * Otherwise their order is preserved. - * - * If name does not match CITE_PATTERN, - * an empty list of strings is returned. - */ - private static List parseRefMarkNameToUniqueCitationKeys(String name) { - Optional op = parseRefMarkName(name); - return (op.map(parsedRefMark -> - parsedRefMark.citationKeys.stream() - .distinct() - .collect(Collectors.toList())) - .orElseGet(ArrayList::new)); - } - - /** - * @return true if name matches the pattern used for JabRef - * reference mark names. - */ - private static boolean isJabRefReferenceMarkName(String name) { - return (CITE_PATTERN.matcher(name).find()); - } - - /** - * Filter a list of reference mark names by `isJabRefReferenceMarkName` - * - * @param names The list to be filtered. - */ - private static List filterIsJabRefReferenceMarkName(List names) { - return (names - .stream() - .filter(CitationGroupsV001.Codec::isJabRefReferenceMarkName) - .collect(Collectors.toList())); - } - /** - * Get reference mark names from the document matching the pattern - * used for JabRef reference mark names. - * - * Note: the names returned are in arbitrary order. - * - * - * - */ - private static List getJabRefReferenceMarkNames(StorageBase.NamedRangeManager manager, - DocumentConnection documentConnection) - throws - NoDocumentException { - List allNames = manager.getUsedNames(documentConnection); - return filterIsJabRefReferenceMarkName(allNames); - } - - /** - * For each name in referenceMarkNames set types[i] and - * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) - * - * @param referenceMarkNames Should only contain parsable names. - * @param types OUT Must be same length as referenceMarkNames. - * @param bibtexKeys OUT First level must be same length as referenceMarkNames. - */ - private static void parseRefMarkNamesToArrays(List referenceMarkNames, - int[] types, - String[][] bibtexKeys) { - - final int nRefMarks = referenceMarkNames.size(); - assert (types.length == nRefMarks); - assert (bibtexKeys.length == nRefMarks); - for (int i = 0; i < nRefMarks; i++) { - final String name = referenceMarkNames.get(i); - Optional op = parseRefMarkName(name); - if (op.isEmpty()) { - // We have a problem. We want types[i] and bibtexKeys[i] - // to correspond to referenceMarkNames.get(i). - // And do not want null in bibtexKeys (or error code in types) - // on return. - throw new IllegalArgumentException( - "parseRefMarkNamesToArrays expects parsable referenceMarkNames"); - } - ParsedRefMark ov = op.get(); - types[i] = ov.itcType; - bibtexKeys[i] = ov.citationKeys.toArray(String[]::new); - } - } - - } } // class CitationGroupsV001 From c78562db4da42c943b7e93c331c24e557c694027 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 21:30:57 +0200 Subject: [PATCH 0516/1068] refactor: separate CitationGroupID.java --- .../gui/openoffice/CitationGroupID.java | 18 ++++++ .../gui/openoffice/CitationGroupsV001.java | 43 +++++-------- .../org/jabref/gui/openoffice/OOBibBase.java | 60 +++++++++---------- 3 files changed, 63 insertions(+), 58 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/CitationGroupID.java diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupID.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupID.java new file mode 100644 index 00000000000..743e9847b1a --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupID.java @@ -0,0 +1,18 @@ +package org.jabref.gui.openoffice; + +/** + * Identifies a citation group in a document. + */ +class CitationGroupID { + String id; + CitationGroupID(String id) { + this.id = id; + } + + /** + * CitationEntry needs refMark or other identifying string + */ + String asString() { + return id; + } +} diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 1af6a98a3b4..b7e1c534775 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -214,19 +214,6 @@ private static void parseRefMarkNamesToArrays(List referenceMarkNames, } - static class CitationGroupID { - String id; - CitationGroupID(String id) { - this.id = id; - } - - /** - * CitationEntry needs refMark or other identifying string - */ - String asString() { - return id; - } - } static class Citation implements CitationSort.ComparableCitation { @@ -647,7 +634,7 @@ public Set getCitationGroupIDs() { /** * Creates a list of {@code - * RangeSortable} values for + * RangeSortable} values for * our {@code CitationGroup} values. Originally designed to be * passed to {@code visualSort}. * @@ -669,7 +656,7 @@ public Set getCitationGroupIDs() { * mark. This is used for numbering the citations. * */ - private static List> + private static List> createVisualSortInput(CitationGroupsV001.CitationGroups cgs, DocumentConnection documentConnection, boolean mapFootnotesToFootnoteMarks) @@ -677,11 +664,11 @@ public Set getCitationGroupIDs() { NoDocumentException, WrappedTargetException { - List cgids = + List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); List vses = new ArrayList<>(); - for (CitationGroupsV001.CitationGroupID cgid : cgids) { + for (CitationGroupID cgid : cgids) { XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); if (range == null) { throw new RuntimeException("getReferenceMarkRangeOrNull returned null"); @@ -710,7 +697,7 @@ public Set getCitationGroupIDs() { */ // Sort within partitions - RangeKeyedMapList> xxs + RangeKeyedMapList> xxs = new RangeKeyedMapList<>(); for (RangeSort.RangeSortEntry v : vses) { @@ -718,9 +705,9 @@ public Set getCitationGroupIDs() { } // build final list - List> res = new ArrayList<>(); + List> res = new ArrayList<>(); - for (TreeMap>> + for (TreeMap>> xs : xxs.partitionValues()) { List oxs = new ArrayList<>(xs.keySet()); @@ -728,9 +715,9 @@ public Set getCitationGroupIDs() { int indexInPartition = 0; for (int i = 0; i < oxs.size(); i++) { XTextRange a = oxs.get(i); - List> avs = xs.get(a); + List> avs = xs.get(a); for (int j = 0; j < avs.size(); j++) { - RangeSort.RangeSortEntry v = avs.get(j); + RangeSort.RangeSortEntry v = avs.get(j); v.indexInPosition = indexInPartition++; if (mapFootnotesToFootnoteMarks) { // Adjust range if we are inside a footnote: @@ -746,9 +733,9 @@ public Set getCitationGroupIDs() { } } // convert - // List> + // List> // to - // List> + // List> return res.stream().map(e -> e).collect(Collectors.toList()); } @@ -766,7 +753,7 @@ public Set getCitationGroupIDs() { * order. * */ - public List + public List getVisuallySortedCitationGroupIDs(DocumentConnection documentConnection, boolean mapFootnotesToFootnoteMarks) throws @@ -774,7 +761,7 @@ public Set getCitationGroupIDs() { NoDocumentException, JabRefException { CitationGroupsV001.CitationGroups cgs = this; - List> vses = + List> vses = createVisualSortInput(cgs, documentConnection, mapFootnotesToFootnoteMarks); @@ -790,7 +777,7 @@ public Set getCitationGroupIDs() { + Localization.lang("To get the visual positions of your citations" + " I need to move the cursor around," + " but could not get it."); - List> sorted = + List> sorted = RangeSortVisual.visualSort(vses, documentConnection, messageOnFailureToObtainAFunctionalXTextViewCursor); @@ -1195,7 +1182,7 @@ List citationRanges(DocumentConnection documentConnection) List xs = new ArrayList<>(numberOfCitationGroups()); - List cgids = + List cgids = new ArrayList<>(this.getCitationGroupIDs()); for (CitationGroupID cgid : cgids) { diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0a523a95719..fbfdeaed992 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -557,7 +557,7 @@ public List getCitationEntries() int n = cgs.numberOfCitationGroups(); List citations = new ArrayList<>(n); - for (CitationGroupsV001.CitationGroupID cgid : cgs.getCitationGroupIDs()) { + for (CitationGroupID cgid : cgs.getCitationGroupIDs()) { String name = cgid.asString(); CitationEntry entry = new CitationEntry( @@ -582,7 +582,7 @@ public List getCitationEntries() * reference mark is surrounded by bold html tag. */ private String getCitationContext(CitationGroupsV001.CitationGroups cgs, - CitationGroupsV001.CitationGroupID cgid, + CitationGroupID cgid, DocumentConnection documentConnection, int charBefore, int charAfter, @@ -894,7 +894,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * Produce citation markers for the case when the citation * markers are the citation keys themselves, separated by commas. */ - private static Map + private static Map produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroupsV001.CitationGroups cgs, OOBibStyle style) throws @@ -904,9 +904,9 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes cgs.createPlainBibliographySortedByComparator(OOBibBase.entryComparator); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); - for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { List cits = cgs.getSortedCitations(cgid); String citMarker = (cits.stream() .map(cit -> cit.citationKey) @@ -934,7 +934,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * in bibtexKeys[i][j] * */ - private static Map + private static Map produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroupsV001.CitationGroups cgs, OOBibStyle style) throws @@ -947,9 +947,9 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); - for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); citMarkers.put(cgid, @@ -963,7 +963,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * Produce citation markers for the case of numbered citations * when the bibliography is not sorted by position. */ - private Map + private Map produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroupsV001.CitationGroups cgs, OOBibStyle style) { assert style.isNumberEntries(); @@ -974,9 +974,9 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); - for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); citMarkers.put(cgid, @@ -996,7 +996,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * @param entries Map BibEntry to BibDatabase. * @param style Bibliography style. */ - private Map + private Map produceCitationMarkersForNormalStyle(CitationGroupsV001.CitationGroups cgs, OOBibStyle style) throws @@ -1017,9 +1017,9 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); Set seenBefore = new HashSet<>(); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); - for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List cits = cg.getSortedCitations(); final int nCitedEntries = cits.size(); @@ -1125,7 +1125,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes private static void fillCitationMarkInCursor(DocumentConnection documentConnection, CitationGroupsV001.CitationGroups cgs, - CitationGroupsV001.CitationGroupID cgid, + CitationGroupID cgid, XTextCursor cursor, String citationText, boolean withText, @@ -1243,7 +1243,7 @@ private void insertReferenceMark(CitationGroupsV001.CitationGroups cgs, CreationException, NoDocumentException { - CitationGroupsV001.CitationGroupID cgid = + CitationGroupID cgid = cgs.createCitationGroup(documentConnection, citationKeys, pageInfo, @@ -1620,7 +1620,7 @@ public void insertCitation(List entries, */ private void applyNewCitationMarkers(DocumentConnection documentConnection, CitationGroupsV001.CitationGroups cgs, - Map citMarkers, + Map citMarkers, OOBibStyle style) throws NoDocumentException, @@ -1648,9 +1648,9 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, // catastrophic consequences for the user. boolean mustTestCharFormat = style.isFormatCitations(); - for (Map.Entry kv : citMarkers.entrySet() ) { + for (Map.Entry kv : citMarkers.entrySet() ) { - CitationGroupsV001.CitationGroupID cgid = kv.getKey(); + CitationGroupID cgid = kv.getKey(); Objects.requireNonNull(cgid); String citationText = kv.getValue(); @@ -1702,10 +1702,10 @@ static class ProduceCitationMarkersResult { CitationGroupsV001.CitationGroups cgs; /** citation markers */ - Map citMarkers; + Map citMarkers; ProduceCitationMarkersResult(CitationGroupsV001.CitationGroups cgs, - Map citMarkers) { + Map citMarkers) { this.cgs = cgs; this.citMarkers = citMarkers; if ( cgs.getBibliography().isEmpty() ) { @@ -1770,7 +1770,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d // { boolean mapFootnotesToFootnoteMarks = true; - List sortedCitationGroupIDs = + List sortedCitationGroupIDs = cgs.getVisuallySortedCitationGroupIDs(documentConnection, mapFootnotesToFootnoteMarks); cgs.setGlobalOrder(sortedCitationGroupIDs); @@ -1779,7 +1779,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d // citMarkers[i] = what goes in the text at referenceMark[i] // String[] citMarkers; - Map citMarkers; + Map citMarkers; // fill citMarkers Map uniqueLetters = new HashMap<>(); @@ -1827,7 +1827,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d sortEntriesByRefMarkNames(CitationGroupsV001.CitationGroups cgs) { Set seen = new HashSet<>(); List res = new ArrayList<>(); - for (CitationGroupsV001.CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { List cits = cgs.getSortedCitations(cgid); // no need to look in the database again @@ -1975,7 +1975,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, int last = ck.where.size(); int i=0; for (CitationGroupsV001.CitationPath p : ck.where) { - CitationGroupsV001.CitationGroupID cgid = p.group; + CitationGroupID cgid = p.group; CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); String refMarkName = cg.referenceMarkName; @@ -2182,7 +2182,7 @@ public void combineCiteMarkers(List databases, boolean madeModifications = false; - List + List referenceMarkNames = cgs.getCitationGroupIDsSortedWithinPartitions(documentConnection, false /* mapFootnotesToFootnoteMarks */); @@ -2218,7 +2218,7 @@ public void combineCiteMarkers(List databases, CitationGroupsV001.CitationGroup prev = null; XTextRange prevRange = null; - for (CitationGroupsV001.CitationGroupID cgid : referenceMarkNames) { + for (CitationGroupID cgid : referenceMarkNames) { CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); XTextRange currentRange = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); @@ -2555,11 +2555,11 @@ public void unCombineCiteMarkers(List databases, boolean madeModifications = false; // boolean mapFootnotesToFootnoteMarks = true; - // List names = + // List names = // getVisuallySortedCitationGroupIDs(cgs, documentConnection, mapFootnotesToFootnoteMarks); // // {@code names} does not need to be sorted. - List names = new ArrayList<>(cgs.getCitationGroupIDs()); + List names = new ArrayList<>(cgs.getCitationGroupIDs()); try { if (useLockControllers) { @@ -2570,7 +2570,7 @@ public void unCombineCiteMarkers(List databases, boolean setCharStyleTested = false; while (pivot < (names.size())) { - CitationGroupsV001.CitationGroupID cgid = names.get(pivot); + CitationGroupID cgid = names.get(pivot); CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); XTextRange range1 = cgs.getReferenceMarkRangeOrNull(documentConnection,cgid); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); From c7fb9bd8be378f58ccad39c987280b48e1df7064 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 23:24:37 +0200 Subject: [PATCH 0517/1068] move ParsedRefMark into Codec --- .../gui/openoffice/CitationGroupsV001.java | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index b7e1c534775..40101facde9 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -49,30 +49,30 @@ class CitationGroupsV001 { private static final Logger LOGGER = LoggerFactory.getLogger(CitedKeys.class); - /** - * This is what we get back from parsing a refMarkName. - * - */ - private static class ParsedRefMark { - /** "", "0", "1" ... */ - public String i; - /** in-text-citation type */ - public int itcType; - /** Citation keys embedded in the reference mark. */ - public List citationKeys; - - ParsedRefMark(String i, int itcType, List citationKeys) { - this.i = i; - this.itcType = itcType; - this.citationKeys = citationKeys; - } - } private static class Codec { private static final String BIB_CITATION = "JR_cite"; private static final Pattern CITE_PATTERN = Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + /** + * This is what we get back from parsing a refMarkName. + * + */ + private static class ParsedRefMark { + /** "", "0", "1" ... */ + public String i; + /** in-text-citation type */ + public int itcType; + /** Citation keys embedded in the reference mark. */ + public List citationKeys; + + ParsedRefMark(String i, int itcType, List citationKeys) { + this.i = i; + this.itcType = itcType; + this.citationKeys = citationKeys; + } + } /** * Produce a reference mark name for JabRef for the given citation @@ -119,7 +119,7 @@ private static Optional parseRefMarkName(String refMarkName) { List keys = Arrays.asList(citeMatcher.group(3).split(",")); String i = citeMatcher.group(1); int itcType = Integer.parseInt(citeMatcher.group(2)); - return (Optional.of(new CitationGroupsV001.ParsedRefMark(i, itcType, keys))); + return (Optional.of(new Codec.ParsedRefMark(i, itcType, keys))); } /** @@ -448,7 +448,7 @@ private static List findUnusedJabrefPropertyNames(DocumentConnection doc WrappedTargetException, NoDocumentException { - Optional op = Codec.parseRefMarkName(refMarkName); + Optional op = Codec.parseRefMarkName(refMarkName); if (op.isEmpty()) { // We have a problem. We want types[i] and bibtexKeys[i] // to correspond to referenceMarkNames.get(i). @@ -457,7 +457,7 @@ private static List findUnusedJabrefPropertyNames(DocumentConnection doc throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" + " found unparsable referenceMarkName"); } - ParsedRefMark ov = op.get(); + Codec.ParsedRefMark ov = op.get(); CitationGroupID id = new CitationGroupID(refMarkName); List citations = ((ov.citationKeys == null) ? new ArrayList<>() From 3980cec2268a1522475fe518d4dcd96d0996d11b Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 23:43:22 +0200 Subject: [PATCH 0518/1068] refactor: separate Codec.java --- .../gui/openoffice/CitationGroupsV001.java | 245 +++--------------- .../java/org/jabref/gui/openoffice/Codec.java | 200 ++++++++++++++ 2 files changed, 241 insertions(+), 204 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/Codec.java diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 40101facde9..412181e8ed4 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -50,169 +50,6 @@ class CitationGroupsV001 { LoggerFactory.getLogger(CitedKeys.class); - private static class Codec { - private static final String BIB_CITATION = "JR_cite"; - private static final Pattern CITE_PATTERN = - Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); - - /** - * This is what we get back from parsing a refMarkName. - * - */ - private static class ParsedRefMark { - /** "", "0", "1" ... */ - public String i; - /** in-text-citation type */ - public int itcType; - /** Citation keys embedded in the reference mark. */ - public List citationKeys; - - ParsedRefMark(String i, int itcType, List citationKeys) { - this.i = i; - this.itcType = itcType; - this.citationKeys = citationKeys; - } - } - - /** - * Produce a reference mark name for JabRef for the given citation - * key and itcType that does not yet appear among the reference - * marks of the document. - * - * @param bibtexKey The citation key. - * @param itcType Encodes the effect of withText and - * inParenthesis options. - * - * The first occurrence of bibtexKey gets no serial number, the - * second gets 0, the third 1 ... - * - * Or the first unused in this series, after removals. - */ - public static String getUniqueReferenceMarkName(DocumentConnection documentConnection, - String bibtexKey, - int itcType) - throws NoDocumentException { - - XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); - int i = 0; - String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; - while (xNamedRefMarks.hasByName(name)) { - name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; - i++; - } - return name; - } - - /** - * Parse a JabRef reference mark name. - * - * @return Optional.empty() on failure. - * - */ - private static Optional parseRefMarkName(String refMarkName) { - - Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); - if (!citeMatcher.find()) { - return Optional.empty(); - } - - List keys = Arrays.asList(citeMatcher.group(3).split(",")); - String i = citeMatcher.group(1); - int itcType = Integer.parseInt(citeMatcher.group(2)); - return (Optional.of(new Codec.ParsedRefMark(i, itcType, keys))); - } - - /** - * Extract the list of citation keys from a reference mark name. - * - * @param name The reference mark name. - * @return The list of citation keys encoded in the name. - * - * In case of duplicated citation keys, - * only the first occurrence. - * Otherwise their order is preserved. - * - * If name does not match CITE_PATTERN, - * an empty list of strings is returned. - */ - private static List parseRefMarkNameToUniqueCitationKeys(String name) { - Optional op = parseRefMarkName(name); - return (op.map(parsedRefMark -> - parsedRefMark.citationKeys.stream() - .distinct() - .collect(Collectors.toList())) - .orElseGet(ArrayList::new)); - } - - /** - * @return true if name matches the pattern used for JabRef - * reference mark names. - */ - private static boolean isJabRefReferenceMarkName(String name) { - return (CITE_PATTERN.matcher(name).find()); - } - - /** - * Filter a list of reference mark names by `isJabRefReferenceMarkName` - * - * @param names The list to be filtered. - */ - private static List filterIsJabRefReferenceMarkName(List names) { - return (names - .stream() - .filter(CitationGroupsV001.Codec::isJabRefReferenceMarkName) - .collect(Collectors.toList())); - } - /** - * Get reference mark names from the document matching the pattern - * used for JabRef reference mark names. - * - * Note: the names returned are in arbitrary order. - * - * - * - */ - private static List getJabRefReferenceMarkNames(StorageBase.NamedRangeManager manager, - DocumentConnection documentConnection) - throws - NoDocumentException { - List allNames = manager.getUsedNames(documentConnection); - return filterIsJabRefReferenceMarkName(allNames); - } - - /** - * For each name in referenceMarkNames set types[i] and - * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) - * - * @param referenceMarkNames Should only contain parsable names. - * @param types OUT Must be same length as referenceMarkNames. - * @param bibtexKeys OUT First level must be same length as referenceMarkNames. - */ - private static void parseRefMarkNamesToArrays(List referenceMarkNames, - int[] types, - String[][] bibtexKeys) { - - final int nRefMarks = referenceMarkNames.size(); - assert (types.length == nRefMarks); - assert (bibtexKeys.length == nRefMarks); - for (int i = 0; i < nRefMarks; i++) { - final String name = referenceMarkNames.get(i); - Optional op = parseRefMarkName(name); - if (op.isEmpty()) { - // We have a problem. We want types[i] and bibtexKeys[i] - // to correspond to referenceMarkNames.get(i). - // And do not want null in bibtexKeys (or error code in types) - // on return. - throw new IllegalArgumentException( - "parseRefMarkNamesToArrays expects parsable referenceMarkNames"); - } - ParsedRefMark ov = op.get(); - types[i] = ov.itcType; - bibtexKeys[i] = ov.citationKeys.toArray(String[]::new); - } - } - - } static class Citation implements CitationSort.ComparableCitation { @@ -412,7 +249,7 @@ private static List findUnusedJabrefPropertyNames(DocumentConnection doc List jabrefPropertyNames = documentConnection.getCustomPropertyNames() .stream() - .filter(CitationGroupsV001.Codec::isJabRefReferenceMarkName) + .filter(Codec::isJabRefReferenceMarkName) .collect(Collectors.toList()); for (String pn : jabrefPropertyNames) { if (!citationGroupNamesSet.contains(pn)) { @@ -1090,46 +927,46 @@ public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConn - /** - * Extract citation keys from names of referenceMarks in the document. - * - * Each citation key is listed only once, in the order of first appearance - * (in `names`, which itself is in arbitrary order) - * - * doc.referenceMarks.names.map(parse).flatten.unique - * - * TODO: avoid direct reference mark manipulation - */ - private List findCitedKeys(DocumentConnection documentConnection) - throws - NoSuchElementException, - WrappedTargetException, - NoDocumentException { - - List names = - Codec.getJabRefReferenceMarkNames(this.citationStorageManager, - documentConnection); - - // assert it supports XTextContent - XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); - for (String name1 : names) { - Object bookmark = xNamedMarks.getByName(name1); - assert (null != DocumentConnection.asTextContent(bookmark)); - } - - // Collect to a flat list while keep only the first appearance. - List keys = new ArrayList<>(); - for (String name1 : names) { - List newKeys = Codec.parseRefMarkNameToUniqueCitationKeys(name1); - for (String key : newKeys) { - if (!keys.contains(key)) { - keys.add(key); - } - } - } - - return keys; - } +// /** +// * Extract citation keys from names of referenceMarks in the document. +// * +// * Each citation key is listed only once, in the order of first appearance +// * (in `names`, which itself is in arbitrary order) +// * +// * doc.referenceMarks.names.map(parse).flatten.unique +// * +// * TODO: avoid direct reference mark manipulation +// */ +// private List findCitedKeys(DocumentConnection documentConnection) +// throws +// NoSuchElementException, +// WrappedTargetException, +// NoDocumentException { +// +// List names = +// Codec.getJabRefReferenceMarkNames(this.citationStorageManager, +// documentConnection); +// +// // assert it supports XTextContent +// XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); +// for (String name1 : names) { +// Object bookmark = xNamedMarks.getByName(name1); +// assert (null != DocumentConnection.asTextContent(bookmark)); +// } +// +// // Collect to a flat list while keep only the first appearance. +// List keys = new ArrayList<>(); +// for (String name1 : names) { +// List newKeys = Codec.parseRefMarkNameToUniqueCitationKeys(name1); +// for (String key : newKeys) { +// if (!keys.contains(key)) { +// keys.add(key); +// } +// } +// } +// +// return keys; +// } /** * Given the name of a reference mark, get the corresponding diff --git a/src/main/java/org/jabref/gui/openoffice/Codec.java b/src/main/java/org/jabref/gui/openoffice/Codec.java new file mode 100644 index 00000000000..b59aee26e23 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/Codec.java @@ -0,0 +1,200 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class Codec { + private static final String BIB_CITATION = "JR_cite"; + private static final Pattern CITE_PATTERN = + Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + + /** + * This is what we get back from parsing a refMarkName. + * + */ + public static class ParsedRefMark { + /** "", "0", "1" ... */ + public String i; + /** in-text-citation type */ + public int itcType; + /** Citation keys embedded in the reference mark. */ + public List citationKeys; + + ParsedRefMark(String i, int itcType, List citationKeys) { + this.i = i; + this.itcType = itcType; + this.citationKeys = citationKeys; + } + } + + /** + * Produce a reference mark name for JabRef for the given citation + * key and itcType that does not yet appear among the reference + * marks of the document. + * + * @param bibtexKey The citation key. + * @param itcType Encodes the effect of withText and + * inParenthesis options. + * + * The first occurrence of bibtexKey gets no serial number, the + * second gets 0, the third 1 ... + * + * Or the first unused in this series, after removals. + */ + public static String getUniqueReferenceMarkName(DocumentConnection documentConnection, + String bibtexKey, + int itcType) + throws NoDocumentException { + + XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); + int i = 0; + String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; + while (xNamedRefMarks.hasByName(name)) { + name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; + i++; + } + return name; + } + + /** + * Parse a JabRef reference mark name. + * + * @return Optional.empty() on failure. + * + */ + public static Optional parseRefMarkName(String refMarkName) { + + Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); + if (!citeMatcher.find()) { + return Optional.empty(); + } + + List keys = Arrays.asList(citeMatcher.group(3).split(",")); + String i = citeMatcher.group(1); + int itcType = Integer.parseInt(citeMatcher.group(2)); + return (Optional.of(new Codec.ParsedRefMark(i, itcType, keys))); + } + +// /** +// * Extract the list of citation keys from a reference mark name. +// * +// * @param name The reference mark name. +// * @return The list of citation keys encoded in the name. +// * +// * In case of duplicated citation keys, +// * only the first occurrence. +// * Otherwise their order is preserved. +// * +// * If name does not match CITE_PATTERN, +// * an empty list of strings is returned. +// */ +// private static List parseRefMarkNameToUniqueCitationKeys(String name) { +// Optional op = parseRefMarkName(name); +// return (op.map(parsedRefMark -> +// parsedRefMark.citationKeys.stream() +// .distinct() +// .collect(Collectors.toList())) +// .orElseGet(ArrayList::new)); +// } + + /** + * @return true if name matches the pattern used for JabRef + * reference mark names. + */ + public static boolean isJabRefReferenceMarkName(String name) { + return (CITE_PATTERN.matcher(name).find()); + } + + /** + * Filter a list of reference mark names by `isJabRefReferenceMarkName` + * + * @param names The list to be filtered. + */ + public static List filterIsJabRefReferenceMarkName(List names) { + return (names + .stream() + .filter(Codec::isJabRefReferenceMarkName) + .collect(Collectors.toList())); + } + /** + * Get reference mark names from the document matching the pattern + * used for JabRef reference mark names. + * + * Note: the names returned are in arbitrary order. + * + * + * + */ + public static List getJabRefReferenceMarkNames(StorageBase.NamedRangeManager manager, + DocumentConnection documentConnection) + throws + NoDocumentException { + List allNames = manager.getUsedNames(documentConnection); + return filterIsJabRefReferenceMarkName(allNames); + } + +// /** +// * For each name in referenceMarkNames set types[i] and +// * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) +// * +// * @param referenceMarkNames Should only contain parsable names. +// * @param types OUT Must be same length as referenceMarkNames. +// * @param bibtexKeys OUT First level must be same length as referenceMarkNames. +// */ +// private static void parseRefMarkNamesToArrays(List referenceMarkNames, +// int[] types, +// String[][] bibtexKeys) { +// +// final int nRefMarks = referenceMarkNames.size(); +// assert (types.length == nRefMarks); +// assert (bibtexKeys.length == nRefMarks); +// for (int i = 0; i < nRefMarks; i++) { +// final String name = referenceMarkNames.get(i); +// Optional op = parseRefMarkName(name); +// if (op.isEmpty()) { +// // We have a problem. We want types[i] and bibtexKeys[i] +// // to correspond to referenceMarkNames.get(i). +// // And do not want null in bibtexKeys (or error code in types) +// // on return. +// throw new IllegalArgumentException( +// "parseRefMarkNamesToArrays expects parsable referenceMarkNames"); +// } +// ParsedRefMark ov = op.get(); +// types[i] = ov.itcType; +// bibtexKeys[i] = ov.citationKeys.toArray(String[]::new); +// } +// } +} From eda1a09fac64494e9852ce03c01a2f700a6ef2fd Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 28 Mar 2021 23:45:43 +0200 Subject: [PATCH 0519/1068] drop some unused code --- .../gui/openoffice/CitationGroupsV001.java | 46 ---------------- .../java/org/jabref/gui/openoffice/Codec.java | 54 ------------------- 2 files changed, 100 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 412181e8ed4..3bf7e69e860 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -49,9 +49,6 @@ class CitationGroupsV001 { private static final Logger LOGGER = LoggerFactory.getLogger(CitedKeys.class); - - - static class Citation implements CitationSort.ComparableCitation { /** key in database */ @@ -925,49 +922,6 @@ public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConn return cg.cgRangeStorage.getFillCursor(documentConnection); } - - -// /** -// * Extract citation keys from names of referenceMarks in the document. -// * -// * Each citation key is listed only once, in the order of first appearance -// * (in `names`, which itself is in arbitrary order) -// * -// * doc.referenceMarks.names.map(parse).flatten.unique -// * -// * TODO: avoid direct reference mark manipulation -// */ -// private List findCitedKeys(DocumentConnection documentConnection) -// throws -// NoSuchElementException, -// WrappedTargetException, -// NoDocumentException { -// -// List names = -// Codec.getJabRefReferenceMarkNames(this.citationStorageManager, -// documentConnection); -// -// // assert it supports XTextContent -// XNameAccess xNamedMarks = documentConnection.getReferenceMarks(); -// for (String name1 : names) { -// Object bookmark = xNamedMarks.getByName(name1); -// assert (null != DocumentConnection.asTextContent(bookmark)); -// } -// -// // Collect to a flat list while keep only the first appearance. -// List keys = new ArrayList<>(); -// for (String name1 : names) { -// List newKeys = Codec.parseRefMarkNameToUniqueCitationKeys(name1); -// for (String key : newKeys) { -// if (!keys.contains(key)) { -// keys.add(key); -// } -// } -// } -// -// return keys; -// } - /** * Given the name of a reference mark, get the corresponding * pageInfo text. diff --git a/src/main/java/org/jabref/gui/openoffice/Codec.java b/src/main/java/org/jabref/gui/openoffice/Codec.java index b59aee26e23..3a373c4cd3b 100644 --- a/src/main/java/org/jabref/gui/openoffice/Codec.java +++ b/src/main/java/org/jabref/gui/openoffice/Codec.java @@ -108,28 +108,6 @@ public static Optional parseRefMarkName(String refMarkName) { return (Optional.of(new Codec.ParsedRefMark(i, itcType, keys))); } -// /** -// * Extract the list of citation keys from a reference mark name. -// * -// * @param name The reference mark name. -// * @return The list of citation keys encoded in the name. -// * -// * In case of duplicated citation keys, -// * only the first occurrence. -// * Otherwise their order is preserved. -// * -// * If name does not match CITE_PATTERN, -// * an empty list of strings is returned. -// */ -// private static List parseRefMarkNameToUniqueCitationKeys(String name) { -// Optional op = parseRefMarkName(name); -// return (op.map(parsedRefMark -> -// parsedRefMark.citationKeys.stream() -// .distinct() -// .collect(Collectors.toList())) -// .orElseGet(ArrayList::new)); -// } - /** * @return true if name matches the pattern used for JabRef * reference mark names. @@ -165,36 +143,4 @@ public static List getJabRefReferenceMarkNames(StorageBase.NamedRangeMan List allNames = manager.getUsedNames(documentConnection); return filterIsJabRefReferenceMarkName(allNames); } - -// /** -// * For each name in referenceMarkNames set types[i] and -// * bibtexKeys[i] to values parsed from referenceMarkNames.get(i) -// * -// * @param referenceMarkNames Should only contain parsable names. -// * @param types OUT Must be same length as referenceMarkNames. -// * @param bibtexKeys OUT First level must be same length as referenceMarkNames. -// */ -// private static void parseRefMarkNamesToArrays(List referenceMarkNames, -// int[] types, -// String[][] bibtexKeys) { -// -// final int nRefMarks = referenceMarkNames.size(); -// assert (types.length == nRefMarks); -// assert (bibtexKeys.length == nRefMarks); -// for (int i = 0; i < nRefMarks; i++) { -// final String name = referenceMarkNames.get(i); -// Optional op = parseRefMarkName(name); -// if (op.isEmpty()) { -// // We have a problem. We want types[i] and bibtexKeys[i] -// // to correspond to referenceMarkNames.get(i). -// // And do not want null in bibtexKeys (or error code in types) -// // on return. -// throw new IllegalArgumentException( -// "parseRefMarkNamesToArrays expects parsable referenceMarkNames"); -// } -// ParsedRefMark ov = op.get(); -// types[i] = ov.itcType; -// bibtexKeys[i] = ov.citationKeys.toArray(String[]::new); -// } -// } } From 3849b3a2aafee08884846a7386f45bded1b76680 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 00:02:54 +0200 Subject: [PATCH 0520/1068] renames from RefMark to MarkName, getUniqueMarkName needs no documentConnection --- .../gui/openoffice/CitationGroupsV001.java | 13 ++++++---- .../java/org/jabref/gui/openoffice/Codec.java | 24 ++++++++++++------- .../org/jabref/gui/openoffice/OOBibBase.java | 11 +-------- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 3bf7e69e860..9fa43774196 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -5,6 +5,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -282,7 +283,7 @@ private static List findUnusedJabrefPropertyNames(DocumentConnection doc WrappedTargetException, NoDocumentException { - Optional op = Codec.parseRefMarkName(refMarkName); + Optional op = Codec.parseRefMarkName(refMarkName); if (op.isEmpty()) { // We have a problem. We want types[i] and bibtexKeys[i] // to correspond to referenceMarkNames.get(i). @@ -291,7 +292,7 @@ private static List findUnusedJabrefPropertyNames(DocumentConnection doc throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" + " found unparsable referenceMarkName"); } - Codec.ParsedRefMark ov = op.get(); + Codec.ParsedMarkName ov = op.get(); CitationGroupID id = new CitationGroupID(refMarkName); List citations = ((ov.citationKeys == null) ? new ArrayList<>() @@ -783,10 +784,12 @@ public CitationGroupID createCitationGroup(DocumentConnection documentConnection citationKeys.stream() .collect(Collectors.joining(",")); + Set usedNames = new HashSet<>( this.citationStorageManager + .getUsedNames(documentConnection) ); String refMarkName = - Codec.getUniqueReferenceMarkName(documentConnection, - xkey, - itcType); + Codec.getUniqueMarkName(usedNames, + xkey, + itcType); CitationGroupID cgid = new CitationGroupID(refMarkName); diff --git a/src/main/java/org/jabref/gui/openoffice/Codec.java b/src/main/java/org/jabref/gui/openoffice/Codec.java index 3a373c4cd3b..3917ad8592c 100644 --- a/src/main/java/org/jabref/gui/openoffice/Codec.java +++ b/src/main/java/org/jabref/gui/openoffice/Codec.java @@ -36,6 +36,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * How and what is encoded in a mark names. + * + * - pageInfo does not appear here. + * - should not depend on the type of marks (reference mark of bookmark) used. + */ class Codec { private static final String BIB_CITATION = "JR_cite"; private static final Pattern CITE_PATTERN = @@ -45,7 +51,7 @@ class Codec { * This is what we get back from parsing a refMarkName. * */ - public static class ParsedRefMark { + public static class ParsedMarkName { /** "", "0", "1" ... */ public String i; /** in-text-citation type */ @@ -53,7 +59,7 @@ public static class ParsedRefMark { /** Citation keys embedded in the reference mark. */ public List citationKeys; - ParsedRefMark(String i, int itcType, List citationKeys) { + ParsedMarkName(String i, int itcType, List citationKeys) { this.i = i; this.itcType = itcType; this.citationKeys = citationKeys; @@ -74,15 +80,15 @@ public static class ParsedRefMark { * * Or the first unused in this series, after removals. */ - public static String getUniqueReferenceMarkName(DocumentConnection documentConnection, - String bibtexKey, - int itcType) + public static String getUniqueMarkName(Set usedNames, + String bibtexKey, + int itcType) throws NoDocumentException { - XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); + // XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); int i = 0; String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; - while (xNamedRefMarks.hasByName(name)) { + while (usedNames.contains(name)) { name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; i++; } @@ -95,7 +101,7 @@ public static String getUniqueReferenceMarkName(DocumentConnection documentConne * @return Optional.empty() on failure. * */ - public static Optional parseRefMarkName(String refMarkName) { + public static Optional parseRefMarkName(String refMarkName) { Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); if (!citeMatcher.find()) { @@ -105,7 +111,7 @@ public static Optional parseRefMarkName(String refMarkName) { List keys = Arrays.asList(citeMatcher.group(3).split(",")); String i = citeMatcher.group(1); int itcType = Integer.parseInt(citeMatcher.group(2)); - return (Optional.of(new Codec.ParsedRefMark(i, itcType, keys))); + return (Optional.of(new Codec.ParsedMarkName(i, itcType, keys))); } /** diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index fbfdeaed992..7083a8fe6f6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2604,18 +2604,9 @@ public void unCombineCiteMarkers(List databases, int last = keys.size() - 1; int i = 0; for (String key : keys) { - // Note: instead of generating a new name, we should explicitly - // recover the original. Otherwise ... - /* - String newName = getUniqueReferenceMarkName( - documentConnection, - key, - OOBibBase.AUTHORYEAR_PAR); - */ - // Note: by using insertReferenceMark (and not something // that accepts List, we lose the extra - // info stored in teh citations. + // info stored in the citations. // We just reread below. List citationKeys = new ArrayList<>(1); citationKeys.add( key ); From 2da9191aab976d67c98532e4e6c579a7ad9e83b6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 00:07:09 +0200 Subject: [PATCH 0521/1068] getJabRefReferenceMarkNames moved back to CitationGroups --- .../gui/openoffice/CitationGroupsV001.java | 25 ++++++++++++++++--- .../java/org/jabref/gui/openoffice/Codec.java | 16 ------------ 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index 9fa43774196..d1519a58263 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -50,6 +50,7 @@ class CitationGroupsV001 { private static final Logger LOGGER = LoggerFactory.getLogger(CitedKeys.class); + static class Citation implements CitationSort.ComparableCitation { /** key in database */ @@ -213,13 +214,12 @@ public CitationGroups(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException { - + this.citationStorageManager = new StorageBaseRefMark.Manager(); // Get the citationGroupNames - List citationGroupNames = - Codec.getJabRefReferenceMarkNames(this.citationStorageManager, - documentConnection); + List citationGroupNames = getJabRefReferenceMarkNames(this.citationStorageManager, + documentConnection); this.pageInfoThrash = findUnusedJabrefPropertyNames(documentConnection, citationGroupNames); @@ -237,6 +237,23 @@ public CitationGroups(DocumentConnection documentConnection) this.bibliography = Optional.empty(); } + /** + * Get reference mark names from the document matching the pattern + * used for JabRef reference mark names. + * + * Note: the names returned are in arbitrary order. + * + * + * + */ + public static List getJabRefReferenceMarkNames(StorageBase.NamedRangeManager manager, + DocumentConnection documentConnection) + throws + NoDocumentException { + List allNames = manager.getUsedNames(documentConnection); + return Codec.filterIsJabRefReferenceMarkName(allNames); + } + private static List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, List citationGroupNames) { // Collect unused jabrefPropertyNames diff --git a/src/main/java/org/jabref/gui/openoffice/Codec.java b/src/main/java/org/jabref/gui/openoffice/Codec.java index 3917ad8592c..ae7d669b793 100644 --- a/src/main/java/org/jabref/gui/openoffice/Codec.java +++ b/src/main/java/org/jabref/gui/openoffice/Codec.java @@ -133,20 +133,4 @@ public static List filterIsJabRefReferenceMarkName(List names) { .filter(Codec::isJabRefReferenceMarkName) .collect(Collectors.toList())); } - /** - * Get reference mark names from the document matching the pattern - * used for JabRef reference mark names. - * - * Note: the names returned are in arbitrary order. - * - * - * - */ - public static List getJabRefReferenceMarkNames(StorageBase.NamedRangeManager manager, - DocumentConnection documentConnection) - throws - NoDocumentException { - List allNames = manager.getUsedNames(documentConnection); - return filterIsJabRefReferenceMarkName(allNames); - } } From 4f4c6696b6cae5497d57f7774badc13637fb6ffb Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 00:13:09 +0200 Subject: [PATCH 0522/1068] rename parseRefMarkName to parseMarkName --- .../java/org/jabref/gui/openoffice/CitationGroupsV001.java | 2 +- src/main/java/org/jabref/gui/openoffice/Codec.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java index d1519a58263..a15e10a6abf 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java @@ -300,7 +300,7 @@ private static List findUnusedJabrefPropertyNames(DocumentConnection doc WrappedTargetException, NoDocumentException { - Optional op = Codec.parseRefMarkName(refMarkName); + Optional op = Codec.parseMarkName(refMarkName); if (op.isEmpty()) { // We have a problem. We want types[i] and bibtexKeys[i] // to correspond to referenceMarkNames.get(i). diff --git a/src/main/java/org/jabref/gui/openoffice/Codec.java b/src/main/java/org/jabref/gui/openoffice/Codec.java index ae7d669b793..487dc4abb5a 100644 --- a/src/main/java/org/jabref/gui/openoffice/Codec.java +++ b/src/main/java/org/jabref/gui/openoffice/Codec.java @@ -96,12 +96,12 @@ public static String getUniqueMarkName(Set usedNames, } /** - * Parse a JabRef reference mark name. + * Parse a JabRef (reference) mark name. * * @return Optional.empty() on failure. * */ - public static Optional parseRefMarkName(String refMarkName) { + public static Optional parseMarkName(String refMarkName) { Matcher citeMatcher = CITE_PATTERN.matcher(refMarkName); if (!citeMatcher.find()) { From 19f9bad5c38b4c81d98e9f34fe739670a85dc156 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 00:25:40 +0200 Subject: [PATCH 0523/1068] CITE_PATTERN only accepts [012] for itcType --- src/main/java/org/jabref/gui/openoffice/Codec.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/Codec.java b/src/main/java/org/jabref/gui/openoffice/Codec.java index 487dc4abb5a..00ac55d6229 100644 --- a/src/main/java/org/jabref/gui/openoffice/Codec.java +++ b/src/main/java/org/jabref/gui/openoffice/Codec.java @@ -39,13 +39,15 @@ /** * How and what is encoded in a mark names. * - * - pageInfo does not appear here. - * - should not depend on the type of marks (reference mark of bookmark) used. + * - pageInfo does not appear here. It is not encoded in the mark name. + * - Does not depend on the type of marks (reference mark of bookmark) used. */ class Codec { private static final String BIB_CITATION = "JR_cite"; private static final Pattern CITE_PATTERN = - Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + // Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); + // itcType is always "0" "1" or "2" + Pattern.compile(BIB_CITATION + "(\\d*)_([012])_(.*)"); /** * This is what we get back from parsing a refMarkName. From 8a5c015a4f076292858c48a87dc3b44647257509 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 15:03:33 +0200 Subject: [PATCH 0524/1068] refactor: split CitationGroupsV001 --- .../org/jabref/gui/openoffice/Backend52.java | 252 ++++ .../org/jabref/gui/openoffice/Citation.java | 82 ++ .../jabref/gui/openoffice/CitationGroup.java | 132 ++ .../jabref/gui/openoffice/CitationGroups.java | 838 +++++++++++ .../gui/openoffice/CitationGroupsV001.java | 1226 ----------------- .../jabref/gui/openoffice/CitationPath.java | 15 + .../org/jabref/gui/openoffice/CitedKey.java | 101 ++ .../org/jabref/gui/openoffice/CitedKeys.java | 104 ++ .../openoffice/{Codec.java => Codec52.java} | 6 +- .../org/jabref/gui/openoffice/Compat.java | 34 + .../gui/openoffice/DocumentConnection.java | 28 +- .../org/jabref/gui/openoffice/OOBibBase.java | 151 +- .../gui/openoffice/OpenOfficePanel.java | 32 +- 13 files changed, 1690 insertions(+), 1311 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/Backend52.java create mode 100644 src/main/java/org/jabref/gui/openoffice/Citation.java create mode 100644 src/main/java/org/jabref/gui/openoffice/CitationGroup.java create mode 100644 src/main/java/org/jabref/gui/openoffice/CitationGroups.java delete mode 100644 src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java create mode 100644 src/main/java/org/jabref/gui/openoffice/CitationPath.java create mode 100644 src/main/java/org/jabref/gui/openoffice/CitedKey.java create mode 100644 src/main/java/org/jabref/gui/openoffice/CitedKeys.java rename src/main/java/org/jabref/gui/openoffice/{Codec.java => Codec52.java} (96%) create mode 100644 src/main/java/org/jabref/gui/openoffice/Compat.java diff --git a/src/main/java/org/jabref/gui/openoffice/Backend52.java b/src/main/java/org/jabref/gui/openoffice/Backend52.java new file mode 100644 index 00000000000..472e3da4abd --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/Backend52.java @@ -0,0 +1,252 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.UnknownPropertyException; + +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class Backend52 { + public final Compat.DataModel dataModel; + public final StorageBase.NamedRangeManager citationStorageManager; + // uses: Codec52 + Backend52() { + this.dataModel = Compat.DataModel.JabRef52; + this.citationStorageManager = new StorageBaseRefMark.Manager(); + } + + /** + * Get reference mark names from the document matching the pattern + * used for JabRef reference mark names. + * + * Note: the names returned are in arbitrary order. + * + */ + public List getJabRefReferenceMarkNames(DocumentConnection documentConnection) + throws + NoDocumentException { + List allNames = this.citationStorageManager.getUsedNames(documentConnection); + return Codec52.filterIsJabRefReferenceMarkName(allNames); + } + + List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, + List citationGroupNames) { + // Collect unused jabrefPropertyNames + Set citationGroupNamesSet = + citationGroupNames.stream().collect(Collectors.toSet()); + + List pageInfoThrash = new ArrayList<>(); + List jabrefPropertyNames = + documentConnection.getCustomPropertyNames() + .stream() + .filter(Codec52::isJabRefReferenceMarkName) + .collect(Collectors.toList()); + for (String pn : jabrefPropertyNames) { + if (!citationGroupNamesSet.contains(pn)) { + pageInfoThrash.add(pn); + } + } + return pageInfoThrash; + } + + /** + * We have circular dependency here: backend uses + * class from ... + */ + public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection documentConnection, + String refMarkName) + throws + WrappedTargetException, + NoDocumentException { + + Optional op = Codec52.parseMarkName(refMarkName); + if (op.isEmpty()) { + // We have a problem. We want types[i] and bibtexKeys[i] + // to correspond to referenceMarkNames.get(i). + // And do not want null in bibtexKeys (or error code in types) + // on return. + throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" + + " found unparsable referenceMarkName"); + } + Codec52.ParsedMarkName ov = op.get(); + CitationGroupID id = new CitationGroupID(refMarkName); + List citations = ((ov.citationKeys == null) + ? new ArrayList<>() + : (ov.citationKeys.stream() + .map(Citation::new) + .collect(Collectors.toList()))); + + Optional pageInfo = documentConnection.getCustomProperty(refMarkName); + + StorageBase.NamedRange sr = citationStorageManager.getFromDocumentOrNull(documentConnection, + refMarkName); + + if (sr == null) { + throw new IllegalArgumentException( + "readCitationGroupFromDocumentOrThrow: referenceMarkName is not in the document"); + } + + CitationGroup cg = new CitationGroup(id, + sr, + ov.itcType, + citations, + pageInfo, + refMarkName); + return cg; + } + + /** + * Create a reference mark with the given name, at the + * end of position. + * + * To reduce the difference from the original representation, we + * only insist on having at least two characters inside reference + * marks. These may be ZERO_WIDTH_SPACE characters or other + * placeholder not likely to appear in a citation mark. + * + * This placeholder is only needed if the citation mark is + * otherwise empty (e.g. when we just create it). + * + * getFillCursorForCitationGroup yields a bracketed cursor, that + * can be used to fill in / overwrite the value inside. + * + * After each getFillCursorForCitationGroup, we require a call to + * cleanFillCursorForCitationGroup, which removes the brackets, + * unless if it would make the content less than two + * characters. If we need only one placeholder, we keep the left + * bracket. If we need two, then the content is empty. The + * removeBracketsFromEmpty parameter of + * cleanFillCursorForCitationGroup overrides this, and for empty + * citations it will remove the brackets, leaving an empty + * reference mark. The idea behind this is that we do not need to + * refill empty marks (itcTypes INVISIBLE_CIT), and the caller + * can tell us that we are dealing with one of these. + * + * Thus the only user-visible difference in citation marks is + * that instead of empty marks we use two brackets, for + * single-character marks we add a left bracket before. + * + * Character-attribute inheritance: updates inherit from the + * first character inside, not from the left. + * + * On return {@code position} is collapsed, and is after the + * inserted space, or at the end of the reference mark. + * + * @param documentConnection Connection to document. + * @param position Collapsed to its end. + * @param insertSpaceAfter We insert a space after the mark, that + * carries on format of characters from + * the original position. + * + * @param withoutBrackets Force empty reference mark (no brackets). + * For use with INVISIBLE_CIT. + * + */ + public CitationGroup createCitationGroup(DocumentConnection documentConnection, + List citationKeys, + Optional pageInfo, + int itcType, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) + throws + CreationException, + NoDocumentException, + WrappedTargetException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException { + + String xkey = + citationKeys.stream() + .collect(Collectors.joining(",")); + + Set usedNames = new HashSet<>( this.citationStorageManager + .getUsedNames(documentConnection) ); + String refMarkName = + Codec52.getUniqueMarkName(usedNames, + xkey, + itcType); + + CitationGroupID cgid = new CitationGroupID(refMarkName); + + List citations = (citationKeys.stream() + .map(Citation::new) + .collect(Collectors.toList())); + + /* + * Apply to document + */ + StorageBase.NamedRange sr = this.citationStorageManager.create(documentConnection, + refMarkName, + position, + insertSpaceAfter, + withoutBrackets); + + if ( pageInfo.isPresent() && !pageInfo.get().equals("") ) { + documentConnection.setCustomProperty(refMarkName, pageInfo.get()); + } else { + documentConnection.removeCustomProperty(refMarkName); + } + + CitationGroup cg = new CitationGroup(cgid, + sr, + itcType, + citations, + pageInfo, + refMarkName); + + return cg; + } + + public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException, + NotRemoveableException, + IllegalTypeException, + PropertyExistException { + + String refMarkName = cg.cgRangeStorage.getName(); + cg.cgRangeStorage.removeFromDocument(documentConnection); + documentConnection.removeCustomProperty(refMarkName); + } + +} // end Backend52 + diff --git a/src/main/java/org/jabref/gui/openoffice/Citation.java b/src/main/java/org/jabref/gui/openoffice/Citation.java new file mode 100644 index 00000000000..d75eaed7540 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/Citation.java @@ -0,0 +1,82 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class Citation implements CitationSort.ComparableCitation { + + /** key in database */ + String citationKey; + /** Result from database lookup. Optional.empty() if not found. */ + Optional db; + /** The number used for numbered citation styles . */ + Optional number; + /** Letter that makes the in-text citation unique. */ + Optional uniqueLetter; + + /** pageInfo: For Compat.DataModel.JabRef53 */ + Optional pageInfo; + + /* missing: something that differentiates this from other + * citations of the same citationKey. In particular, a + * CitationGroup may contain multiple citations of the same + * source. We use CitationPath.storageIndexInGroup to refer to + * citations. + */ + + // TODO: Citation constructor needs dataModel, to check + // if usage of pageInfo confirms to expectations. + Citation(String citationKey) { + this.citationKey = citationKey; + this.db = Optional.empty(); + this.number = Optional.empty(); + this.uniqueLetter = Optional.empty(); + this.pageInfo = Optional.empty(); + } + + @Override + public String getCitationKey(){ + return citationKey; + } + + @Override + public Optional getBibEntry(){ + return (db.isPresent() + ? Optional.of(db.get().entry) + : Optional.empty()); + } +} diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroup.java b/src/main/java/org/jabref/gui/openoffice/CitationGroup.java new file mode 100644 index 00000000000..b8f24353ef7 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroup.java @@ -0,0 +1,132 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +class CitationGroup { + CitationGroupID cgid; + StorageBase.NamedRange cgRangeStorage; // knows referenceMarkName + int itcType; + List citations; + List localOrder; + + /** For Compat.DataModel.JabRef52 pageInfo belongs to the group */ + Optional pageInfo; + + /** + * Locator in document, replaced with cgRangeStorage + * TODO: replace referenceMarkName with + * getReferenceMarkName(){ return backed.cgRangeStorage.getName(); } + */ + String referenceMarkName; + + CitationGroup( + CitationGroupID cgid, + StorageBase.NamedRange cgRangeStorage, + int itcType, + List citations, + Optional pageInfo, + String referenceMarkName) { + this.cgid = cgid; + this.cgRangeStorage = cgRangeStorage; + this.itcType = itcType; + this.citations = citations; + this.pageInfo = pageInfo; + this.referenceMarkName = referenceMarkName; + this.localOrder = makeIndices(citations.size()); + } + + + + /** Integers 0..(n-1) */ + static List makeIndices(int n) { + return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); + } + + List getSortedCitations() { + List res = new ArrayList<>(citations.size()); + for (int i : localOrder) { + res.add(citations.get(i)); + } + return res; + } + + List getSortedNumbers() { + List cits = getSortedCitations(); + return (cits.stream() + .map(cit -> cit.number.orElseThrow(RuntimeException::new)) + .collect(Collectors.toList())); + } + + class CitationAndIndex implements CitationSort.ComparableCitation { + Citation c; + int i; + CitationAndIndex(Citation c, int i) { + this.c = c; + this.i = i; + } + + @Override + public String getCitationKey(){ + return c.getCitationKey(); + } + + @Override + public Optional getBibEntry(){ + return c.getBibEntry(); + } + } + + /** + * Sort citations for presentation within a CitationGroup. + */ + void imposeLocalOrderByComparator(Comparator entryComparator) { + List cks = new ArrayList<>(); + for (int i = 0; i < citations.size(); i++) { + Citation c = citations.get(i); + cks.add(new CitationAndIndex(c, i)); + } + cks.sort(new CitationSort.CitationComparator(entryComparator, true)); + + List o = new ArrayList<>(); + for (CitationAndIndex ck : cks) { + o.add(ck.i); + } + this.localOrder = o; + } +} // class CitationGroup diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroups.java b/src/main/java/org/jabref/gui/openoffice/CitationGroups.java new file mode 100644 index 00000000000..76a013a8668 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroups.java @@ -0,0 +1,838 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * At the start of GUI actions we may want to check the state of the document. + * + * Operations: + * createCitationGroup + * deleteCitationGroup + * + */ + +class CitationGroups { + + private static final Logger LOGGER = + LoggerFactory.getLogger(CitationGroups.class); + + // public final Compat.DataModel dataModel; + // private StorageBase.NamedRangeManager citationStorageManager; + public final Backend52 backend; + + /** + * Original CitationGroups Data + */ + private Map citationGroups; + + /** + * Extra Data + */ + // For custom properties belonging to us, but + // without a corresponding reference mark. + // These can be deleted. + private List pageInfoThrash; + + private Optional> globalOrder; + + private Optional citedKeysAfterDatabaseLookup; + + /** + * This is going to be the bibliography + */ + private Optional bibliography; + + /** + * Constructor + */ + public CitationGroups(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + // TODO: dataModel should come from looking at the + // document and preferences. + // + this.backend = new Backend52(); + + // Get the citationGroupNames + List citationGroupNames = this.backend.getJabRefReferenceMarkNames(documentConnection); + + this.pageInfoThrash = + this.backend.findUnusedJabrefPropertyNames(documentConnection, + citationGroupNames); + + this.citationGroups = readCitationGroupsFromDocument(this.backend, + documentConnection, + citationGroupNames); + + // Now we have almost every information from the document about citations. + // What is left out: the ranges controlled by the reference marks. + // But (I guess) those change too easily, so we only ask when actually needed. + + this.globalOrder = Optional.empty(); + this.citedKeysAfterDatabaseLookup = Optional.empty(); + this.bibliography = Optional.empty(); + } + + + + private static Map + readCitationGroupsFromDocument(Backend52 backend, + DocumentConnection documentConnection, + List citationGroupNames) + throws + WrappedTargetException, + NoDocumentException { + + Map citationGroups = new HashMap<>(); + for (int i = 0; i < citationGroupNames.size(); i++) { + final String name = citationGroupNames.get(i); + CitationGroup cg = + backend.readCitationGroupFromDocumentOrThrow(documentConnection, name); + citationGroups.put(cg.cgid, cg); + } + return citationGroups; + } + + public void setDatabaseLookupResults(Set where, + Optional db) { + for (CitationPath p : where) { + CitationGroup cg = this.citationGroups.get(p.group); + if (cg == null) { + LOGGER.warn("CitationGroups.setDatabaseLookupResult: group missing"); + continue; + } + Citation cit = cg.citations.get(p.storageIndexInGroup); + cit.db = db; + } + } + + public CitedKeys lookupEntriesInDatabases(List databases) { + CitationGroups cgs = this; + + CitedKeys cks = cgs.getCitedKeys(); + + cks.lookupInDatabases(databases); + cks.distributeDatabaseLookupResults(cgs); + // record we did a database lookup + // and allow extracting unresolved keys. + this.citedKeysAfterDatabaseLookup = Optional.of(cks); + return cks; + } + + public void setNumbers(Set where, + Optional number) { + for (CitationPath p : where) { + CitationGroup cg = this.citationGroups.get(p.group); + if (cg == null) { + LOGGER.warn("CitationGroups.setNumbers: group missing"); + continue; + } + Citation cit = cg.citations.get(p.storageIndexInGroup); + cit.number = number; + } + } + + public void setUniqueLetters(Set where, + Optional uniqueLetter) { + for (CitationPath p : where) { + CitationGroup cg = this.citationGroups.get(p.group); + if (cg == null) { + LOGGER.warn("CitationGroups.setUniqueLetters: group missing"); + continue; + } + Citation cit = cg.citations.get(p.storageIndexInGroup); + cit.uniqueLetter = uniqueLetter; + } + } + + public void imposeLocalOrderByComparator(Comparator entryComparator) { + for (CitationGroup cg : citationGroups.values()) { + cg.imposeLocalOrderByComparator(entryComparator); + } + } + + public CitedKeys getCitedKeys() { + LinkedHashMap res = new LinkedHashMap<>(); + for (CitationGroup cg : citationGroups.values()) { + int storageIndexInGroup = 0; + for (Citation cit : cg.citations) { + String key = cit.citationKey; + CitationPath p = new CitationPath(cg.cgid, storageIndexInGroup); + if (res.containsKey(key)) { + res.get(key).addPath(p, cit); + } else { + res.put(key, new CitedKey(key, p, cit)); + } + storageIndexInGroup++; + } + } + return new CitedKeys(res); + } + + /** + * CitedKeys created iterating citations in (globalOrder,localOrder) + */ + public CitedKeys getCitedKeysSortedInOrderOfAppearance() { + LinkedHashMap res = new LinkedHashMap<>(); + if (globalOrder.isEmpty()) { + throw new RuntimeException("getSortedCitedKeys: no globalOrder"); + } + for (CitationGroupID cgid : globalOrder.get()) { + CitationGroup cg = getCitationGroup(cgid) + .orElseThrow(RuntimeException::new); + for (int i : cg.localOrder) { + Citation cit = cg.citations.get(i); + String citationKey = cit.citationKey; + CitationPath p = new CitationPath(cgid, i); + if (res.containsKey(citationKey)) { + res.get(citationKey).addPath(p, cit); + } else { + res.put(citationKey, new CitedKey(citationKey, p, cit)); + } + } + } + return new CitedKeys(res); + } + + Optional getBibliography() { + return bibliography; + } + + public void createNumberedBibliographySortedInOrderOfAppearance() { + CitationGroups cgs = this; + if (!cgs.bibliography.isEmpty()) { + throw new RuntimeException( + "createNumberedBibliographySortedInOrderOfAppearance: already have a bibliography"); + } + CitedKeys sortedCitedKeys = + cgs.getCitedKeysSortedInOrderOfAppearance(); + sortedCitedKeys.numberCitedKeysInCurrentOrder(); + sortedCitedKeys.distributeNumbers(cgs); + cgs.bibliography = Optional.of(sortedCitedKeys); + } + + public void createNumberedBibliographySortedByComparator(Comparator entryComparator) { + CitationGroups cgs = this; + if (!cgs.bibliography.isEmpty()) { + throw new RuntimeException( + "createNumberedBibliographySortedByComparator: already have a bibliography"); + } + CitedKeys citedKeys = cgs.getCitedKeys(); + citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup + citedKeys.numberCitedKeysInCurrentOrder(); + citedKeys.distributeNumbers(cgs); + this.bibliography = Optional.of(citedKeys); + } + + public void createPlainBibliographySortedByComparator(Comparator entryComparator) { + CitationGroups cgs = this; + if (!this.bibliography.isEmpty()) { + throw new RuntimeException( + "createPlainBibliographySortedByComparator: already have a bibliography"); + } + CitedKeys citedKeys = cgs.getCitedKeys(); + citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup + // citedKeys.numberCitedKeysInCurrentOrder(); + // citedKeys.distributeNumbers(); + this.bibliography = Optional.of(citedKeys); + } + + public Set getCitationGroupIDs() { + return citationGroups.keySet(); + } + + /** + * Creates a list of {@code + * RangeSortable} values for + * our {@code CitationGroup} values. Originally designed to be + * passed to {@code visualSort}. + * + * The elements of the returned list are actually of type {@code + * RangeSortEntry}. + * + * The result is sorted within {@code XTextRange.getText()} + * partitions of the citation groups according to their {@code + * XTextRange} (before mapping to footnote marks). + * + * In the result, RangeSortable.getIndexInPosition() contains + * unique indexes within the original partition (not after + * mapFootnotesToFootnoteMarks). + * + * @param cgs The source of CitationGroup values. + * @param documentConnection Connection to the document. + * @param mapFootnotesToFootnoteMarks If true, replace ranges in + * footnotes with the range of the corresponding footnote + * mark. This is used for numbering the citations. + * + */ + private static List> + createVisualSortInput(CitationGroups cgs, + DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + NoDocumentException, + WrappedTargetException { + + List cgids = + new ArrayList<>(cgs.getCitationGroupIDs()); + + List vses = new ArrayList<>(); + for (CitationGroupID cgid : cgids) { + XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); + if (range == null) { + throw new RuntimeException("getReferenceMarkRangeOrNull returned null"); + } + vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); + } + + /* + * At this point we are almost ready to return vses. + * + * For example we may want to number citations in a footnote + * as if it appeared where the footnote mark is. + * + * The following code replaces ranges within footnotes with + * the range for the corresponding footnote mark. + * + * This brings further ambiguity if we have multiple + * citations within the same footnote: for the comparison + * they become indistinguishable. Numbering between them is + * not controlled. Also combineCiteMarkers will see them in + * the wrong order (if we use this comparison), and will not + * be able to merge. To avoid these, we sort textually within + * each .getText() partition and add indexInPosition + * accordingly. + * + */ + + // Sort within partitions + RangeKeyedMapList> xxs + = new RangeKeyedMapList<>(); + + for (RangeSort.RangeSortEntry v : vses) { + xxs.add(v.getRange(), v); + } + + // build final list + List> res = new ArrayList<>(); + + for (TreeMap>> + xs : xxs.partitionValues()) { + + List oxs = new ArrayList<>(xs.keySet()); + + int indexInPartition = 0; + for (int i = 0; i < oxs.size(); i++) { + XTextRange a = oxs.get(i); + List> avs = xs.get(a); + for (int j = 0; j < avs.size(); j++) { + RangeSort.RangeSortEntry v = avs.get(j); + v.indexInPosition = indexInPartition++; + if (mapFootnotesToFootnoteMarks) { + // Adjust range if we are inside a footnote: + if (unoQI(XFootnote.class, v.range.getText()) != null) { + // Find the linking footnote marker: + XFootnote footer = unoQI(XFootnote.class, v.range.getText()); + // The footnote's anchor gives the correct position in the text: + v.range = footer.getAnchor(); + } + } + res.add(v); + } + } + } + // convert + // List> + // to + // List> + return res.stream().map(e -> e).collect(Collectors.toList()); + } + + /** + * Return JabRef reference mark names sorted by their visual positions. + * + * @param mapFootnotesToFootnoteMarks If true, sort reference + * marks in footnotes as if they appeared at the + * corresponding footnote mark. + * + * @return JabRef reference mark names sorted by these positions. + * + * Limitation: for two column layout visual (top-down, + * left-right) order does not match the expected (textual) + * order. + * + */ + public List getVisuallySortedCitationGroupIDs(DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + WrappedTargetException, + NoDocumentException, + JabRefException { + CitationGroups cgs = this; + List> vses = + createVisualSortInput(cgs, + documentConnection, + mapFootnotesToFootnoteMarks); + + if (vses.size() != cgs.citationGroups.size()) { + throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + + " vses.size() != cgs.citationGroups.size()"); + } + + String messageOnFailureToObtainAFunctionalXTextViewCursor = + Localization.lang("Please move the cursor into the document text.") + + "\n" + + Localization.lang("To get the visual positions of your citations" + + " I need to move the cursor around," + + " but could not get it."); + List> sorted = + RangeSortVisual.visualSort(vses, + documentConnection, + messageOnFailureToObtainAFunctionalXTextViewCursor); + + if (sorted.size() != cgs.citationGroups.size()) { + // This Fired + throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + + " sorted.size() != cgs.citationGroups.size()"); + } + + return (sorted.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList())); + } + + /** + * Calculate and return citation group IDs in visual order. + */ + public List + getCitationGroupIDsSortedWithinPartitions(DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + NoDocumentException, + WrappedTargetException { + // This is like getVisuallySortedCitationGroupIDs, + // but we skip the visualSort part. + CitationGroups cgs = this; + // boolean mapFootnotesToFootnoteMarks = false; + List> vses = + CitationGroups.createVisualSortInput(cgs, + documentConnection, + mapFootnotesToFootnoteMarks); + + if (vses.size() != cgs.citationGroups.size()) { + throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" + + " vses.size() != cgs.citationGroups.size()"); + } + return (vses.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList())); + } + + /** + * Citation group IDs in {@code globalOrder} + */ + public List getSortedCitationGroupIDs() { + if (globalOrder.isEmpty()) { + throw new RuntimeException("getSortedCitationGroupIDs: not ordered yet"); + } + return globalOrder.get(); + } + + public void setGlobalOrder(List globalOrder) { + Objects.requireNonNull(globalOrder); + if (globalOrder.size() != citationGroups.size()) { + throw new RuntimeException( + "setGlobalOrder: globalOrder.size() != citationGroups.size()"); + } + this.globalOrder = Optional.of(globalOrder); + } + + public Optional getCitationGroup(CitationGroupID cgid) { + CitationGroup e = citationGroups.get(cgid); + return Optional.ofNullable(e); + } + + /** + * Call this when the citation group is unquestionably there. + */ + public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { + CitationGroup e = citationGroups.get(cgid); + if (e == null) { + throw new RuntimeException("getCitationGroupOrThrow:" + + " the requested CitationGroup is not available"); + } + return e; + } + + private Optional getReferenceMarkName(CitationGroupID cgid) { + return getCitationGroup(cgid).map(cg -> cg.referenceMarkName); + } + + private Optional getItcType(CitationGroupID cgid) { + return getCitationGroup(cgid).map(cg -> cg.itcType); + } + + public int numberOfCitationGroups() { + return citationGroups.size(); + } + + public Optional getPageInfo(CitationGroupID cgid) { + return (getCitationGroup(cgid) + .map(cg -> cg.pageInfo) + .flatMap(x -> x)); + } + + public Optional> getCitations(CitationGroupID cgid) { + return getCitationGroup(cgid).map(cg -> cg.citations); + } + + public List getSortedCitations(CitationGroupID cgid) { + Optional cg = getCitationGroup(cgid); + if (cg.isEmpty()) { + throw new RuntimeException("getSortedCitations: invalid cgid"); + } + return cg.get().getSortedCitations(); + } + + /** + * Create a reference mark with the given name, at the + * end of position. + * + * To reduce the difference from the original representation, we + * only insist on having at least two characters inside reference + * marks. These may be ZERO_WIDTH_SPACE characters or other + * placeholder not likely to appear in a citation mark. + * + * This placeholder is only needed if the citation mark is + * otherwise empty (e.g. when we just create it). + * + * getFillCursorForCitationGroup yields a bracketed cursor, that + * can be used to fill in / overwrite the value inside. + * + * After each getFillCursorForCitationGroup, we require a call to + * cleanFillCursorForCitationGroup, which removes the brackets, + * unless if it would make the content less than two + * characters. If we need only one placeholder, we keep the left + * bracket. If we need two, then the content is empty. The + * removeBracketsFromEmpty parameter of + * cleanFillCursorForCitationGroup overrides this, and for empty + * citations it will remove the brackets, leaving an empty + * reference mark. The idea behind this is that we do not need to + * refill empty marks (itcTypes INVISIBLE_CIT), and the caller + * can tell us that we are dealing with one of these. + * + * Thus the only user-visible difference in citation marks is + * that instead of empty marks we use two brackets, for + * single-character marks we add a left bracket before. + * + * Character-attribute inheritance: updates inherit from the + * first character inside, not from the left. + * + * On return {@code position} is collapsed, and is after the + * inserted space, or at the end of the reference mark. + * + * @param documentConnection Connection to document. + * @param position Collapsed to its end. + * @param insertSpaceAfter We insert a space after the mark, that + * carries on format of characters from + * the original position. + * + * @param withoutBrackets Force empty reference mark (no brackets). + * For use with INVISIBLE_CIT. + * + */ + public CitationGroupID createCitationGroup(DocumentConnection documentConnection, + List citationKeys, + Optional pageInfo, + int itcType, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) + throws + CreationException, + NoDocumentException, + WrappedTargetException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException { + + CitationGroup cg = backend.createCitationGroup(documentConnection, + citationKeys, + pageInfo, + itcType, + position, + insertSpaceAfter, + withoutBrackets); + + // add to our data + this.citationGroups.put(cg.cgid, cg); + // invalidate globalOrder. + // TODO: look out for localOrder! + this.globalOrder = Optional.empty(); + + return cg.cgid; + } + + public void removeCitationGroups(List cgs, DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException { + + for (CitationGroup cg : cgs) { + removeCitationGroup( cg, documentConnection ); + } + } + + /* + * Remove it both from {@code this} and the document. + * + * TODO: either invalidate or update the extra data we are storing + * (bibliography). Update may be complicated, since we do + * not know how the bibliography was generated: it was partially done + * outside CitationGroupsV001, and we did not store how. + */ + public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException { + + // documentConnection.removeReferenceMark(cg.referenceMarkName); + backend.removeCitationGroup(cg, documentConnection); + this.citationGroups.remove(cg.cgid); + this.globalOrder.map(l -> l.remove(cg.cgid)); + + // Invalidate CitedKeys + this.citedKeysAfterDatabaseLookup = Optional.empty(); + this.bibliography = Optional.empty(); + /* + * this.citedKeysAfterDatabaseLookup.map(cks -> cks.forgetCitationGroup(cg.cgid)); + * this.bibliography.map(cks -> cks.forgetCitationGroup(cg.cgid)); + */ + } + + /** + * Remove brackets, but if the result would become empty, leave + * them; if the result would be a single characer, leave the left bracket. + * + * @param removeBracketsFromEmpty is intended to force removal if + * we are working on an "Empty citation" (INVISIBLE_CIT). + */ + public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, + CitationGroupID cgid) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + cg.cgRangeStorage.cleanFillCursor(documentConnection); + } + + /** + * Cursor for the reference marks as is, not prepared for filling, + * but does not need cleanFillCursorForCitationGroup either. + */ + public XTextCursor getRawCursorForCitationGroup(CitationGroupID cgid, + DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + return cg.cgRangeStorage.getRawCursor(documentConnection); + } + + public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, + CitationGroupID cgid) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + return cg.cgRangeStorage.getFillCursor(documentConnection); + } + + /** + * Given the name of a reference mark, get the corresponding + * pageInfo text. + * + * @param documentConnection Connection to a document. + * @param name Name of the custom property to query. + * @return "" for missing or empty pageInfo + */ + private static String getPageInfoForReferenceMarkName(DocumentConnection documentConnection, + String name) + throws + WrappedTargetException, + UnknownPropertyException { + + Optional pageInfo = documentConnection.getCustomProperty(name); + if (pageInfo.isEmpty() || pageInfo.get().isEmpty()) { + return ""; + } + return pageInfo.get(); + } + + /** + * ranges controlled by citation groups should not overlap with each other. + * + * @param cgid : Must be known. + * @return Null if the reference mark is missing. + * + * TODO: getReferenceMarkRangeOrNull vs getRawCursorForCitationGroup + */ + public XTextRange getReferenceMarkRangeOrNull(DocumentConnection documentConnection, + CitationGroupID cgid) + throws + NoDocumentException, + WrappedTargetException { + String name = (this.getReferenceMarkName(cgid) + .orElseThrow(RuntimeException::new)); + return documentConnection.getReferenceMarkRangeOrNull(name); + } + + /** + * @return A RangeForOverlapCheck for each citation group. + * + * result.size() == nRefMarks + */ + List citationRanges(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + List xs = new ArrayList<>(numberOfCitationGroups()); + + List cgids = + new ArrayList<>(this.getCitationGroupIDs()); + + for (CitationGroupID cgid : cgids) { + XTextRange r = this.getReferenceMarkRangeOrNull(documentConnection, cgid); + String name = this.getCitationGroup(cgid).get().referenceMarkName; + xs.add(new RangeForOverlapCheck( + r, cgid, + RangeForOverlapCheck.REFERENCE_MARK_KIND, + name)); + } + return xs; + } + + /** + * @return A range for each footnote mark where the footnote + * contains at least one citation group. + * + * Purpose: We do not want markers of footnotes containing + * reference marks to overlap with reference + * marks. Overwriting these footnote marks might kill our + * reference marks in the footnote. + * + */ + List footnoteMarkRanges(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + // Avoid inserting the same mark twice. + // Could use RangeSet if we had that. + RangeKeyedMap seen = new RangeKeyedMap<>(); + + List xs = new ArrayList<>(); + + List citRanges = citationRanges(documentConnection); + + for (RangeForOverlapCheck base : citRanges) { + XTextRange r = base.range; + + XTextRange footnoteMarkRange = + DocumentConnection.getFootnoteMarkRangeOrNull(r); + + if (footnoteMarkRange == null) { + // not in footnote + continue; + } + + boolean seenContains = seen.containsKey(footnoteMarkRange); + if (!seenContains) { + seen.put(footnoteMarkRange, true); + xs.add(new RangeForOverlapCheck( + footnoteMarkRange, + base.i, // cgid :: identifies of citation group + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + base.description)); + } + } + return xs; + } + + public void show() { + System.out.printf("CitationGroupsV001%n"); + System.out.printf(" citationGroups.size: %d%n", citationGroups.size()); + System.out.printf(" pageInfoThrash.size: %d%n", pageInfoThrash.size()); + System.out.printf(" globalOrder: %s%n", + (globalOrder.isEmpty() + ? "isEmpty" + : String.format("%d", globalOrder.get().size()))); + } + + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if + * available, otherwise null. + */ + private static T unoQI(Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + +} diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java b/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java deleted file mode 100644 index a15e10a6abf..00000000000 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupsV001.java +++ /dev/null @@ -1,1226 +0,0 @@ -package org.jabref.gui.openoffice; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; - -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XText; -import com.sun.star.text.XTextContent; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextRange; -import com.sun.star.uno.UnoRuntime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * At the start of GUI actions we may want to check the state of the document. - * - * Operations: - * createCitationGroup - * deleteCitationGroup - * - */ -class CitationGroupsV001 { - - private static final Logger LOGGER = - LoggerFactory.getLogger(CitedKeys.class); - - - static class Citation implements CitationSort.ComparableCitation { - - /** key in database */ - String citationKey; - /** Result from database lookup. Optional.empty() if not found. */ - Optional db; - /** The number used for numbered citation styles . */ - Optional number; - /** Letter that makes the in-text citation unique. */ - Optional uniqueLetter; - - /* missing: something that differentiates this from other - * citations of the same citationKey. In particular, a - * CitationGroup may contain multiple citations of the same - * source. We use CitationPath.storageIndexInGroup to refer to - * citations. - */ - - Citation(String citationKey) { - this.citationKey = citationKey; - this.db = Optional.empty(); - this.number = Optional.empty(); - this.uniqueLetter = Optional.empty(); - } - - @Override - public String getCitationKey(){ - return citationKey; - } - - @Override - public Optional getBibEntry(){ - return (db.isPresent() - ? Optional.of(db.get().entry) - : Optional.empty()); - } - } - - public static class CitationGroup { - CitationGroupID cgid; - StorageBase.NamedRange cgRangeStorage; - int itcType; - List citations; - List localOrder; - // Currently pageInfo belongs to the group - Optional pageInfo; - - /** - * Locator in document - */ - String referenceMarkName; - - CitationGroup( - CitationGroupID cgid, - StorageBase.NamedRange cgRangeStorage, - int itcType, - List citations, - Optional pageInfo, - String referenceMarkName) { - this.cgid = cgid; - this.cgRangeStorage = cgRangeStorage; - this.itcType = itcType; - this.citations = citations; - this.pageInfo = pageInfo; - this.referenceMarkName = referenceMarkName; - this.localOrder = makeIndices(citations.size()); - } - - /** Integers 0..(n-1) */ - static List makeIndices(int n) { - return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); - } - - List - getSortedCitations() { - List res = new ArrayList<>(citations.size()); - for (int i : localOrder) { - res.add(citations.get(i)); - } - return res; - } - - List - getSortedNumbers() { - List cits = getSortedCitations(); - return (cits.stream() - .map(cit -> cit.number.orElseThrow(RuntimeException::new)) - .collect(Collectors.toList())); - } - - class CitationAndIndex implements CitationSort.ComparableCitation { - Citation c; - int i; - CitationAndIndex(Citation c, int i) { - this.c = c; - this.i = i; - } - - @Override - public String getCitationKey(){ - return c.getCitationKey(); - } - - @Override - public Optional getBibEntry(){ - return c.getBibEntry(); - } - } - - /** - * Sort citations for presentation within a CitationGroup. - */ - void imposeLocalOrderByComparator(Comparator entryComparator) { - List cks = new ArrayList<>(); - for (int i = 0; i < citations.size(); i++) { - Citation c = citations.get(i); - cks.add(new CitationAndIndex(c, i)); - } - cks.sort(new CitationSort.CitationComparator(entryComparator, true)); - - List o = new ArrayList<>(); - for (CitationAndIndex ck : cks) { - o.add(ck.i); - } - this.localOrder = o; - } - } // class CitationGroup - - /** - * - */ - public static class CitationGroups { - private StorageBase.NamedRangeManager citationStorageManager; - - /** - * Original CitationGroups Data - */ - private Map citationGroups; - - /** - * Extra Data - */ - // For custom properties belonging to us, but - // without a corresponding reference mark. - // These can be deleted. - private List pageInfoThrash; - - private Optional> globalOrder; - - private Optional citedKeysAfterDatabaseLookup; - - /** - * This is going to be the bibliography - */ - private Optional bibliography; - - /** - * Constructor - */ - public CitationGroups(DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException { - - this.citationStorageManager = new StorageBaseRefMark.Manager(); - - // Get the citationGroupNames - List citationGroupNames = getJabRefReferenceMarkNames(this.citationStorageManager, - documentConnection); - - this.pageInfoThrash = findUnusedJabrefPropertyNames(documentConnection, - citationGroupNames); - - this.citationGroups = readCitationGroupsFromDocument(this.citationStorageManager, - documentConnection, - citationGroupNames); - - // Now we have almost every information from the document about citations. - // What is left out: the ranges controlled by the reference marks. - // But (I guess) those change too easily, so we only ask when actually needed. - - this.globalOrder = Optional.empty(); - this.citedKeysAfterDatabaseLookup = Optional.empty(); - this.bibliography = Optional.empty(); - } - - /** - * Get reference mark names from the document matching the pattern - * used for JabRef reference mark names. - * - * Note: the names returned are in arbitrary order. - * - * - * - */ - public static List getJabRefReferenceMarkNames(StorageBase.NamedRangeManager manager, - DocumentConnection documentConnection) - throws - NoDocumentException { - List allNames = manager.getUsedNames(documentConnection); - return Codec.filterIsJabRefReferenceMarkName(allNames); - } - - private static List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, - List citationGroupNames) { - // Collect unused jabrefPropertyNames - Set citationGroupNamesSet = - citationGroupNames.stream().collect(Collectors.toSet()); - - List pageInfoThrash = new ArrayList<>(); - List jabrefPropertyNames = - documentConnection.getCustomPropertyNames() - .stream() - .filter(Codec::isJabRefReferenceMarkName) - .collect(Collectors.toList()); - for (String pn : jabrefPropertyNames) { - if (!citationGroupNamesSet.contains(pn)) { - pageInfoThrash.add(pn); - } - } - return pageInfoThrash; - } - - private static Map - readCitationGroupsFromDocument(StorageBase.NamedRangeManager citationStorageManager, - DocumentConnection documentConnection, - List citationGroupNames) - throws - WrappedTargetException, - NoDocumentException { - - Map citationGroups = new HashMap<>(); - for (int i = 0; i < citationGroupNames.size(); i++) { - final String name = citationGroupNames.get(i); - CitationGroup cg = - readCitationGroupFromDocumentOrThrow(citationStorageManager, documentConnection, name); - citationGroups.put(cg.cgid, cg); - } - return citationGroups; - } - - private static CitationGroup - readCitationGroupFromDocumentOrThrow(StorageBase.NamedRangeManager citationStorageManager, - DocumentConnection documentConnection, - String refMarkName) - throws - WrappedTargetException, - NoDocumentException { - - Optional op = Codec.parseMarkName(refMarkName); - if (op.isEmpty()) { - // We have a problem. We want types[i] and bibtexKeys[i] - // to correspond to referenceMarkNames.get(i). - // And do not want null in bibtexKeys (or error code in types) - // on return. - throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" - + " found unparsable referenceMarkName"); - } - Codec.ParsedMarkName ov = op.get(); - CitationGroupID id = new CitationGroupID(refMarkName); - List citations = ((ov.citationKeys == null) - ? new ArrayList<>() - : (ov.citationKeys.stream() - .map(Citation::new) - .collect(Collectors.toList()))); - - Optional pageInfo = documentConnection.getCustomProperty(refMarkName); - - StorageBase.NamedRange sr = citationStorageManager.getFromDocumentOrNull(documentConnection, - refMarkName); - - if (sr == null) { - throw new IllegalArgumentException( - "readCitationGroupFromDocumentOrThrow: referenceMarkName is not in the document"); - } - - CitationGroup cg = new CitationGroup(id, - sr, - ov.itcType, - citations, - pageInfo, - refMarkName); - return cg; - } - - public void setDatabaseLookupResults(Set where, - Optional db) { - for (CitationPath p : where) { - CitationGroup cg = this.citationGroups.get(p.group); - if (cg == null) { - LOGGER.warn("CitationGroups.setDatabaseLookupResult: group missing"); - continue; - } - Citation cit = cg.citations.get(p.storageIndexInGroup); - cit.db = db; - } - } - - public CitationGroupsV001.CitedKeys lookupEntriesInDatabases(List databases) { - CitationGroupsV001.CitationGroups cgs = this; - - CitationGroupsV001.CitedKeys cks = cgs.getCitedKeys(); - - cks.lookupInDatabases(databases); - cks.distributeDatabaseLookupResults(cgs); - // record we did a database lookup - // and allow extracting unresolved keys. - this.citedKeysAfterDatabaseLookup = Optional.of(cks); - return cks; - } - - public void setNumbers(Set where, - Optional number) { - for (CitationPath p : where) { - CitationGroup cg = this.citationGroups.get(p.group); - if (cg == null) { - LOGGER.warn("CitationGroups.setNumbers: group missing"); - continue; - } - Citation cit = cg.citations.get(p.storageIndexInGroup); - cit.number = number; - } - } - - public void setUniqueLetters(Set where, - Optional uniqueLetter) { - for (CitationPath p : where) { - CitationGroup cg = this.citationGroups.get(p.group); - if (cg == null) { - LOGGER.warn("CitationGroups.setUniqueLetters: group missing"); - continue; - } - Citation cit = cg.citations.get(p.storageIndexInGroup); - cit.uniqueLetter = uniqueLetter; - } - } - - public void imposeLocalOrderByComparator(Comparator entryComparator) { - for (CitationGroup cg : citationGroups.values()) { - cg.imposeLocalOrderByComparator(entryComparator); - } - } - - public CitedKeys getCitedKeys() { - LinkedHashMap res = new LinkedHashMap<>(); - for (CitationGroup cg : citationGroups.values()) { - int storageIndexInGroup = 0; - for (Citation cit : cg.citations) { - String key = cit.citationKey; - CitationPath p = new CitationPath(cg.cgid, storageIndexInGroup); - if (res.containsKey(key)) { - res.get(key).addPath(p, cit); - } else { - res.put(key, new CitedKey(key, p, cit)); - } - storageIndexInGroup++; - } - } - return new CitedKeys(res); - } - - /** - * CitedKeys created iterating citations in (globalOrder,localOrder) - */ - public CitedKeys getCitedKeysSortedInOrderOfAppearance() { - LinkedHashMap res = new LinkedHashMap<>(); - if (globalOrder.isEmpty()) { - throw new RuntimeException("getSortedCitedKeys: no globalOrder"); - } - for (CitationGroupID cgid : globalOrder.get()) { - CitationGroup cg = getCitationGroup(cgid) - .orElseThrow(RuntimeException::new); - for (int i : cg.localOrder) { - Citation cit = cg.citations.get(i); - String citationKey = cit.citationKey; - CitationPath p = new CitationPath(cgid, i); - if (res.containsKey(citationKey)) { - res.get(citationKey).addPath(p, cit); - } else { - res.put(citationKey, new CitedKey(citationKey, p, cit)); - } - } - } - return new CitedKeys(res); - } - - Optional getBibliography() { - return bibliography; - } - - public void createNumberedBibliographySortedInOrderOfAppearance() { - CitationGroupsV001.CitationGroups cgs = this; - if (!cgs.bibliography.isEmpty()) { - throw new RuntimeException( - "createNumberedBibliographySortedInOrderOfAppearance: already have a bibliography"); - } - CitationGroupsV001.CitedKeys sortedCitedKeys = - cgs.getCitedKeysSortedInOrderOfAppearance(); - sortedCitedKeys.numberCitedKeysInCurrentOrder(); - sortedCitedKeys.distributeNumbers(cgs); - cgs.bibliography = Optional.of(sortedCitedKeys); - } - - public void createNumberedBibliographySortedByComparator(Comparator entryComparator) { - CitationGroupsV001.CitationGroups cgs = this; - if (!cgs.bibliography.isEmpty()) { - throw new RuntimeException( - "createNumberedBibliographySortedByComparator: already have a bibliography"); - } - CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); - citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup - citedKeys.numberCitedKeysInCurrentOrder(); - citedKeys.distributeNumbers(cgs); - this.bibliography = Optional.of(citedKeys); - } - - public void createPlainBibliographySortedByComparator(Comparator entryComparator) { - CitationGroupsV001.CitationGroups cgs = this; - if (!this.bibliography.isEmpty()) { - throw new RuntimeException( - "createPlainBibliographySortedByComparator: already have a bibliography"); - } - CitationGroupsV001.CitedKeys citedKeys = cgs.getCitedKeys(); - citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup - // citedKeys.numberCitedKeysInCurrentOrder(); - // citedKeys.distributeNumbers(); - this.bibliography = Optional.of(citedKeys); - } - - public Set getCitationGroupIDs() { - return citationGroups.keySet(); - } - - /** - * Creates a list of {@code - * RangeSortable} values for - * our {@code CitationGroup} values. Originally designed to be - * passed to {@code visualSort}. - * - * The elements of the returned list are actually of type {@code - * RangeSortEntry}. - * - * The result is sorted within {@code XTextRange.getText()} - * partitions of the citation groups according to their {@code - * XTextRange} (before mapping to footnote marks). - * - * In the result, RangeSortable.getIndexInPosition() contains - * unique indexes within the original partition (not after - * mapFootnotesToFootnoteMarks). - * - * @param cgs The source of CitationGroup values. - * @param documentConnection Connection to the document. - * @param mapFootnotesToFootnoteMarks If true, replace ranges in - * footnotes with the range of the corresponding footnote - * mark. This is used for numbering the citations. - * - */ - private static List> - createVisualSortInput(CitationGroupsV001.CitationGroups cgs, - DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - NoDocumentException, - WrappedTargetException { - - List cgids = - new ArrayList<>(cgs.getCitationGroupIDs()); - - List vses = new ArrayList<>(); - for (CitationGroupID cgid : cgids) { - XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); - if (range == null) { - throw new RuntimeException("getReferenceMarkRangeOrNull returned null"); - } - vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); - } - - /* - * At this point we are almost ready to return vses. - * - * For example we may want to number citations in a footnote - * as if it appeared where the footnote mark is. - * - * The following code replaces ranges within footnotes with - * the range for the corresponding footnote mark. - * - * This brings further ambiguity if we have multiple - * citations within the same footnote: for the comparison - * they become indistinguishable. Numbering between them is - * not controlled. Also combineCiteMarkers will see them in - * the wrong order (if we use this comparison), and will not - * be able to merge. To avoid these, we sort textually within - * each .getText() partition and add indexInPosition - * accordingly. - * - */ - - // Sort within partitions - RangeKeyedMapList> xxs - = new RangeKeyedMapList<>(); - - for (RangeSort.RangeSortEntry v : vses) { - xxs.add(v.getRange(), v); - } - - // build final list - List> res = new ArrayList<>(); - - for (TreeMap>> - xs : xxs.partitionValues()) { - - List oxs = new ArrayList<>(xs.keySet()); - - int indexInPartition = 0; - for (int i = 0; i < oxs.size(); i++) { - XTextRange a = oxs.get(i); - List> avs = xs.get(a); - for (int j = 0; j < avs.size(); j++) { - RangeSort.RangeSortEntry v = avs.get(j); - v.indexInPosition = indexInPartition++; - if (mapFootnotesToFootnoteMarks) { - // Adjust range if we are inside a footnote: - if (unoQI(XFootnote.class, v.range.getText()) != null) { - // Find the linking footnote marker: - XFootnote footer = unoQI(XFootnote.class, v.range.getText()); - // The footnote's anchor gives the correct position in the text: - v.range = footer.getAnchor(); - } - } - res.add(v); - } - } - } - // convert - // List> - // to - // List> - return res.stream().map(e -> e).collect(Collectors.toList()); - } - - /** - * Return JabRef reference mark names sorted by their visual positions. - * - * @param mapFootnotesToFootnoteMarks If true, sort reference - * marks in footnotes as if they appeared at the - * corresponding footnote mark. - * - * @return JabRef reference mark names sorted by these positions. - * - * Limitation: for two column layout visual (top-down, - * left-right) order does not match the expected (textual) - * order. - * - */ - public List - getVisuallySortedCitationGroupIDs(DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - WrappedTargetException, - NoDocumentException, - JabRefException { - CitationGroupsV001.CitationGroups cgs = this; - List> vses = - createVisualSortInput(cgs, - documentConnection, - mapFootnotesToFootnoteMarks); - - if (vses.size() != cgs.citationGroups.size()) { - throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " vses.size() != cgs.citationGroups.size()"); - } - - String messageOnFailureToObtainAFunctionalXTextViewCursor = - Localization.lang("Please move the cursor into the document text.") - + "\n" - + Localization.lang("To get the visual positions of your citations" - + " I need to move the cursor around," - + " but could not get it."); - List> sorted = - RangeSortVisual.visualSort(vses, - documentConnection, - messageOnFailureToObtainAFunctionalXTextViewCursor); - - if (sorted.size() != cgs.citationGroups.size()) { - // This Fired - throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " sorted.size() != cgs.citationGroups.size()"); - } - - return (sorted.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList())); - } - - /** - * Calculate and return citation group IDs in visual order. - */ - public List - getCitationGroupIDsSortedWithinPartitions(DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - NoDocumentException, - WrappedTargetException { - // This is like getVisuallySortedCitationGroupIDs, - // but we skip the visualSort part. - CitationGroupsV001.CitationGroups cgs = this; - // boolean mapFootnotesToFootnoteMarks = false; - List> vses = - CitationGroupsV001.CitationGroups.createVisualSortInput(cgs, - documentConnection, - mapFootnotesToFootnoteMarks); - - if (vses.size() != cgs.citationGroups.size()) { - throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" - + " vses.size() != cgs.citationGroups.size()"); - } - return (vses.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList())); - } - - /** - * Citation group IDs in {@code globalOrder} - */ - public List getSortedCitationGroupIDs() { - if (globalOrder.isEmpty()) { - throw new RuntimeException("getSortedCitationGroupIDs: not ordered yet"); - } - return globalOrder.get(); - } - - public void setGlobalOrder(List globalOrder) { - Objects.requireNonNull(globalOrder); - if (globalOrder.size() != citationGroups.size()) { - throw new RuntimeException( - "CitationGroupsV001.setGlobalOrder: globalOrder.size() != citationGroups.size()"); - } - this.globalOrder = Optional.of(globalOrder); - } - - public Optional getCitationGroup(CitationGroupID cgid) { - CitationGroup e = citationGroups.get(cgid); - return Optional.ofNullable(e); - } - - /** - * Call this when the citation group is unquestionably there. - */ - public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { - CitationGroup e = citationGroups.get(cgid); - if (e == null) { - throw new RuntimeException("CitationGroupsV001.getCitationGroupOrThrow:" - + " the requested CitationGroup is not available"); - } - return e; - } - - private Optional getReferenceMarkName(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.referenceMarkName); - } - - private Optional getItcType(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.itcType); - } - - public int numberOfCitationGroups() { - return citationGroups.size(); - } - - public Optional getPageInfo(CitationGroupID cgid) { - return (getCitationGroup(cgid) - .map(cg -> cg.pageInfo) - .flatMap(x -> x)); - } - - public Optional> getCitations(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.citations); - } - - public List getSortedCitations(CitationGroupID cgid) { - Optional cg = getCitationGroup(cgid); - if (cg.isEmpty()) { - throw new RuntimeException("getSortedCitations: invalid cgid"); - } - return cg.get().getSortedCitations(); - } - - /** - * Create a reference mark with the given name, at the - * end of position. - * - * To reduce the difference from the original representation, we - * only insist on having at least two characters inside reference - * marks. These may be ZERO_WIDTH_SPACE characters or other - * placeholder not likely to appear in a citation mark. - * - * This placeholder is only needed if the citation mark is - * otherwise empty (e.g. when we just create it). - * - * getFillCursorForCitationGroup yields a bracketed cursor, that - * can be used to fill in / overwrite the value inside. - * - * After each getFillCursorForCitationGroup, we require a call to - * cleanFillCursorForCitationGroup, which removes the brackets, - * unless if it would make the content less than two - * characters. If we need only one placeholder, we keep the left - * bracket. If we need two, then the content is empty. The - * removeBracketsFromEmpty parameter of - * cleanFillCursorForCitationGroup overrides this, and for empty - * citations it will remove the brackets, leaving an empty - * reference mark. The idea behind this is that we do not need to - * refill empty marks (itcTypes INVISIBLE_CIT), and the caller - * can tell us that we are dealing with one of these. - * - * Thus the only user-visible difference in citation marks is - * that instead of empty marks we use two brackets, for - * single-character marks we add a left bracket before. - * - * Character-attribute inheritance: updates inherit from the - * first character inside, not from the left. - * - * On return {@code position} is collapsed, and is after the - * inserted space, or at the end of the reference mark. - * - * @param documentConnection Connection to document. - * @param position Collapsed to its end. - * @param insertSpaceAfter We insert a space after the mark, that - * carries on format of characters from - * the original position. - * - * @param withoutBrackets Force empty reference mark (no brackets). - * For use with INVISIBLE_CIT. - * - */ - public CitationGroupID createCitationGroup(DocumentConnection documentConnection, - List citationKeys, - Optional pageInfo, - int itcType, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) - throws - CreationException, - NoDocumentException, - WrappedTargetException { - - String xkey = - citationKeys.stream() - .collect(Collectors.joining(",")); - - Set usedNames = new HashSet<>( this.citationStorageManager - .getUsedNames(documentConnection) ); - String refMarkName = - Codec.getUniqueMarkName(usedNames, - xkey, - itcType); - - CitationGroupID cgid = new CitationGroupID(refMarkName); - - List citations = - citationKeys.stream() - .map(Citation::new) - .collect(Collectors.toList()); - - /* - * Apply to document - */ - StorageBase.NamedRange sr = createReferenceMarkForCitationGroup( - this.citationStorageManager, - documentConnection, - refMarkName, - position, - insertSpaceAfter, - withoutBrackets); - - CitationGroup cg = new CitationGroup(cgid, - sr, - itcType, - citations, - pageInfo, - refMarkName); - - // add to our data - this.citationGroups.put(cgid, cg); - // invalidate globalOrder. - // TODO: look out for localOrder! - this.globalOrder = Optional.empty(); - - return cgid; - } - - private static StorageBase.NamedRange - createReferenceMarkForCitationGroup(StorageBase.NamedRangeManager manager, - DocumentConnection documentConnection, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) - throws - CreationException { - - return manager.create(documentConnection, - refMarkName, - position, - insertSpaceAfter, - withoutBrackets); - } - - /* - * Remove it from the {@code this} and the document. - * - * TODO: either invalidate or update the extra data we are storing - * (bibliography). Update may be complicated, since we do - * not know how the bibliography was generated: it was partially done - * outside CitationGroupsV001, and we did not store how. - */ - public void removeCitationGroups(List cgs, DocumentConnection documentConnection) - throws - WrappedTargetException, - NoDocumentException, - NoSuchElementException { - - for (CitationGroup cg : cgs) { - //documentConnection.removeReferenceMark(cg.referenceMarkName); - cg.cgRangeStorage.removeFromDocument(documentConnection); - this.citationGroups.remove(cg.cgid); - this.globalOrder.map(l -> l.remove(cg.cgid)); - - // Invalidate CitedKeys - this.citedKeysAfterDatabaseLookup = Optional.empty(); - this.bibliography = Optional.empty(); - /* - * this.citedKeysAfterDatabaseLookup.map(cks -> cks.forgetCitationGroup(cg.cgid)); - * this.bibliography.map(cks -> cks.forgetCitationGroup(cg.cgid)); - */ - } - } - - public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) - throws - WrappedTargetException, - NoDocumentException, - NoSuchElementException { - - removeCitationGroups(Collections.singletonList(cg), documentConnection); - } - - /** - * Remove brackets, but if the result would become empty, leave - * them; if the result would be a single characer, leave the left bracket. - * - * @param removeBracketsFromEmpty is intended to force removal if - * we are working on an "Empty citation" (INVISIBLE_CIT). - */ - public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, - CitationGroupID cgid) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - cg.cgRangeStorage.cleanFillCursor(documentConnection); - } - - /** - * Cursor for the reference marks as is, not prepared for filling, - * but does not need cleanFillCursorForCitationGroup either. - */ - public XTextCursor getRawCursorForCitationGroup(CitationGroupID cgid, - DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return cg.cgRangeStorage.getRawCursor(documentConnection); - } - - public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, - CitationGroupID cgid) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return cg.cgRangeStorage.getFillCursor(documentConnection); - } - - /** - * Given the name of a reference mark, get the corresponding - * pageInfo text. - * - * @param documentConnection Connection to a document. - * @param name Name of the custom property to query. - * @return "" for missing or empty pageInfo - */ - private static String getPageInfoForReferenceMarkName(DocumentConnection documentConnection, - String name) - throws - WrappedTargetException, - UnknownPropertyException { - - Optional pageInfo = documentConnection.getCustomProperty(name); - if (pageInfo.isEmpty() || pageInfo.get().isEmpty()) { - return ""; - } - return pageInfo.get(); - } - - /** - * ranges controlled by citation groups should not overlap with each other. - * - * @param cgid : Must be known. - * @return Null if the reference mark is missing. - * - * TODO: getReferenceMarkRangeOrNull vs getRawCursorForCitationGroup - */ - public XTextRange getReferenceMarkRangeOrNull(DocumentConnection documentConnection, - CitationGroupID cgid) - throws - NoDocumentException, - WrappedTargetException { - String name = (this.getReferenceMarkName(cgid) - .orElseThrow(RuntimeException::new)); - return documentConnection.getReferenceMarkRangeOrNull(name); - } - - /** - * @return A RangeForOverlapCheck for each citation group. - * - * result.size() == nRefMarks - */ - List citationRanges(DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException { - - List xs = new ArrayList<>(numberOfCitationGroups()); - - List cgids = - new ArrayList<>(this.getCitationGroupIDs()); - - for (CitationGroupID cgid : cgids) { - XTextRange r = this.getReferenceMarkRangeOrNull(documentConnection, cgid); - String name = this.getCitationGroup(cgid).get().referenceMarkName; - xs.add(new RangeForOverlapCheck( - r, cgid, - RangeForOverlapCheck.REFERENCE_MARK_KIND, - name)); - } - return xs; - } - - /** - * @return A range for each footnote mark where the footnote - * contains at least one citation group. - * - * Purpose: We do not want markers of footnotes containing - * reference marks to overlap with reference - * marks. Overwriting these footnote marks might kill our - * reference marks in the footnote. - * - */ - List footnoteMarkRanges(DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException { - - // Avoid inserting the same mark twice. - // Could use RangeSet if we had that. - RangeKeyedMap seen = new RangeKeyedMap<>(); - - List xs = new ArrayList<>(); - - List citRanges = citationRanges(documentConnection); - - for (RangeForOverlapCheck base : citRanges) { - XTextRange r = base.range; - - XTextRange footnoteMarkRange = - DocumentConnection.getFootnoteMarkRangeOrNull(r); - - if (footnoteMarkRange == null) { - // not in footnote - continue; - } - - boolean seenContains = seen.containsKey(footnoteMarkRange); - if (!seenContains) { - seen.put(footnoteMarkRange, true); - xs.add(new RangeForOverlapCheck( - footnoteMarkRange, - base.i, // cgid :: identifies of citation group - RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + base.description)); - } - } - return xs; - } - - public void show() { - System.out.printf("CitationGroupsV001%n"); - System.out.printf(" citationGroups.size: %d%n", citationGroups.size()); - System.out.printf(" pageInfoThrash.size: %d%n", pageInfoThrash.size()); - System.out.printf(" globalOrder: %s%n", - (globalOrder.isEmpty() - ? "isEmpty" - : String.format("%d", globalOrder.get().size()))); - } -} - - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if - * available, otherwise null. - */ - private static T unoQI(Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - - - - /** - * Identifies a citation with the citation group containing it and - * its storage index within. - */ - public static class CitationPath { - CitationGroupID group; - int storageIndexInGroup; - CitationPath(CitationGroupID group, - int storageIndexInGroup) { - this.group = group; - this.storageIndexInGroup = storageIndexInGroup; - } - } - - - public static class CitedKey implements CitationSort.ComparableCitation { - String citationKey; - LinkedHashSet where; - Optional db; - Optional number; // For Numbered citation styles. - Optional uniqueLetter; // For AuthorYear citation styles. - Optional normCitMarker; // For AuthorYear citation styles. - - CitedKey(String citationKey, CitationPath p, Citation cit) { - this.citationKey = citationKey; - this.where = new LinkedHashSet<>(); // remember order - this.where.add(p); - this.db = cit.db; - this.number = cit.number; - this.uniqueLetter = cit.uniqueLetter; - this.normCitMarker = Optional.empty(); - } - - @Override - public String getCitationKey(){ - return citationKey; - } - - @Override - public Optional getBibEntry(){ - return (db.isPresent() - ? Optional.of(db.get().entry) - : Optional.empty()); - } - - /** - * Appends to end of {@code where} - */ - void addPath(CitationPath p, Citation cit) { - this.where.add(p); - if (cit.db != this.db) { - throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); - } - if (cit.number != this.number) { - throw new RuntimeException("CitedKey.addPath: mismatch on cit.number"); - } - if (cit.uniqueLetter != this.uniqueLetter) { - throw new RuntimeException("CitedKey.addPath: mismatch on cit.uniqueLetter"); - } - } - - void lookupInDatabases(List databases) { - this.db = CitationDatabaseLookup.lookup(databases, this.citationKey); - } - - void distributeDatabaseLookupResult(CitationGroupsV001.CitationGroups cgs) { - cgs.setDatabaseLookupResults(where, db); - } - - void distributeNumber(CitationGroupsV001.CitationGroups cgs) { - cgs.setNumbers(where, number); - } - - void distributeUniqueLetter(CitationGroupsV001.CitationGroups cgs) { - cgs.setUniqueLetters(where, uniqueLetter); - } - } // class CitedKey - - public static class CitedKeys { - - /** - * Order-preserving map from citation keys to associated data. - */ - LinkedHashMap data; - - CitedKeys(LinkedHashMap data) { - this.data = data; - } - - /** - * The cited keys in sorted order. - */ - public List values() { - return new ArrayList<>(data.values()); - } - - /** - * Sort entries for the bibliography. - */ - void sortByComparator(Comparator entryComparator) { - List cks = new ArrayList<>(data.values()); - cks.sort(new CitationSort.CitationComparator(entryComparator, true)); - LinkedHashMap newData = new LinkedHashMap<>(); - for (CitedKey ck : cks) { - newData.put(ck.citationKey, ck); - } - data = newData; - } - - void numberCitedKeysInCurrentOrder() { - int i = 1; - for (CitedKey ck : data.values()) { - ck.number = Optional.of(i); // was: -1 for UndefinedBibtexEntry - i++; - } - } - - void lookupInDatabases(List databases) { - for (CitedKey ck : this.data.values()) { - ck.lookupInDatabases(databases); - } - } - - void distributeDatabaseLookupResults(CitationGroupsV001.CitationGroups cgs) { - for (CitedKey ck : this.data.values()) { - ck.distributeDatabaseLookupResult(cgs); - } - } - - void distributeNumbers(CitationGroupsV001.CitationGroups cgs) { - for (CitedKey ck : this.data.values()) { - ck.distributeNumber(cgs); - } - } - - void distributeUniqueLetters(CitationGroupsV001.CitationGroups cgs) { - for (CitedKey ck : this.data.values()) { - ck.distributeUniqueLetter(cgs); - } - } - - } // class CitedKeys - - -} // class CitationGroupsV001 - diff --git a/src/main/java/org/jabref/gui/openoffice/CitationPath.java b/src/main/java/org/jabref/gui/openoffice/CitationPath.java new file mode 100644 index 00000000000..71ea7e4af5b --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/CitationPath.java @@ -0,0 +1,15 @@ +package org.jabref.gui.openoffice; + +/** + * Identifies a citation with the citation group containing it and + * its storage index within. + */ +class CitationPath { + CitationGroupID group; + int storageIndexInGroup; + CitationPath(CitationGroupID group, + int storageIndexInGroup) { + this.group = group; + this.storageIndexInGroup = storageIndexInGroup; + } +} diff --git a/src/main/java/org/jabref/gui/openoffice/CitedKey.java b/src/main/java/org/jabref/gui/openoffice/CitedKey.java new file mode 100644 index 00000000000..f07bc2969e8 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/CitedKey.java @@ -0,0 +1,101 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class CitedKey implements CitationSort.ComparableCitation { + String citationKey; + LinkedHashSet where; + Optional db; + Optional number; // For Numbered citation styles. + Optional uniqueLetter; // For AuthorYear citation styles. + Optional normCitMarker; // For AuthorYear citation styles. + + CitedKey(String citationKey, CitationPath p, Citation cit) { + this.citationKey = citationKey; + this.where = new LinkedHashSet<>(); // remember order + this.where.add(p); + this.db = cit.db; + this.number = cit.number; + this.uniqueLetter = cit.uniqueLetter; + this.normCitMarker = Optional.empty(); + } + + @Override + public String getCitationKey(){ + return citationKey; + } + + @Override + public Optional getBibEntry(){ + return (db.isPresent() + ? Optional.of(db.get().entry) + : Optional.empty()); + } + + /** + * Appends to end of {@code where} + */ + void addPath(CitationPath p, Citation cit) { + this.where.add(p); + if (cit.db != this.db) { + throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); + } + if (cit.number != this.number) { + throw new RuntimeException("CitedKey.addPath: mismatch on cit.number"); + } + if (cit.uniqueLetter != this.uniqueLetter) { + throw new RuntimeException("CitedKey.addPath: mismatch on cit.uniqueLetter"); + } + } + + void lookupInDatabases(List databases) { + this.db = CitationDatabaseLookup.lookup(databases, this.citationKey); + } + + void distributeDatabaseLookupResult(CitationGroups cgs) { + cgs.setDatabaseLookupResults(where, db); + } + + void distributeNumber(CitationGroups cgs) { + cgs.setNumbers(where, number); + } + + void distributeUniqueLetter(CitationGroups cgs) { + cgs.setUniqueLetters(where, uniqueLetter); + } +} // class CitedKey diff --git a/src/main/java/org/jabref/gui/openoffice/CitedKeys.java b/src/main/java/org/jabref/gui/openoffice/CitedKeys.java new file mode 100644 index 00000000000..014f94b80a1 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/CitedKeys.java @@ -0,0 +1,104 @@ +package org.jabref.gui.openoffice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +class CitedKeys { + + /** + * Order-preserving map from citation keys to associated data. + */ + LinkedHashMap data; + + CitedKeys(LinkedHashMap data) { + this.data = data; + } + + /** + * The cited keys in sorted order. + */ + public List values() { + return new ArrayList<>(data.values()); + } + + /** + * Sort entries for the bibliography. + */ + void sortByComparator(Comparator entryComparator) { + List cks = new ArrayList<>(data.values()); + cks.sort(new CitationSort.CitationComparator(entryComparator, true)); + LinkedHashMap newData = new LinkedHashMap<>(); + for (CitedKey ck : cks) { + newData.put(ck.citationKey, ck); + } + data = newData; + } + + void numberCitedKeysInCurrentOrder() { + int i = 1; + for (CitedKey ck : data.values()) { + ck.number = Optional.of(i); // was: -1 for UndefinedBibtexEntry + i++; + } + } + + void lookupInDatabases(List databases) { + for (CitedKey ck : this.data.values()) { + ck.lookupInDatabases(databases); + } + } + + void distributeDatabaseLookupResults(CitationGroups cgs) { + for (CitedKey ck : this.data.values()) { + ck.distributeDatabaseLookupResult(cgs); + } + } + + void distributeNumbers(CitationGroups cgs) { + for (CitedKey ck : this.data.values()) { + ck.distributeNumber(cgs); + } + } + + void distributeUniqueLetters(CitationGroups cgs) { + for (CitedKey ck : this.data.values()) { + ck.distributeUniqueLetter(cgs); + } + } + +} // class CitedKeys diff --git a/src/main/java/org/jabref/gui/openoffice/Codec.java b/src/main/java/org/jabref/gui/openoffice/Codec52.java similarity index 96% rename from src/main/java/org/jabref/gui/openoffice/Codec.java rename to src/main/java/org/jabref/gui/openoffice/Codec52.java index 00ac55d6229..b3b65e92d86 100644 --- a/src/main/java/org/jabref/gui/openoffice/Codec.java +++ b/src/main/java/org/jabref/gui/openoffice/Codec52.java @@ -42,7 +42,7 @@ * - pageInfo does not appear here. It is not encoded in the mark name. * - Does not depend on the type of marks (reference mark of bookmark) used. */ -class Codec { +class Codec52 { private static final String BIB_CITATION = "JR_cite"; private static final Pattern CITE_PATTERN = // Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); @@ -113,7 +113,7 @@ public static Optional parseMarkName(String refMarkName) { List keys = Arrays.asList(citeMatcher.group(3).split(",")); String i = citeMatcher.group(1); int itcType = Integer.parseInt(citeMatcher.group(2)); - return (Optional.of(new Codec.ParsedMarkName(i, itcType, keys))); + return (Optional.of(new Codec52.ParsedMarkName(i, itcType, keys))); } /** @@ -132,7 +132,7 @@ public static boolean isJabRefReferenceMarkName(String name) { public static List filterIsJabRefReferenceMarkName(List names) { return (names .stream() - .filter(Codec::isJabRefReferenceMarkName) + .filter(Codec52::isJabRefReferenceMarkName) .collect(Collectors.toList())); } } diff --git a/src/main/java/org/jabref/gui/openoffice/Compat.java b/src/main/java/org/jabref/gui/openoffice/Compat.java new file mode 100644 index 00000000000..68565031791 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/Compat.java @@ -0,0 +1,34 @@ +package org.jabref.gui.openoffice; + +class Compat { + + /** What is the data stored? */ + public enum DataModel { + /** + * JabRef52: + * pageInfo belongs to CitationGroup, not Citation. + * + * Note: pageInfo stored in [File]/[Properties]/[Custom Properties] + * + * under the same name as the reference mark for the + * CitationGroup. + * + * JabRef "Merge" leaves pageInfo values of the parts joined + * around. Separate, or a new citation may pick these up. + * + * In-text citep format: "[ ... ; pageInfo]", injected just before the + * closing parenthesis (here "]"), with "; " as a separator. + * + * citet format: the same, (injected to parens around + * year of last citation of the group) + */ + JabRef52, + + /** + * JabRef53: + * pageInfo belongs to Citation. + * Need: formatting citation needs to know about these, inject after each year part + */ + JabRef53 + } +} diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java index e13f33aaa9d..d3b010ca934 100644 --- a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java @@ -462,7 +462,7 @@ class DocumentConnection { public void setCustomProperty(String property, String value) throws - UnknownPropertyException, + // UnknownPropertyException, NotRemoveableException, PropertyExistException, IllegalTypeException, @@ -471,7 +471,7 @@ class DocumentConnection { XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); if (psi.hasPropertyByName(property)) { - this.userProperties.removeProperty(property); + this.removeCustomProperty(property); } if (value != null) { @@ -483,6 +483,30 @@ class DocumentConnection { } } + /** + * @param property Name of a custom document property in the + * current document. + */ + public void removeCustomProperty(String property) + throws + // UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException { + + XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + + if (psi.hasPropertyByName(property)) { + try { + this.userProperties.removeProperty(property); + } catch (UnknownPropertyException ex) { + throw new RuntimeException("removeCustomProperty caught UnknownPropertyException" + + " (should be impossible)"); + } + } + } + /** * @throws NoDocumentException If cannot get reference marks * diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7083a8fe6f6..8e775790c80 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -468,7 +468,7 @@ private static T unoQI(Class zInterface, * @param requireSeparation Report range pairs that only share a boundary. * @param reportAtMost Limit number of overlaps reported (0 for no limit) */ - public void checkRangeOverlaps(CitationGroupsV001.CitationGroups cgs, + public void checkRangeOverlaps(CitationGroups cgs, DocumentConnection documentConnection, boolean requireSeparation, int reportAtMost) @@ -553,7 +553,7 @@ public List getCitationEntries() CreationException { DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); + CitationGroups cgs = new CitationGroups(documentConnection); int n = cgs.numberOfCitationGroups(); List citations = new ArrayList<>(n); @@ -581,7 +581,7 @@ public List getCitationEntries() * @param htmlMarkup If true, the text belonging to the * reference mark is surrounded by bold html tag. */ - private String getCitationContext(CitationGroupsV001.CitationGroups cgs, + private String getCitationContext(CitationGroups cgs, CitationGroupID cgid, DocumentConnection documentConnection, int charBefore, @@ -765,7 +765,7 @@ public void applyCitationEntries( * * **************************************/ - private String normalizedCitationMarkerForNormalStyle(CitationGroupsV001.CitedKey ck, + private String normalizedCitationMarkerForNormalStyle(CitedKey ck, OOBibStyle style) { if (ck.db.isEmpty()){ return String.format("(Unresolved(%s))", ck.citationKey); @@ -786,10 +786,10 @@ private String normalizedCitationMarkerForNormalStyle(CitationGroupsV001.CitedKe * Fills {@code sortedCitedKeys//normCitMarker} */ private void - createNormalizedCitationMarkersForNormalStyle(CitationGroupsV001.CitedKeys sortedCitedKeys, + createNormalizedCitationMarkersForNormalStyle(CitedKeys sortedCitedKeys, OOBibStyle style) { - for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.data.values()) { + for (CitedKey ck : sortedCitedKeys.data.values()) { ck.normCitMarker = Optional.of(normalizedCitationMarkerForNormalStyle(ck, style)); } } @@ -811,8 +811,8 @@ private String normalizedCitationMarkerForNormalStyle(CitationGroupsV001.CitedKe * * Depends on: style, citations and their order. */ - void createUniqueLetters(CitationGroupsV001.CitedKeys sortedCitedKeys, - CitationGroupsV001.CitationGroups cgs) { + void createUniqueLetters(CitedKeys sortedCitedKeys, + CitationGroups cgs) { // ncm2clks: ncm (normCitMarker) to clks (clashing keys : list of citation keys fighting for it). // @@ -823,7 +823,7 @@ void createUniqueLetters(CitationGroupsV001.CitedKeys sortedCitedKeys, // unique letter it receives. // Map> ncm2clks = new HashMap<>(); - for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.values()) { + for (CitedKey ck : sortedCitedKeys.values()) { String ncm = ck.normCitMarker.get(); String citationKey = ck.citationKey; @@ -843,7 +843,7 @@ void createUniqueLetters(CitationGroupsV001.CitedKeys sortedCitedKeys, // Map uniqueLetters = new HashMap<>(); // uniqueLetters.clear(); - for (CitationGroupsV001.CitedKey ck : sortedCitedKeys.data.values()) { + for (CitedKey ck : sortedCitedKeys.data.values()) { ck.uniqueLetter = Optional.empty(); } @@ -895,7 +895,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * markers are the citation keys themselves, separated by commas. */ private static Map - produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroupsV001.CitationGroups cgs, + produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroups cgs, OOBibStyle style) throws BibEntryNotFoundException { @@ -907,7 +907,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - List cits = cgs.getSortedCitations(cgid); + List cits = cgs.getSortedCitations(cgid); String citMarker = (cits.stream() .map(cit -> cit.citationKey) .collect(Collectors.joining(","))); @@ -935,7 +935,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * */ private static Map - produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroupsV001.CitationGroups cgs, + produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, OOBibStyle style) throws BibEntryNotFoundException { @@ -950,7 +950,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, false)); @@ -964,7 +964,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * when the bibliography is not sorted by position. */ private Map - produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroupsV001.CitationGroups cgs, + produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, OOBibStyle style) { assert style.isNumberEntries(); assert !style.isSortByPosition(); @@ -977,7 +977,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, false)); @@ -997,7 +997,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * @param style Bibliography style. */ private Map - produceCitationMarkersForNormalStyle(CitationGroupsV001.CitationGroups cgs, + produceCitationMarkersForNormalStyle(CitationGroups cgs, OOBibStyle style) throws BibEntryNotFoundException { @@ -1006,7 +1006,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes assert !style.isNumberEntries(); // Citations in (Au1, Au2 2000) form - CitationGroupsV001.CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); + CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); createNormalizedCitationMarkersForNormalStyle(sortedCitedKeys, style); createUniqueLetters(sortedCitedKeys, cgs); // calls distributeUniqueLetters(cgs) @@ -1020,8 +1020,8 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - List cits = cg.getSortedCitations(); + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + List cits = cg.getSortedCitations(); final int nCitedEntries = cits.size(); int[] firstLimAuthors = new int[nCitedEntries]; String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; @@ -1124,7 +1124,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes } private static void fillCitationMarkInCursor(DocumentConnection documentConnection, - CitationGroupsV001.CitationGroups cgs, + CitationGroups cgs, CitationGroupID cgid, XTextCursor cursor, String citationText, @@ -1224,7 +1224,7 @@ private static void italicizeRangeFromPosition(XTextCursor position, * @param position OUT: left collapsed, just after the space inserted, * or after the reference mark inserted. */ - private void insertReferenceMark(CitationGroupsV001.CitationGroups cgs, + private void insertReferenceMark(CitationGroups cgs, DocumentConnection documentConnection, List citationKeys, Optional pageInfo, @@ -1236,26 +1236,28 @@ private void insertReferenceMark(CitationGroupsV001.CitationGroups cgs, boolean insertSpaceAfter) throws UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + PropertyVetoException, WrappedTargetException, PropertyVetoException, IllegalArgumentException, UndefinedCharacterFormatException, CreationException, - NoDocumentException { + NoDocumentException, + IllegalTypeException { - CitationGroupID cgid = - cgs.createCitationGroup(documentConnection, - citationKeys, - pageInfo, - itcType, - position, - insertSpaceAfter, - !withText /* withoutBrackets */); + CitationGroupID cgid = cgs.createCitationGroup(documentConnection, + citationKeys, + pageInfo, + itcType, + position, + insertSpaceAfter, + !withText /* withoutBrackets */); if (withText) { - XTextCursor c2 = - cgs.getFillCursorForCitationGroup(documentConnection, - cgid); + XTextCursor c2 = cgs.getFillCursorForCitationGroup(documentConnection, + cgid); fillCitationMarkInCursor(documentConnection, cgs, @@ -1430,7 +1432,7 @@ public void insertCitation(List entries, } DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); + CitationGroups cgs = new CitationGroups(documentConnection); // TODO: imposeLocalOrder boolean useUndoContext = true; @@ -1619,7 +1621,7 @@ public void insertCitation(List entries, * */ private void applyNewCitationMarkers(DocumentConnection documentConnection, - CitationGroupsV001.CitationGroups cgs, + CitationGroups cgs, Map citMarkers, OOBibStyle style) throws @@ -1656,7 +1658,7 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, String citationText = kv.getValue(); Objects.requireNonNull(citationText); - CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); boolean withText = (cg.itcType != OOBibBase.INVISIBLE_CIT); @@ -1699,12 +1701,12 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, */ static class ProduceCitationMarkersResult { - CitationGroupsV001.CitationGroups cgs; + CitationGroups cgs; /** citation markers */ Map citMarkers; - ProduceCitationMarkersResult(CitationGroupsV001.CitationGroups cgs, + ProduceCitationMarkersResult(CitationGroups cgs, Map citMarkers) { this.cgs = cgs; this.citMarkers = citMarkers; @@ -1714,7 +1716,7 @@ static class ProduceCitationMarkersResult { } } - public CitationGroupsV001.CitedKeys + public CitedKeys getBibliography() { if ( cgs.getBibliography().isEmpty() ) { throw new RuntimeException( @@ -1724,9 +1726,9 @@ static class ProduceCitationMarkersResult { } public List getUnresolvedKeys() { - CitationGroupsV001.CitedKeys bib = getBibliography(); + CitedKeys bib = getBibliography(); List unresolvedKeys = new ArrayList<>(); - for (CitationGroupsV001.CitedKey ck : bib.values()) { + for (CitedKey ck : bib.values()) { if ( ck.db.isEmpty() ) { unresolvedKeys.add(ck.citationKey); } @@ -1747,7 +1749,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d UnknownPropertyException, JabRefException { - CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); + CitationGroups cgs = new CitationGroups(documentConnection); cgs.lookupEntriesInDatabases( databases ); @@ -1823,15 +1825,15 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d * * Used by rebuildBibTextSection */ - private List - sortEntriesByRefMarkNames(CitationGroupsV001.CitationGroups cgs) { + private List + sortEntriesByRefMarkNames(CitationGroups cgs) { Set seen = new HashSet<>(); - List res = new ArrayList<>(); + List res = new ArrayList<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - List cits = cgs.getSortedCitations(cgid); + List cits = cgs.getSortedCitations(cgid); // no need to look in the database again - for (CitationGroupsV001.Citation cit : cgs.getSortedCitations(cgid)) { + for (Citation cit : cgs.getSortedCitations(cgid)) { String key = cit.citationKey; if (!seen.contains(key)) { res.add(cit); @@ -1850,8 +1852,8 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d */ private void rebuildBibTextSection(DocumentConnection documentConnection, OOBibStyle style, - CitationGroupsV001.CitationGroups cgs, - CitationGroupsV001.CitedKeys bibliography) + CitationGroups cgs, + CitedKeys bibliography) throws NoSuchElementException, WrappedTargetException, @@ -1884,8 +1886,8 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, */ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, XTextCursor cursor, - CitationGroupsV001.CitationGroups cgs, - CitationGroupsV001.CitedKeys bibliography, + CitationGroups cgs, + CitedKeys bibliography, OOBibStyle style, String parFormat) throws @@ -1919,7 +1921,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, System.out.printf("Ref isNumberEntries %s\n", style.isNumberEntries()); } - for (CitationGroupsV001.CitedKey ck : bibliography.values()) { + for (CitedKey ck : bibliography.values()) { if (debugThisFun) { @@ -1974,9 +1976,9 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, int last = ck.where.size(); int i=0; - for (CitationGroupsV001.CitationPath p : ck.where) { + for (CitationPath p : ck.where) { CitationGroupID cgid = p.group; - CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); String refMarkName = cg.referenceMarkName; if (i > 0) { @@ -2090,8 +2092,8 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) * Assumes the section named `OOBibBase.BIB_SECTION_NAME` exists. */ private void populateBibTextSection(DocumentConnection documentConnection, - CitationGroupsV001.CitationGroups cgs, - CitationGroupsV001.CitedKeys bibliography, + CitationGroups cgs, + CitedKeys bibliography, OOBibStyle style) throws NoSuchElementException, @@ -2157,10 +2159,13 @@ public void combineCiteMarkers(List databases, IOException, WrappedTargetException, NoSuchElementException, + NotRemoveableException, IllegalArgumentException, UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, + PropertyExistException, + IllegalTypeException, CreationException, BibEntryNotFoundException, NoDocumentException, @@ -2174,7 +2179,7 @@ public void combineCiteMarkers(List databases, final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); + CitationGroups cgs = new CitationGroups(documentConnection); try { documentConnection.enterUndoContext("Merge citations"); @@ -2201,7 +2206,7 @@ public void combineCiteMarkers(List databases, * * joinableGroupsCursors provides the range for each group */ - List> joinableGroups = new ArrayList<>(); + List> joinableGroups = new ArrayList<>(); List joinableGroupsCursors = new ArrayList<>(); // Since we only join groups with identical itcTypes, we @@ -2212,14 +2217,14 @@ public void combineCiteMarkers(List databases, if (referenceMarkNames.size() > 0) { // current group of CitationGroup values - List currentGroup = new ArrayList<>(); + List currentGroup = new ArrayList<>(); XTextCursor currentGroupCursor = null; XTextCursor cursorBetween = null; - CitationGroupsV001.CitationGroup prev = null; + CitationGroup prev = null; XTextRange prevRange = null; for (CitationGroupID cgid : referenceMarkNames) { - CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); XTextRange currentRange = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); Objects.requireNonNull(currentRange); @@ -2426,12 +2431,12 @@ public void combineCiteMarkers(List databases, // pageInfos currently belong to the CitationGroup, // but it is not clear how should handle them here. // - List newGroupCitations = new ArrayList<>(); + List newGroupCitations = new ArrayList<>(); List> pageInfos = new ArrayList<>(); int itcType = joinableGroups.get(gi).get(0).itcType; for (int gj = 0; gj < joinableGroups.get(gi).size(); gj++) { - CitationGroupsV001.CitationGroup rk = joinableGroups.get(gi).get(gj); + CitationGroup rk = joinableGroups.get(gi).get(gj); //newGroupCitations.addAll(Arrays.asList(bibtexKeys[rk])); newGroupCitations.addAll( rk.citations); pageInfos.add( rk.pageInfo ); @@ -2535,7 +2540,10 @@ public void unCombineCiteMarkers(List databases, IllegalArgumentException, UndefinedCharacterFormatException, UnknownPropertyException, + NotRemoveableException, PropertyVetoException, + PropertyExistException, + IllegalTypeException, CreationException, BibEntryNotFoundException, NoDocumentException, @@ -2548,7 +2556,7 @@ public void unCombineCiteMarkers(List databases, final boolean useLockControllers = true; DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); + CitationGroups cgs = new CitationGroups(documentConnection); try { documentConnection.enterUndoContext("Separate citations"); @@ -2571,7 +2579,7 @@ public void unCombineCiteMarkers(List databases, while (pivot < (names.size())) { CitationGroupID cgid = names.get(pivot); - CitationGroupsV001.CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); XTextRange range1 = cgs.getReferenceMarkRangeOrNull(documentConnection,cgid); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); @@ -2586,7 +2594,7 @@ public void unCombineCiteMarkers(List databases, } Optional oldPageInfo = cg.pageInfo; - List cits=cg.citations; + List cits=cg.citations; if ( cits.size() <= 1 ) { pivot++; continue; @@ -2731,8 +2739,8 @@ public ExportCitedHelperResult exportCitedHelper(List databases, // DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - CitationGroupsV001.CitationGroups cgs = new CitationGroupsV001.CitationGroups(documentConnection); - CitationGroupsV001.CitedKeys cks = cgs.getCitedKeys(); + CitationGroups cgs = new CitationGroups(documentConnection); + CitedKeys cks = cgs.getCitedKeys(); cks.lookupInDatabases( databases ); @@ -2743,7 +2751,7 @@ public ExportCitedHelperResult exportCitedHelper(List databases, List entriesToInsert = new ArrayList<>(); Set seen = new HashSet<>(); - for (CitationGroupsV001.CitedKey ck : cks.values()) { + for (CitedKey ck : cks.values()) { if ( ck.db.isEmpty() ) { unresolvedKeys.add(ck.citationKey); continue; @@ -2887,8 +2895,7 @@ public List updateDocumentActionHelper(List databases, documentConnection.enterUndoContext("Refresh bibliography"); boolean requireSeparation = false; - CitationGroupsV001.CitationGroups cgs = - new CitationGroupsV001.CitationGroups(documentConnection); + CitationGroups cgs = new CitationGroups(documentConnection); int maxReportedOverlaps = 10; checkRangeOverlaps(cgs, this.xDocumentConnection, requireSeparation, maxReportedOverlaps); final boolean useLockControllers = true; diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 914710ebc15..b4d04abc97d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -268,10 +268,18 @@ private void initPanel() { reportUndefinedCharacterFormat(ex); } catch (NoDocumentException ex) { showNoDocumentErrorMessage(); - } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | - CreationException | NoSuchElementException | WrappedTargetException | IOException | - InvalidStateException | - BibEntryNotFoundException ex) { + } catch (com.sun.star.lang.IllegalArgumentException + | UnknownPropertyException + | PropertyVetoException + | PropertyExistException + | CreationException + | NoSuchElementException + | NotRemoveableException + | IllegalTypeException + | WrappedTargetException + | IOException + | InvalidStateException + | BibEntryNotFoundException ex) { LOGGER.warn("Problem combining cite markers", ex); } }); @@ -290,10 +298,18 @@ private void initPanel() { showNoDocumentErrorMessage(); } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); - } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | - CreationException | NoSuchElementException | WrappedTargetException | IOException | - InvalidStateException | - BibEntryNotFoundException ex) { + } catch (com.sun.star.lang.IllegalArgumentException + | UnknownPropertyException + | PropertyVetoException + | PropertyExistException + | IllegalTypeException + | NotRemoveableException + | CreationException + | NoSuchElementException + | WrappedTargetException + | IOException + | InvalidStateException + | BibEntryNotFoundException ex) { LOGGER.warn("Problem uncombining cite markers", ex); } }); From dbbbe9677087a68a652463c19d26ffbafc054243 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 17:14:06 +0200 Subject: [PATCH 0525/1068] refactor: largely finished Backend52 Tested healthReport() information dialog, will remove. --- .../org/jabref/gui/openoffice/Backend52.java | 81 +++++++++- .../jabref/gui/openoffice/CitationGroups.java | 141 ++++++++---------- .../org/jabref/gui/openoffice/OOBibBase.java | 22 ++- .../jabref/gui/openoffice/StorageBase.java | 12 ++ .../gui/openoffice/StorageBaseRefMark.java | 6 +- 5 files changed, 181 insertions(+), 81 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/Backend52.java b/src/main/java/org/jabref/gui/openoffice/Backend52.java index 472e3da4abd..02aefc5e0da 100644 --- a/src/main/java/org/jabref/gui/openoffice/Backend52.java +++ b/src/main/java/org/jabref/gui/openoffice/Backend52.java @@ -64,8 +64,15 @@ public List getJabRefReferenceMarkNames(DocumentConnection documentConne return Codec52.filterIsJabRefReferenceMarkName(allNames); } - List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, - List citationGroupNames) { + /** + * Names of custom properties belonging to us, but without a + * corresponding reference mark. These can be deleted. + * + * @param citationGroupNames These are the names that are used. + * + */ + private List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, + List citationGroupNames) { // Collect unused jabrefPropertyNames Set citationGroupNamesSet = citationGroupNames.stream().collect(Collectors.toSet()); @@ -84,6 +91,26 @@ List findUnusedJabrefPropertyNames(DocumentConnection documentConnection return pageInfoThrash; } + /** + * @return null if all is OK, message text otherwise. + */ + public String healthReport(DocumentConnection documentConnection) + throws + NoDocumentException { + List pageInfoThrash = + this.findUnusedJabrefPropertyNames(documentConnection, + this.getJabRefReferenceMarkNames(documentConnection)); + if ( pageInfoThrash.isEmpty() ){ + return null; //"Backend52: found no unused pageInfo data"; + } + String msg = ( + "Backend52: found unused pageInfo data, with names listed below.\n" + + "In LibreOffice you may remove these in [File]/[Properties]/[Custom Properties]\n" + ); + msg += "" + String.join( "\n", pageInfoThrash ) + ""; + return msg; + } + /** * We have circular dependency here: backend uses * class from ... @@ -248,5 +275,55 @@ public void removeCitationGroup(CitationGroup cg, DocumentConnection documentCon documentConnection.removeCustomProperty(refMarkName); } + /** + * + * @return Null if the reference mark is missing. + * + */ + public XTextRange getMarkRangeOrNull(CitationGroup cg, + DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + return cg.cgRangeStorage.getMarkRangeOrNull(documentConnection); + } + + /** + * Cursor for the reference marks as is, not prepared for filling, + * but does not need cleanFillCursorForCitationGroup either. + */ + public XTextCursor getRawCursorForCitationGroup(CitationGroup cg, + DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + return cg.cgRangeStorage.getRawCursor(documentConnection); + } + + /** + * Must be followed by call to cleanFillCursorForCitationGroup + */ + public XTextCursor getFillCursorForCitationGroup(CitationGroup cg, + DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + return cg.cgRangeStorage.getFillCursor(documentConnection); + } + + /** To be called after getFillCursorForCitationGroup */ + public void cleanFillCursorForCitationGroup(CitationGroup cg, + DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + cg.cgRangeStorage.cleanFillCursor(documentConnection); + } + } // end Backend52 diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroups.java b/src/main/java/org/jabref/gui/openoffice/CitationGroups.java index 76a013a8668..e6bf774cf47 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroups.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroups.java @@ -66,10 +66,6 @@ class CitationGroups { /** * Extra Data */ - // For custom properties belonging to us, but - // without a corresponding reference mark. - // These can be deleted. - private List pageInfoThrash; private Optional> globalOrder; @@ -96,9 +92,6 @@ public CitationGroups(DocumentConnection documentConnection) // Get the citationGroupNames List citationGroupNames = this.backend.getJabRefReferenceMarkNames(documentConnection); - this.pageInfoThrash = - this.backend.findUnusedJabrefPropertyNames(documentConnection, - citationGroupNames); this.citationGroups = readCitationGroupsFromDocument(this.backend, documentConnection, @@ -114,6 +107,13 @@ public CitationGroups(DocumentConnection documentConnection) } + public String healthReport(DocumentConnection documentConnection) + throws + NoDocumentException { + String r1 = backend.healthReport(documentConnection); + // add more? + return r1; + } private static Map readCitationGroupsFromDocument(Backend52 backend, @@ -318,9 +318,9 @@ public Set getCitationGroupIDs() { List vses = new ArrayList<>(); for (CitationGroupID cgid : cgids) { - XTextRange range = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); + XTextRange range = cgs.getMarkRangeOrNull(documentConnection, cgid); if (range == null) { - throw new RuntimeException("getReferenceMarkRangeOrNull returned null"); + throw new RuntimeException("getMarkRangeOrNull returned null"); } vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); } @@ -627,15 +627,23 @@ public void removeCitationGroups(List cgs, DocumentConnection doc } } - /* - * Remove it both from {@code this} and the document. + /** + * Remove {@code cg} both from {@code this} and the document. + * + * Note: we invalidate the extra data we are storing + * (bibliography). + * + * Update would be complicated, since we do not know how the + * bibliography was generated: it was partially done outside + * CitationGroups, and we did not store how. + * + * So we stay with invalidating. + * Note: localOrder, numbering, uniqueLetters are not adjusted, + * it is easier to reread everything for a refresh. * - * TODO: either invalidate or update the extra data we are storing - * (bibliography). Update may be complicated, since we do - * not know how the bibliography was generated: it was partially done - * outside CitationGroupsV001, and we did not store how. */ - public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) + public void removeCitationGroup(CitationGroup cg, + DocumentConnection documentConnection) throws WrappedTargetException, NoDocumentException, @@ -644,36 +652,34 @@ public void removeCitationGroup(CitationGroup cg, DocumentConnection documentCon PropertyExistException, IllegalTypeException { - // documentConnection.removeReferenceMark(cg.referenceMarkName); + // Apply backend.removeCitationGroup(cg, documentConnection); this.citationGroups.remove(cg.cgid); + + // Update what we can. this.globalOrder.map(l -> l.remove(cg.cgid)); - // Invalidate CitedKeys + // Invalidate what we cannot update: CitedKeys this.citedKeysAfterDatabaseLookup = Optional.empty(); this.bibliography = Optional.empty(); - /* - * this.citedKeysAfterDatabaseLookup.map(cks -> cks.forgetCitationGroup(cg.cgid)); - * this.bibliography.map(cks -> cks.forgetCitationGroup(cg.cgid)); - */ + // Could also: reset citation.number, citation.uniqueLetter. } /** - * Remove brackets, but if the result would become empty, leave - * them; if the result would be a single characer, leave the left bracket. + * ranges controlled by citation groups should not overlap with each other. + * + * @param cgid : Must be known, throws if not. + * @return Null if the reference mark is missing. * - * @param removeBracketsFromEmpty is intended to force removal if - * we are working on an "Empty citation" (INVISIBLE_CIT). */ - public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, - CitationGroupID cgid) + public XTextRange getMarkRangeOrNull(DocumentConnection documentConnection, + CitationGroupID cgid) throws NoDocumentException, - WrappedTargetException, - CreationException { + WrappedTargetException { CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - cg.cgRangeStorage.cleanFillCursor(documentConnection); + return backend.getMarkRangeOrNull(cg, documentConnection); } /** @@ -688,7 +694,7 @@ public XTextCursor getRawCursorForCitationGroup(CitationGroupID cgid, CreationException { CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return cg.cgRangeStorage.getRawCursor(documentConnection); + return backend.getRawCursorForCitationGroup(cg, documentConnection); } public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, @@ -699,46 +705,25 @@ public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConn CreationException { CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return cg.cgRangeStorage.getFillCursor(documentConnection); + return backend.getFillCursorForCitationGroup(cg, documentConnection); } /** - * Given the name of a reference mark, get the corresponding - * pageInfo text. + * Remove brackets, but if the result would become empty, leave + * them; if the result would be a single characer, leave the left bracket. * - * @param documentConnection Connection to a document. - * @param name Name of the custom property to query. - * @return "" for missing or empty pageInfo + * @param removeBracketsFromEmpty is intended to force removal if + * we are working on an "Empty citation" (INVISIBLE_CIT). */ - private static String getPageInfoForReferenceMarkName(DocumentConnection documentConnection, - String name) + public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, + CitationGroupID cgid) throws + NoDocumentException, WrappedTargetException, - UnknownPropertyException { - - Optional pageInfo = documentConnection.getCustomProperty(name); - if (pageInfo.isEmpty() || pageInfo.get().isEmpty()) { - return ""; - } - return pageInfo.get(); - } + CreationException { - /** - * ranges controlled by citation groups should not overlap with each other. - * - * @param cgid : Must be known. - * @return Null if the reference mark is missing. - * - * TODO: getReferenceMarkRangeOrNull vs getRawCursorForCitationGroup - */ - public XTextRange getReferenceMarkRangeOrNull(DocumentConnection documentConnection, - CitationGroupID cgid) - throws - NoDocumentException, - WrappedTargetException { - String name = (this.getReferenceMarkName(cgid) - .orElseThrow(RuntimeException::new)); - return documentConnection.getReferenceMarkRangeOrNull(name); + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + backend.cleanFillCursorForCitationGroup(cg,documentConnection); } /** @@ -753,16 +738,16 @@ List citationRanges(DocumentConnection documentConnection) List xs = new ArrayList<>(numberOfCitationGroups()); - List cgids = - new ArrayList<>(this.getCitationGroupIDs()); + List cgids = new ArrayList<>(this.getCitationGroupIDs()); for (CitationGroupID cgid : cgids) { - XTextRange r = this.getReferenceMarkRangeOrNull(documentConnection, cgid); - String name = this.getCitationGroup(cgid).get().referenceMarkName; - xs.add(new RangeForOverlapCheck( - r, cgid, - RangeForOverlapCheck.REFERENCE_MARK_KIND, - name)); + XTextRange r = this.getMarkRangeOrNull(documentConnection, cgid); + CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + String name = cg.cgRangeStorage.getName(); + xs.add(new RangeForOverlapCheck(r, + cgid, + RangeForOverlapCheck.REFERENCE_MARK_KIND, + name)); } return xs; } @@ -776,6 +761,10 @@ List citationRanges(DocumentConnection documentConnection) * marks. Overwriting these footnote marks might kill our * reference marks in the footnote. * + * Note: Here we directly communicate to the document, not + * through the backend. This is because mapping ranges to + * footnote marks does not depend on how do we mark or + * structure those ranges. */ List footnoteMarkRanges(DocumentConnection documentConnection) throws @@ -814,10 +803,12 @@ List footnoteMarkRanges(DocumentConnection documentConnect return xs; } - public void show() { - System.out.printf("CitationGroupsV001%n"); + /** + * This is for debugging, can be removed. + */ + public void xshow() { + System.out.printf("CitationGroups%n"); System.out.printf(" citationGroups.size: %d%n", citationGroups.size()); - System.out.printf(" pageInfoThrash.size: %d%n", pageInfoThrash.size()); System.out.printf(" globalOrder: %s%n", (globalOrder.isEmpty() ? "isEmpty" diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8e775790c80..3c9f86efed4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1149,7 +1149,6 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti // when creating. String citText; - // String pageInfo = getPageInfoForReferenceMarkName(documentConnection, name); Optional pageInfo = cgs.getPageInfo(cgid); citText = ((pageInfo.isEmpty() || pageInfo.get().equals("")) ? citationText @@ -2226,7 +2225,7 @@ public void combineCiteMarkers(List databases, for (CitationGroupID cgid : referenceMarkNames) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - XTextRange currentRange = cgs.getReferenceMarkRangeOrNull(documentConnection, cgid); + XTextRange currentRange = cgs.getMarkRangeOrNull(documentConnection, cgid); Objects.requireNonNull(currentRange); boolean addToGroup = true; @@ -2580,7 +2579,7 @@ public void unCombineCiteMarkers(List databases, while (pivot < (names.size())) { CitationGroupID cgid = names.get(pivot); CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - XTextRange range1 = cgs.getReferenceMarkRangeOrNull(documentConnection,cgid); + XTextRange range1 = cgs.getMarkRangeOrNull(documentConnection,cgid); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); // If we are supposed to set character format for @@ -2896,8 +2895,25 @@ public List updateDocumentActionHelper(List databases, boolean requireSeparation = false; CitationGroups cgs = new CitationGroups(documentConnection); + + if (false) { + // Check unused Custom Properties. + // Problem: annoying and not helpful. + // We could offer cleanup, or do it silently, + // but that would destroy potentially recoverable data. + // + // What we would prefer is to keep pageInfo with the range, + // preferably in a copy-pastable form. + String healthReport = cgs.healthReport(documentConnection); + if (healthReport != null){ + dialogService.showInformationDialogAndWait( "Note", healthReport ); + } + } + + // Check Range overlaps int maxReportedOverlaps = 10; checkRangeOverlaps(cgs, this.xDocumentConnection, requireSeparation, maxReportedOverlaps); + final boolean useLockControllers = true; ProduceCitationMarkersResult x = produceCitationMarkers(documentConnection, databases, diff --git a/src/main/java/org/jabref/gui/openoffice/StorageBase.java b/src/main/java/org/jabref/gui/openoffice/StorageBase.java index eb0f7a3594f..4a97c0e846b 100644 --- a/src/main/java/org/jabref/gui/openoffice/StorageBase.java +++ b/src/main/java/org/jabref/gui/openoffice/StorageBase.java @@ -45,6 +45,15 @@ interface HasName { } interface HasTextRange { + + /** + * @return Null if the mark is missing from the document. + */ + public XTextRange getMarkRangeOrNull(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException; + /** * Cursor for the reference marks as is, not prepared for filling, * but does not need cleanFillCursorForCitationGroup either. @@ -79,6 +88,9 @@ public void cleanFillCursor(DocumentConnection documentConnection) WrappedTargetException, CreationException ; + /** + * Note: create is in NamedRangeManager + */ public void removeFromDocument(DocumentConnection documentConnection) throws WrappedTargetException, diff --git a/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java index 9472bbf39bf..254fc367bea 100644 --- a/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java @@ -196,7 +196,8 @@ public void removeFromDocument(DocumentConnection documentConnection) * * See: getReferenceMarkRangeOrNull */ - public XTextRange getRangeOrNull(DocumentConnection documentConnection) + @Override + public XTextRange getMarkRangeOrNull(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException { @@ -208,6 +209,9 @@ public XTextRange getRangeOrNull(DocumentConnection documentConnection) * Cursor for the reference marks as is, not prepared for filling, * but does not need cleanFillCursorForCitationGroup either. * + * @return null if reference mark is missing from the document, + * otherwise an XTextCursor for getMarkRangeOrNull + * * See: getRawCursorForCitationGroup */ @Override From 0a6b33aecf60b9ca883173ee487d8754997d5df7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 17:30:17 +0200 Subject: [PATCH 0526/1068] removed healthReport showInformationDialogAndWait --- .../org/jabref/gui/openoffice/OOBibBase.java | 93 +------------------ 1 file changed, 3 insertions(+), 90 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3c9f86efed4..367da7db29a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1144,7 +1144,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti Objects.requireNonNull(citationText); Objects.requireNonNull(style); - // Last minute editing: If there is "page info" for this + // TODO: Last minute editing: If there is "page info" for this // citation mark, we should inject it into the citation marker // when creating. @@ -1166,8 +1166,6 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti cursor.setString(""); } - // documentConnection.insertReferenceMark(name, cursor, true); - // Last minute editing: find "et al." (OOBibStyle.ET_AL_STRING) and // format it as italic. @@ -2736,8 +2734,6 @@ public ExportCitedHelperResult exportCitedHelper(List databases, NoDocumentException, UnknownPropertyException { - // DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - CitationGroups cgs = new CitationGroups(documentConnection); CitedKeys cks = cgs.getCitedKeys(); cks.lookupInDatabases( databases ); @@ -2745,10 +2741,9 @@ public ExportCitedHelperResult exportCitedHelper(List databases, List unresolvedKeys = new ArrayList<>(); BibDatabase resultDatabase = new BibDatabase(); - // List cited = findCitedKeys(documentConnection); List entriesToInsert = new ArrayList<>(); - Set seen = new HashSet<>(); + Set seen = new HashSet<>(); // Only add crossReference once. for (CitedKey ck : cks.values()) { if ( ck.db.isEmpty() ) { @@ -2768,23 +2763,6 @@ public ExportCitedHelperResult exportCitedHelper(List databases, clonedEntry .getField(StandardField.CROSSREF) .ifPresent(crossReference -> { - // If the crossReference entry is not already in the database - - // broken logic here: - - // we just created resultDatabase, and - // added nothing yet. - - // Question: why do we use - // entriesToInsert instead of directly adding to resultDatabase? - // And why do we not look for it in entriesToInsert? - // With the present code we are always adding it. - // How does BibDatabase handle this situation? - /* - boolean isNew = (resultDatabase - .getEntryByCitationKey(crossReference) - .isEmpty()); - */ boolean isNew = !seen.contains( crossReference ); if (isNew) { // Add it if it is in the current library @@ -2797,55 +2775,6 @@ public ExportCitedHelperResult exportCitedHelper(List databases, } } - /* - // For each cited key - for (String key : cited) { - // Loop through the available databases - for (BibDatabase loopDatabase : databases) { - Optional entry = loopDatabase.getEntryByCitationKey(key); - if (entry.isEmpty()) { - continue; - } - // If entry found - BibEntry clonedEntry = (BibEntry) entry.get().clone(); - - // Insert a copy of the entry - entriesToInsert.add(clonedEntry); - - // Check if the cloned entry has a cross-reference field - clonedEntry - .getField(StandardField.CROSSREF) - .ifPresent(crossReference -> { - // If the crossReference entry is not already in the database - - // broken logic here: - - // we just created resultDatabase, and - // added nothing yet. - - // Question: why do we use - // entriesToInsert instead of directly adding to resultDatabase? - // And why do we not look for it in entriesToInsert? - // With the present code we are always adding it. - // How does BibDatabase handle this situation? - boolean isNew = (resultDatabase - .getEntryByCitationKey(crossReference) - .isEmpty()); - if (isNew) { - // Add it if it is in the current library - loopDatabase - .getEntryByCitationKey(crossReference) - .ifPresent(entriesToInsert::add); - } - }); - - // Be happy with the first found BibEntry and move on to next key - break; - } - // key not found here. No action. - } - */ - resultDatabase.insertEntries(entriesToInsert); return new ExportCitedHelperResult( unresolvedKeys, resultDatabase ); } @@ -2896,20 +2825,6 @@ public List updateDocumentActionHelper(List databases, boolean requireSeparation = false; CitationGroups cgs = new CitationGroups(documentConnection); - if (false) { - // Check unused Custom Properties. - // Problem: annoying and not helpful. - // We could offer cleanup, or do it silently, - // but that would destroy potentially recoverable data. - // - // What we would prefer is to keep pageInfo with the range, - // preferably in a copy-pastable form. - String healthReport = cgs.healthReport(documentConnection); - if (healthReport != null){ - dialogService.showInformationDialogAndWait( "Note", healthReport ); - } - } - // Check Range overlaps int maxReportedOverlaps = 10; checkRangeOverlaps(cgs, this.xDocumentConnection, requireSeparation, maxReportedOverlaps); @@ -2932,9 +2847,7 @@ public List updateDocumentActionHelper(List databases, x.getBibliography()); return x.getUnresolvedKeys(); } finally { - if (useLockControllers - // && documentConnection.hasControllersLocked() - ) { + if (useLockControllers && documentConnection.hasControllersLocked()) { documentConnection.unlockControllers(); } } From 548c8db9bf64c625a316441e95f25dc48daee7df Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 18:40:37 +0200 Subject: [PATCH 0527/1068] format --- .../org/jabref/gui/openoffice/DocumentConnection.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java index d3b010ca934..16fd8de0506 100644 --- a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java @@ -787,12 +787,9 @@ public void removeCustomProperty(String property) * @param range Cursor marking the location or range for * the reference mark. */ - public XNamed - insertReferenceMark( - String name, - XTextRange range, - boolean absorb - ) + public XNamed insertReferenceMark(String name, + XTextRange range, + boolean absorb) throws CreationException { From 755c563e83e1388a5cc2e703628bd9d10942f9d6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 18:41:18 +0200 Subject: [PATCH 0528/1068] fit OOBibStyle.java to window width --- .../jabref/logic/openoffice/OOBibStyle.java | 193 +++++++++++++----- 1 file changed, 139 insertions(+), 54 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 794b2fbb148..1deb68c619e 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -161,7 +161,8 @@ private void setDefaultProperties() { properties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1"); // Set default properties for the citation marker: - citProperties.put(AUTHOR_FIELD, FieldFactory.serializeOrFields(StandardField.AUTHOR, StandardField.EDITOR)); + citProperties.put(AUTHOR_FIELD, + FieldFactory.serializeOrFields(StandardField.AUTHOR, StandardField.EDITOR)); citProperties.put(YEAR_FIELD, StandardField.YEAR.getName()); citProperties.put(MAX_AUTHORS, 3); citProperties.put(MAX_AUTHORS_FIRST, -1); @@ -350,7 +351,8 @@ private void handleStructureLine(String line) { try { String formatString = line.substring(index + 1); - Layout layout = new LayoutHelper(new StringReader(formatString), this.prefs).getLayoutFromText(); + StringReader reader = new StringReader(formatString); + Layout layout = new LayoutHelper(reader, this.prefs).getLayoutFromText(); EntryType type = EntryTypeFactory.parse(line.substring(0, index)); if (!isDefaultLayoutPresent && line.substring(0, index).equals(OOBibStyle.DEFAULT_MARK)) { @@ -440,7 +442,9 @@ public String getNumCitationMarker(List number, int minGroupingCount, b if (i > 0) { sb.append(getStringCitProperty(CITATION_SEPARATOR)); } - sb.append(lNum.get(i) > 0 ? String.valueOf(lNum.get(i)) : OOBibStyle.UNDEFINED_CITATION_MARKER); + sb.append(lNum.get(i) > 0 + ? String.valueOf(lNum.get(i)) + : OOBibStyle.UNDEFINED_CITATION_MARKER); written++; } } else { @@ -476,21 +480,27 @@ public String getNumCitationMarker(List number, int minGroupingCount, b } /** - * Format the marker for the in-text citation according to this BIB style. Uniquefier letters are added as - * provided by the uniquefiers argument. If successive entries within the citation are uniquefied from each other, - * this method will perform a grouping of these entries. + * Format the marker for the in-text citation according to this + * BIB style. Uniquefier letters are added as provided by the + * uniquefiers argument. If successive entries within the citation + * are uniquefied from each other, this method will perform a + * grouping of these entries. * * @param entries The list of JabRef BibEntry providing the data. * @param database A map of BibEntry-BibDatabase pairs. * @param inParenthesis Signals whether a parenthesized citation or an in-text citation is wanted. - * @param uniquefiers Strings to add behind the year for each entry in case it's needed to separate similar - * entries. - * @param unlimAuthors Boolean for each entry. If true, we should not use "et al" formatting regardless - * of the number of authors. Can be null to indicate that no entries should have unlimited names. + * @param uniquefiers Strings to add behind the year for each entry in case it's needed + * to separate similar entries. + * @param unlimAuthors Boolean for each entry. If true, we should not use "et al" formatting + * regardless of the number of authors. + * Can be null to indicate that no entries should have unlimited names. * @return The formatted citation. */ - public String getCitationMarker(List entries, Map database, boolean inParenthesis, - String[] uniquefiers, int[] unlimAuthors) { + public String getCitationMarker(List entries, + Map database, + boolean inParenthesis, + String[] uniquefiers, + int[] unlimAuthors) { // Look for groups of uniquefied entries that should be combined in the output. // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). int piv = -1; @@ -511,12 +521,17 @@ public String getCitationMarker(List entries, Map entries, Map maxAuthors) && (unlimAuthors[i] != prevALim))) { + || ((al.getNumberOfAuthors() > maxAuthors) + && (unlimAuthors[i] != prevALim))) { // No match. Update piv to exclude the previous entry. But first check if the // previous entry was part of a group: if ((piv > -1) && (i > (piv + 1))) { @@ -577,21 +593,41 @@ private void group(List entries, String[] uniquefiers, int from, int t * * @param entries The list of BibEntry to get fields from. * @param database A map of BibEntry-BibDatabase pairs. - * @param uniquifiers Optional parameter to separate similar citations. Elements can be null if not needed. + * @param uniquifiers Optional parameter to separate similar citations. + * Elements can be null if not needed. * @return The formatted citation. */ - private String getAuthorYearParenthesisMarker(List entries, Map database, - String[] uniquifiers, int[] unlimAuthors) { - - String authorField = getStringCitProperty(AUTHOR_FIELD); // The bibtex field providing author names, e.g. "author" or "editor". - int maxA = getIntCitProperty(MAX_AUTHORS); // The maximum number of authors to write out in full without using etal. Set to - // -1 to always write out all authors. - String yearSep = getStringCitProperty(YEAR_SEPARATOR); // The String to separate authors from year, e.g. "; ". - String startBrace = getStringCitProperty(BRACKET_BEFORE); // The opening parenthesis. - String endBrace = getStringCitProperty(BRACKET_AFTER); // The closing parenthesis. - String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); // The String to separate citations from each other. - String yearField = getStringCitProperty(YEAR_FIELD); // The bibtex field providing the year, e.g. "year". - String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR); // The String to add between the two last author names, e.g. " & ". + private String getAuthorYearParenthesisMarker(List entries, + Map database, + String[] uniquifiers, + int[] unlimAuthors) { + + // The bibtex field providing author names, e.g. "author" or + // "editor". + String authorField = getStringCitProperty(AUTHOR_FIELD); + + // The maximum number of authors to write out in full without + // using etal. Set to -1 to always write out all authors. + int maxA = getIntCitProperty(MAX_AUTHORS); + + // The String to separate authors from year, e.g. "; ". + String yearSep = getStringCitProperty(YEAR_SEPARATOR); + + // The opening parenthesis. + String startBrace = getStringCitProperty(BRACKET_BEFORE); + + // The closing parenthesis. + String endBrace = getStringCitProperty(BRACKET_AFTER); + + // The String to separate citations from each other. + String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); + + // The bibtex field providing the year, e.g. "year". + String yearField = getStringCitProperty(YEAR_FIELD); + + // The String to add between the two last author names, e.g. " & ". + String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR); + StringBuilder sb = new StringBuilder(startBrace); for (int j = 0; j < entries.size(); j++) { BibEntry currentEntry = entries.get(j); @@ -632,18 +668,34 @@ private String getAuthorYearParenthesisMarker(List entries, Map entries, Map database, + private String getAuthorYearInTextMarker(List entries, + Map database, String[] uniquefiers, int[] unlimAuthors) { - String authorField = getStringCitProperty(AUTHOR_FIELD); // The bibtex field providing author names, e.g. "author" or "editor". - int maxA = getIntCitProperty(MAX_AUTHORS); // The maximum number of authors to write out in full without using etal. Set to - // -1 to always write out all authors. - String yearSep = getStringCitProperty(IN_TEXT_YEAR_SEPARATOR); // The String to separate authors from year, e.g. "; ". - String startBrace = getStringCitProperty(BRACKET_BEFORE); // The opening parenthesis. - String endBrace = getStringCitProperty(BRACKET_AFTER); // The closing parenthesis. - String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); // The String to separate citations from each other. - String yearField = getStringCitProperty(YEAR_FIELD); // The bibtex field providing the year, e.g. "year". - String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR_IN_TEXT); // The String to add between the two last author names, e.g. " & ". + // The bibtex field providing author names, e.g. "author" or "editor". + String authorField = getStringCitProperty(AUTHOR_FIELD); + + // The maximum number of authors to write out in full without using etal. Set to + // -1 to always write out all authors. + int maxA = getIntCitProperty(MAX_AUTHORS); + + // The String to separate authors from year, e.g. "; ". + String yearSep = getStringCitProperty(IN_TEXT_YEAR_SEPARATOR); + + // The opening parenthesis. + String startBrace = getStringCitProperty(BRACKET_BEFORE); + + // The closing parenthesis. + String endBrace = getStringCitProperty(BRACKET_AFTER); + + // The String to separate citations from each other. + String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); + + // The bibtex field providing the year, e.g. "year". + String yearField = getStringCitProperty(YEAR_FIELD); + + // The String to add between the two last author names, e.g. " & ". + String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR_IN_TEXT); if (andString == null) { // Use the default one if no explicit separator for text is defined @@ -688,8 +740,10 @@ private String getAuthorYearInTextMarker(List entries, Map 0) { + // The first author sb.append(getAuthorLastName(al, 0)); } - if ((al.getNumberOfAuthors() > 1) && ((al.getNumberOfAuthors() <= maxAuthors) || (maxAuthors < 0))) { + + boolean emitAllAuthors = ((nAuthors <= maxAuthors) || (maxAuthors < 0)); + if ((nAuthors >= 2) && emitAllAuthors) { + // Emit last names, except for the last author int j = 1; - while (j < (al.getNumberOfAuthors() - 1)) { + while (j < (nAuthors - 1)) { sb.append(authorSep); sb.append(getAuthorLastName(al, j)); j++; } - if (al.getNumberOfAuthors() > 2) { + // oxfordComma if at least 3 authors + if (nAuthors >= 3) { sb.append(oxfordComma); } + // Emit "and LastAuthor" sb.append(andString); - sb.append(getAuthorLastName(al, al.getNumberOfAuthors() - 1)); - } else if (al.getNumberOfAuthors() > maxAuthors) { + sb.append(getAuthorLastName(al, nAuthors - 1)); + + } else if (nAuthors > maxAuthors) { + // maxAuthors nAuthors result + // 0 1 "Smith et al" Seems wrong + // -1 1 "Smith et al" Seems wrong + // -1 0 "et al" Why not ""? sb.append(etAlString); } sb.append(yearSep); From 7e7e0f2202c420d7570f7fa122a8a9ce42b814fb Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 18:44:00 +0200 Subject: [PATCH 0529/1068] createAuthorList adds etAlString only for nAuthors > 1 --- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 1deb68c619e..31bb8cd532c 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -977,11 +977,11 @@ private String createAuthorList(String author, sb.append(andString); sb.append(getAuthorLastName(al, nAuthors - 1)); - } else if (nAuthors > maxAuthors) { + } else if (nAuthors > maxAuthors && nAuthors > 1) { // maxAuthors nAuthors result - // 0 1 "Smith et al" Seems wrong - // -1 1 "Smith et al" Seems wrong - // -1 0 "et al" Why not ""? + // 0 1 "Smith" + // -1 1 "Smith" + // -1 0 "" sb.append(etAlString); } sb.append(yearSep); From cb5727d3727a34d3c99f144e80cd6a3ed694f29d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 29 Mar 2021 19:29:24 +0200 Subject: [PATCH 0530/1068] add arg pageInfoForCitationGroup to citation marker generators The do not use it yet. --- .../org/jabref/gui/openoffice/OOBibBase.java | 35 ++++-- .../jabref/logic/openoffice/OOBibStyle.java | 11 +- .../logic/openoffice/OOBibStyleTest.java | 111 ++++++++++++------ 3 files changed, 111 insertions(+), 46 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 367da7db29a..ad312577402 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -775,11 +775,13 @@ private String normalizedCitationMarkerForNormalStyle(CitedKey ck, entries.put( ce, ck.db.get().database ); // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: + String pageInfoForCitationGroup = null; return style.getCitationMarker(Collections.singletonList(ce), entries, true, null, - new int[] {-1} /* no limit on authors */); + new int[] {-1}, /* no limit on authors */ + pageInfoForCitationGroup); } /** @@ -952,8 +954,12 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); + String pageInfoForCitationGroup = cg.pageInfo.orElse(null); citMarkers.put(cgid, - style.getNumCitationMarker(numbers, minGroupingCount, false)); + style.getNumCitationMarker(numbers, + minGroupingCount, + false, + pageInfoForCitationGroup)); } return citMarkers; @@ -979,8 +985,12 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); + String pageInfoForCitationGroup = cg.pageInfo.orElse(null); citMarkers.put(cgid, - style.getNumCitationMarker(numbers, minGroupingCount, false)); + style.getNumCitationMarker(numbers, + minGroupingCount, + false, /*inList*/ + pageInfoForCitationGroup)); } return citMarkers; } @@ -1081,13 +1091,18 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes entries.put(e,d); firstLimAuthors2[0] = firstLimAuthors[j]; uniqueLetterForCitedEntry2[0] = uniqueLetterForCitedEntry[j]; + // Attribute pageInfoForCitationGroup to the last + String pageInfoForCitationGroup = (j == (nCitedEntries-1) + ? cg.pageInfo.orElse(null) + : null); s = (s + style.getCitationMarker( cEntries, entries, cg.itcType == OOBibBase.AUTHORYEAR_PAR, uniqueLetterForCitedEntry2, - firstLimAuthors2 + firstLimAuthors2, + pageInfoForCitationGroup )); } else { s = s + String.format("(Unresolved(%s))", currentKey); @@ -1108,13 +1123,15 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes entries.put(e,d); } + String pageInfoForCitationGroup = cg.pageInfo.orElse(null); citMarkers.put( cgid, style.getCitationMarker( cEntries, entries, cg.itcType == OOBibBase.AUTHORYEAR_PAR, uniqueLetterForCitedEntry, - firstLimAuthors + firstLimAuthors, + pageInfoForCitationGroup ) ); } @@ -1515,6 +1532,7 @@ public void insertCitation(List entries, databaseMap.put(entry, database); } + String pageInfoForCitationGroup = null; // The text we insert String citeText = style.isNumberEntries() @@ -1524,7 +1542,8 @@ public void insertCitation(List entries, databaseMap, inParenthesis, null, - null); + null, + pageInfoForCitationGroup); if (citeText.equals("")) { citeText = "[?]"; @@ -1944,9 +1963,11 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); int minGroupingCount = 2; List numbers = Collections.singletonList(ck.number.get()); + String pageInfoForCitationGroup = null; // no pageInfo for the bibliography String marker = style.getNumCitationMarker(numbers, minGroupingCount, - true); + true, + pageInfoForCitationGroup); OOUtil.insertTextAtCurrentLocation(documentConnection.xText, cursor, diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 31bb8cd532c..6a27c0a8431 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -414,9 +414,14 @@ public Layout getReferenceFormat(EntryType type) { * Format a number-based citation marker for the given number. * * @param number The citation numbers. + * @param pageInfoForCitationGroup Nullable. In case of multiple entries, + * attributed to the last. * @return The text for the citation. */ - public String getNumCitationMarker(List number, int minGroupingCount, boolean inList) { + public String getNumCitationMarker(List number, + int minGroupingCount, + boolean inList, + String pageInfoForCitationGroup) { String bracketBefore = getStringCitProperty(BRACKET_BEFORE); if (inList && (citProperties.containsKey(BRACKET_BEFORE_IN_LIST))) { bracketBefore = getStringCitProperty(BRACKET_BEFORE_IN_LIST); @@ -494,13 +499,15 @@ public String getNumCitationMarker(List number, int minGroupingCount, b * @param unlimAuthors Boolean for each entry. If true, we should not use "et al" formatting * regardless of the number of authors. * Can be null to indicate that no entries should have unlimited names. + * @param pageInfoForCitationGroup Nullable, attibuted to the last entry * @return The formatted citation. */ public String getCitationMarker(List entries, Map database, boolean inParenthesis, String[] uniquefiers, - int[] unlimAuthors) { + int[] unlimAuthors, + String pageInfoForCitationGroup) { // Look for groups of uniquefied entries that should be combined in the output. // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). int piv = -1; diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 093a5eb6348..cda11f5ffed 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -10,6 +10,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Optional; import java.util.Map; import java.util.Set; @@ -84,16 +85,17 @@ void testNumerical() throws IOException { void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), -1, true)); - assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, false)); - assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), 0, true)); - assertEquals("[1-3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, true)); - assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, true)); - assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, true)); - assertEquals("[1; 3; 12] ", style.getNumCitationMarker(Arrays.asList(1, 12, 3), 1, true)); - assertEquals("[3-5; 7; 10-12] ", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, true)); - - String citation = style.getNumCitationMarker(Arrays.asList(1), -1, false); + String empty = null; + assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), -1, true, empty)); + assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, false, empty)); + assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), 0, true, empty)); + assertEquals("[1-3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, true, empty)); + assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, true, empty)); + assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, true, empty)); + assertEquals("[1; 3; 12] ", style.getNumCitationMarker(Arrays.asList(1, 12, 3), 1, true, empty)); + assertEquals("[3-5; 7; 10-12] ", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, true, empty)); + + String citation = style.getNumCitationMarker(Arrays.asList(1), -1, false, empty); assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); } @@ -101,18 +103,19 @@ void testGetNumCitationMarker() throws IOException { void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + String empty = null; assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4] ", - style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, true)); + style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, true, empty)); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarker(Arrays.asList(0), 1, true)); + style.getNumCitationMarker(Arrays.asList(0), 1, true, empty)); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3] ", - style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, true)); + style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, true, empty)); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, true)); + style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, true, empty)); } @Test @@ -143,12 +146,13 @@ void testGetCitationMarker() throws IOException { Map entryDBMap = new HashMap<>(); entryDBMap.put(entry, database); + String empty = null; assertEquals("[Boström et al., 2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, null)); + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, null, empty)); assertEquals("Boström et al. [2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, false, null, new int[]{3})); + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, false, null, new int[]{3}, empty)); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, new int[]{5})); + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, new int[]{5}, empty)); } @Test @@ -232,7 +236,9 @@ void testInstitutionAuthorMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + String empty = null; + assertEquals("[JabRef Development Team, 2016]", + style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @Test @@ -252,7 +258,9 @@ void testVonAuthorMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[von Beta, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + String empty = null; + assertEquals("[von Beta, 2016]", + style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @Test @@ -270,7 +278,8 @@ void testNullAuthorMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + String empty = null; + assertEquals("[, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @Test @@ -288,7 +297,9 @@ void testNullYearMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[von Beta, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + String empty = null; + assertEquals("[von Beta, ]", + style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @Test @@ -305,7 +316,8 @@ void testEmptyEntryMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + String empty = null; + assertEquals("[, ]", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @Test @@ -338,10 +350,16 @@ void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { entryDBMap.put(entry, database); } + String empty = null; assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", - style.getCitationMarker(entries, entryDBMap, true, null, null)); + style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", - style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); + style.getCitationMarker(entries, + entryDBMap, + true, + new String[]{"a", "b", ""}, + new int[]{1, 1, 1}, + empty)); } @Test @@ -374,10 +392,16 @@ void testGetCitationMarkerInTextUniquefiers() throws IOException { entryDBMap.put(entry, database); } + String empty = null; assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", - style.getCitationMarker(entries, entryDBMap, false, null, null)); + style.getCitationMarker(entries, entryDBMap, false, null, null, empty)); assertEquals("Beta [2000a,b]; Epsilon [2001]", - style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); + style.getCitationMarker(entries, + entryDBMap, + false, + new String[]{"a", "b", ""}, + new int[]{1, 1, 1}, + empty)); } @Test @@ -411,8 +435,14 @@ void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExc entryDBMap.put(entry, database); } + String empty = null; assertEquals("[Beta, 2000a,b,c]", - style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); + style.getCitationMarker(entries, + entryDBMap, + true, + new String[]{"a", "b", "c"}, + new int[]{1, 1, 1}, + empty)); } @Test @@ -446,17 +476,23 @@ void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException entryDBMap.put(entry, database); } + String empty = null; assertEquals("Beta [2000a,b,c]", - style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); + style.getCitationMarker(entries, + entryDBMap, + false, + new String[]{"a", "b", "c"}, + new int[]{1, 1, 1}, + empty)); } @Test // TODO: equals only work when initialized from file, not from reader void testEquals() throws IOException { OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); assertEquals(style1, style2); } @@ -464,27 +500,27 @@ void testEquals() throws IOException { // TODO: equals only work when initialized from file, not from reader void testNotEquals() throws IOException { OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); assertNotEquals(style1, style2); } @Test void testCompareToEqual() throws IOException { OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); assertEquals(0, style1.compareTo(style2)); } @Test void testCompareToNotEqual() throws IOException { OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); assertTrue(style1.compareTo(style2) > 0); assertFalse(style2.compareTo(style1) > 0); } @@ -504,8 +540,9 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); + String empty = null; assertEquals("von Beta, Epsilon, & Tau, 2016", - style.getCitationMarker(entries, entryDBMap, true, null, null)); + style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @Test From f296836e4fbacb242e4d4bce8c5ae5ddaafbe7b1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 1 Apr 2021 00:12:51 +0200 Subject: [PATCH 0531/1068] List pageInfosForCitations --- .../org/jabref/gui/openoffice/Backend52.java | 170 ++++++++++++++++-- .../jabref/gui/openoffice/CitationGroup.java | 2 - .../jabref/gui/openoffice/CitationGroups.java | 8 +- .../org/jabref/gui/openoffice/OOBibBase.java | 134 +++++++------- .../jabref/logic/openoffice/OOBibStyle.java | 13 +- .../logic/openoffice/OOBibStyleTest.java | 26 +-- 6 files changed, 246 insertions(+), 107 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/Backend52.java b/src/main/java/org/jabref/gui/openoffice/Backend52.java index 02aefc5e0da..ba2b9df023f 100644 --- a/src/main/java/org/jabref/gui/openoffice/Backend52.java +++ b/src/main/java/org/jabref/gui/openoffice/Backend52.java @@ -206,7 +206,8 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc */ public CitationGroup createCitationGroup(DocumentConnection documentConnection, List citationKeys, - Optional pageInfo, + // Optional pageInfo, + List pageInfosForCitations, int itcType, XTextCursor position, boolean insertSpaceAfter, @@ -232,9 +233,12 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, CitationGroupID cgid = new CitationGroupID(refMarkName); - List citations = (citationKeys.stream() - .map(Citation::new) - .collect(Collectors.toList())); + List citations = new ArrayList<>(citationKeys.size()); + for (int i = 0; i < citationKeys.size(); i++) { + Citation cit = new Citation(citationKeys.get(i)); + citations.add(cit); + // cit.setPageInfo(getJabRef53PageInfo(pageInfosForCitations, i)); + } /* * Apply to document @@ -245,20 +249,156 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, insertSpaceAfter, withoutBrackets); - if ( pageInfo.isPresent() && !pageInfo.get().equals("") ) { - documentConnection.setCustomProperty(refMarkName, pageInfo.get()); - } else { - documentConnection.removeCustomProperty(refMarkName); + switch (dataModel){ + case JabRef52: + Optional pageInfo = getJabRef52PageInfoFromList( pageInfosForCitations ); + if ( pageInfo.isPresent() && !pageInfo.get().equals("") ) { + documentConnection.setCustomProperty(refMarkName, pageInfo.get()); + } else { + documentConnection.removeCustomProperty(refMarkName); + } + CitationGroup cg = new CitationGroup(cgid, + sr, + itcType, + citations, + pageInfo, + refMarkName); + return cg; + default: + throw new RuntimeException("Backend52 requires JabRef52 dataModel"); } + } - CitationGroup cg = new CitationGroup(cgid, - sr, - itcType, - citations, - pageInfo, - refMarkName); + Optional getJabRef52PageInfoFromList(List pageInfosForCitations) { + if (pageInfosForCitations == null) { + return Optional.empty(); + } + int n = pageInfosForCitations.size(); + if (n == 0) { + return Optional.empty(); + } + return Optional.ofNullable(pageInfosForCitations.get(n-1)); + } - return cg; + /** + * @param pageInfo Nullable. + */ + static List fakePageInfosForCitations(String pageInfo, + int nCitations, + boolean mayReturnNull) { + // JabRef53 style pageInfo list, or null + List pageInfosForCitations = null; + if (!mayReturnNull || (pageInfo != null && !pageInfo.equals(""))) { + pageInfosForCitations = new ArrayList<>(nCitations); + for (int i = 0; i < nCitations; i++) { + if (i == nCitations - 1) { + pageInfosForCitations.add(pageInfo); + } else { + pageInfosForCitations.add(null); + } + } + } + return pageInfosForCitations; + } + + /** + * @return List of nullable pageInfo values, one for each citation. + * Result contains null for missing pageInfo values. + * The list itself is not null. + * + * For Compat.DataModel.JabRef52 the last citation gets + * the CitationGroup.pageInfo + * + * The result is passed to OOBibStyle.getCitationMarker or + * OOBibStyle.getNumCitationMarker + * + * TODO: we may want class DataModel52, DataModel53 and split this. + */ + static List getPageInfosForCitations(Compat.DataModel dataModel, CitationGroup cg) { + switch (dataModel){ + case JabRef52: + // check conformance to dataModel + for ( int i = 0; i < cg.citations.size(); i++ ) { + if ( cg.citations.get(i).pageInfo.isPresent() ) { + throw new RuntimeException("getPageInfosForCitations:" + + " found Citation.pageInfo under JabRef52 dataModel"); + } + } + // A list of null values, except the last that comes from this.pageInfo + return Backend52.fakePageInfosForCitations(cg.pageInfo.orElse(null), + cg.citations.size(), + false /*mayReturnNull*/); + + case JabRef53: + // check conformance to dataModel + if (cg.pageInfo.isPresent()) { + throw new RuntimeException("getPageInfosForCitations:" + + " found CitationGroup.pageInfo under JabRef53 dataModel"); + } + // pageInfo values from citations, empty mapped to null. + return (cg.citations.stream() + .map(cit -> cit.pageInfo.orElse(null)) + .collect(Collectors.toList())); + + default: + throw new RuntimeException("getPageInfosForCitations:" + + "unhandled dataModel"); + } + } + + /** + * @return A list with one nullable pageInfo entry for each citation in + * joinableGroups. + */ + static List combinePageInfos(Compat.DataModel dataModel, + List joinableGroup ) { + switch (dataModel) { + case JabRef52: + // collect to cgPageInfos + List> cgPageInfos = (joinableGroup.stream() + .map(cg -> cg.pageInfo) + .collect(Collectors.toList())); + + // Try to do something of the cgPageInfos. + String cgPageInfo = (cgPageInfos.stream() + .filter(pi -> pi.isPresent()) + .map(pi -> pi.get()) + .distinct() + .collect(Collectors.joining("; "))); + + int nCitations = (joinableGroup.stream() + .map(cg -> cg.citations.size()) + .mapToInt(Integer::intValue).sum()); + + return Backend52.fakePageInfosForCitations(cgPageInfo, + nCitations, + false /*mayReturnNull*/); + + case JabRef53: + return (joinableGroup.stream() + .flatMap( cg -> (cg.citations.stream() + .map(cit -> cit.pageInfo.orElse(null)))) + .collect(Collectors.toList())); + default: + throw new RuntimeException("unhandled dataModel here"); + } + } + + /** + * + */ + public List combinePageInfos(List joinableGroup ) { + return combinePageInfos(this.dataModel, joinableGroup); + } + + /* + * @return A list of nullable pageInfo values, one for each citation. + * Result contains null for missing pageInfo values. + * The list itself is not null. + * + */ + public List getPageInfosForCitations(CitationGroup cg) { + return getPageInfosForCitations(this.dataModel, cg); } public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroup.java b/src/main/java/org/jabref/gui/openoffice/CitationGroup.java index b8f24353ef7..786056c4b83 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroup.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroup.java @@ -71,8 +71,6 @@ class CitationGroup { this.localOrder = makeIndices(citations.size()); } - - /** Integers 0..(n-1) */ static List makeIndices(int n) { return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroups.java b/src/main/java/org/jabref/gui/openoffice/CitationGroups.java index e6bf774cf47..9adee3623f4 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroups.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroups.java @@ -106,6 +106,9 @@ public CitationGroups(DocumentConnection documentConnection) this.bibliography = Optional.empty(); } + public Compat.DataModel getDataModel() { + return backend.dataModel; + } public String healthReport(DocumentConnection documentConnection) throws @@ -583,7 +586,8 @@ public List getSortedCitations(CitationGroupID cgid) { */ public CitationGroupID createCitationGroup(DocumentConnection documentConnection, List citationKeys, - Optional pageInfo, + //Optional pageInfo, + List pageInfosForCitations, int itcType, XTextCursor position, boolean insertSpaceAfter, @@ -598,7 +602,7 @@ public CitationGroupID createCitationGroup(DocumentConnection documentConnection CitationGroup cg = backend.createCitationGroup(documentConnection, citationKeys, - pageInfo, + pageInfosForCitations, itcType, position, insertSpaceAfter, diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ad312577402..835fc0d6b79 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -775,13 +775,12 @@ private String normalizedCitationMarkerForNormalStyle(CitedKey ck, entries.put( ce, ck.db.get().database ); // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: - String pageInfoForCitationGroup = null; return style.getCitationMarker(Collections.singletonList(ce), entries, true, null, new int[] {-1}, /* no limit on authors */ - pageInfoForCitationGroup); + null /*pageInfosForCitations*/); } /** @@ -954,12 +953,11 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); - String pageInfoForCitationGroup = cg.pageInfo.orElse(null); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, false, - pageInfoForCitationGroup)); + cgs.backend.getPageInfosForCitations(cg))); } return citMarkers; @@ -985,12 +983,11 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); - String pageInfoForCitationGroup = cg.pageInfo.orElse(null); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, - false, /*inList*/ - pageInfoForCitationGroup)); + false, /* inList */ + cgs.backend.getPageInfosForCitations(cg))); } return citMarkers; } @@ -1072,6 +1069,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes } } + List pageInfosForCitations = cgs.backend.getPageInfosForCitations(cg); if ( hasUnresolved ) { /* * Some entries are unresolved. @@ -1091,10 +1089,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes entries.put(e,d); firstLimAuthors2[0] = firstLimAuthors[j]; uniqueLetterForCitedEntry2[0] = uniqueLetterForCitedEntry[j]; - // Attribute pageInfoForCitationGroup to the last - String pageInfoForCitationGroup = (j == (nCitedEntries-1) - ? cg.pageInfo.orElse(null) - : null); + List pageInfo = pageInfosForCitations.subList(j,j+1); s = (s + style.getCitationMarker( cEntries, @@ -1102,8 +1097,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes cg.itcType == OOBibBase.AUTHORYEAR_PAR, uniqueLetterForCitedEntry2, firstLimAuthors2, - pageInfoForCitationGroup - )); + pageInfo)); } else { s = s + String.format("(Unresolved(%s))", currentKey); } @@ -1123,7 +1117,6 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes entries.put(e,d); } - String pageInfoForCitationGroup = cg.pageInfo.orElse(null); citMarkers.put( cgid, style.getCitationMarker( cEntries, @@ -1131,7 +1124,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes cg.itcType == OOBibBase.AUTHORYEAR_PAR, uniqueLetterForCitedEntry, firstLimAuthors, - pageInfoForCitationGroup + pageInfosForCitations ) ); } @@ -1241,7 +1234,8 @@ private static void italicizeRangeFromPosition(XTextCursor position, private void insertReferenceMark(CitationGroups cgs, DocumentConnection documentConnection, List citationKeys, - Optional pageInfo, + // Optional pageInfo, + List pageInfosForCitations, int itcType, String citationText, XTextCursor position, @@ -1263,7 +1257,7 @@ private void insertReferenceMark(CitationGroups cgs, CitationGroupID cgid = cgs.createCitationGroup(documentConnection, citationKeys, - pageInfo, + pageInfosForCitations, itcType, position, insertSpaceAfter, @@ -1393,6 +1387,12 @@ private static String insertCitationGetCitationKey(BibEntry entry) { * @param pageInfo A single page-info for these entries. Stored in custom property * with the same name as the reference mark. * + * This is a GUI call, and we are not ready + * to get multiple pageInfo values there. + * + * In case of multiple entries, pageInfo goes + * to the last citation (as apparently did in JabRef52). + * * Related https://latex.org/forum/viewtopic.php?t=14331 * """ * Q: What I would like is something like this: @@ -1532,18 +1532,21 @@ public void insertCitation(List entries, databaseMap.put(entry, database); } - String pageInfoForCitationGroup = null; + // JabRef53 style pageInfo list, or null + List pageInfosForCitations = + Backend52.fakePageInfosForCitations(pageInfo, + entries.size(), + true /* mayReturnNull */); + // The text we insert - String citeText = - style.isNumberEntries() - ? "[-]" // A dash only. Presumably we expect a refresh later. - : style.getCitationMarker( - entries, - databaseMap, - inParenthesis, - null, - null, - pageInfoForCitationGroup); + String citeText = (style.isNumberEntries() + ? "[-]" // A dash only. Only refresh later. + : style.getCitationMarker(entries, + databaseMap, + inParenthesis, + null, + null, + pageInfosForCitations)); if (citeText.equals("")) { citeText = "[?]"; @@ -1552,7 +1555,7 @@ public void insertCitation(List entries, insertReferenceMark(cgs, documentConnection, citationKeys, - Optional.ofNullable(pageInfo), + pageInfosForCitations, itcType, citeText, cursor, @@ -1963,11 +1966,11 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); int minGroupingCount = 2; List numbers = Collections.singletonList(ck.number.get()); - String pageInfoForCitationGroup = null; // no pageInfo for the bibliography + List pageInfosForCitations = null; // no pageInfo for the bibliography String marker = style.getNumCitationMarker(numbers, minGroupingCount, true, - pageInfoForCitationGroup); + pageInfosForCitations); OOUtil.insertTextAtCurrentLocation(documentConnection.xText, cursor, @@ -2437,6 +2440,7 @@ public void combineCiteMarkers(List databases, */ for (int gi = 0; gi < joinableGroups.size(); gi++) { + List joinableGroup = joinableGroups.get(gi); /* * Join those in joinableGroups.get(gi) */ @@ -2446,39 +2450,24 @@ public void combineCiteMarkers(List databases, // adding to newGroupCitations, then removing // the original CitationGroup values) // - // pageInfos currently belong to the CitationGroup, + // cgPageInfos currently belong to the CitationGroup, // but it is not clear how should handle them here. // List newGroupCitations = new ArrayList<>(); - List> pageInfos = new ArrayList<>(); - int itcType = joinableGroups.get(gi).get(0).itcType; - - for (int gj = 0; gj < joinableGroups.get(gi).size(); gj++) { - CitationGroup rk = joinableGroups.get(gi).get(gj); - //newGroupCitations.addAll(Arrays.asList(bibtexKeys[rk])); - newGroupCitations.addAll( rk.citations); - pageInfos.add( rk.pageInfo ); + for (CitationGroup rk : joinableGroup) { + newGroupCitations.addAll(rk.citations); } - // Try to do something of the pageInfo values. - // - String pageInfo = ""; - pageInfos.stream() - .filter(pi -> pi.isPresent()) - .map(pi -> pi.get()) - .distinct() - .collect(Collectors.joining("; ")); + int itcType = joinableGroup.get(0).itcType; - /* - * joinGroups( documentConnection, oldGroups, cursor, removeOldGroups ) - */ + List pageInfosForCitations = + cgs.backend.combinePageInfos(joinableGroup); - // Remove the old referenceMarkNames from the document. + // Remove the old citation groups from the document. // We might want to do this via backends. - for (int gj = 0; gj < joinableGroups.get(gi).size(); gj++) { - // int rk = joinableGroups.get(gi).get(gj); + for (int gj = 0; gj < joinableGroup.size(); gj++) { // documentConnection.removeReferenceMark(referenceMarkNames.get(rk)); - cgs.removeCitationGroups( joinableGroups.get(gi), documentConnection ); + cgs.removeCitationGroups( joinableGroup, documentConnection ); } XTextCursor textCursor = joinableGroupsCursors.get(gi); @@ -2495,7 +2484,7 @@ public void combineCiteMarkers(List databases, cgs, documentConnection, citationKeys, - Optional.ofNullable(pageInfo == "" ? null : pageInfo), + pageInfosForCitations, // Optional.ofNullable(pageInfo == "" ? null : pageInfo), itcType, // OOBibBase.AUTHORYEAR_PAR, // itcType "tmp", textCursor, @@ -2611,7 +2600,9 @@ public void unCombineCiteMarkers(List databases, setCharStyleTested = true; } - Optional oldPageInfo = cg.pageInfo; + List pageInfosForCitations = cgs.backend.getPageInfosForCitations(cg); + // Optional oldPageInfo = cg.pageInfo; + List cits=cg.citations; if ( cits.size() <= 1 ) { pivot++; @@ -2622,40 +2613,43 @@ public void unCombineCiteMarkers(List databases, cits.stream().map(cit -> cit.citationKey).collect(Collectors.toList()); cgs.removeCitationGroup( cg, documentConnection ); - // documentConnection.removeReferenceMark(names.get(pivot)); // Now we own the content of cits - // Insert bookmark for each key - int last = keys.size() - 1; - int i = 0; - for (String key : keys) { + // Insert mark for each key + final int last = keys.size() - 1; + //for (String key : keys) { + for (int i = 0; i < keys.size(); i++) { // Note: by using insertReferenceMark (and not something // that accepts List, we lose the extra // info stored in the citations. // We just reread below. - List citationKeys = new ArrayList<>(1); - citationKeys.add( key ); + + //List citationKeys = new ArrayList<>(Arrays.asList(keys.get(i))); + // List pageInfos = new ArrayList<>( + // Arrays.asList(pageInfosForCitations.get(i))); + + // citationKeys.add(keys.get(i)); + // pageInfos.add(pageInfosForCitations.get(i)); + boolean insertSpaceAfter = (i != last); insertReferenceMark( cgs, documentConnection, - citationKeys, - ((i==last) ? oldPageInfo : Optional.empty()), // put into the last one + keys.subList(i,i+1), //citationKeys, + pageInfosForCitations.subList(i,i+1), //pageInfos, OOBibBase.AUTHORYEAR_PAR, // itcType, //newName, "tmp", textCursor, - /* withText should be itcType != OOBibBase.INVISIBLE_CIT */ - true, + true, /* withText. Should be itcType != OOBibBase.INVISIBLE_CIT */ style, insertSpaceAfter ); textCursor.collapseToEnd(); - i++; } - madeModifications = true; + madeModifications = true; pivot++; } } finally { diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 6a27c0a8431..dfd3cbe14e0 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -414,14 +414,15 @@ public Layout getReferenceFormat(EntryType type) { * Format a number-based citation marker for the given number. * * @param number The citation numbers. - * @param pageInfoForCitationGroup Nullable. In case of multiple entries, - * attributed to the last. + * @param pageInfosForCitations Null for "none", or a list with + * pageInfo for each citation. These can be null as well. + * * @return The text for the citation. */ public String getNumCitationMarker(List number, int minGroupingCount, boolean inList, - String pageInfoForCitationGroup) { + List pageInfosForCitations) { String bracketBefore = getStringCitProperty(BRACKET_BEFORE); if (inList && (citProperties.containsKey(BRACKET_BEFORE_IN_LIST))) { bracketBefore = getStringCitProperty(BRACKET_BEFORE_IN_LIST); @@ -499,7 +500,8 @@ public String getNumCitationMarker(List number, * @param unlimAuthors Boolean for each entry. If true, we should not use "et al" formatting * regardless of the number of authors. * Can be null to indicate that no entries should have unlimited names. - * @param pageInfoForCitationGroup Nullable, attibuted to the last entry + * @param pageInfosForCitations Null for "none", or a list with + * pageInfo for each citation. These can be null as well. * @return The formatted citation. */ public String getCitationMarker(List entries, @@ -507,7 +509,8 @@ public String getCitationMarker(List entries, boolean inParenthesis, String[] uniquefiers, int[] unlimAuthors, - String pageInfoForCitationGroup) { + List pageInfosForCitations + ) { // Look for groups of uniquefied entries that should be combined in the output. // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). int piv = -1; diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index cda11f5ffed..8ab90819b36 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -85,7 +85,7 @@ void testNumerical() throws IOException { void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - String empty = null; + List empty = null; assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), -1, true, empty)); assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, false, empty)); assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), 0, true, empty)); @@ -103,7 +103,7 @@ void testGetNumCitationMarker() throws IOException { void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - String empty = null; + List empty = null; assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4] ", style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, true, empty)); @@ -146,7 +146,7 @@ void testGetCitationMarker() throws IOException { Map entryDBMap = new HashMap<>(); entryDBMap.put(entry, database); - String empty = null; + List empty = null; assertEquals("[Boström et al., 2006]", style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, null, empty)); assertEquals("Boström et al. [2006]", @@ -236,7 +236,7 @@ void testInstitutionAuthorMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - String empty = null; + List empty = null; assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @@ -258,7 +258,7 @@ void testVonAuthorMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - String empty = null; + List empty = null; assertEquals("[von Beta, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @@ -278,7 +278,7 @@ void testNullAuthorMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - String empty = null; + List empty = null; assertEquals("[, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @@ -297,7 +297,7 @@ void testNullYearMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - String empty = null; + List empty = null; assertEquals("[von Beta, ]", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @@ -316,7 +316,7 @@ void testEmptyEntryMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - String empty = null; + List empty = null; assertEquals("[, ]", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @@ -350,7 +350,7 @@ void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { entryDBMap.put(entry, database); } - String empty = null; + List empty = null; assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", @@ -392,7 +392,7 @@ void testGetCitationMarkerInTextUniquefiers() throws IOException { entryDBMap.put(entry, database); } - String empty = null; + List empty = null; assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", style.getCitationMarker(entries, entryDBMap, false, null, null, empty)); assertEquals("Beta [2000a,b]; Epsilon [2001]", @@ -435,7 +435,7 @@ void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExc entryDBMap.put(entry, database); } - String empty = null; + List empty = null; assertEquals("[Beta, 2000a,b,c]", style.getCitationMarker(entries, entryDBMap, @@ -476,7 +476,7 @@ void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException entryDBMap.put(entry, database); } - String empty = null; + List empty = null; assertEquals("Beta [2000a,b,c]", style.getCitationMarker(entries, entryDBMap, @@ -540,7 +540,7 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - String empty = null; + List empty = null; assertEquals("von Beta, Epsilon, & Tau, 2016", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } From fbc8f0603de41a17a6f3a9af1f6bf0507c3dc063 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 1 Apr 2021 11:05:43 +0200 Subject: [PATCH 0532/1068] format --- .../org/jabref/gui/openoffice/Backend52.java | 7 +- .../org/jabref/gui/openoffice/OOBibBase.java | 74 +++++++------------ 2 files changed, 33 insertions(+), 48 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/Backend52.java b/src/main/java/org/jabref/gui/openoffice/Backend52.java index ba2b9df023f..6f70af0f4f8 100644 --- a/src/main/java/org/jabref/gui/openoffice/Backend52.java +++ b/src/main/java/org/jabref/gui/openoffice/Backend52.java @@ -349,9 +349,12 @@ static List getPageInfosForCitations(Compat.DataModel dataModel, Citatio /** * @return A list with one nullable pageInfo entry for each citation in * joinableGroups. + * + * TODO: JabRef52 combinePageInfos is not reversible. Should warn + * user to check the result. Or ask what to do. */ static List combinePageInfos(Compat.DataModel dataModel, - List joinableGroup ) { + List joinableGroup) { switch (dataModel) { case JabRef52: // collect to cgPageInfos @@ -385,7 +388,7 @@ static List combinePageInfos(Compat.DataModel dataModel, } /** - * + * */ public List combinePageInfos(List joinableGroup ) { return combinePageInfos(this.dataModel, joinableGroup); diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 835fc0d6b79..ded43e9d154 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2466,7 +2466,6 @@ public void combineCiteMarkers(List databases, // Remove the old citation groups from the document. // We might want to do this via backends. for (int gj = 0; gj < joinableGroup.size(); gj++) { - // documentConnection.removeReferenceMark(referenceMarkNames.get(rk)); cgs.removeCitationGroups( joinableGroup, documentConnection ); } @@ -2480,18 +2479,18 @@ public void combineCiteMarkers(List databases, .collect(Collectors.toList()); // Insert reference mark: - insertReferenceMark( - cgs, - documentConnection, - citationKeys, - pageInfosForCitations, // Optional.ofNullable(pageInfo == "" ? null : pageInfo), - itcType, // OOBibBase.AUTHORYEAR_PAR, // itcType - "tmp", - textCursor, - true, // withText - style, - false // insertSpaceAfter: no, it is already there (or could be) - ); + insertReferenceMark(cgs, + documentConnection, + citationKeys, + pageInfosForCitations, + itcType, // OOBibBase.AUTHORYEAR_PAR + "tmp", + textCursor, + true, // withText + style, + false /* insertSpaceAfter: no, it + * is already there (or + * could be) */); } // for gi madeModifications = (joinableGroups.size() > 0); @@ -2514,13 +2513,10 @@ public void combineCiteMarkers(List databases, if (useLockControllers) { documentConnection.lockControllers(); } - applyNewCitationMarkers( - documentConnection, - //x.jabRefReferenceMarkNamesSortedByPosition, - x.cgs, - x.citMarkers, - //x.itcTypes, - style); + applyNewCitationMarkers(documentConnection, + x.cgs, + x.citMarkers, + style); } finally { if (useLockControllers) { documentConnection.unlockControllers(); @@ -2569,10 +2565,6 @@ public void unCombineCiteMarkers(List databases, documentConnection.enterUndoContext("Separate citations"); boolean madeModifications = false; - // boolean mapFootnotesToFootnoteMarks = true; - // List names = - // getVisuallySortedCitationGroupIDs(cgs, documentConnection, mapFootnotesToFootnoteMarks); - // // {@code names} does not need to be sorted. List names = new ArrayList<>(cgs.getCitationGroupIDs()); @@ -2600,8 +2592,8 @@ public void unCombineCiteMarkers(List databases, setCharStyleTested = true; } + // Note: JabRef52 returns cg.pageInfo for the last citation. List pageInfosForCitations = cgs.backend.getPageInfosForCitations(cg); - // Optional oldPageInfo = cg.pageInfo; List cits=cg.citations; if ( cits.size() <= 1 ) { @@ -2618,34 +2610,24 @@ public void unCombineCiteMarkers(List databases, // Insert mark for each key final int last = keys.size() - 1; - //for (String key : keys) { for (int i = 0; i < keys.size(); i++) { // Note: by using insertReferenceMark (and not something // that accepts List, we lose the extra // info stored in the citations. // We just reread below. - //List citationKeys = new ArrayList<>(Arrays.asList(keys.get(i))); - // List pageInfos = new ArrayList<>( - // Arrays.asList(pageInfosForCitations.get(i))); - - // citationKeys.add(keys.get(i)); - // pageInfos.add(pageInfosForCitations.get(i)); - boolean insertSpaceAfter = (i != last); - insertReferenceMark( - cgs, - documentConnection, - keys.subList(i,i+1), //citationKeys, - pageInfosForCitations.subList(i,i+1), //pageInfos, - OOBibBase.AUTHORYEAR_PAR, // itcType, - //newName, - "tmp", - textCursor, - true, /* withText. Should be itcType != OOBibBase.INVISIBLE_CIT */ - style, - insertSpaceAfter - ); + insertReferenceMark(cgs, + documentConnection, + keys.subList(i,i+1), //citationKeys, + pageInfosForCitations.subList(i,i+1), //pageInfos, + OOBibBase.AUTHORYEAR_PAR, // itcType, + "tmp", + textCursor, + true, /* withText. + * Should be itcType != OOBibBase.INVISIBLE_CIT */ + style, + insertSpaceAfter); textCursor.collapseToEnd(); } From f130f742ea4190e50ab75f44e0222f55b029c5d4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 1 Apr 2021 23:09:58 +0200 Subject: [PATCH 0533/1068] getNumCitationMarker now processes its pageInfosForCitations arg Its booean inList argument changed to CitationMarkerPurpose purpose --- .../org/jabref/gui/openoffice/OOBibBase.java | 7 +- .../openoffice/CitationMarkerPurpose.java | 9 + .../jabref/logic/openoffice/OOBibStyle.java | 358 +++++++++++++++--- .../logic/openoffice/OOBibStyleTest.java | 235 +++++++++++- 4 files changed, 534 insertions(+), 75 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ded43e9d154..4ba6d052014 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -33,6 +33,7 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; import org.jabref.logic.openoffice.CitationEntry; +import org.jabref.logic.openoffice.CitationMarkerPurpose; import org.jabref.logic.openoffice.OOBibStyle; import org.jabref.logic.openoffice.OOPreFormatter; import org.jabref.logic.openoffice.OOUtil; @@ -956,7 +957,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, - false, + CitationMarkerPurpose.CITATION, cgs.backend.getPageInfosForCitations(cg))); } @@ -986,7 +987,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, - false, /* inList */ + CitationMarkerPurpose.CITATION, /* inList */ cgs.backend.getPageInfosForCitations(cg))); } return citMarkers; @@ -1969,7 +1970,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, List pageInfosForCitations = null; // no pageInfo for the bibliography String marker = style.getNumCitationMarker(numbers, minGroupingCount, - true, + CitationMarkerPurpose.BIBLIOGRAPHY, /*inList*/ pageInfosForCitations); OOUtil.insertTextAtCurrentLocation(documentConnection.xText, diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java b/src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java new file mode 100644 index 00000000000..1e9e4579dee --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java @@ -0,0 +1,9 @@ +package org.jabref.logic.openoffice; + +public enum CitationMarkerPurpose { + /** Creating citation marker for in-text citation. */ + CITATION, + /** Creating citation marker for the bibliography. */ + BIBLIOGRAPHY +} + diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index dfd3cbe14e0..c2edbf574c7 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -11,6 +11,7 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; +import java.util.function.ToIntFunction; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -410,77 +411,330 @@ public Layout getReferenceFormat(EntryType type) { } } + + /** + * Make sure that (1) we have exactly one entry for each + * citation, (2) each entry is either null or is not empty when trimmed. + */ + public List regularizePageInfosForCitations(List pageInfosForCitations, + int nCitations) { + if ( pageInfosForCitations == null ) { + List res = new ArrayList<>( nCitations ); + for (int i = 0; i < nCitations; i++) { + res.add(null); + } + return res; + } else { + if ( pageInfosForCitations.size() != nCitations ) { + throw new RuntimeException("regularizePageInfosForCitations:" + + " pageInfosForCitations.size() != nCitations"); + } + List res = new ArrayList<>(nCitations); + for (int i = 0; i < nCitations; i++) { + String p = pageInfosForCitations.get(i); + if ( p != null ) { + String pt = p.trim(); + if (pt.equals("")) { + p = null; + } else { + p = pt; + } + } + res.add(p); + } + return res; + } + } + + private class NumberWithPageInfo { + int num; + String pageInfo; + NumberWithPageInfo(int num, String pageInfo) { + this.num = num; + this.pageInfo = pageInfo; + } + } + + /* + * null comes before non-null + */ + private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPageInfo b) { + int res = Integer.compare(a.num, b.num); + if (res == 0) { + if (a.pageInfo == null && b.pageInfo == null) { + res = 0; + } else if (a.pageInfo == null) { + res = -1; + } else if (b.pageInfo == null) { + res = +1; + } else { + res = a.pageInfo.compareTo(b.pageInfo); + } + } + return res; + } + + /** - * Format a number-based citation marker for the given number. + * Format a number-based citation marker for the given number or numbers. * - * @param number The citation numbers. - * @param pageInfosForCitations Null for "none", or a list with - * pageInfo for each citation. These can be null as well. + * @param numbers The citation numbers. + * + * A zero in the list means: could not look this up + * in the databases. Positive integers are the valid numbers. + * + * @param minGroupingCount Zero and negative means never group + * + * @param purpose BIBLIOGRAPHY (was: inList==True) when creating for a bibliography entry, + * CITATION (was: inList=false) when creating in-text citation. + * + * If BIBLIOGRAPHY, prefer BRACKET_BEFORE_IN_LIST over BRACKET_BEFORE, + * and BRACKET_AFTER_IN_LIST over BRACKET_AFTER. + * + * https://docs.jabref.org/cite/openofficeintegration + * + * BracketBeforeInList : The opening bracket for citation + * numbering in the reference list. + * + * BracketAfterInList : The closing bracket for citation + * numbering in the reference list. + * + * @param pageInfosForCitations Null for "none", or a list with a + * pageInfo for each citation. Any or all of these can be null as well. * * @return The text for the citation. + * */ - public String getNumCitationMarker(List number, + public String getNumCitationMarker(List numbers, int minGroupingCount, - boolean inList, + // boolean purpose, + CitationMarkerPurpose purpose, List pageInfosForCitations) { + + final boolean joinIsDisabled = (minGroupingCount <= 0); + final int notFoundInDatabases = 0; + final int nCitations = numbers.size(); + + /** + * strictPurpose: if true, expect (nCitations == 1) when purpose==BIBLIOGRAPHY + * + * + */ + final boolean strictPurpose = false; + + /* + * purpose == BIBLIOGRAPHY means: we are formatting for the + * bibliography, (not for in-text citation). + * + * + */ String bracketBefore = getStringCitProperty(BRACKET_BEFORE); - if (inList && (citProperties.containsKey(BRACKET_BEFORE_IN_LIST))) { - bracketBefore = getStringCitProperty(BRACKET_BEFORE_IN_LIST); - } String bracketAfter = getStringCitProperty(BRACKET_AFTER); - if (inList && (citProperties.containsKey(BRACKET_AFTER_IN_LIST))) { - bracketAfter = getStringCitProperty(BRACKET_AFTER_IN_LIST); + + if (purpose == CitationMarkerPurpose.BIBLIOGRAPHY) { + // prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST + if (citProperties.containsKey(BRACKET_BEFORE_IN_LIST)) { + bracketBefore = getStringCitProperty(BRACKET_BEFORE_IN_LIST); + } + if (citProperties.containsKey(BRACKET_AFTER_IN_LIST)) { + bracketAfter = getStringCitProperty(BRACKET_AFTER_IN_LIST); + } + + if (strictPurpose) { + // If (purpose==BIBLIOGRAPHY), then + // we expect exactly one number here, and can handle quickly + // Yet we get + // org.jabref.logic.openoffice.OOBibStyleTest + // Test testGetNumCitationMarker() FAILED // nCitations = 3 + // Test testGetNumCitationMarkerUndefined() FAILED // nCitations = 4 + // + if (nCitations != 1) { + throw new RuntimeException( + "getNumCitationMarker:" + + "nCitations != 1 for purpose==BIBLIOGRAPHY." + + String.format(" nCitations = %d", nCitations)); + } + // + StringBuilder sb = new StringBuilder(bracketBefore); + final int current = numbers.get(0); + if ( current < 0 ) { + throw new RuntimeException("getNumCitationMarker: found negative value"); + } + sb.append(current != notFoundInDatabases + ? String.valueOf(current) + : OOBibStyle.UNDEFINED_CITATION_MARKER); + sb.append(bracketAfter); + return sb.toString(); + } + } + + /* + * From here: + * - formatting for in-text (not for bibliography) + * - need to care about pageInfosForCitations + * - In case strictPurpose allows us to get here, and purpose==BIBLIOGRAPHY, + * then just use a pageInfos filled with null values. + */ + List pageInfos = + regularizePageInfosForCitations((purpose==CitationMarkerPurpose.BIBLIOGRAPHY + ? null + : pageInfosForCitations), + numbers.size()); + + + // Sort the numbers, together with the corresponding pageInfo values + List nps = new ArrayList<>(); + for (int i = 0; i < nCitations; i++) { + nps.add( new NumberWithPageInfo(numbers.get(i), pageInfos.get(i)) ); } - // Sort the numbers: - List lNum = new ArrayList<>(number); - Collections.sort(lNum); + Collections.sort(nps, OOBibStyle::compareNumberWithPageInfo ); + + + // "[" StringBuilder sb = new StringBuilder(bracketBefore); - int combineFrom = -1; - int written = 0; - for (int i = 0; i < lNum.size(); i++) { - int i1 = lNum.get(i); - if (combineFrom < 0) { - // Check if next entry is the next in the ref list: - if ((i < (lNum.size() - 1)) && (lNum.get(i + 1) == (i1 + 1)) && (i1 > 0)) { - combineFrom = i1; - } else { - // Add single entry: - if (i > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); + + ToIntFunction> emitBlock = (List block) -> { + // uses: sb, this, + + final int blockSize = block.size(); + if (blockSize == 0) { + throw new RuntimeException("We should not get here"); + // return 0; + } + + if (blockSize == 1) { + // Add single entry: + final int num = block.get(0).num; + sb.append(num == notFoundInDatabases + ? OOBibStyle.UNDEFINED_CITATION_MARKER + : String.valueOf(num)); + // TODO: pageInfo here + String pageInfo = block.get(0).pageInfo; + if ( pageInfo != null ) { + sb.append(getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo); + } + } else if (blockSize >= 2) { + // block has at least 2 elements + if (blockSize < 2) { + throw new RuntimeException("impossible: (blockSize < 2)"); + } + // None of these elements has a pageInfo, + // because if it had, we would not join. + for (NumberWithPageInfo x : block) { + if (x.pageInfo != null) { + throw new RuntimeException("impossible: (x.pageInfo != null)"); } - sb.append(lNum.get(i) > 0 - ? String.valueOf(lNum.get(i)) - : OOBibStyle.UNDEFINED_CITATION_MARKER); - written++; } - } else { - // We are building a list of combined entries. - // Check if it ends here: - if ((i == (lNum.size() - 1)) || (lNum.get(i + 1) != (i1 + 1))) { - if (written > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); + // None of these elements needs UNDEFINED_CITATION_MARKER, + // because if it did, we would not join. + for (NumberWithPageInfo x : block) { + if (x.num == notFoundInDatabases) { + throw new RuntimeException("impossible: (x.num == notFoundInDatabases)"); } - if ((minGroupingCount > 0) && (((i1 + 1) - combineFrom) >= minGroupingCount)) { - sb.append(combineFrom); - sb.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); - sb.append(i1); - written++; - } else { - // Either we should never group, or there aren't enough - // entries in this case to group. Output all: - for (int jj = combineFrom; jj <= i1; jj++) { - sb.append(jj); - if (jj < i1) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); - } - written++; + } + // consecutive elements have consecutive numbers + for (int j = 1; j < blockSize; j++) { + if (block.get(j).num != (block.get(j - 1).num + 1)) { + throw new RuntimeException("impossible: consecutive elements" + + " without consecutive numbers"); + } + } + + int first = block.get(0).num; + int last = block.get(blockSize-1).num; + if (((last + 1) - first) >= minGroupingCount) { + // Emit: "first-last" + sb.append(first); + sb.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); + sb.append(last); + } else { + // Emit: first,first+1,...,last + for (int j = 0; j < blockSize; j++) { + if (j > 0) { + sb.append(getStringCitProperty(CITATION_SEPARATOR)); } + sb.append(block.get(j).num); } - combineFrom = -1; } - // If it doesn't end here, just keep iterating. } + return 1; + }; + + /* + * Original: + * [2,3,4] -> [2-4] + * [0,1,2] -> [??,1,2] + * [0,1,2,3] -> [??,1-3] + * + * Now we have to consider: duplicate numbers and pageInfos + * [1,1] -> [1] + * [1,1 "pp nn"] -> keep separate if pageInfo differs + * [1 "pp nn",1 "pp nn"] -> [1 "pp nn"] + */ + + int blocksEmitted = 0; + List currentBlock = new ArrayList<>(); + List nextBlock = new ArrayList<>(); + + + for (int i = 0; i < nCitations; i++) { + + final NumberWithPageInfo current = nps.get(i); + if ( current.num < 0 ) { + throw new RuntimeException("getNumCitationMarker: found negative value"); + } + + if (currentBlock.size() == 0){ + currentBlock.add(current); + } else { + NumberWithPageInfo prev = currentBlock.get(currentBlock.size()-1); + if ((notFoundInDatabases == current.num) + || (notFoundInDatabases == prev.num)) { + nextBlock.add(current); // do not join if not found + } else if (joinIsDisabled) { + nextBlock.add(current); // join disabled + } else if ( compareNumberWithPageInfo(current, prev) == 0 ) { + // Same as prev, just forget it. + } else if ((current.num == (prev.num + 1)) + && (prev.pageInfo == null) + && (current.pageInfo == null)) { + // Just two consecutive numbers without pageInfo: join + currentBlock.add(current); + } else { + // do not join + nextBlock.add(current); + } + } + + if (nextBlock.size() > 0) { + // emit current block + // We are emitting a block + if (blocksEmitted > 0) { + sb.append(getStringCitProperty(CITATION_SEPARATOR)); + } + int emittedNow = emitBlock.applyAsInt(currentBlock); + if ( emittedNow > 0 ) { + blocksEmitted += emittedNow; + currentBlock = nextBlock; + nextBlock = new ArrayList<>(); + } + } // blockSize != 0 + + } // for i + + if (nextBlock.size() != 0) { + throw new RuntimeException("impossible: (nextBlock.size() != 0) after loop"); } + + if (currentBlock.size() > 0) { + // We are emitting a block + if (blocksEmitted > 0) { + sb.append(getStringCitProperty(CITATION_SEPARATOR)); + } + emitBlock.applyAsInt(currentBlock); + } + + // Emit: "]" sb.append(bracketAfter); return sb.toString(); } diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 8ab90819b36..a4fcbe1de8e 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -84,19 +84,172 @@ void testNumerical() throws IOException { @Test void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); List empty = null; - assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), -1, true, empty)); - assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, false, empty)); - assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), 0, true, empty)); - assertEquals("[1-3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, true, empty)); - assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, true, empty)); - assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, true, empty)); - assertEquals("[1; 3; 12] ", style.getNumCitationMarker(Arrays.asList(1, 12, 3), 1, true, empty)); - assertEquals("[3-5; 7; 10-12] ", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, true, empty)); - - String citation = style.getNumCitationMarker(Arrays.asList(1), -1, false, empty); - assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); + + // Unfortunately these two are both "; " in + // jabref/src/main/resources/resource/openoffice/default_numerical.jstyle + // We might want to change one of them + // style.getStringCitProperty(OOBibStyle.PAGE_INFO_SEPARATOR); + // style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR); + + /* The default numerical style uses "[1]", no space after "]" for in-text, + * but "[1] " with space after "]" for the bibliography. + */ + assertEquals("[1]", + style.getNumCitationMarker(Arrays.asList(1), + -1, + CitationMarkerPurpose.CITATION, + empty)); + + // Identical numeric entries are joined. + assertEquals("[1; 2]", + style.getNumCitationMarker(Arrays.asList(1,2,1,2), + 3, + CitationMarkerPurpose.CITATION, + empty)); + // ... unless minGroupingCount <= 0 + assertEquals("[1; 1; 2; 2]", + style.getNumCitationMarker(Arrays.asList(1,2,1,2), + 0, + CitationMarkerPurpose.CITATION, + empty)); + // ... or have different pageInfos + assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", + style.getNumCitationMarker(Arrays.asList(1,1,2,2,3,3), + 1, + CitationMarkerPurpose.CITATION, + Arrays.asList("p1a","p1b","p2","p2",null,null))); + + // Consecutive numbers can become a range ... + assertEquals("[1-3]", + style.getNumCitationMarker(Arrays.asList(1, 2, 3), + 1, /* minGroupingCount */ + CitationMarkerPurpose.CITATION, + empty)); + + // ... unless minGroupingCount is too high + assertEquals("[1; 2; 3]", + style.getNumCitationMarker(Arrays.asList(1, 2, 3), + 4, /* minGroupingCount */ + CitationMarkerPurpose.CITATION, + empty)); + + // ... or if minGroupingCount <= 0 + assertEquals("[1; 2; 3]", + style.getNumCitationMarker(Arrays.asList(1, 2, 3), + 0, /* minGroupingCount */ + CitationMarkerPurpose.CITATION, + empty)); + // ... a pageInfo needs to be emitted + assertEquals("[1; p1; 2-3]", + style.getNumCitationMarker(Arrays.asList(1, 2, 3), + 1, /* minGroupingCount */ + CitationMarkerPurpose.CITATION, + Arrays.asList("p1",null,null))); + + // null and "" pageInfos are taken as equal. + // Due to trimming, " " is the same as well. + assertEquals("[1]", + style.getNumCitationMarker(Arrays.asList(1, 1, 1), + 1, /* minGroupingCount */ + CitationMarkerPurpose.CITATION, + Arrays.asList("",null," "))); + // pageInfos are trimmed + assertEquals("[1; p1]", + style.getNumCitationMarker(Arrays.asList(1, 1, 1), + 1, /* minGroupingCount */ + CitationMarkerPurpose.CITATION, + Arrays.asList("p1"," p1","p1 "))); + + // The citation numbers come out sorted + assertEquals("[3-5; 7; 10-12]", + style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + 1, + CitationMarkerPurpose.CITATION, + empty)); + + // pageInfos are sorted together with the numbers + // (but they inhibit ranges where they are, even if they are identical, + // but not empty-or-null) + assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", + style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + 1, + CitationMarkerPurpose.CITATION, + Arrays.asList("px", "p7", "p3", "p4", + "px", "px", "p5"))); + + + // pageInfo sorting (for the same number) + assertEquals("[1; 1; a; 1; b]", + style.getNumCitationMarker(Arrays.asList(1, 1, 1), + 1, /* minGroupingCount */ + CitationMarkerPurpose.CITATION, + Arrays.asList("","b","a "))); + + // pageInfo sorting (for the same number) is not numeric. + assertEquals("[1; p100; 1; p20; 1; p9]", + style.getNumCitationMarker(Arrays.asList(1, 1, 1), + 1, /* minGroupingCount */ + CitationMarkerPurpose.CITATION, + Arrays.asList("p20","p9","p100"))); + + /* + * BIBLIOGRAPHY : I think + * style.getNumCitationMarkerForBibliography(int num); + * should be enough: we only need it for a single number, never more. + * Consequently minGroupingCount is not needed. + * Nor do we need pageInfo in the bibliography. + */ + assertEquals("[1] ", + style.getNumCitationMarker(Arrays.asList(1), + -1, + CitationMarkerPurpose.BIBLIOGRAPHY, + empty)); + assertEquals("[1] ", + style.getNumCitationMarker(Arrays.asList(1), + 0, + CitationMarkerPurpose.BIBLIOGRAPHY, + empty)); + + // (The following CitationMarkerPurpose.BIBLIOGRAPHY tests do + // not correspond to actual use.) + if (true) { + assertEquals("[1-3] ", + style.getNumCitationMarker(Arrays.asList(1, 2, 3), + 1, /* minGroupingCount */ + CitationMarkerPurpose.BIBLIOGRAPHY, + empty)); + assertEquals("[1; 2; 3] ", + style.getNumCitationMarker(Arrays.asList(1, 2, 3), + 5, + CitationMarkerPurpose.BIBLIOGRAPHY, + empty)); + assertEquals("[1; 2; 3] ", + style.getNumCitationMarker(Arrays.asList(1, 2, 3), + -1, + CitationMarkerPurpose.BIBLIOGRAPHY, + empty)); + assertEquals("[1; 3; 12] ", + style.getNumCitationMarker(Arrays.asList(1, 12, 3), + 1, + CitationMarkerPurpose.BIBLIOGRAPHY, + empty)); + assertEquals("[3-5; 7; 10-12] ", + style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + 1, + CitationMarkerPurpose.BIBLIOGRAPHY, + empty)); + } + + // test insertPageInfo + if (true) { + String citation = style.getNumCitationMarker(Arrays.asList(1), + -1, + CitationMarkerPurpose.CITATION, + empty); + assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); + } } @Test @@ -104,18 +257,60 @@ void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); List empty = null; - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4] ", - style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, true, empty)); + // unresolved citations look like [??] + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", + style.getNumCitationMarker(Arrays.asList(0), + 1, + CitationMarkerPurpose.CITATION, + empty)); + + // pageInfo is shown for unresolved citations + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; p1]", + style.getNumCitationMarker(Arrays.asList(0), + 1, + CitationMarkerPurpose.CITATION, + Arrays.asList("p1"))); + + // unresolved citations sorted to the front + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4]", + style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), + 1, + CitationMarkerPurpose.CITATION, + empty)); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3]", + style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), + 1, + CitationMarkerPurpose.CITATION, + empty)); + + // multiple unresolved citations are not collapsed + assertEquals("[" + + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", + style.getNumCitationMarker(Arrays.asList(0, 0, 0), + 1, + CitationMarkerPurpose.CITATION, + empty)); + + /* + * BIBLIOGRAPHY + */ assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarker(Arrays.asList(0), 1, true, empty)); + style.getNumCitationMarker(Arrays.asList(0), + 1, + CitationMarkerPurpose.BIBLIOGRAPHY, + empty)); - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3] ", - style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, true, empty)); + // pageInfo is not used for the bibliography + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", + style.getNumCitationMarker(Arrays.asList(0), + 1, + CitationMarkerPurpose.BIBLIOGRAPHY, + Arrays.asList("p1"))); - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " - + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, true, empty)); } @Test From b460f94a37bc8b287ca2a8f20f7db76f26f6043b Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 10:33:46 +0200 Subject: [PATCH 0534/1068] getNumCitationMarkerForInText, getNumCitationMarkerForBibliography Moved CitationMarkerPurpose from public API to OOBibStyle private view. Using getNumCitationMarkerForInText and getNumCitationMarkerForBibliography instead in the API. getNumCitationMarker renamed to getNumCitationMarkerCommon and made private. --- .../org/jabref/gui/openoffice/OOBibBase.java | 28 +-- .../openoffice/CitationMarkerPurpose.java | 6 - .../jabref/logic/openoffice/OOBibStyle.java | 69 ++++-- .../logic/openoffice/OOBibStyleTest.java | 216 +++++++----------- 4 files changed, 150 insertions(+), 169 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4ba6d052014..8da85371e25 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -33,7 +33,6 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; import org.jabref.logic.openoffice.CitationEntry; -import org.jabref.logic.openoffice.CitationMarkerPurpose; import org.jabref.logic.openoffice.OOBibStyle; import org.jabref.logic.openoffice.OOPreFormatter; import org.jabref.logic.openoffice.OOUtil; @@ -954,11 +953,11 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); + List pageInfos = cgs.backend.getPageInfosForCitations(cg); citMarkers.put(cgid, - style.getNumCitationMarker(numbers, - minGroupingCount, - CitationMarkerPurpose.CITATION, - cgs.backend.getPageInfosForCitations(cg))); + style.getNumCitationMarkerForInText(numbers, + minGroupingCount, + pageInfos)); } return citMarkers; @@ -984,11 +983,11 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); + List pageInfos = cgs.backend.getPageInfosForCitations(cg); citMarkers.put(cgid, - style.getNumCitationMarker(numbers, - minGroupingCount, - CitationMarkerPurpose.CITATION, /* inList */ - cgs.backend.getPageInfosForCitations(cg))); + style.getNumCitationMarkerForInText(numbers, + minGroupingCount, + pageInfos)); } return citMarkers; } @@ -1965,13 +1964,10 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // Note: minGroupingCount is pointless here, we are // formatting a single entry. // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - int minGroupingCount = 2; - List numbers = Collections.singletonList(ck.number.get()); - List pageInfosForCitations = null; // no pageInfo for the bibliography - String marker = style.getNumCitationMarker(numbers, - minGroupingCount, - CitationMarkerPurpose.BIBLIOGRAPHY, /*inList*/ - pageInfosForCitations); + // int minGroupingCount = 2; + int number = ck.number.get(); + // List pageInfosForCitations = null; // no pageInfo for the bibliography + String marker = style.getNumCitationMarkerForBibliography(number); OOUtil.insertTextAtCurrentLocation(documentConnection.xText, cursor, diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java b/src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java index 1e9e4579dee..f9fdb1abb2d 100644 --- a/src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java +++ b/src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java @@ -1,9 +1,3 @@ package org.jabref.logic.openoffice; -public enum CitationMarkerPurpose { - /** Creating citation marker for in-text citation. */ - CITATION, - /** Creating citation marker for the bibliography. */ - BIBLIOGRAPHY -} diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index c2edbf574c7..e4b6a127d2c 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -9,6 +9,7 @@ import java.io.StringReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.function.ToIntFunction; @@ -474,10 +475,54 @@ private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPag return res; } + /** + * See {@see getNumCitationMarkerCommon} for details. + */ + public String getNumCitationMarkerForInText(List numbers, + int minGroupingCount, + List pageInfosForCitations) { + return getNumCitationMarkerCommon(numbers, + minGroupingCount, + CitationMarkerPurpose.CITATION, + pageInfosForCitations); + } + + /** + * Create a numeric marker for use in the bibliography as label for the entry. + * + * To support for example numbers in superscript without brackets for the text, + * but "[1]" form for the bibliogaphy, the style can provide + * the optional "BracketBeforeInList" and "BracketAfterInList" strings + * to be used here in stead of "BracketBefore" and "BracketAfter" + * + * @return "[${number}]" where + * "[" stands for BRACKET_BEFORE_IN_LIST (with fallback BRACKET_BEFORE) + * "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER) + * "${number}" stands for number formatted. + */ + public String getNumCitationMarkerForBibliography(int number) { + return getNumCitationMarkerCommon(Arrays.asList(number), + 0, + CitationMarkerPurpose.BIBLIOGRAPHY, + null); + } + + private enum CitationMarkerPurpose { + /** Creating citation marker for in-text citation. */ + CITATION, + /** Creating citation marker for the bibliography. */ + BIBLIOGRAPHY + } /** * Format a number-based citation marker for the given number or numbers. * + * This is the common implementation behind + * getNumCitationMarkerForInText and + * getNumCitationMarkerForBibliography. The latter could be easily + * separated unless there is (or going to be) a need for handling + * multiple numbers or page info by getNumCitationMarkerForBibliography. + * * @param numbers The citation numbers. * * A zero in the list means: could not look this up @@ -488,16 +533,9 @@ private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPag * @param purpose BIBLIOGRAPHY (was: inList==True) when creating for a bibliography entry, * CITATION (was: inList=false) when creating in-text citation. * - * If BIBLIOGRAPHY, prefer BRACKET_BEFORE_IN_LIST over BRACKET_BEFORE, - * and BRACKET_AFTER_IN_LIST over BRACKET_AFTER. - * - * https://docs.jabref.org/cite/openofficeintegration - * - * BracketBeforeInList : The opening bracket for citation - * numbering in the reference list. - * - * BracketAfterInList : The closing bracket for citation - * numbering in the reference list. + * If BIBLIOGRAPHY: Prefer BRACKET_BEFORE_IN_LIST over BRACKET_BEFORE, + * and BRACKET_AFTER_IN_LIST over BRACKET_AFTER. + * Ignore pageInfosForCitations. * * @param pageInfosForCitations Null for "none", or a list with a * pageInfo for each citation. Any or all of these can be null as well. @@ -505,11 +543,10 @@ private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPag * @return The text for the citation. * */ - public String getNumCitationMarker(List numbers, - int minGroupingCount, - // boolean purpose, - CitationMarkerPurpose purpose, - List pageInfosForCitations) { + private String getNumCitationMarkerCommon(List numbers, + int minGroupingCount, + CitationMarkerPurpose purpose, + List pageInfosForCitations) { final boolean joinIsDisabled = (minGroupingCount <= 0); final int notFoundInDatabases = 0; @@ -520,7 +557,7 @@ public String getNumCitationMarker(List numbers, * * */ - final boolean strictPurpose = false; + final boolean strictPurpose = true; /* * purpose == BIBLIOGRAPHY means: we are formatting for the diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index a4fcbe1de8e..0c5f7860d12 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -82,7 +82,7 @@ void testNumerical() throws IOException { } @Test - void testGetNumCitationMarker() throws IOException { + void testGetNumCitationMarkerForInText() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); List empty = null; @@ -97,103 +97,109 @@ void testGetNumCitationMarker() throws IOException { * but "[1] " with space after "]" for the bibliography. */ assertEquals("[1]", - style.getNumCitationMarker(Arrays.asList(1), - -1, - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(1), + -1, + empty)); // Identical numeric entries are joined. assertEquals("[1; 2]", - style.getNumCitationMarker(Arrays.asList(1,2,1,2), - 3, - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(1,2,1,2), + 3, + empty)); // ... unless minGroupingCount <= 0 assertEquals("[1; 1; 2; 2]", - style.getNumCitationMarker(Arrays.asList(1,2,1,2), - 0, - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(1,2,1,2), + 0, + empty)); // ... or have different pageInfos assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", - style.getNumCitationMarker(Arrays.asList(1,1,2,2,3,3), - 1, - CitationMarkerPurpose.CITATION, - Arrays.asList("p1a","p1b","p2","p2",null,null))); + style.getNumCitationMarkerForInText(Arrays.asList(1,1,2,2,3,3), + 1, + Arrays.asList("p1a","p1b","p2","p2",null,null))); // Consecutive numbers can become a range ... assertEquals("[1-3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), - 1, /* minGroupingCount */ - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + 1, /* minGroupingCount */ + empty)); // ... unless minGroupingCount is too high assertEquals("[1; 2; 3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), - 4, /* minGroupingCount */ - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + 4, /* minGroupingCount */ + empty)); // ... or if minGroupingCount <= 0 assertEquals("[1; 2; 3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), - 0, /* minGroupingCount */ - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + 0, /* minGroupingCount */ + empty)); // ... a pageInfo needs to be emitted assertEquals("[1; p1; 2-3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), - 1, /* minGroupingCount */ - CitationMarkerPurpose.CITATION, - Arrays.asList("p1",null,null))); + style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + 1, /* minGroupingCount */ + Arrays.asList("p1",null,null))); // null and "" pageInfos are taken as equal. // Due to trimming, " " is the same as well. assertEquals("[1]", - style.getNumCitationMarker(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - CitationMarkerPurpose.CITATION, - Arrays.asList("",null," "))); + style.getNumCitationMarkerForInText(Arrays.asList(1, 1, 1), + 1, /* minGroupingCount */ + Arrays.asList("",null," "))); // pageInfos are trimmed assertEquals("[1; p1]", - style.getNumCitationMarker(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - CitationMarkerPurpose.CITATION, - Arrays.asList("p1"," p1","p1 "))); + style.getNumCitationMarkerForInText(Arrays.asList(1, 1, 1), + 1, /* minGroupingCount */ + Arrays.asList("p1"," p1","p1 "))); // The citation numbers come out sorted assertEquals("[3-5; 7; 10-12]", - style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), - 1, - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + 1, + empty)); // pageInfos are sorted together with the numbers // (but they inhibit ranges where they are, even if they are identical, // but not empty-or-null) assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", - style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), - 1, - CitationMarkerPurpose.CITATION, - Arrays.asList("px", "p7", "p3", "p4", - "px", "px", "p5"))); + style.getNumCitationMarkerForInText(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + 1, + Arrays.asList("px", "p7", "p3", "p4", + "px", "px", "p5"))); // pageInfo sorting (for the same number) assertEquals("[1; 1; a; 1; b]", - style.getNumCitationMarker(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - CitationMarkerPurpose.CITATION, - Arrays.asList("","b","a "))); + style.getNumCitationMarkerForInText(Arrays.asList(1, 1, 1), + 1, /* minGroupingCount */ + Arrays.asList("","b","a "))); // pageInfo sorting (for the same number) is not numeric. assertEquals("[1; p100; 1; p20; 1; p9]", - style.getNumCitationMarker(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - CitationMarkerPurpose.CITATION, - Arrays.asList("p20","p9","p100"))); + style.getNumCitationMarkerForInText(Arrays.asList(1, 1, 1), + 1, /* minGroupingCount */ + Arrays.asList("p20","p9","p100"))); + assertEquals("[1-3]", + style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + 1, /* minGroupingCount */ + empty)); + assertEquals("[1; 2; 3]", + style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + 5, + empty)); + assertEquals("[1; 2; 3]", + style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + -1, + empty)); + assertEquals("[1; 3; 12]", + style.getNumCitationMarkerForInText(Arrays.asList(1, 12, 3), + 1, + empty)); + assertEquals("[3-5; 7; 10-12]", + style.getNumCitationMarkerForInText(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + 1, + empty)); /* * BIBLIOGRAPHY : I think * style.getNumCitationMarkerForBibliography(int num); @@ -202,51 +208,14 @@ void testGetNumCitationMarker() throws IOException { * Nor do we need pageInfo in the bibliography. */ assertEquals("[1] ", - style.getNumCitationMarker(Arrays.asList(1), - -1, - CitationMarkerPurpose.BIBLIOGRAPHY, - empty)); - assertEquals("[1] ", - style.getNumCitationMarker(Arrays.asList(1), - 0, - CitationMarkerPurpose.BIBLIOGRAPHY, - empty)); + style.getNumCitationMarkerForBibliography(1)); - // (The following CitationMarkerPurpose.BIBLIOGRAPHY tests do - // not correspond to actual use.) - if (true) { - assertEquals("[1-3] ", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), - 1, /* minGroupingCount */ - CitationMarkerPurpose.BIBLIOGRAPHY, - empty)); - assertEquals("[1; 2; 3] ", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), - 5, - CitationMarkerPurpose.BIBLIOGRAPHY, - empty)); - assertEquals("[1; 2; 3] ", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), - -1, - CitationMarkerPurpose.BIBLIOGRAPHY, - empty)); - assertEquals("[1; 3; 12] ", - style.getNumCitationMarker(Arrays.asList(1, 12, 3), - 1, - CitationMarkerPurpose.BIBLIOGRAPHY, - empty)); - assertEquals("[3-5; 7; 10-12] ", - style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), - 1, - CitationMarkerPurpose.BIBLIOGRAPHY, - empty)); - } - - // test insertPageInfo + /* + * test insertPageInfo + */ if (true) { - String citation = style.getNumCitationMarker(Arrays.asList(1), + String citation = style.getNumCitationMarkerForInText(Arrays.asList(1), -1, - CitationMarkerPurpose.CITATION, empty); assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); } @@ -260,56 +229,41 @@ void testGetNumCitationMarkerUndefined() throws IOException { // unresolved citations look like [??] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", - style.getNumCitationMarker(Arrays.asList(0), - 1, - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(0), + 1, + empty)); // pageInfo is shown for unresolved citations assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; p1]", - style.getNumCitationMarker(Arrays.asList(0), - 1, - CitationMarkerPurpose.CITATION, - Arrays.asList("p1"))); + style.getNumCitationMarkerForInText(Arrays.asList(0), + 1, + Arrays.asList("p1"))); // unresolved citations sorted to the front assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4]", - style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), - 1, - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(4, 2, 3, 0), + 1, + empty)); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), - 1, - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3, 0), + 1, + empty)); // multiple unresolved citations are not collapsed assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", - style.getNumCitationMarker(Arrays.asList(0, 0, 0), - 1, - CitationMarkerPurpose.CITATION, - empty)); + style.getNumCitationMarkerForInText(Arrays.asList(0, 0, 0), + 1, + empty)); /* * BIBLIOGRAPHY */ assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarker(Arrays.asList(0), - 1, - CitationMarkerPurpose.BIBLIOGRAPHY, - empty)); - - // pageInfo is not used for the bibliography - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarker(Arrays.asList(0), - 1, - CitationMarkerPurpose.BIBLIOGRAPHY, - Arrays.asList("p1"))); + style.getNumCitationMarkerForBibliography(0)); } From 066dfd40410e7180c4e94d51b58e1e5c5cbb983a Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 11:59:12 +0200 Subject: [PATCH 0535/1068] ceckstyle on OOBibStyle.java, drop CitationMarkerPurpose.java --- .../openoffice/CitationMarkerPurpose.java | 3 - .../jabref/logic/openoffice/OOBibStyle.java | 153 ++++++++++++------ 2 files changed, 102 insertions(+), 54 deletions(-) delete mode 100644 src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java b/src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java deleted file mode 100644 index f9fdb1abb2d..00000000000 --- a/src/main/java/org/jabref/logic/openoffice/CitationMarkerPurpose.java +++ /dev/null @@ -1,3 +0,0 @@ -package org.jabref.logic.openoffice; - - diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index e4b6a127d2c..69f3a1fc872 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -9,10 +9,8 @@ import java.io.StringReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; -import java.util.function.ToIntFunction; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -21,6 +19,7 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; +import java.util.function.ToIntFunction; import java.util.regex.Pattern; import org.jabref.logic.layout.Layout; @@ -412,28 +411,27 @@ public Layout getReferenceFormat(EntryType type) { } } - /** * Make sure that (1) we have exactly one entry for each * citation, (2) each entry is either null or is not empty when trimmed. */ public List regularizePageInfosForCitations(List pageInfosForCitations, int nCitations) { - if ( pageInfosForCitations == null ) { - List res = new ArrayList<>( nCitations ); + if (pageInfosForCitations == null) { + List res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { res.add(null); } return res; } else { - if ( pageInfosForCitations.size() != nCitations ) { + if (pageInfosForCitations.size() != nCitations) { throw new RuntimeException("regularizePageInfosForCitations:" + " pageInfosForCitations.size() != nCitations"); } List res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { String p = pageInfosForCitations.get(i); - if ( p != null ) { + if (p != null) { String pt = p.trim(); if (pt.equals("")) { p = null; @@ -447,7 +445,11 @@ public List regularizePageInfosForCitations(List pageInfosForCit } } - private class NumberWithPageInfo { + /* + * Helper class for sorting citation numbers while + * maintaining their correspondance to pageInfos. + */ + private static class NumberWithPageInfo { int num; String pageInfo; NumberWithPageInfo(int num, String pageInfo) { @@ -456,7 +458,9 @@ private class NumberWithPageInfo { } } - /* + /** + * Defines sort order for NumberWithPageInfo entries. + * * null comes before non-null */ private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPageInfo b) { @@ -493,15 +497,15 @@ public String getNumCitationMarkerForInText(List numbers, * To support for example numbers in superscript without brackets for the text, * but "[1]" form for the bibliogaphy, the style can provide * the optional "BracketBeforeInList" and "BracketAfterInList" strings - * to be used here in stead of "BracketBefore" and "BracketAfter" + * to be used in the bibliography instead of "BracketBefore" and "BracketAfter" * * @return "[${number}]" where * "[" stands for BRACKET_BEFORE_IN_LIST (with fallback BRACKET_BEFORE) * "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER) - * "${number}" stands for number formatted. + * "${number}" stands for the formatted number. */ public String getNumCitationMarkerForBibliography(int number) { - return getNumCitationMarkerCommon(Arrays.asList(number), + return getNumCitationMarkerCommon(Collections.singletonList(number), 0, CitationMarkerPurpose.BIBLIOGRAPHY, null); @@ -528,6 +532,17 @@ private enum CitationMarkerPurpose { * A zero in the list means: could not look this up * in the databases. Positive integers are the valid numbers. * + * Duplicate citation numbers are allowed: + * + * - If their pageInfos are identical, only a + * single instance is emitted. + * + * - If their pageInfos differ, the number is emitted with each + * distinct pageInfo. + * + * For pageInfo null and "" (after + * pageInfo.trim()) are considered equal (and missing). + * * @param minGroupingCount Zero and negative means never group * * @param purpose BIBLIOGRAPHY (was: inList==True) when creating for a bibliography entry, @@ -552,22 +567,20 @@ private String getNumCitationMarkerCommon(List numbers, final int notFoundInDatabases = 0; final int nCitations = numbers.size(); - /** - * strictPurpose: if true, expect (nCitations == 1) when purpose==BIBLIOGRAPHY - * - * + /* + * strictPurpose: if true, require (nCitations == 1) when (purpose == BIBLIOGRAPHY), + * otherwise allow multiple citation numbers and process the BIBLIOGRAPHY case + * as CITATION with no pageInfo. */ final boolean strictPurpose = true; + String bracketBefore = getStringCitProperty(BRACKET_BEFORE); + String bracketAfter = getStringCitProperty(BRACKET_AFTER); + /* * purpose == BIBLIOGRAPHY means: we are formatting for the * bibliography, (not for in-text citation). - * - * */ - String bracketBefore = getStringCitProperty(BRACKET_BEFORE); - String bracketAfter = getStringCitProperty(BRACKET_AFTER); - if (purpose == CitationMarkerPurpose.BIBLIOGRAPHY) { // prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST if (citProperties.containsKey(BRACKET_BEFORE_IN_LIST)) { @@ -580,11 +593,6 @@ private String getNumCitationMarkerCommon(List numbers, if (strictPurpose) { // If (purpose==BIBLIOGRAPHY), then // we expect exactly one number here, and can handle quickly - // Yet we get - // org.jabref.logic.openoffice.OOBibStyleTest - // Test testGetNumCitationMarker() FAILED // nCitations = 3 - // Test testGetNumCitationMarkerUndefined() FAILED // nCitations = 4 - // if (nCitations != 1) { throw new RuntimeException( "getNumCitationMarker:" @@ -594,7 +602,7 @@ private String getNumCitationMarkerCommon(List numbers, // StringBuilder sb = new StringBuilder(bracketBefore); final int current = numbers.get(0); - if ( current < 0 ) { + if (current < 0) { throw new RuntimeException("getNumCitationMarker: found negative value"); } sb.append(current != notFoundInDatabases @@ -609,27 +617,60 @@ private String getNumCitationMarkerCommon(List numbers, * From here: * - formatting for in-text (not for bibliography) * - need to care about pageInfosForCitations - * - In case strictPurpose allows us to get here, and purpose==BIBLIOGRAPHY, - * then just use a pageInfos filled with null values. + * + * - In case {@code strictPurpose} above is set to false and allows us to + * get here, and {@code purpose==BIBLIOGRAPHY}, then we just fill + * pageInfos with null values. */ List pageInfos = - regularizePageInfosForCitations((purpose==CitationMarkerPurpose.BIBLIOGRAPHY + regularizePageInfosForCitations((purpose == CitationMarkerPurpose.BIBLIOGRAPHY ? null : pageInfosForCitations), numbers.size()); - // Sort the numbers, together with the corresponding pageInfo values List nps = new ArrayList<>(); for (int i = 0; i < nCitations; i++) { - nps.add( new NumberWithPageInfo(numbers.get(i), pageInfos.get(i)) ); + nps.add(new NumberWithPageInfo(numbers.get(i), pageInfos.get(i))); } - Collections.sort(nps, OOBibStyle::compareNumberWithPageInfo ); - + Collections.sort(nps, OOBibStyle::compareNumberWithPageInfo); // "[" StringBuilder sb = new StringBuilder(bracketBefore); + /* + * int emitBlock(List block) + * + * Given a block containing 1 or (two or more) + * NumberWithPageInfo entries collected as singletons or + * joinable into an "i-j" form, append to {@code sb} the + * formatted text. + * + * Assumes: + * + * - block is not empty + * + * - For a block with a single element the element may have + * pageInfo and its num part may be zero + * (notFoundInDatabases). + * + * - For a block with two or more elements + * + * - The elements do not have pageInfo and their num part is + * not zero. + * + * - The elements num parts are consecutive positive integers, + * without repetition. + * + * Note: this function is long enough to move into a separate method. + * On the other hand, its assumptions strongly tie it to + * the loop below that collects the block. + * + * @return The number of blocks emitted. Since currently + * throws if the block is empty, the returned value is + * always 1. + * + */ ToIntFunction> emitBlock = (List block) -> { // uses: sb, this, @@ -645,12 +686,17 @@ private String getNumCitationMarkerCommon(List numbers, sb.append(num == notFoundInDatabases ? OOBibStyle.UNDEFINED_CITATION_MARKER : String.valueOf(num)); - // TODO: pageInfo here - String pageInfo = block.get(0).pageInfo; - if ( pageInfo != null ) { + // Emit pageInfo + String pageInfo = block.get(0).pageInfo; + if (pageInfo != null) { sb.append(getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo); } - } else if (blockSize >= 2) { + } else { + + /* + * Check assumptions + */ + // block has at least 2 elements if (blockSize < 2) { throw new RuntimeException("impossible: (blockSize < 2)"); @@ -677,9 +723,16 @@ private String getNumCitationMarkerCommon(List numbers, } } - int first = block.get(0).num; - int last = block.get(blockSize-1).num; - if (((last + 1) - first) >= minGroupingCount) { + /* + * Do the actual work + */ + if (blockSize >= minGroupingCount) { + int first = block.get(0).num; + int last = block.get(blockSize - 1).num; + if (((last + 1) - first) != blockSize) { + throw new RuntimeException("impossible:" + + " blockSize and length of num range differ"); + } // Emit: "first-last" sb.append(first); sb.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); @@ -713,24 +766,23 @@ private String getNumCitationMarkerCommon(List numbers, List currentBlock = new ArrayList<>(); List nextBlock = new ArrayList<>(); - for (int i = 0; i < nCitations; i++) { final NumberWithPageInfo current = nps.get(i); - if ( current.num < 0 ) { + if (current.num < 0) { throw new RuntimeException("getNumCitationMarker: found negative value"); } - if (currentBlock.size() == 0){ + if (currentBlock.size() == 0) { currentBlock.add(current); } else { - NumberWithPageInfo prev = currentBlock.get(currentBlock.size()-1); + NumberWithPageInfo prev = currentBlock.get(currentBlock.size() - 1); if ((notFoundInDatabases == current.num) || (notFoundInDatabases == prev.num)) { nextBlock.add(current); // do not join if not found } else if (joinIsDisabled) { nextBlock.add(current); // join disabled - } else if ( compareNumberWithPageInfo(current, prev) == 0 ) { + } else if (compareNumberWithPageInfo(current, prev) == 0) { // Same as prev, just forget it. } else if ((current.num == (prev.num + 1)) && (prev.pageInfo == null) @@ -750,7 +802,7 @@ private String getNumCitationMarkerCommon(List numbers, sb.append(getStringCitProperty(CITATION_SEPARATOR)); } int emittedNow = emitBlock.applyAsInt(currentBlock); - if ( emittedNow > 0 ) { + if (emittedNow > 0) { blocksEmitted += emittedNow; currentBlock = nextBlock; nextBlock = new ArrayList<>(); @@ -1089,9 +1141,9 @@ private String getAuthorLastName(AuthorList al, int number) { * Take a finished citation and insert a string at the end (but * inside the end bracket) separated by "PageInfoSeparator" * - * @param citation - * @param pageInfo - * @return + * @param citation A formatted citation probably ending with BRACKET_AFTER. + * @param pageInfo Text to be inserted. + * @return The modified citation. */ public String insertPageInfo(String citation, String pageInfo) { String bracketAfter = getStringCitProperty(BRACKET_AFTER); @@ -1228,7 +1280,6 @@ public int hashCode() { return Objects.hash(path, name, citProperties, properties); } - /** * @param maxAuthors The maximum number of authors to write out in * full without using etal. Set to -1 to always From d5735ae8ee37c4c48118a84434193babfa79c904 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 14:48:28 +0200 Subject: [PATCH 0536/1068] format --- .../jabref/logic/openoffice/OOBibStyle.java | 42 ++++++++++++++----- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 69f3a1fc872..b1d69ba9c95 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -41,19 +41,34 @@ import org.slf4j.LoggerFactory; /** - * This class embodies a bibliography formatting for OpenOffice, which is composed - * of the following elements: + * + * This class embodies bibliography formatting for OpenOffice, which + * is composed of the following elements: + * *

- * 1) Each OO BIB entry type must have a formatting. A formatting is an array of elements, each - * of which is either a piece of constant text, an entry field value, or a tab. Each element has - * a character format associated with it. + * 1) For each type of {@code BibEntry} we need a formatting specification, + * termed {@code Layout} here. + * + * A formatting is an array of elements, each of which is either + * - a piece of constant text, + * - an entry field value, + * - or a tab. + * Each element has a character format associated with it. *

- * 2) Many field values (e.g. author) need to be formatted before input to OpenOffice. The style - * has the responsibility of formatting all field values. Formatting is handled by 0-n - * JabRef LayoutFormatter classes. + * 2) Many field values (e.g. author) need to be formatted before + * input to OpenOffice. + * + * The style has the responsibility of formatting all field + * values. + * + * Formatting is handled by {@code LayoutFormatter} classes. *

- * 3) If the entries are not numbered, a citation marker must be produced for each entry. This - * operation is performed for each JabRef BibEntry. + * 3) A citation marker must be produced for each entry. + * + * For non-numbered styles this operation is performed for each + * {@code BibEntry} by {@code getCitationMarker}, for numbered styles by + * {@code getNumCitationMarkerForInText}. + * */ public class OOBibStyle implements Comparable { @@ -67,6 +82,7 @@ public class OOBibStyle implements Comparable { public static final String TITLE = "Title"; public static final String UNDEFINED_CITATION_MARKER = "??"; + private static final Pattern NUM_PATTERN = Pattern.compile("-?\\d+"); private static final String LAYOUT_MRK = "LAYOUT"; private static final String PROPERTIES_MARK = "PROPERTIES"; @@ -107,12 +123,15 @@ public class OOBibStyle implements Comparable { private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); private final SortedSet journals = new TreeSet<>(); + // Formatter to be run on fields before they are used as part of citation marker: private final LayoutFormatter fieldFormatter = new OOPreFormatter(); + // reference layout mapped from entry type: private final Map bibLayout = new HashMap<>(); private final Map properties = new HashMap<>(); private final Map citProperties = new HashMap<>(); + private final boolean fromResource; private final String path; private final Charset encoding; @@ -125,7 +144,8 @@ public class OOBibStyle implements Comparable { private String localCopy; private boolean isDefaultLayoutPresent; - public OOBibStyle(File styleFile, LayoutFormatterPreferences prefs, + public OOBibStyle(File styleFile, + LayoutFormatterPreferences prefs, Charset encoding) throws IOException { this.prefs = Objects.requireNonNull(prefs); this.styleFile = Objects.requireNonNull(styleFile); From 528b3c815bdbf64d3ad828007e52b52cdf0776ee Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 17:54:03 +0200 Subject: [PATCH 0537/1068] refactor: extract OOBibStyleParser --- .../jabref/logic/openoffice/OOBibStyle.java | 194 +++------------ .../logic/openoffice/OOBibStyleParser.java | 234 ++++++++++++++++++ 2 files changed, 268 insertions(+), 160 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index b1d69ba9c95..d90de78aa8c 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -83,13 +83,6 @@ public class OOBibStyle implements Comparable { public static final String TITLE = "Title"; public static final String UNDEFINED_CITATION_MARKER = "??"; - private static final Pattern NUM_PATTERN = Pattern.compile("-?\\d+"); - private static final String LAYOUT_MRK = "LAYOUT"; - private static final String PROPERTIES_MARK = "PROPERTIES"; - private static final String CITATION_MARK = "CITATION"; - private static final String NAME_MARK = "NAME"; - private static final String JOURNALS_MARK = "JOURNALS"; - private static final String DEFAULT_MARK = "default"; private static final String BRACKET_AFTER_IN_LIST = "BracketAfterInList"; private static final String BRACKET_BEFORE_IN_LIST = "BracketBeforeInList"; private static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; @@ -119,31 +112,39 @@ public class OOBibStyle implements Comparable { private static final String AUTHOR_SEPARATOR = "AuthorSeparator"; - private static final Pattern QUOTED = Pattern.compile("\".*\""); - private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); - private final SortedSet journals = new TreeSet<>(); // Formatter to be run on fields before they are used as part of citation marker: private final LayoutFormatter fieldFormatter = new OOPreFormatter(); // reference layout mapped from entry type: - private final Map bibLayout = new HashMap<>(); - private final Map properties = new HashMap<>(); - private final Map citProperties = new HashMap<>(); + // private final Map bibLayout = new HashMap<>(); + // private final Map properties = new HashMap<>(); + // private final Map citProperties = new HashMap<>(); private final boolean fromResource; private final String path; private final Charset encoding; - private final LayoutFormatterPreferences prefs; - private String name = ""; - private Layout defaultBibLayout; - private boolean valid; + + // used in OOBibStyleParser + protected String name = ""; + protected String localCopy; + protected final LayoutFormatterPreferences prefs; + protected Layout defaultBibLayout; + protected boolean isDefaultLayoutPresent; + // reference layout mapped from entry type: + protected final Map bibLayout = new HashMap<>(); + protected final Map properties = new HashMap<>(); + protected final Map citProperties = new HashMap<>(); + protected boolean valid; + protected final SortedSet journals = new TreeSet<>(); + private File styleFile; private long styleFileModificationTime = Long.MIN_VALUE; - private String localCopy; - private boolean isDefaultLayoutPresent; + /** + * Construct from user-provided style file. + */ public OOBibStyle(File styleFile, LayoutFormatterPreferences prefs, Charset encoding) throws IOException { @@ -156,6 +157,9 @@ public OOBibStyle(File styleFile, path = styleFile.getPath(); } + /** + * Construct from resource. + */ public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) throws IOException { this.prefs = Objects.requireNonNull(prefs); Objects.requireNonNull(resourcePath); @@ -230,6 +234,10 @@ public Set getJournals() { private void initialize(InputStream stream) throws IOException { Objects.requireNonNull(stream); + // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html + // + // The try-with-resources Statement + // try (Reader reader = new InputStreamReader(stream, encoding)) { readFormatFile(reader); } @@ -276,79 +284,11 @@ private boolean isUpToDate() { } } + /** + * Parse a *.jstyle file from {@code in}. + */ private void readFormatFile(Reader in) throws IOException { - - // First read all the contents of the file: - StringBuilder sb = new StringBuilder(); - int c; - while ((c = in.read()) != -1) { - sb.append((char) c); - } - - // Store a local copy for viewing - localCopy = sb.toString(); - - // Break into separate lines: - String[] lines = sb.toString().split("\n"); - BibStyleMode mode = BibStyleMode.NONE; - - for (String line1 : lines) { - String line = line1; - if (!line.isEmpty() && (line.charAt(line.length() - 1) == '\r')) { - line = line.substring(0, line.length() - 1); - } - // Check for empty line or comment: - if (line.trim().isEmpty() || (line.charAt(0) == '#')) { - continue; - } - // Check if we should change mode: - switch (line) { - case NAME_MARK: - mode = BibStyleMode.NAME; - continue; - case LAYOUT_MRK: - mode = BibStyleMode.LAYOUT; - continue; - case PROPERTIES_MARK: - mode = BibStyleMode.PROPERTIES; - continue; - case CITATION_MARK: - mode = BibStyleMode.CITATION; - continue; - case JOURNALS_MARK: - mode = BibStyleMode.JOURNALS; - continue; - default: - break; - } - - switch (mode) { - case NAME: - if (!line.trim().isEmpty()) { - name = line.trim(); - } - break; - case LAYOUT: - handleStructureLine(line); - break; - case PROPERTIES: - handlePropertiesLine(line, properties); - break; - case CITATION: - handlePropertiesLine(line, citProperties); - break; - case JOURNALS: - handleJournalsLine(line); - break; - default: - break; - } - } - // Set validity boolean based on whether we found anything interesting - // in the file: - if ((mode != BibStyleMode.NONE) && isDefaultLayoutPresent) { - valid = true; - } + OOBibStyleParser.readFormatFile(in, this); } /** @@ -361,66 +301,8 @@ public boolean isValid() { return valid; } - /** - * Parse a line providing bibliography structure information for an entry type. - * - * @param line The string containing the structure description. - */ - private void handleStructureLine(String line) { - int index = line.indexOf('='); - if ((index > 0) && (index < (line.length() - 1))) { - - try { - String formatString = line.substring(index + 1); - StringReader reader = new StringReader(formatString); - Layout layout = new LayoutHelper(reader, this.prefs).getLayoutFromText(); - EntryType type = EntryTypeFactory.parse(line.substring(0, index)); - - if (!isDefaultLayoutPresent && line.substring(0, index).equals(OOBibStyle.DEFAULT_MARK)) { - isDefaultLayoutPresent = true; - defaultBibLayout = layout; - } else { - bibLayout.put(type, layout); - } - } catch (IOException ex) { - LOGGER.warn("Cannot parse bibliography structure", ex); - } - } - } - /** - * Parse a line providing a property name and value. - * - * @param line The line containing the formatter names. - */ - private void handlePropertiesLine(String line, Map map) { - int index = line.indexOf('='); - if ((index > 0) && (index <= (line.length() - 1))) { - String propertyName = line.substring(0, index).trim(); - String value = line.substring(index + 1); - if ((value.trim().length() > 1) && QUOTED.matcher(value.trim()).matches()) { - value = value.trim().substring(1, value.trim().length() - 1); - } - Object toSet = value; - if (NUM_PATTERN.matcher(value).matches()) { - toSet = Integer.parseInt(value); - } else if ("true".equalsIgnoreCase(value.trim())) { - toSet = Boolean.TRUE; - } else if ("false".equalsIgnoreCase(value.trim())) { - toSet = Boolean.FALSE; - } - map.put(propertyName, toSet); - } - } - - /** - * Parse a line providing a journal name for which this style is valid. - */ - private void handleJournalsLine(String line) { - if (!line.trim().isEmpty()) { - journals.add(line.trim()); - } - } + // --- end of parser -------- public Layout getReferenceFormat(EntryType type) { Layout l = bibLayout.get(type); @@ -1302,8 +1184,8 @@ public int hashCode() { /** * @param maxAuthors The maximum number of authors to write out in - * full without using etal. Set to -1 to always - * write out all authors. + * full without using etal. Set to -1 to always write out + * all authors. */ private String createAuthorList(String author, int maxAuthors, @@ -1360,12 +1242,4 @@ private String createAuthorList(String author, return sb.toString(); } - enum BibStyleMode { - NONE, - LAYOUT, - PROPERTIES, - CITATION, - NAME, - JOURNALS - } } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java new file mode 100644 index 00000000000..b97c3dcf38e --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -0,0 +1,234 @@ +package org.jabref.logic.openoffice; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.Map; +import java.util.SortedSet; +import java.util.regex.Pattern; + +import org.jabref.logic.layout.Layout; +import org.jabref.logic.layout.LayoutHelper; +import org.jabref.model.entry.types.EntryType; +import org.jabref.model.entry.types.EntryTypeFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Parse a "*.jstyle" file + */ + +class OOBibStyleParser { + + private static final String LAYOUT_MRK = "LAYOUT"; + private static final String PROPERTIES_MARK = "PROPERTIES"; + private static final String CITATION_MARK = "CITATION"; + private static final String NAME_MARK = "NAME"; + private static final String JOURNALS_MARK = "JOURNALS"; + private static final String DEFAULT_MARK = "default"; + + private static final Pattern QUOTED = Pattern.compile("\".*\""); + private static final Pattern NUM_PATTERN = Pattern.compile("-?\\d+"); + + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyleParser.class); + + /** + * Parse a *.jstyle file from {@code in}. + * + * - Does not reset style, only adds things. + */ + public static void readFormatFile(Reader in, OOBibStyle style) throws IOException { + + // First read all the contents of the file: + StringBuilder sb = new StringBuilder(); + int c; + while ((c = in.read()) != -1) { + sb.append((char) c); + } + + // Store a local copy for viewing + style.localCopy = sb.toString(); + + // Break into separate lines: + String[] lines = sb.toString().split("\n"); + BibStyleMode mode = BibStyleMode.NONE; + + for (String line1 : lines) { + String line = line1; + + // Drop "\r" from end of line + if (!line.isEmpty() + && (line.charAt(line.length() - 1) == '\r')) { + line = line.substring(0, line.length() - 1); + } + + // Skip empty line or comment: + if (line.trim().isEmpty() || (line.charAt(0) == '#')) { + continue; + } + + // Check if we should change mode: + switch (line) { + case NAME_MARK: + mode = BibStyleMode.NAME; + continue; + case LAYOUT_MRK: + mode = BibStyleMode.LAYOUT; + continue; + case PROPERTIES_MARK: + mode = BibStyleMode.PROPERTIES; + continue; + case CITATION_MARK: + mode = BibStyleMode.CITATION; + continue; + case JOURNALS_MARK: + mode = BibStyleMode.JOURNALS; + continue; + default: + break; + } + + switch (mode) { + case NAME: + if (!line.trim().isEmpty()) { + style.name = line.trim(); + } + break; + case LAYOUT: + handleLayoutLine(line, style); + break; + case PROPERTIES: + handlePropertiesLine(line, style.properties); + break; + case CITATION: + handlePropertiesLine(line, style.citProperties); + break; + case JOURNALS: + handleJournalsLine(line, style.journals); + break; + default: + break; + } + } + + // Set validity boolean based on whether we found anything interesting + // in the file: + if ((mode != BibStyleMode.NONE) && style.isDefaultLayoutPresent) { + style.valid = true; + } + } + + /** + * Parse a line providing bibliography structure information for an entry type. + * + * @param line The string containing the structure description. + * + * Expecting a line from below the "LAYOUT" tag in *.jstyle, + * in "name=RHS" form. Silently ignores lines not matching this pattern. + * + * The "name" part is passed to {@code EntryTypeFactory.parse(name);} + * The "RHS" part is passed to {@code new LayoutHelper( ..., style.prefs).getLayoutFromText();} + * + */ + private static void handleLayoutLine(String line, OOBibStyle style) { + /* + * uses: + * style.prefs + * style.isDefaultLayoutPresent = x + * style.defaultBibLayout = x + * style.bibLayout.put() + * + */ + // "^([^=]+)[=](.+)$" With formatString = $2; name = $1; + + /* + * Split the line at the first '='. + * Do nothing if either half is empty, or "=" is not present. + * + * Note: maye should signal somehow that this line was not processed. + * + */ + int index = line.indexOf('='); + if (index <= 0) { + return; /* No "=" or line[0] == "=" */ + } + if (index >= (line.length() - 1)) { + return; /* First "=" is at the last character. */ + } + + String name = line.substring(0, index); + String formatString = line.substring(index + 1); + + // Parse name: actually look up in a closed list, or + // return {@code new UnknownEntryType(typeName)} + EntryType type = EntryTypeFactory.parse(name); + + // Parse the formatString. Apparently does not depend on EntryType. + StringReader reader = new StringReader(formatString); + Layout layout; + try { + layout = new LayoutHelper(reader, style.prefs).getLayoutFromText(); + } catch (IOException ex) { + LOGGER.warn("Cannot parse bibliography structure", ex); + return; + } + + /* At the first DEFAULT_MARK, put into defaultBibLayout, otherwise + * add to bibLayout. + * + * Note: Adding the second DEFAULT_MARK to bibLayout may be unintended. + * + */ + if (!style.isDefaultLayoutPresent && name.equals(DEFAULT_MARK)) { + style.isDefaultLayoutPresent = true; + style.defaultBibLayout = layout; + } else { + style.bibLayout.put(type, layout); + } + } + + /** + * Parse a line providing a property name and value. + * + * @param line The line containing the formatter names. + */ + private static void handlePropertiesLine(String line, Map map) { + int index = line.indexOf('='); + if ((index > 0) && (index <= (line.length() - 1))) { + String propertyName = line.substring(0, index).trim(); + String value = line.substring(index + 1); + if ((value.trim().length() > 1) && QUOTED.matcher(value.trim()).matches()) { + value = value.trim().substring(1, value.trim().length() - 1); + } + Object toSet = value; + if (NUM_PATTERN.matcher(value).matches()) { + toSet = Integer.parseInt(value); + } else if ("true".equalsIgnoreCase(value.trim())) { + toSet = Boolean.TRUE; + } else if ("false".equalsIgnoreCase(value.trim())) { + toSet = Boolean.FALSE; + } + map.put(propertyName, toSet); + } + } + + /** + * Parse a line providing a journal name for which this style is valid. + */ + private static void handleJournalsLine(String line, SortedSet journals) { + if (!line.trim().isEmpty()) { + journals.add(line.trim()); + } + } + + enum BibStyleMode { + NONE, + LAYOUT, + PROPERTIES, + CITATION, + NAME, + JOURNALS + } + +} From b8941d6d93efe7dd3f2e85231fbbd0faff94853c Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 18:50:06 +0200 Subject: [PATCH 0538/1068] refactor: OOBibStyleGetNumCitationMarker.java --- .../jabref/logic/openoffice/OOBibStyle.java | 464 +++--------------- .../OOBibStyleGetNumCitationMarker.java | 432 ++++++++++++++++ 2 files changed, 488 insertions(+), 408 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index d90de78aa8c..23f1d8888c9 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -83,8 +83,15 @@ public class OOBibStyle implements Comparable { public static final String TITLE = "Title"; public static final String UNDEFINED_CITATION_MARKER = "??"; - private static final String BRACKET_AFTER_IN_LIST = "BracketAfterInList"; - private static final String BRACKET_BEFORE_IN_LIST = "BracketBeforeInList"; + // These are used in OOBibStyleGetNumCitationMarker + protected static final String BRACKET_AFTER = "BracketAfter"; + protected static final String BRACKET_BEFORE = "BracketBefore"; + protected static final String BRACKET_AFTER_IN_LIST = "BracketAfterInList"; + protected static final String BRACKET_BEFORE_IN_LIST = "BracketBeforeInList"; + protected static final String GROUPED_NUMBERS_SEPARATOR = "GroupedNumbersSeparator"; + protected static final String PAGE_INFO_SEPARATOR = "PageInfoSeparator"; + protected static final String CITATION_SEPARATOR = "CitationSeparator"; + private static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; private static final String CITATION_KEY_CITATIONS = "BibTeXKeyCitations"; private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations"; @@ -93,15 +100,10 @@ public class OOBibStyle implements Comparable { private static final String ITALIC_CITATIONS = "ItalicCitations"; private static final String CITATION_CHARACTER_FORMAT = "CitationCharacterFormat"; private static final String FORMAT_CITATIONS = "FormatCitations"; - private static final String GROUPED_NUMBERS_SEPARATOR = "GroupedNumbersSeparator"; - private static final String PAGE_INFO_SEPARATOR = "PageInfoSeparator"; - private static final String CITATION_SEPARATOR = "CitationSeparator"; private static final String IN_TEXT_YEAR_SEPARATOR = "InTextYearSeparator"; private static final String MAX_AUTHORS = "MaxAuthors"; private static final String YEAR_FIELD = "YearField"; private static final String AUTHOR_FIELD = "AuthorField"; - private static final String BRACKET_AFTER = "BracketAfter"; - private static final String BRACKET_BEFORE = "BracketBefore"; private static final String IS_NUMBER_ENTRIES = "IsNumberEntries"; private static final String IS_SORT_BY_POSITION = "IsSortByPosition"; private static final String SORT_ALGORITHM = "SortAlgorithm"; @@ -109,7 +111,6 @@ public class OOBibStyle implements Comparable { private static final String YEAR_SEPARATOR = "YearSeparator"; private static final String AUTHOR_LAST_SEPARATOR_IN_TEXT = "AuthorLastSeparatorInText"; private static final String AUTHOR_LAST_SEPARATOR = "AuthorLastSeparator"; - private static final String AUTHOR_SEPARATOR = "AuthorSeparator"; private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); @@ -117,16 +118,17 @@ public class OOBibStyle implements Comparable { // Formatter to be run on fields before they are used as part of citation marker: private final LayoutFormatter fieldFormatter = new OOPreFormatter(); - // reference layout mapped from entry type: - // private final Map bibLayout = new HashMap<>(); - // private final Map properties = new HashMap<>(); - // private final Map citProperties = new HashMap<>(); private final boolean fromResource; private final String path; private final Charset encoding; - // used in OOBibStyleParser + private File styleFile; + private long styleFileModificationTime = Long.MIN_VALUE; + + /* + * Used or modified in OOBibStyleParser.readFormatFile() + */ protected String name = ""; protected String localCopy; protected final LayoutFormatterPreferences prefs; @@ -139,9 +141,6 @@ public class OOBibStyle implements Comparable { protected boolean valid; protected final SortedSet journals = new TreeSet<>(); - private File styleFile; - private long styleFileModificationTime = Long.MIN_VALUE; - /** * Construct from user-provided style file. */ @@ -170,10 +169,6 @@ public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) throws path = resourcePath; } - public Layout getDefaultBibLayout() { - return defaultBibLayout; - } - private void setDefaultProperties() { // Set default property values: properties.put(TITLE, "Bibliography"); @@ -187,7 +182,8 @@ private void setDefaultProperties() { // Set default properties for the citation marker: citProperties.put(AUTHOR_FIELD, - FieldFactory.serializeOrFields(StandardField.AUTHOR, StandardField.EDITOR)); + FieldFactory.serializeOrFields(StandardField.AUTHOR, + StandardField.EDITOR)); citProperties.put(YEAR_FIELD, StandardField.YEAR.getName()); citProperties.put(MAX_AUTHORS, 3); citProperties.put(MAX_AUTHORS_FIRST, -1); @@ -215,6 +211,10 @@ private void setDefaultProperties() { citProperties.put(OXFORD_COMMA, ""); } + public Layout getDefaultBibLayout() { + return defaultBibLayout; + } + public String getName() { return name; } @@ -231,6 +231,11 @@ public Set getJournals() { return Collections.unmodifiableSet(journals); } + /** + * Note: current values are not reset: there may remain data from + * earlier versions of the input. This may be confusing for the + * user (modified file until it works, but next time it fails again). + */ private void initialize(InputStream stream) throws IOException { Objects.requireNonNull(stream); @@ -239,7 +244,21 @@ private void initialize(InputStream stream) throws IOException { // The try-with-resources Statement // try (Reader reader = new InputStreamReader(stream, encoding)) { - readFormatFile(reader); + OOBibStyleParser.readFormatFile(reader, this); + } + } + + /** + * If this style was initialized from a file on disk, check whether the file + * is unmodified since initialization. + * + * @return true if the file has not been modified, false otherwise. + */ + private boolean isUpToDate() { + if (styleFile == null) { + return true; + } else { + return styleFile.lastModified() == this.styleFileModificationTime; } } @@ -270,27 +289,6 @@ private void reload() throws IOException { } } - /** - * If this style was initialized from a file on disk, check whether the file - * is unmodified since initialization. - * - * @return true if the file has not been modified, false otherwise. - */ - private boolean isUpToDate() { - if (styleFile == null) { - return true; - } else { - return styleFile.lastModified() == this.styleFileModificationTime; - } - } - - /** - * Parse a *.jstyle file from {@code in}. - */ - private void readFormatFile(Reader in) throws IOException { - OOBibStyleParser.readFormatFile(in, this); - } - /** * After initializing this style from a file, this method can be used to check * whether the file appeared to be a proper style file. @@ -301,9 +299,6 @@ public boolean isValid() { return valid; } - - // --- end of parser -------- - public Layout getReferenceFormat(EntryType type) { Layout l = bibLayout.get(type); if (l == null) { @@ -317,8 +312,8 @@ public Layout getReferenceFormat(EntryType type) { * Make sure that (1) we have exactly one entry for each * citation, (2) each entry is either null or is not empty when trimmed. */ - public List regularizePageInfosForCitations(List pageInfosForCitations, - int nCitations) { + public static List regularizePageInfosForCitations(List pageInfosForCitations, + int nCitations) { if (pageInfosForCitations == null) { List res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { @@ -347,39 +342,6 @@ public List regularizePageInfosForCitations(List pageInfosForCit } } - /* - * Helper class for sorting citation numbers while - * maintaining their correspondance to pageInfos. - */ - private static class NumberWithPageInfo { - int num; - String pageInfo; - NumberWithPageInfo(int num, String pageInfo) { - this.num = num; - this.pageInfo = pageInfo; - } - } - - /** - * Defines sort order for NumberWithPageInfo entries. - * - * null comes before non-null - */ - private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPageInfo b) { - int res = Integer.compare(a.num, b.num); - if (res == 0) { - if (a.pageInfo == null && b.pageInfo == null) { - res = 0; - } else if (a.pageInfo == null) { - res = -1; - } else if (b.pageInfo == null) { - res = +1; - } else { - res = a.pageInfo.compareTo(b.pageInfo); - } - } - return res; - } /** * See {@see getNumCitationMarkerCommon} for details. @@ -387,10 +349,10 @@ private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPag public String getNumCitationMarkerForInText(List numbers, int minGroupingCount, List pageInfosForCitations) { - return getNumCitationMarkerCommon(numbers, - minGroupingCount, - CitationMarkerPurpose.CITATION, - pageInfosForCitations); + return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForInText(this, + numbers, + minGroupingCount, + pageInfosForCitations); } /** @@ -407,327 +369,8 @@ public String getNumCitationMarkerForInText(List numbers, * "${number}" stands for the formatted number. */ public String getNumCitationMarkerForBibliography(int number) { - return getNumCitationMarkerCommon(Collections.singletonList(number), - 0, - CitationMarkerPurpose.BIBLIOGRAPHY, - null); - } - - private enum CitationMarkerPurpose { - /** Creating citation marker for in-text citation. */ - CITATION, - /** Creating citation marker for the bibliography. */ - BIBLIOGRAPHY - } - - /** - * Format a number-based citation marker for the given number or numbers. - * - * This is the common implementation behind - * getNumCitationMarkerForInText and - * getNumCitationMarkerForBibliography. The latter could be easily - * separated unless there is (or going to be) a need for handling - * multiple numbers or page info by getNumCitationMarkerForBibliography. - * - * @param numbers The citation numbers. - * - * A zero in the list means: could not look this up - * in the databases. Positive integers are the valid numbers. - * - * Duplicate citation numbers are allowed: - * - * - If their pageInfos are identical, only a - * single instance is emitted. - * - * - If their pageInfos differ, the number is emitted with each - * distinct pageInfo. - * - * For pageInfo null and "" (after - * pageInfo.trim()) are considered equal (and missing). - * - * @param minGroupingCount Zero and negative means never group - * - * @param purpose BIBLIOGRAPHY (was: inList==True) when creating for a bibliography entry, - * CITATION (was: inList=false) when creating in-text citation. - * - * If BIBLIOGRAPHY: Prefer BRACKET_BEFORE_IN_LIST over BRACKET_BEFORE, - * and BRACKET_AFTER_IN_LIST over BRACKET_AFTER. - * Ignore pageInfosForCitations. - * - * @param pageInfosForCitations Null for "none", or a list with a - * pageInfo for each citation. Any or all of these can be null as well. - * - * @return The text for the citation. - * - */ - private String getNumCitationMarkerCommon(List numbers, - int minGroupingCount, - CitationMarkerPurpose purpose, - List pageInfosForCitations) { - - final boolean joinIsDisabled = (minGroupingCount <= 0); - final int notFoundInDatabases = 0; - final int nCitations = numbers.size(); - - /* - * strictPurpose: if true, require (nCitations == 1) when (purpose == BIBLIOGRAPHY), - * otherwise allow multiple citation numbers and process the BIBLIOGRAPHY case - * as CITATION with no pageInfo. - */ - final boolean strictPurpose = true; - - String bracketBefore = getStringCitProperty(BRACKET_BEFORE); - String bracketAfter = getStringCitProperty(BRACKET_AFTER); - - /* - * purpose == BIBLIOGRAPHY means: we are formatting for the - * bibliography, (not for in-text citation). - */ - if (purpose == CitationMarkerPurpose.BIBLIOGRAPHY) { - // prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST - if (citProperties.containsKey(BRACKET_BEFORE_IN_LIST)) { - bracketBefore = getStringCitProperty(BRACKET_BEFORE_IN_LIST); - } - if (citProperties.containsKey(BRACKET_AFTER_IN_LIST)) { - bracketAfter = getStringCitProperty(BRACKET_AFTER_IN_LIST); - } - - if (strictPurpose) { - // If (purpose==BIBLIOGRAPHY), then - // we expect exactly one number here, and can handle quickly - if (nCitations != 1) { - throw new RuntimeException( - "getNumCitationMarker:" - + "nCitations != 1 for purpose==BIBLIOGRAPHY." - + String.format(" nCitations = %d", nCitations)); - } - // - StringBuilder sb = new StringBuilder(bracketBefore); - final int current = numbers.get(0); - if (current < 0) { - throw new RuntimeException("getNumCitationMarker: found negative value"); - } - sb.append(current != notFoundInDatabases - ? String.valueOf(current) - : OOBibStyle.UNDEFINED_CITATION_MARKER); - sb.append(bracketAfter); - return sb.toString(); - } - } - - /* - * From here: - * - formatting for in-text (not for bibliography) - * - need to care about pageInfosForCitations - * - * - In case {@code strictPurpose} above is set to false and allows us to - * get here, and {@code purpose==BIBLIOGRAPHY}, then we just fill - * pageInfos with null values. - */ - List pageInfos = - regularizePageInfosForCitations((purpose == CitationMarkerPurpose.BIBLIOGRAPHY - ? null - : pageInfosForCitations), - numbers.size()); - - // Sort the numbers, together with the corresponding pageInfo values - List nps = new ArrayList<>(); - for (int i = 0; i < nCitations; i++) { - nps.add(new NumberWithPageInfo(numbers.get(i), pageInfos.get(i))); - } - Collections.sort(nps, OOBibStyle::compareNumberWithPageInfo); - - // "[" - StringBuilder sb = new StringBuilder(bracketBefore); - - /* - * int emitBlock(List block) - * - * Given a block containing 1 or (two or more) - * NumberWithPageInfo entries collected as singletons or - * joinable into an "i-j" form, append to {@code sb} the - * formatted text. - * - * Assumes: - * - * - block is not empty - * - * - For a block with a single element the element may have - * pageInfo and its num part may be zero - * (notFoundInDatabases). - * - * - For a block with two or more elements - * - * - The elements do not have pageInfo and their num part is - * not zero. - * - * - The elements num parts are consecutive positive integers, - * without repetition. - * - * Note: this function is long enough to move into a separate method. - * On the other hand, its assumptions strongly tie it to - * the loop below that collects the block. - * - * @return The number of blocks emitted. Since currently - * throws if the block is empty, the returned value is - * always 1. - * - */ - ToIntFunction> emitBlock = (List block) -> { - // uses: sb, this, - - final int blockSize = block.size(); - if (blockSize == 0) { - throw new RuntimeException("We should not get here"); - // return 0; - } - - if (blockSize == 1) { - // Add single entry: - final int num = block.get(0).num; - sb.append(num == notFoundInDatabases - ? OOBibStyle.UNDEFINED_CITATION_MARKER - : String.valueOf(num)); - // Emit pageInfo - String pageInfo = block.get(0).pageInfo; - if (pageInfo != null) { - sb.append(getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo); - } - } else { - - /* - * Check assumptions - */ - - // block has at least 2 elements - if (blockSize < 2) { - throw new RuntimeException("impossible: (blockSize < 2)"); - } - // None of these elements has a pageInfo, - // because if it had, we would not join. - for (NumberWithPageInfo x : block) { - if (x.pageInfo != null) { - throw new RuntimeException("impossible: (x.pageInfo != null)"); - } - } - // None of these elements needs UNDEFINED_CITATION_MARKER, - // because if it did, we would not join. - for (NumberWithPageInfo x : block) { - if (x.num == notFoundInDatabases) { - throw new RuntimeException("impossible: (x.num == notFoundInDatabases)"); - } - } - // consecutive elements have consecutive numbers - for (int j = 1; j < blockSize; j++) { - if (block.get(j).num != (block.get(j - 1).num + 1)) { - throw new RuntimeException("impossible: consecutive elements" - + " without consecutive numbers"); - } - } - - /* - * Do the actual work - */ - if (blockSize >= minGroupingCount) { - int first = block.get(0).num; - int last = block.get(blockSize - 1).num; - if (((last + 1) - first) != blockSize) { - throw new RuntimeException("impossible:" - + " blockSize and length of num range differ"); - } - // Emit: "first-last" - sb.append(first); - sb.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); - sb.append(last); - } else { - // Emit: first,first+1,...,last - for (int j = 0; j < blockSize; j++) { - if (j > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); - } - sb.append(block.get(j).num); - } - } - } - return 1; - }; - - /* - * Original: - * [2,3,4] -> [2-4] - * [0,1,2] -> [??,1,2] - * [0,1,2,3] -> [??,1-3] - * - * Now we have to consider: duplicate numbers and pageInfos - * [1,1] -> [1] - * [1,1 "pp nn"] -> keep separate if pageInfo differs - * [1 "pp nn",1 "pp nn"] -> [1 "pp nn"] - */ - - int blocksEmitted = 0; - List currentBlock = new ArrayList<>(); - List nextBlock = new ArrayList<>(); - - for (int i = 0; i < nCitations; i++) { - - final NumberWithPageInfo current = nps.get(i); - if (current.num < 0) { - throw new RuntimeException("getNumCitationMarker: found negative value"); - } - - if (currentBlock.size() == 0) { - currentBlock.add(current); - } else { - NumberWithPageInfo prev = currentBlock.get(currentBlock.size() - 1); - if ((notFoundInDatabases == current.num) - || (notFoundInDatabases == prev.num)) { - nextBlock.add(current); // do not join if not found - } else if (joinIsDisabled) { - nextBlock.add(current); // join disabled - } else if (compareNumberWithPageInfo(current, prev) == 0) { - // Same as prev, just forget it. - } else if ((current.num == (prev.num + 1)) - && (prev.pageInfo == null) - && (current.pageInfo == null)) { - // Just two consecutive numbers without pageInfo: join - currentBlock.add(current); - } else { - // do not join - nextBlock.add(current); - } - } - - if (nextBlock.size() > 0) { - // emit current block - // We are emitting a block - if (blocksEmitted > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); - } - int emittedNow = emitBlock.applyAsInt(currentBlock); - if (emittedNow > 0) { - blocksEmitted += emittedNow; - currentBlock = nextBlock; - nextBlock = new ArrayList<>(); - } - } // blockSize != 0 - - } // for i - - if (nextBlock.size() != 0) { - throw new RuntimeException("impossible: (nextBlock.size() != 0) after loop"); - } - - if (currentBlock.size() > 0) { - // We are emitting a block - if (blocksEmitted > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); - } - emitBlock.applyAsInt(currentBlock); - } - - // Emit: "]" - sb.append(bracketAfter); - return sb.toString(); + return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, + number); } /** @@ -832,13 +475,18 @@ public String getCitationMarker(List entries, * @param from The first index to group (inclusive) * @param to The last index to group (inclusive) */ - private void group(List entries, String[] uniquefiers, int from, int to) { + private void group(List entries, + String[] uniquefiers, + int from, + int to) { + String separator = getStringCitProperty(UNIQUEFIER_SEPARATOR); + StringBuilder sb = new StringBuilder(uniquefiers[from]); for (int i = from + 1; i <= to; i++) { sb.append(separator); sb.append(uniquefiers[i]); - entries.set(i, null); + entries.set(i, null); // kill BibEntry? } uniquefiers[from] = sb.toString(); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java new file mode 100644 index 00000000000..3c428885622 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java @@ -0,0 +1,432 @@ +package org.jabref.logic.openoffice; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.function.ToIntFunction; +import java.util.regex.Pattern; + +import org.jabref.logic.layout.Layout; +import org.jabref.logic.layout.LayoutFormatter; +import org.jabref.logic.layout.LayoutFormatterPreferences; +import org.jabref.logic.layout.LayoutHelper; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.Author; +import org.jabref.model.entry.AuthorList; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; +import org.jabref.model.entry.field.FieldFactory; +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.strings.StringUtil; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class OOBibStyleGetNumCitationMarker { + /* + * Helper class for sorting citation numbers while + * maintaining their correspondance to pageInfos. + */ + private static class NumberWithPageInfo { + int num; + String pageInfo; + NumberWithPageInfo(int num, String pageInfo) { + this.num = num; + this.pageInfo = pageInfo; + } + } + + /** + * Defines sort order for NumberWithPageInfo entries. + * + * null comes before non-null + */ + private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPageInfo b) { + int res = Integer.compare(a.num, b.num); + if (res == 0) { + if (a.pageInfo == null && b.pageInfo == null) { + res = 0; + } else if (a.pageInfo == null) { + res = -1; + } else if (b.pageInfo == null) { + res = +1; + } else { + res = a.pageInfo.compareTo(b.pageInfo); + } + } + return res; + } + + private enum CitationMarkerPurpose { + /** Creating citation marker for in-text citation. */ + CITATION, + /** Creating citation marker for the bibliography. */ + BIBLIOGRAPHY + } + + /** + * See {@see getNumCitationMarkerCommon} for details. + */ + public static String getNumCitationMarkerForInText(OOBibStyle style, + List numbers, + int minGroupingCount, + List pageInfosForCitations) { + return getNumCitationMarkerCommon(style, + numbers, + minGroupingCount, + CitationMarkerPurpose.CITATION, + pageInfosForCitations); + } + + /** + * Create a numeric marker for use in the bibliography as label for the entry. + * + * To support for example numbers in superscript without brackets for the text, + * but "[1]" form for the bibliogaphy, the style can provide + * the optional "BracketBeforeInList" and "BracketAfterInList" strings + * to be used in the bibliography instead of "BracketBefore" and "BracketAfter" + * + * @return "[${number}]" where + * "[" stands for BRACKET_BEFORE_IN_LIST (with fallback BRACKET_BEFORE) + * "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER) + * "${number}" stands for the formatted number. + */ + public static String getNumCitationMarkerForBibliography(OOBibStyle style, + int number) { + return getNumCitationMarkerCommon(style, + Collections.singletonList(number), + 0, + CitationMarkerPurpose.BIBLIOGRAPHY, + null); + } + + /** + * Format a number-based citation marker for the given number or numbers. + * + * This is the common implementation behind + * getNumCitationMarkerForInText and + * getNumCitationMarkerForBibliography. The latter could be easily + * separated unless there is (or going to be) a need for handling + * multiple numbers or page info by getNumCitationMarkerForBibliography. + * + * @param numbers The citation numbers. + * + * A zero in the list means: could not look this up + * in the databases. Positive integers are the valid numbers. + * + * Duplicate citation numbers are allowed: + * + * - If their pageInfos are identical, only a + * single instance is emitted. + * + * - If their pageInfos differ, the number is emitted with each + * distinct pageInfo. + * + * For pageInfo null and "" (after + * pageInfo.trim()) are considered equal (and missing). + * + * @param minGroupingCount Zero and negative means never group + * + * @param purpose BIBLIOGRAPHY (was: inList==True) when creating for a bibliography entry, + * CITATION (was: inList=false) when creating in-text citation. + * + * If BIBLIOGRAPHY: Prefer BRACKET_BEFORE_IN_LIST over BRACKET_BEFORE, + * and BRACKET_AFTER_IN_LIST over BRACKET_AFTER. + * Ignore pageInfosForCitations. + * + * @param pageInfosForCitations Null for "none", or a list with a + * pageInfo for each citation. Any or all of these can be null as well. + * + * @return The text for the citation. + * + */ + private static String getNumCitationMarkerCommon(OOBibStyle style, + List numbers, + int minGroupingCount, + CitationMarkerPurpose purpose, + List pageInfosForCitations) { + + final boolean joinIsDisabled = (minGroupingCount <= 0); + final int notFoundInDatabases = 0; + final int nCitations = numbers.size(); + + /* + * strictPurpose: if true, require (nCitations == 1) when (purpose == BIBLIOGRAPHY), + * otherwise allow multiple citation numbers and process the BIBLIOGRAPHY case + * as CITATION with no pageInfo. + */ + final boolean strictPurpose = true; + + String bracketBefore = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE); + String bracketAfter = style.getStringCitProperty(OOBibStyle.BRACKET_AFTER); + + /* + * purpose == BIBLIOGRAPHY means: we are formatting for the + * bibliography, (not for in-text citation). + */ + if (purpose == CitationMarkerPurpose.BIBLIOGRAPHY) { + // prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST + if (style.citProperties.containsKey(OOBibStyle.BRACKET_BEFORE_IN_LIST)) { + bracketBefore = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE_IN_LIST); + } + if (style.citProperties.containsKey(OOBibStyle.BRACKET_AFTER_IN_LIST)) { + bracketAfter = style.getStringCitProperty(OOBibStyle.BRACKET_AFTER_IN_LIST); + } + + if (strictPurpose) { + // If (purpose==BIBLIOGRAPHY), then + // we expect exactly one number here, and can handle quickly + if (nCitations != 1) { + throw new RuntimeException( + "getNumCitationMarker:" + + "nCitations != 1 for purpose==BIBLIOGRAPHY." + + String.format(" nCitations = %d", nCitations)); + } + // + StringBuilder sb = new StringBuilder(bracketBefore); + final int current = numbers.get(0); + if (current < 0) { + throw new RuntimeException("getNumCitationMarker: found negative value"); + } + sb.append(current != notFoundInDatabases + ? String.valueOf(current) + : OOBibStyle.UNDEFINED_CITATION_MARKER); + sb.append(bracketAfter); + return sb.toString(); + } + } + + /* + * From here: + * - formatting for in-text (not for bibliography) + * - need to care about pageInfosForCitations + * + * - In case {@code strictPurpose} above is set to false and allows us to + * get here, and {@code purpose==BIBLIOGRAPHY}, then we just fill + * pageInfos with null values. + */ + List pageInfos = + OOBibStyle.regularizePageInfosForCitations((purpose == CitationMarkerPurpose.BIBLIOGRAPHY + ? null + : pageInfosForCitations), + numbers.size()); + + // Sort the numbers, together with the corresponding pageInfo values + List nps = new ArrayList<>(); + for (int i = 0; i < nCitations; i++) { + nps.add(new NumberWithPageInfo(numbers.get(i), pageInfos.get(i))); + } + Collections.sort(nps, OOBibStyleGetNumCitationMarker::compareNumberWithPageInfo); + + // "[" + StringBuilder sb = new StringBuilder(bracketBefore); + + /* + * int emitBlock(List block) + * + * Given a block containing 1 or (two or more) + * NumberWithPageInfo entries collected as singletons or + * joinable into an "i-j" form, append to {@code sb} the + * formatted text. + * + * Assumes: + * + * - block is not empty + * + * - For a block with a single element the element may have + * pageInfo and its num part may be zero + * (notFoundInDatabases). + * + * - For a block with two or more elements + * + * - The elements do not have pageInfo and their num part is + * not zero. + * + * - The elements num parts are consecutive positive integers, + * without repetition. + * + * Note: this function is long enough to move into a separate method. + * On the other hand, its assumptions strongly tie it to + * the loop below that collects the block. + * + * @return The number of blocks emitted. Since currently + * throws if the block is empty, the returned value is + * always 1. + * + */ + ToIntFunction> emitBlock = (List block) -> { + // uses: sb, this, + + final int blockSize = block.size(); + if (blockSize == 0) { + throw new RuntimeException("We should not get here"); + // return 0; + } + + if (blockSize == 1) { + // Add single entry: + final int num = block.get(0).num; + sb.append(num == notFoundInDatabases + ? OOBibStyle.UNDEFINED_CITATION_MARKER + : String.valueOf(num)); + // Emit pageInfo + String pageInfo = block.get(0).pageInfo; + if (pageInfo != null) { + sb.append(style.getStringCitProperty(OOBibStyle.PAGE_INFO_SEPARATOR) + pageInfo); + } + } else { + + /* + * Check assumptions + */ + + // block has at least 2 elements + if (blockSize < 2) { + throw new RuntimeException("impossible: (blockSize < 2)"); + } + // None of these elements has a pageInfo, + // because if it had, we would not join. + for (NumberWithPageInfo x : block) { + if (x.pageInfo != null) { + throw new RuntimeException("impossible: (x.pageInfo != null)"); + } + } + // None of these elements needs UNDEFINED_CITATION_MARKER, + // because if it did, we would not join. + for (NumberWithPageInfo x : block) { + if (x.num == notFoundInDatabases) { + throw new RuntimeException("impossible: (x.num == notFoundInDatabases)"); + } + } + // consecutive elements have consecutive numbers + for (int j = 1; j < blockSize; j++) { + if (block.get(j).num != (block.get(j - 1).num + 1)) { + throw new RuntimeException("impossible: consecutive elements" + + " without consecutive numbers"); + } + } + + /* + * Do the actual work + */ + if (blockSize >= minGroupingCount) { + int first = block.get(0).num; + int last = block.get(blockSize - 1).num; + if (((last + 1) - first) != blockSize) { + throw new RuntimeException("impossible:" + + " blockSize and length of num range differ"); + } + // Emit: "first-last" + sb.append(first); + sb.append(style.getStringCitProperty(OOBibStyle.GROUPED_NUMBERS_SEPARATOR)); + sb.append(last); + } else { + // Emit: first,first+1,...,last + for (int j = 0; j < blockSize; j++) { + if (j > 0) { + sb.append(style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR)); + } + sb.append(block.get(j).num); + } + } + } + return 1; + }; + + /* + * Original: + * [2,3,4] -> [2-4] + * [0,1,2] -> [??,1,2] + * [0,1,2,3] -> [??,1-3] + * + * Now we have to consider: duplicate numbers and pageInfos + * [1,1] -> [1] + * [1,1 "pp nn"] -> keep separate if pageInfo differs + * [1 "pp nn",1 "pp nn"] -> [1 "pp nn"] + */ + + int blocksEmitted = 0; + List currentBlock = new ArrayList<>(); + List nextBlock = new ArrayList<>(); + + for (int i = 0; i < nCitations; i++) { + + final NumberWithPageInfo current = nps.get(i); + if (current.num < 0) { + throw new RuntimeException("getNumCitationMarker: found negative value"); + } + + if (currentBlock.size() == 0) { + currentBlock.add(current); + } else { + NumberWithPageInfo prev = currentBlock.get(currentBlock.size() - 1); + if ((notFoundInDatabases == current.num) + || (notFoundInDatabases == prev.num)) { + nextBlock.add(current); // do not join if not found + } else if (joinIsDisabled) { + nextBlock.add(current); // join disabled + } else if (compareNumberWithPageInfo(current, prev) == 0) { + // Same as prev, just forget it. + } else if ((current.num == (prev.num + 1)) + && (prev.pageInfo == null) + && (current.pageInfo == null)) { + // Just two consecutive numbers without pageInfo: join + currentBlock.add(current); + } else { + // do not join + nextBlock.add(current); + } + } + + if (nextBlock.size() > 0) { + // emit current block + // We are emitting a block + if (blocksEmitted > 0) { + sb.append(style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR)); + } + int emittedNow = emitBlock.applyAsInt(currentBlock); + if (emittedNow > 0) { + blocksEmitted += emittedNow; + currentBlock = nextBlock; + nextBlock = new ArrayList<>(); + } + } // blockSize != 0 + + } // for i + + if (nextBlock.size() != 0) { + throw new RuntimeException("impossible: (nextBlock.size() != 0) after loop"); + } + + if (currentBlock.size() > 0) { + // We are emitting a block + if (blocksEmitted > 0) { + sb.append(style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR)); + } + emitBlock.applyAsInt(currentBlock); + } + + // Emit: "]" + sb.append(bracketAfter); + return sb.toString(); + } + +} From 1f7e277e0845d3fe2229336b91d01c967a27cd5d Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 21:18:36 +0200 Subject: [PATCH 0539/1068] made getCitationMarker static --- .../jabref/logic/openoffice/OOBibStyle.java | 172 +++++++++++------- 1 file changed, 103 insertions(+), 69 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 23f1d8888c9..59014c1d4de 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -399,6 +399,25 @@ public String getCitationMarker(List entries, int[] unlimAuthors, List pageInfosForCitations ) { + + OOBibStyle style = this; + return getCitationMarker(style, + entries, + database, + inParenthesis, + uniquefiers, + unlimAuthors, + pageInfosForCitations); + } + + public static String getCitationMarker(OOBibStyle style, + List entries, + Map database, + boolean inParenthesis, + String[] uniquefiers, + int[] unlimAuthors, + List pageInfosForCitations + ) { // Look for groups of uniquefied entries that should be combined in the output. // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). int piv = -1; @@ -411,7 +430,7 @@ public String getCitationMarker(List entries, // Check if we just passed a group of more than one entry with uniquefier: if ((piv > -1) && (i > (piv + 1))) { // Do the grouping: - group(entries, uniquefiers, piv, i - 1); + group(style, entries, uniquefiers, piv, i - 1); } piv = -1; @@ -419,22 +438,27 @@ public String getCitationMarker(List entries, BibEntry currentEntry = entries.get(i); if (piv == -1) { piv = i; - tmpMarker = getAuthorYearParenthesisMarker(Collections.singletonList(currentEntry), - database, - null, - unlimAuthors); + tmpMarker = + getAuthorYearParenthesisMarker(style, + Collections.singletonList(currentEntry), + database, + null, + unlimAuthors); } else { // See if this entry can go into a group with the previous one: String thisMarker = - getAuthorYearParenthesisMarker(Collections.singletonList(currentEntry), + getAuthorYearParenthesisMarker(style, + Collections.singletonList(currentEntry), database, null, unlimAuthors); - String authorField = getStringCitProperty(AUTHOR_FIELD); - int maxAuthors = getIntCitProperty(MAX_AUTHORS); - String author = getCitationMarkerField(currentEntry, database.get(currentEntry), - authorField); + String authorField = style.getStringCitProperty(AUTHOR_FIELD); + int maxAuthors = style.getIntCitProperty(MAX_AUTHORS); + String author = getCitationMarkerField(style, + currentEntry, + database.get(currentEntry), + authorField); AuthorList al = AuthorList.parse(author); int prevALim = unlimAuthors[i - 1]; // i always at least 1 here if (!thisMarker.equals(tmpMarker) @@ -444,7 +468,7 @@ public String getCitationMarker(List entries, // previous entry was part of a group: if ((piv > -1) && (i > (piv + 1))) { // Do the grouping: - group(entries, uniquefiers, piv, i - 1); + group(style, entries, uniquefiers, piv, i - 1); } tmpMarker = thisMarker; piv = i; @@ -456,31 +480,33 @@ public String getCitationMarker(List entries, // Finished with the loop. See if the last entries form a group: if (piv >= 0) { // Do the grouping: - group(entries, uniquefiers, piv, uniquefiers.length - 1); + group(style, entries, uniquefiers, piv, uniquefiers.length - 1); } } if (inParenthesis) { - return getAuthorYearParenthesisMarker(entries, database, uniquefiers, unlimAuthors); + return getAuthorYearParenthesisMarker(style, entries, database, uniquefiers, unlimAuthors); } else { - return getAuthorYearInTextMarker(entries, database, uniquefiers, unlimAuthors); + return getAuthorYearInTextMarker(style, entries, database, uniquefiers, unlimAuthors); } } /** - * Modify entry and uniquefier arrays to facilitate a grouped presentation of uniquefied entries. + * Modify entry and uniquefier arrays to facilitate a grouped + * presentation of uniquefied entries. * * @param entries The entry array. * @param uniquefiers The uniquefier array. * @param from The first index to group (inclusive) * @param to The last index to group (inclusive) */ - private void group(List entries, - String[] uniquefiers, - int from, - int to) { + private static void group(OOBibStyle style, + List entries, + String[] uniquefiers, + int from, + int to) { - String separator = getStringCitProperty(UNIQUEFIER_SEPARATOR); + String separator = style.getStringCitProperty(UNIQUEFIER_SEPARATOR); StringBuilder sb = new StringBuilder(uniquefiers[from]); for (int i = from + 1; i <= to; i++) { @@ -500,36 +526,37 @@ private void group(List entries, * Elements can be null if not needed. * @return The formatted citation. */ - private String getAuthorYearParenthesisMarker(List entries, - Map database, - String[] uniquifiers, - int[] unlimAuthors) { + private static String getAuthorYearParenthesisMarker(OOBibStyle style, + List entries, + Map database, + String[] uniquifiers, + int[] unlimAuthors) { // The bibtex field providing author names, e.g. "author" or // "editor". - String authorField = getStringCitProperty(AUTHOR_FIELD); + String authorField = style.getStringCitProperty(AUTHOR_FIELD); // The maximum number of authors to write out in full without // using etal. Set to -1 to always write out all authors. - int maxA = getIntCitProperty(MAX_AUTHORS); + int maxA = style.getIntCitProperty(MAX_AUTHORS); // The String to separate authors from year, e.g. "; ". - String yearSep = getStringCitProperty(YEAR_SEPARATOR); + String yearSep = style.getStringCitProperty(YEAR_SEPARATOR); // The opening parenthesis. - String startBrace = getStringCitProperty(BRACKET_BEFORE); + String startBrace = style.getStringCitProperty(BRACKET_BEFORE); // The closing parenthesis. - String endBrace = getStringCitProperty(BRACKET_AFTER); + String endBrace = style.getStringCitProperty(BRACKET_AFTER); // The String to separate citations from each other. - String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); + String citationSeparator = style.getStringCitProperty(CITATION_SEPARATOR); // The bibtex field providing the year, e.g. "year". - String yearField = getStringCitProperty(YEAR_FIELD); + String yearField = style.getStringCitProperty(YEAR_FIELD); // The String to add between the two last author names, e.g. " & ". - String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR); + String andString = style.getStringCitProperty(AUTHOR_LAST_SEPARATOR); StringBuilder sb = new StringBuilder(startBrace); for (int j = 0; j < entries.size(); j++) { @@ -548,10 +575,10 @@ private String getAuthorYearParenthesisMarker(List entries, int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[j]; int maxAuthors = unlimA > 0 ? unlimA : maxA; - String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); - String authorString = createAuthorList(author, maxAuthors, andString, yearSep); + String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); + String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); sb.append(authorString); - String year = getCitationMarkerField(currentEntry, currentDatabase, yearField); + String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); if (year != null) { sb.append(year); } @@ -571,38 +598,39 @@ private String getAuthorYearParenthesisMarker(List entries, * @param uniquefiers Optional parameters to separate similar citations. Can be null if not needed. * @return The formatted citation. */ - private String getAuthorYearInTextMarker(List entries, - Map database, - String[] uniquefiers, - int[] unlimAuthors) { + private static String getAuthorYearInTextMarker(OOBibStyle style, + List entries, + Map database, + String[] uniquefiers, + int[] unlimAuthors) { // The bibtex field providing author names, e.g. "author" or "editor". - String authorField = getStringCitProperty(AUTHOR_FIELD); + String authorField = style.getStringCitProperty(AUTHOR_FIELD); // The maximum number of authors to write out in full without using etal. Set to // -1 to always write out all authors. - int maxA = getIntCitProperty(MAX_AUTHORS); + int maxA = style.getIntCitProperty(MAX_AUTHORS); // The String to separate authors from year, e.g. "; ". - String yearSep = getStringCitProperty(IN_TEXT_YEAR_SEPARATOR); + String yearSep = style.getStringCitProperty(IN_TEXT_YEAR_SEPARATOR); // The opening parenthesis. - String startBrace = getStringCitProperty(BRACKET_BEFORE); + String startBrace = style.getStringCitProperty(BRACKET_BEFORE); // The closing parenthesis. - String endBrace = getStringCitProperty(BRACKET_AFTER); + String endBrace = style.getStringCitProperty(BRACKET_AFTER); // The String to separate citations from each other. - String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); + String citationSeparator = style.getStringCitProperty(CITATION_SEPARATOR); // The bibtex field providing the year, e.g. "year". - String yearField = getStringCitProperty(YEAR_FIELD); + String yearField = style.getStringCitProperty(YEAR_FIELD); // The String to add between the two last author names, e.g. " & ". - String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR_IN_TEXT); + String andString = style.getStringCitProperty(AUTHOR_LAST_SEPARATOR_IN_TEXT); if (andString == null) { // Use the default one if no explicit separator for text is defined - andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR); + andString = style.getStringCitProperty(AUTHOR_LAST_SEPARATOR); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < entries.size(); i++) { @@ -620,11 +648,11 @@ private String getAuthorYearInTextMarker(List entries, if (i > 0) { sb.append(citationSeparator); } - String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); - String authorString = createAuthorList(author, maxAuthors, andString, yearSep); + String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); + String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); sb.append(authorString); sb.append(startBrace); - String year = getCitationMarkerField(currentEntry, currentDatabase, yearField); + String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); if (year != null) { sb.append(year); } @@ -634,12 +662,12 @@ private String getAuthorYearInTextMarker(List entries, sb.append(endBrace); } return sb.toString(); - } /** - * This method looks up a field for an entry in a database. Any number of backup fields can be used - * if the primary field is empty. + * This method looks up a field for an entry in a database. Any + * number of backup fields can be used if the primary field is + * empty. * * @param entry The entry. * @param database The database the entry belongs to. @@ -649,19 +677,22 @@ private String getAuthorYearInTextMarker(List entries, * specify StandardField.orFields(StandardField.AUTHOR, StandardField.EDITOR). * @return The resolved field content, or an empty string if the field(s) were empty. */ - private String getCitationMarkerField(BibEntry entry, BibDatabase database, String fields) { + private static String getCitationMarkerField(OOBibStyle style, + BibEntry entry, + BibDatabase database, + String fields) { Objects.requireNonNull(entry, "Entry cannot be null"); Objects.requireNonNull(database, "database cannot be null"); - Set authorFields = FieldFactory.parseOrFields(getStringCitProperty(AUTHOR_FIELD)); + Set authorFields = FieldFactory.parseOrFields(style.getStringCitProperty(AUTHOR_FIELD)); for (Field field : FieldFactory.parseOrFields(fields)) { Optional content = entry.getResolvedFieldOrAlias(field, database); if ((content.isPresent()) && !content.get().trim().isEmpty()) { if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content.get())) { - return "{" + fieldFormatter.format(content.get()) + "}"; + return "{" + style.fieldFormatter.format(content.get()) + "}"; } - return fieldFormatter.format(content.get()); + return style.fieldFormatter.format(content.get()); } } // No luck? Return an empty string: @@ -675,7 +706,9 @@ private String getCitationMarkerField(BibEntry entry, BibDatabase database, Stri * @param number The number of the author to return. * @return The author name, or an empty String if inapplicable. */ - private String getAuthorLastName(AuthorList al, int number) { + private static String getAuthorLastName(OOBibStyle style, + AuthorList al, + int number) { StringBuilder sb = new StringBuilder(); if (al.getNumberOfAuthors() > number) { @@ -835,23 +868,24 @@ public int hashCode() { * full without using etal. Set to -1 to always write out * all authors. */ - private String createAuthorList(String author, - int maxAuthors, - String andString, - String yearSep) { + private static String createAuthorList(OOBibStyle style, + String author, + int maxAuthors, + String andString, + String yearSep) { Objects.requireNonNull(author); // The String to represent authors that are not mentioned, // e.g. " et al." - String etAlString = getStringCitProperty(ET_AL_STRING); + String etAlString = style.getStringCitProperty(ET_AL_STRING); // The String to add between author names except the last two, // e.g. ", ". - String authorSep = getStringCitProperty(AUTHOR_SEPARATOR); + String authorSep = style.getStringCitProperty(AUTHOR_SEPARATOR); // The String to put after the second to last author in case // of three or more authors - String oxfordComma = getStringCitProperty(OXFORD_COMMA); + String oxfordComma = style.getStringCitProperty(OXFORD_COMMA); StringBuilder sb = new StringBuilder(); AuthorList al = AuthorList.parse(author); @@ -859,7 +893,7 @@ private String createAuthorList(String author, if (nAuthors > 0) { // The first author - sb.append(getAuthorLastName(al, 0)); + sb.append(getAuthorLastName(style, al, 0)); } boolean emitAllAuthors = ((nAuthors <= maxAuthors) || (maxAuthors < 0)); @@ -868,7 +902,7 @@ private String createAuthorList(String author, int j = 1; while (j < (nAuthors - 1)) { sb.append(authorSep); - sb.append(getAuthorLastName(al, j)); + sb.append(getAuthorLastName(style, al, j)); j++; } // oxfordComma if at least 3 authors @@ -877,7 +911,7 @@ private String createAuthorList(String author, } // Emit "and LastAuthor" sb.append(andString); - sb.append(getAuthorLastName(al, nAuthors - 1)); + sb.append(getAuthorLastName(style, al, nAuthors - 1)); } else if (nAuthors > maxAuthors && nAuthors > 1) { // maxAuthors nAuthors result From 73dd5403c7aedc26be362c34c89970df23c45a7a Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 21:37:18 +0200 Subject: [PATCH 0540/1068] refactor: OOBibStyleGetCitationMarker.java --- .../jabref/logic/openoffice/OOBibStyle.java | 410 +---------------- .../OOBibStyleGetCitationMarker.java | 418 ++++++++++++++++++ 2 files changed, 439 insertions(+), 389 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 59014c1d4de..80d2967bbeb 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -92,7 +92,19 @@ public class OOBibStyle implements Comparable { protected static final String PAGE_INFO_SEPARATOR = "PageInfoSeparator"; protected static final String CITATION_SEPARATOR = "CitationSeparator"; - private static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; + // These are used in OOBibStyleGetCitationMarker + protected static final String AUTHOR_FIELD = "AuthorField"; + protected static final String MAX_AUTHORS = "MaxAuthors"; + protected static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; + protected static final String YEAR_SEPARATOR = "YearSeparator"; + protected static final String AUTHOR_LAST_SEPARATOR = "AuthorLastSeparator"; + protected static final String IN_TEXT_YEAR_SEPARATOR = "InTextYearSeparator"; + protected static final String YEAR_FIELD = "YearField"; + protected static final String AUTHOR_LAST_SEPARATOR_IN_TEXT = "AuthorLastSeparatorInText"; + protected static final String OXFORD_COMMA = "OxfordComma"; + protected static final String AUTHOR_SEPARATOR = "AuthorSeparator"; + + private static final String CITATION_KEY_CITATIONS = "BibTeXKeyCitations"; private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations"; private static final String SUPERSCRIPT_CITATIONS = "SuperscriptCitations"; @@ -100,23 +112,14 @@ public class OOBibStyle implements Comparable { private static final String ITALIC_CITATIONS = "ItalicCitations"; private static final String CITATION_CHARACTER_FORMAT = "CitationCharacterFormat"; private static final String FORMAT_CITATIONS = "FormatCitations"; - private static final String IN_TEXT_YEAR_SEPARATOR = "InTextYearSeparator"; - private static final String MAX_AUTHORS = "MaxAuthors"; - private static final String YEAR_FIELD = "YearField"; - private static final String AUTHOR_FIELD = "AuthorField"; private static final String IS_NUMBER_ENTRIES = "IsNumberEntries"; private static final String IS_SORT_BY_POSITION = "IsSortByPosition"; private static final String SORT_ALGORITHM = "SortAlgorithm"; - private static final String OXFORD_COMMA = "OxfordComma"; - private static final String YEAR_SEPARATOR = "YearSeparator"; - private static final String AUTHOR_LAST_SEPARATOR_IN_TEXT = "AuthorLastSeparatorInText"; - private static final String AUTHOR_LAST_SEPARATOR = "AuthorLastSeparator"; - private static final String AUTHOR_SEPARATOR = "AuthorSeparator"; private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); // Formatter to be run on fields before they are used as part of citation marker: - private final LayoutFormatter fieldFormatter = new OOPreFormatter(); + protected final LayoutFormatter fieldFormatter = new OOPreFormatter(); private final boolean fromResource; @@ -401,324 +404,15 @@ public String getCitationMarker(List entries, ) { OOBibStyle style = this; - return getCitationMarker(style, - entries, - database, - inParenthesis, - uniquefiers, - unlimAuthors, - pageInfosForCitations); - } - - public static String getCitationMarker(OOBibStyle style, - List entries, - Map database, - boolean inParenthesis, - String[] uniquefiers, - int[] unlimAuthors, - List pageInfosForCitations - ) { - // Look for groups of uniquefied entries that should be combined in the output. - // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). - int piv = -1; - String tmpMarker = null; - if (uniquefiers != null) { - for (int i = 0; i < uniquefiers.length; i++) { - - if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { - // This entry has no uniquefier. - // Check if we just passed a group of more than one entry with uniquefier: - if ((piv > -1) && (i > (piv + 1))) { - // Do the grouping: - group(style, entries, uniquefiers, piv, i - 1); - } - - piv = -1; - } else { - BibEntry currentEntry = entries.get(i); - if (piv == -1) { - piv = i; - tmpMarker = - getAuthorYearParenthesisMarker(style, - Collections.singletonList(currentEntry), - database, - null, - unlimAuthors); - } else { - // See if this entry can go into a group with the previous one: - String thisMarker = - getAuthorYearParenthesisMarker(style, - Collections.singletonList(currentEntry), - database, - null, - unlimAuthors); - - String authorField = style.getStringCitProperty(AUTHOR_FIELD); - int maxAuthors = style.getIntCitProperty(MAX_AUTHORS); - String author = getCitationMarkerField(style, - currentEntry, - database.get(currentEntry), - authorField); - AuthorList al = AuthorList.parse(author); - int prevALim = unlimAuthors[i - 1]; // i always at least 1 here - if (!thisMarker.equals(tmpMarker) - || ((al.getNumberOfAuthors() > maxAuthors) - && (unlimAuthors[i] != prevALim))) { - // No match. Update piv to exclude the previous entry. But first check if the - // previous entry was part of a group: - if ((piv > -1) && (i > (piv + 1))) { - // Do the grouping: - group(style, entries, uniquefiers, piv, i - 1); - } - tmpMarker = thisMarker; - piv = i; - } - } - } - - } - // Finished with the loop. See if the last entries form a group: - if (piv >= 0) { - // Do the grouping: - group(style, entries, uniquefiers, piv, uniquefiers.length - 1); - } - } - - if (inParenthesis) { - return getAuthorYearParenthesisMarker(style, entries, database, uniquefiers, unlimAuthors); - } else { - return getAuthorYearInTextMarker(style, entries, database, uniquefiers, unlimAuthors); - } - } - - /** - * Modify entry and uniquefier arrays to facilitate a grouped - * presentation of uniquefied entries. - * - * @param entries The entry array. - * @param uniquefiers The uniquefier array. - * @param from The first index to group (inclusive) - * @param to The last index to group (inclusive) - */ - private static void group(OOBibStyle style, - List entries, - String[] uniquefiers, - int from, - int to) { - - String separator = style.getStringCitProperty(UNIQUEFIER_SEPARATOR); - - StringBuilder sb = new StringBuilder(uniquefiers[from]); - for (int i = from + 1; i <= to; i++) { - sb.append(separator); - sb.append(uniquefiers[i]); - entries.set(i, null); // kill BibEntry? - } - uniquefiers[from] = sb.toString(); - } - - /** - * This method produces (Author, year) style citation strings in many different forms. - * - * @param entries The list of BibEntry to get fields from. - * @param database A map of BibEntry-BibDatabase pairs. - * @param uniquifiers Optional parameter to separate similar citations. - * Elements can be null if not needed. - * @return The formatted citation. - */ - private static String getAuthorYearParenthesisMarker(OOBibStyle style, - List entries, - Map database, - String[] uniquifiers, - int[] unlimAuthors) { - - // The bibtex field providing author names, e.g. "author" or - // "editor". - String authorField = style.getStringCitProperty(AUTHOR_FIELD); - - // The maximum number of authors to write out in full without - // using etal. Set to -1 to always write out all authors. - int maxA = style.getIntCitProperty(MAX_AUTHORS); - - // The String to separate authors from year, e.g. "; ". - String yearSep = style.getStringCitProperty(YEAR_SEPARATOR); - - // The opening parenthesis. - String startBrace = style.getStringCitProperty(BRACKET_BEFORE); - - // The closing parenthesis. - String endBrace = style.getStringCitProperty(BRACKET_AFTER); - - // The String to separate citations from each other. - String citationSeparator = style.getStringCitProperty(CITATION_SEPARATOR); - - // The bibtex field providing the year, e.g. "year". - String yearField = style.getStringCitProperty(YEAR_FIELD); - - // The String to add between the two last author names, e.g. " & ". - String andString = style.getStringCitProperty(AUTHOR_LAST_SEPARATOR); - - StringBuilder sb = new StringBuilder(startBrace); - for (int j = 0; j < entries.size(); j++) { - BibEntry currentEntry = entries.get(j); - - // Check if this entry has been nulled due to grouping with the previous entry(ies): - if (currentEntry == null) { - continue; - } - - if (j > 0) { - sb.append(citationSeparator); - } - - BibDatabase currentDatabase = database.get(currentEntry); - int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[j]; - int maxAuthors = unlimA > 0 ? unlimA : maxA; - - String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); - String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); - sb.append(authorString); - String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); - if (year != null) { - sb.append(year); - } - if ((uniquifiers != null) && (uniquifiers[j] != null)) { - sb.append(uniquifiers[j]); - } - } - sb.append(endBrace); - return sb.toString(); - } - - /** - * This method produces "Author (year)" style citation strings in many different forms. - * - * @param entries The list of BibEntry to get fields from. - * @param database A map of BibEntry-BibDatabase pairs. - * @param uniquefiers Optional parameters to separate similar citations. Can be null if not needed. - * @return The formatted citation. - */ - private static String getAuthorYearInTextMarker(OOBibStyle style, - List entries, - Map database, - String[] uniquefiers, - int[] unlimAuthors) { - // The bibtex field providing author names, e.g. "author" or "editor". - String authorField = style.getStringCitProperty(AUTHOR_FIELD); - - // The maximum number of authors to write out in full without using etal. Set to - // -1 to always write out all authors. - int maxA = style.getIntCitProperty(MAX_AUTHORS); - - // The String to separate authors from year, e.g. "; ". - String yearSep = style.getStringCitProperty(IN_TEXT_YEAR_SEPARATOR); - - // The opening parenthesis. - String startBrace = style.getStringCitProperty(BRACKET_BEFORE); - - // The closing parenthesis. - String endBrace = style.getStringCitProperty(BRACKET_AFTER); - - // The String to separate citations from each other. - String citationSeparator = style.getStringCitProperty(CITATION_SEPARATOR); - - // The bibtex field providing the year, e.g. "year". - String yearField = style.getStringCitProperty(YEAR_FIELD); - - // The String to add between the two last author names, e.g. " & ". - String andString = style.getStringCitProperty(AUTHOR_LAST_SEPARATOR_IN_TEXT); - - if (andString == null) { - // Use the default one if no explicit separator for text is defined - andString = style.getStringCitProperty(AUTHOR_LAST_SEPARATOR); - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < entries.size(); i++) { - BibEntry currentEntry = entries.get(i); - - // Check if this entry has been nulled due to grouping with the previous entry(ies): - if (currentEntry == null) { - continue; - } - - BibDatabase currentDatabase = database.get(currentEntry); - int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[i]; - int maxAuthors = unlimA > 0 ? unlimA : maxA; - - if (i > 0) { - sb.append(citationSeparator); - } - String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); - String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); - sb.append(authorString); - sb.append(startBrace); - String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); - if (year != null) { - sb.append(year); - } - if ((uniquefiers != null) && (uniquefiers[i] != null)) { - sb.append(uniquefiers[i]); - } - sb.append(endBrace); - } - return sb.toString(); - } - - /** - * This method looks up a field for an entry in a database. Any - * number of backup fields can be used if the primary field is - * empty. - * - * @param entry The entry. - * @param database The database the entry belongs to. - * @param fields The field, or succession of fields, to look up. - * If backup fields are needed, separate - * field names by /. E.g. to use "author" with "editor" as backup, - * specify StandardField.orFields(StandardField.AUTHOR, StandardField.EDITOR). - * @return The resolved field content, or an empty string if the field(s) were empty. - */ - private static String getCitationMarkerField(OOBibStyle style, - BibEntry entry, - BibDatabase database, - String fields) { - Objects.requireNonNull(entry, "Entry cannot be null"); - Objects.requireNonNull(database, "database cannot be null"); - - Set authorFields = FieldFactory.parseOrFields(style.getStringCitProperty(AUTHOR_FIELD)); - for (Field field : FieldFactory.parseOrFields(fields)) { - Optional content = entry.getResolvedFieldOrAlias(field, database); - - if ((content.isPresent()) && !content.get().trim().isEmpty()) { - if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content.get())) { - return "{" + style.fieldFormatter.format(content.get()) + "}"; - } - return style.fieldFormatter.format(content.get()); - } - } - // No luck? Return an empty string: - return ""; + return OOBibStyleGetCitationMarker.getCitationMarker(style, + entries, + database, + inParenthesis, + uniquefiers, + unlimAuthors, + pageInfosForCitations); } - /** - * Look up the nth author and return the proper last name for citation markers. - * - * @param al The author list. - * @param number The number of the author to return. - * @return The author name, or an empty String if inapplicable. - */ - private static String getAuthorLastName(OOBibStyle style, - AuthorList al, - int number) { - StringBuilder sb = new StringBuilder(); - - if (al.getNumberOfAuthors() > number) { - Author a = al.getAuthor(number); - a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> sb.append(von).append(' ')); - sb.append(a.getLast().orElse("")); - } - - return sb.toString(); - } /** * Take a finished citation and insert a string at the end (but @@ -862,66 +556,4 @@ public boolean equals(Object o) { public int hashCode() { return Objects.hash(path, name, citProperties, properties); } - - /** - * @param maxAuthors The maximum number of authors to write out in - * full without using etal. Set to -1 to always write out - * all authors. - */ - private static String createAuthorList(OOBibStyle style, - String author, - int maxAuthors, - String andString, - String yearSep) { - Objects.requireNonNull(author); - - // The String to represent authors that are not mentioned, - // e.g. " et al." - String etAlString = style.getStringCitProperty(ET_AL_STRING); - - // The String to add between author names except the last two, - // e.g. ", ". - String authorSep = style.getStringCitProperty(AUTHOR_SEPARATOR); - - // The String to put after the second to last author in case - // of three or more authors - String oxfordComma = style.getStringCitProperty(OXFORD_COMMA); - - StringBuilder sb = new StringBuilder(); - AuthorList al = AuthorList.parse(author); - final int nAuthors = al.getNumberOfAuthors(); - - if (nAuthors > 0) { - // The first author - sb.append(getAuthorLastName(style, al, 0)); - } - - boolean emitAllAuthors = ((nAuthors <= maxAuthors) || (maxAuthors < 0)); - if ((nAuthors >= 2) && emitAllAuthors) { - // Emit last names, except for the last author - int j = 1; - while (j < (nAuthors - 1)) { - sb.append(authorSep); - sb.append(getAuthorLastName(style, al, j)); - j++; - } - // oxfordComma if at least 3 authors - if (nAuthors >= 3) { - sb.append(oxfordComma); - } - // Emit "and LastAuthor" - sb.append(andString); - sb.append(getAuthorLastName(style, al, nAuthors - 1)); - - } else if (nAuthors > maxAuthors && nAuthors > 1) { - // maxAuthors nAuthors result - // 0 1 "Smith" - // -1 1 "Smith" - // -1 0 "" - sb.append(etAlString); - } - sb.append(yearSep); - return sb.toString(); - } - } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java new file mode 100644 index 00000000000..f0cf61e8d66 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -0,0 +1,418 @@ +package org.jabref.logic.openoffice; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.function.ToIntFunction; +import java.util.regex.Pattern; + +import org.jabref.logic.layout.Layout; +import org.jabref.logic.layout.LayoutFormatter; +import org.jabref.logic.layout.LayoutFormatterPreferences; +import org.jabref.logic.layout.LayoutHelper; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.Author; +import org.jabref.model.entry.AuthorList; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; +import org.jabref.model.entry.field.FieldFactory; +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.strings.StringUtil; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class OOBibStyleGetCitationMarker { + + + + public static String getCitationMarker(OOBibStyle style, + List entries, + Map database, + boolean inParenthesis, + String[] uniquefiers, + int[] unlimAuthors, + List pageInfosForCitations + ) { + // Look for groups of uniquefied entries that should be combined in the output. + // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). + int piv = -1; + String tmpMarker = null; + if (uniquefiers != null) { + for (int i = 0; i < uniquefiers.length; i++) { + + if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { + // This entry has no uniquefier. + // Check if we just passed a group of more than one entry with uniquefier: + if ((piv > -1) && (i > (piv + 1))) { + // Do the grouping: + group(style, entries, uniquefiers, piv, i - 1); + } + + piv = -1; + } else { + BibEntry currentEntry = entries.get(i); + if (piv == -1) { + piv = i; + tmpMarker = + getAuthorYearParenthesisMarker(style, + Collections.singletonList(currentEntry), + database, + null, + unlimAuthors); + } else { + // See if this entry can go into a group with the previous one: + String thisMarker = + getAuthorYearParenthesisMarker(style, + Collections.singletonList(currentEntry), + database, + null, + unlimAuthors); + + String authorField = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); + int maxAuthors = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); + String author = getCitationMarkerField(style, + currentEntry, + database.get(currentEntry), + authorField); + AuthorList al = AuthorList.parse(author); + int prevALim = unlimAuthors[i - 1]; // i always at least 1 here + if (!thisMarker.equals(tmpMarker) + || ((al.getNumberOfAuthors() > maxAuthors) + && (unlimAuthors[i] != prevALim))) { + // No match. Update piv to exclude the previous entry. But first check if the + // previous entry was part of a group: + if ((piv > -1) && (i > (piv + 1))) { + // Do the grouping: + group(style, entries, uniquefiers, piv, i - 1); + } + tmpMarker = thisMarker; + piv = i; + } + } + } + + } + // Finished with the loop. See if the last entries form a group: + if (piv >= 0) { + // Do the grouping: + group(style, entries, uniquefiers, piv, uniquefiers.length - 1); + } + } + + if (inParenthesis) { + return getAuthorYearParenthesisMarker(style, entries, database, uniquefiers, unlimAuthors); + } else { + return getAuthorYearInTextMarker(style, entries, database, uniquefiers, unlimAuthors); + } + } + + /** + * Modify entry and uniquefier arrays to facilitate a grouped + * presentation of uniquefied entries. + * + * @param entries The entry array. + * @param uniquefiers The uniquefier array. + * @param from The first index to group (inclusive) + * @param to The last index to group (inclusive) + */ + private static void group(OOBibStyle style, + List entries, + String[] uniquefiers, + int from, + int to) { + + String separator = style.getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); + + StringBuilder sb = new StringBuilder(uniquefiers[from]); + for (int i = from + 1; i <= to; i++) { + sb.append(separator); + sb.append(uniquefiers[i]); + entries.set(i, null); // kill BibEntry? + } + uniquefiers[from] = sb.toString(); + } + + /** + * This method produces (Author, year) style citation strings in many different forms. + * + * @param entries The list of BibEntry to get fields from. + * @param database A map of BibEntry-BibDatabase pairs. + * @param uniquifiers Optional parameter to separate similar citations. + * Elements can be null if not needed. + * @return The formatted citation. + */ + private static String getAuthorYearParenthesisMarker(OOBibStyle style, + List entries, + Map database, + String[] uniquifiers, + int[] unlimAuthors) { + + // The bibtex field providing author names, e.g. "author" or + // "editor". + String authorField = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); + + // The maximum number of authors to write out in full without + // using etal. Set to -1 to always write out all authors. + int maxA = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); + + // The String to separate authors from year, e.g. "; ". + String yearSep = style.getStringCitProperty(OOBibStyle.YEAR_SEPARATOR); + + // The opening parenthesis. + String startBrace = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE); + + // The closing parenthesis. + String endBrace = style.getStringCitProperty(OOBibStyle.BRACKET_AFTER); + + // The String to separate citations from each other. + String citationSeparator = style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR); + + // The bibtex field providing the year, e.g. "year". + String yearField = style.getStringCitProperty(OOBibStyle.YEAR_FIELD); + + // The String to add between the two last author names, e.g. " & ". + String andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); + + StringBuilder sb = new StringBuilder(startBrace); + for (int j = 0; j < entries.size(); j++) { + BibEntry currentEntry = entries.get(j); + + // Check if this entry has been nulled due to grouping with the previous entry(ies): + if (currentEntry == null) { + continue; + } + + if (j > 0) { + sb.append(citationSeparator); + } + + BibDatabase currentDatabase = database.get(currentEntry); + int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[j]; + int maxAuthors = unlimA > 0 ? unlimA : maxA; + + String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); + String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); + sb.append(authorString); + String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); + if (year != null) { + sb.append(year); + } + if ((uniquifiers != null) && (uniquifiers[j] != null)) { + sb.append(uniquifiers[j]); + } + } + sb.append(endBrace); + return sb.toString(); + } + + /** + * This method produces "Author (year)" style citation strings in many different forms. + * + * @param entries The list of BibEntry to get fields from. + * @param database A map of BibEntry-BibDatabase pairs. + * @param uniquefiers Optional parameters to separate similar citations. Can be null if not needed. + * @return The formatted citation. + */ + private static String getAuthorYearInTextMarker(OOBibStyle style, + List entries, + Map database, + String[] uniquefiers, + int[] unlimAuthors) { + // The bibtex field providing author names, e.g. "author" or "editor". + String authorField = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); + + // The maximum number of authors to write out in full without using etal. Set to + // -1 to always write out all authors. + int maxA = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); + + // The String to separate authors from year, e.g. "; ". + String yearSep = style.getStringCitProperty(OOBibStyle.IN_TEXT_YEAR_SEPARATOR); + + // The opening parenthesis. + String startBrace = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE); + + // The closing parenthesis. + String endBrace = style.getStringCitProperty(OOBibStyle.BRACKET_AFTER); + + // The String to separate citations from each other. + String citationSeparator = style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR); + + // The bibtex field providing the year, e.g. "year". + String yearField = style.getStringCitProperty(OOBibStyle.YEAR_FIELD); + + // The String to add between the two last author names, e.g. " & ". + String andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT); + + if (andString == null) { + // Use the default one if no explicit separator for text is defined + andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < entries.size(); i++) { + BibEntry currentEntry = entries.get(i); + + // Check if this entry has been nulled due to grouping with the previous entry(ies): + if (currentEntry == null) { + continue; + } + + BibDatabase currentDatabase = database.get(currentEntry); + int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[i]; + int maxAuthors = unlimA > 0 ? unlimA : maxA; + + if (i > 0) { + sb.append(citationSeparator); + } + String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); + String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); + sb.append(authorString); + sb.append(startBrace); + String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); + if (year != null) { + sb.append(year); + } + if ((uniquefiers != null) && (uniquefiers[i] != null)) { + sb.append(uniquefiers[i]); + } + sb.append(endBrace); + } + return sb.toString(); + } + + /** + * This method looks up a field for an entry in a database. Any + * number of backup fields can be used if the primary field is + * empty. + * + * @param entry The entry. + * @param database The database the entry belongs to. + * @param fields The field, or succession of fields, to look up. + * If backup fields are needed, separate + * field names by /. E.g. to use "author" with "editor" as backup, + * specify StandardField.orFields(StandardField.AUTHOR, StandardField.EDITOR). + * @return The resolved field content, or an empty string if the field(s) were empty. + */ + private static String getCitationMarkerField(OOBibStyle style, + BibEntry entry, + BibDatabase database, + String fields) { + Objects.requireNonNull(entry, "Entry cannot be null"); + Objects.requireNonNull(database, "database cannot be null"); + + Set authorFields = + FieldFactory.parseOrFields(style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD)); + for (Field field : FieldFactory.parseOrFields(fields)) { + Optional content = entry.getResolvedFieldOrAlias(field, database); + + if ((content.isPresent()) && !content.get().trim().isEmpty()) { + if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content.get())) { + return "{" + style.fieldFormatter.format(content.get()) + "}"; + } + return style.fieldFormatter.format(content.get()); + } + } + // No luck? Return an empty string: + return ""; + } + + /** + * Look up the nth author and return the proper last name for citation markers. + * + * @param al The author list. + * @param number The number of the author to return. + * @return The author name, or an empty String if inapplicable. + */ + private static String getAuthorLastName(OOBibStyle style, + AuthorList al, + int number) { + StringBuilder sb = new StringBuilder(); + + if (al.getNumberOfAuthors() > number) { + Author a = al.getAuthor(number); + a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> sb.append(von).append(' ')); + sb.append(a.getLast().orElse("")); + } + + return sb.toString(); + } + /** + * @param maxAuthors The maximum number of authors to write out in + * full without using etal. Set to -1 to always write out + * all authors. + */ + private static String createAuthorList(OOBibStyle style, + String author, + int maxAuthors, + String andString, + String yearSep) { + Objects.requireNonNull(author); + + // The String to represent authors that are not mentioned, + // e.g. " et al." + String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); + + // The String to add between author names except the last two, + // e.g. ", ". + String authorSep = style.getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR); + + // The String to put after the second to last author in case + // of three or more authors + String oxfordComma = style.getStringCitProperty(OOBibStyle.OXFORD_COMMA); + + StringBuilder sb = new StringBuilder(); + AuthorList al = AuthorList.parse(author); + final int nAuthors = al.getNumberOfAuthors(); + + if (nAuthors > 0) { + // The first author + sb.append(getAuthorLastName(style, al, 0)); + } + + boolean emitAllAuthors = ((nAuthors <= maxAuthors) || (maxAuthors < 0)); + if ((nAuthors >= 2) && emitAllAuthors) { + // Emit last names, except for the last author + int j = 1; + while (j < (nAuthors - 1)) { + sb.append(authorSep); + sb.append(getAuthorLastName(style, al, j)); + j++; + } + // oxfordComma if at least 3 authors + if (nAuthors >= 3) { + sb.append(oxfordComma); + } + // Emit "and LastAuthor" + sb.append(andString); + sb.append(getAuthorLastName(style, al, nAuthors - 1)); + + } else if (nAuthors > maxAuthors && nAuthors > 1) { + // maxAuthors nAuthors result + // 0 1 "Smith" + // -1 1 "Smith" + // -1 0 "" + sb.append(etAlString); + } + sb.append(yearSep); + return sb.toString(); + } + +} From 9f80d6bcccfaf7472977c11cb5c97a1e2f1274d6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 23:03:25 +0200 Subject: [PATCH 0541/1068] add: regularizePageInfo, comparePageInfoc --- .../jabref/logic/openoffice/OOBibStyle.java | 42 +++++++-- .../OOBibStyleGetCitationMarker.java | 94 +++++++++++++------ .../OOBibStyleGetNumCitationMarker.java | 10 +- 3 files changed, 101 insertions(+), 45 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 80d2967bbeb..295f983bea1 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -311,6 +311,18 @@ public Layout getReferenceFormat(EntryType type) { } } + public static String regularizePageInfo( String p ) { + if (p == null) { + return null; + } + String pt = p.trim(); + if (pt.equals("")) { + return null; + } else { + return pt; + } + } + /** * Make sure that (1) we have exactly one entry for each * citation, (2) each entry is either null or is not empty when trimmed. @@ -331,21 +343,33 @@ public static List regularizePageInfosForCitations(List pageInfo List res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { String p = pageInfosForCitations.get(i); - if (p != null) { - String pt = p.trim(); - if (pt.equals("")) { - p = null; - } else { - p = pt; - } - } - res.add(p); + res.add(regularizePageInfo(p)); } return res; } } + /** + * Defines sort order for pageInfo strings. + * + * null comes before non-null + */ + public static int comparePageInfo(String a, String b) { + String aa = regularizePageInfo(a); + String bb = regularizePageInfo(b); + if (aa == null && bb == null) { + return 0; + } + if (aa == null) { + return -1; + } + if (bb == null) { + return +1; + } + return aa.compareTo(bb); + } + /** * See {@see getNumCitationMarkerCommon} for details. */ diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index f0cf61e8d66..f7c7ed72218 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -42,8 +42,51 @@ class OOBibStyleGetCitationMarker { - + /** + * Modify entry and uniquefier arrays to facilitate a grouped + * presentation of uniquefied entries. + * + * entries[ (from+1 .. to) ] = null + * uniquefiers[from] = String.join( separator, uniquefiers.subList(from,to_inclusive) ) + * + * @param entries The entry array. + * @param uniquefiers The uniquefier array. + * @param from The first index to group (inclusive) + * @param to The last index to group (inclusive) + */ + private static void group(OOBibStyle style, + List entries, + String[] uniquefiers, + int from, + int to) { + String separator = style.getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); + + StringBuilder sb = new StringBuilder(uniquefiers[from]); + for (int i = from + 1; i <= to; i++) { + sb.append(separator); + sb.append(uniquefiers[i]); + entries.set(i, null); // kill BibEntry? + } + uniquefiers[from] = sb.toString(); + } + + + /** + * @param entries + * @param database + * @param inParenthesis Emit "(Au, 2000)" if true, "Au (2000)" if false. + * @param uniquefiers null or of length entries.size(), with + * elements null or letter making a cited + * source unique in citations. + * + * @param unlimAuthors Can this be null? + * If not null, then its elements are ... + * + * @param pageInfosForCitations + * May be null. + * Any or of its elements can be null. + */ public static String getCitationMarker(OOBibStyle style, List entries, Map database, @@ -52,11 +95,33 @@ public static String getCitationMarker(OOBibStyle style, int[] unlimAuthors, List pageInfosForCitations ) { + + List pageInfos = + OOBibStyle.regularizePageInfosForCitations(pageInfosForCitations, + entries.size()); + // Original: + // // Look for groups of uniquefied entries that should be combined in the output. // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). + // + // Now: + // - handle pageInfos + // - allow duplicate entries with same or different pageInfos. + // + // We assume entries are already sorted, all we need is to + // group consecutive entries if we can. + // + // TODO: imposeLocalOrder should consider pageInfos, to make + // sure multiple citations of the same entry with the same pageInfos + // + // + // int piv = -1; + String tmpMarker = null; + if (uniquefiers != null) { + for (int i = 0; i < uniquefiers.length; i++) { if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { @@ -116,7 +181,7 @@ public static String getCitationMarker(OOBibStyle style, // Do the grouping: group(style, entries, uniquefiers, piv, uniquefiers.length - 1); } - } + } // if uniquefiers are not null if (inParenthesis) { return getAuthorYearParenthesisMarker(style, entries, database, uniquefiers, unlimAuthors); @@ -125,31 +190,6 @@ public static String getCitationMarker(OOBibStyle style, } } - /** - * Modify entry and uniquefier arrays to facilitate a grouped - * presentation of uniquefied entries. - * - * @param entries The entry array. - * @param uniquefiers The uniquefier array. - * @param from The first index to group (inclusive) - * @param to The last index to group (inclusive) - */ - private static void group(OOBibStyle style, - List entries, - String[] uniquefiers, - int from, - int to) { - - String separator = style.getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); - - StringBuilder sb = new StringBuilder(uniquefiers[from]); - for (int i = from + 1; i <= to; i++) { - sb.append(separator); - sb.append(uniquefiers[i]); - entries.set(i, null); // kill BibEntry? - } - uniquefiers[from] = sb.toString(); - } /** * This method produces (Author, year) style citation strings in many different forms. diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java index 3c428885622..e6c07825a66 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java @@ -62,15 +62,7 @@ private static class NumberWithPageInfo { private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPageInfo b) { int res = Integer.compare(a.num, b.num); if (res == 0) { - if (a.pageInfo == null && b.pageInfo == null) { - res = 0; - } else if (a.pageInfo == null) { - res = -1; - } else if (b.pageInfo == null) { - res = +1; - } else { - res = a.pageInfo.compareTo(b.pageInfo); - } + res = OOBibStyle.comparePageInfo( a.pageInfo, b.pageInfo ); } return res; } From 638c585cb15ea953fda1d224714525a703c3516c Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 23:06:17 +0200 Subject: [PATCH 0542/1068] imposeLocalOrder now considers pageInfo --- .../org/jabref/gui/openoffice/Citation.java | 5 + .../jabref/gui/openoffice/CitationGroup.java | 6 ++ .../jabref/gui/openoffice/CitationSort.java | 11 ++- .../org/jabref/gui/openoffice/CitedKey.java | 10 ++ .../OOBibStyleGetCitationMarker.java | 94 ++++++------------- 5 files changed, 57 insertions(+), 69 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/Citation.java b/src/main/java/org/jabref/gui/openoffice/Citation.java index d75eaed7540..fdaf51136c9 100644 --- a/src/main/java/org/jabref/gui/openoffice/Citation.java +++ b/src/main/java/org/jabref/gui/openoffice/Citation.java @@ -73,6 +73,11 @@ public String getCitationKey(){ return citationKey; } + @Override + public String getPageInfoOrNull(){ + return pageInfo.orElse(null); + } + @Override public Optional getBibEntry(){ return (db.isPresent() diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroup.java b/src/main/java/org/jabref/gui/openoffice/CitationGroup.java index 786056c4b83..9ab6033fd11 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroup.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroup.java @@ -94,6 +94,7 @@ List getSortedNumbers() { class CitationAndIndex implements CitationSort.ComparableCitation { Citation c; int i; + CitationAndIndex(Citation c, int i) { this.c = c; this.i = i; @@ -108,6 +109,11 @@ public String getCitationKey(){ public Optional getBibEntry(){ return c.getBibEntry(); } + + @Override + public String getPageInfoOrNull(){ + return c.pageInfo.orElse(null); + } } /** diff --git a/src/main/java/org/jabref/gui/openoffice/CitationSort.java b/src/main/java/org/jabref/gui/openoffice/CitationSort.java index 5dad446cb6a..b2a7fa154b6 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationSort.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationSort.java @@ -4,12 +4,14 @@ import java.util.Optional; import org.jabref.model.entry.BibEntry; +import org.jabref.logic.openoffice.OOBibStyle; class CitationSort { interface ComparableCitation { public String getCitationKey(); public Optional getBibEntry(); + public String getPageInfoOrNull(); } static class CitationComparator implements Comparator { @@ -43,8 +45,13 @@ public int compare(ComparableCitation a, ComparableCitation b) { return mul; } // Proper comparison of entries - return entryComparator.compare(abe.get(), - bbe.get()); + int res = entryComparator.compare(abe.get(), + bbe.get()); + // Also consider pageInfo + if (res == 0) { + OOBibStyle.comparePageInfo( a.getPageInfoOrNull(), b.getPageInfoOrNull() ); + } + return res; } } diff --git a/src/main/java/org/jabref/gui/openoffice/CitedKey.java b/src/main/java/org/jabref/gui/openoffice/CitedKey.java index f07bc2969e8..96323c95d35 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitedKey.java +++ b/src/main/java/org/jabref/gui/openoffice/CitedKey.java @@ -67,6 +67,16 @@ public Optional getBibEntry(){ : Optional.empty()); } + /** No pageInfo is needed for sorting the bibliography, + * getPageInfoOrNull always returns null. Only exists to implement ComparableCitation. + * + * @return null + */ + @Override + public String getPageInfoOrNull(){ + return null; + } + /** * Appends to end of {@code where} */ diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index f7c7ed72218..f0cf61e8d66 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -42,51 +42,8 @@ class OOBibStyleGetCitationMarker { - /** - * Modify entry and uniquefier arrays to facilitate a grouped - * presentation of uniquefied entries. - * - * entries[ (from+1 .. to) ] = null - * uniquefiers[from] = String.join( separator, uniquefiers.subList(from,to_inclusive) ) - * - * @param entries The entry array. - * @param uniquefiers The uniquefier array. - * @param from The first index to group (inclusive) - * @param to The last index to group (inclusive) - */ - private static void group(OOBibStyle style, - List entries, - String[] uniquefiers, - int from, - int to) { + - String separator = style.getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); - - StringBuilder sb = new StringBuilder(uniquefiers[from]); - for (int i = from + 1; i <= to; i++) { - sb.append(separator); - sb.append(uniquefiers[i]); - entries.set(i, null); // kill BibEntry? - } - uniquefiers[from] = sb.toString(); - } - - - /** - * @param entries - * @param database - * @param inParenthesis Emit "(Au, 2000)" if true, "Au (2000)" if false. - * @param uniquefiers null or of length entries.size(), with - * elements null or letter making a cited - * source unique in citations. - * - * @param unlimAuthors Can this be null? - * If not null, then its elements are ... - * - * @param pageInfosForCitations - * May be null. - * Any or of its elements can be null. - */ public static String getCitationMarker(OOBibStyle style, List entries, Map database, @@ -95,33 +52,11 @@ public static String getCitationMarker(OOBibStyle style, int[] unlimAuthors, List pageInfosForCitations ) { - - List pageInfos = - OOBibStyle.regularizePageInfosForCitations(pageInfosForCitations, - entries.size()); - // Original: - // // Look for groups of uniquefied entries that should be combined in the output. // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). - // - // Now: - // - handle pageInfos - // - allow duplicate entries with same or different pageInfos. - // - // We assume entries are already sorted, all we need is to - // group consecutive entries if we can. - // - // TODO: imposeLocalOrder should consider pageInfos, to make - // sure multiple citations of the same entry with the same pageInfos - // - // - // int piv = -1; - String tmpMarker = null; - if (uniquefiers != null) { - for (int i = 0; i < uniquefiers.length; i++) { if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { @@ -181,7 +116,7 @@ public static String getCitationMarker(OOBibStyle style, // Do the grouping: group(style, entries, uniquefiers, piv, uniquefiers.length - 1); } - } // if uniquefiers are not null + } if (inParenthesis) { return getAuthorYearParenthesisMarker(style, entries, database, uniquefiers, unlimAuthors); @@ -190,6 +125,31 @@ public static String getCitationMarker(OOBibStyle style, } } + /** + * Modify entry and uniquefier arrays to facilitate a grouped + * presentation of uniquefied entries. + * + * @param entries The entry array. + * @param uniquefiers The uniquefier array. + * @param from The first index to group (inclusive) + * @param to The last index to group (inclusive) + */ + private static void group(OOBibStyle style, + List entries, + String[] uniquefiers, + int from, + int to) { + + String separator = style.getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); + + StringBuilder sb = new StringBuilder(uniquefiers[from]); + for (int i = from + 1; i <= to; i++) { + sb.append(separator); + sb.append(uniquefiers[i]); + entries.set(i, null); // kill BibEntry? + } + uniquefiers[from] = sb.toString(); + } /** * This method produces (Author, year) style citation strings in many different forms. From 1fc6b0017c2f62d082792182caa4e52c6175a6ee Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 23:11:35 +0200 Subject: [PATCH 0543/1068] refactor: move group forward --- .../OOBibStyleGetCitationMarker.java | 54 ++++++++++--------- 1 file changed, 28 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index f0cf61e8d66..c68dec4e9b7 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -42,7 +42,34 @@ class OOBibStyleGetCitationMarker { - + /** + * Modify entry and uniquefier arrays to facilitate a grouped + * presentation of uniquefied entries. + * + * entries[ (from+1 .. to) ] = null + * uniquefiers[from] = String.join( separator, uniquefiers.subList(from,to_inclusive) ) + * + * @param entries The entry array. + * @param uniquefiers The uniquefier array. + * @param from The first index to group (inclusive) + * @param to The last index to group (inclusive) + */ + private static void group(OOBibStyle style, + List entries, + String[] uniquefiers, + int from, + int to) { + + String separator = style.getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); + + StringBuilder sb = new StringBuilder(uniquefiers[from]); + for (int i = from + 1; i <= to; i++) { + sb.append(separator); + sb.append(uniquefiers[i]); + entries.set(i, null); // kill BibEntry? + } + uniquefiers[from] = sb.toString(); + } public static String getCitationMarker(OOBibStyle style, List entries, @@ -125,31 +152,6 @@ public static String getCitationMarker(OOBibStyle style, } } - /** - * Modify entry and uniquefier arrays to facilitate a grouped - * presentation of uniquefied entries. - * - * @param entries The entry array. - * @param uniquefiers The uniquefier array. - * @param from The first index to group (inclusive) - * @param to The last index to group (inclusive) - */ - private static void group(OOBibStyle style, - List entries, - String[] uniquefiers, - int from, - int to) { - - String separator = style.getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); - - StringBuilder sb = new StringBuilder(uniquefiers[from]); - for (int i = from + 1; i <= to; i++) { - sb.append(separator); - sb.append(uniquefiers[i]); - entries.set(i, null); // kill BibEntry? - } - uniquefiers[from] = sb.toString(); - } /** * This method produces (Author, year) style citation strings in many different forms. From 8228b7a149fe5fa84617233957cea4a11a4a7ac6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 2 Apr 2021 23:12:31 +0200 Subject: [PATCH 0544/1068] comments --- .../OOBibStyleGetCitationMarker.java | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index c68dec4e9b7..f7c7ed72218 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -71,6 +71,22 @@ private static void group(OOBibStyle style, uniquefiers[from] = sb.toString(); } + + /** + * @param entries + * @param database + * @param inParenthesis Emit "(Au, 2000)" if true, "Au (2000)" if false. + * @param uniquefiers null or of length entries.size(), with + * elements null or letter making a cited + * source unique in citations. + * + * @param unlimAuthors Can this be null? + * If not null, then its elements are ... + * + * @param pageInfosForCitations + * May be null. + * Any or of its elements can be null. + */ public static String getCitationMarker(OOBibStyle style, List entries, Map database, @@ -79,11 +95,33 @@ public static String getCitationMarker(OOBibStyle style, int[] unlimAuthors, List pageInfosForCitations ) { + + List pageInfos = + OOBibStyle.regularizePageInfosForCitations(pageInfosForCitations, + entries.size()); + // Original: + // // Look for groups of uniquefied entries that should be combined in the output. // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). + // + // Now: + // - handle pageInfos + // - allow duplicate entries with same or different pageInfos. + // + // We assume entries are already sorted, all we need is to + // group consecutive entries if we can. + // + // TODO: imposeLocalOrder should consider pageInfos, to make + // sure multiple citations of the same entry with the same pageInfos + // + // + // int piv = -1; + String tmpMarker = null; + if (uniquefiers != null) { + for (int i = 0; i < uniquefiers.length; i++) { if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { @@ -143,7 +181,7 @@ public static String getCitationMarker(OOBibStyle style, // Do the grouping: group(style, entries, uniquefiers, piv, uniquefiers.length - 1); } - } + } // if uniquefiers are not null if (inParenthesis) { return getAuthorYearParenthesisMarker(style, entries, database, uniquefiers, unlimAuthors); From 4bee0bd7ac5d55d4735a90d4f6db9e84265750da Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 4 Apr 2021 21:55:42 +0200 Subject: [PATCH 0545/1068] format, comments --- .../OOBibStyleGetCitationMarker.java | 41 +++++++-- .../logic/openoffice/OOBibStyleTest.java | 88 +++++++++++++------ 2 files changed, 97 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index f7c7ed72218..05819dfa61d 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -111,9 +111,10 @@ public static String getCitationMarker(OOBibStyle style, // We assume entries are already sorted, all we need is to // group consecutive entries if we can. // - // TODO: imposeLocalOrder should consider pageInfos, to make - // sure multiple citations of the same entry with the same pageInfos + // We also assume, that identical entries have the same uniquefier. // + // Possibilites for two consecutive entries: + // a.entry != b.entry, // // int piv = -1; @@ -316,6 +317,7 @@ private static String getAuthorYearInTextMarker(OOBibStyle style, } BibDatabase currentDatabase = database.get(currentEntry); + int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[i]; int maxAuthors = unlimA > 0 ? unlimA : maxA; @@ -375,7 +377,11 @@ private static String getCitationMarkerField(OOBibStyle style, } /** - * Look up the nth author and return the proper last name for citation markers. + * Look up the nth author and return the "proper" last name for + * citation markers. + * + * Note: "proper" in the sense that it includes the "von" part + * of the name (followed by a space) if there is one. * * @param al The author list. * @param number The number of the author to return. @@ -394,10 +400,30 @@ private static String getAuthorLastName(OOBibStyle style, return sb.toString(); } + /** - * @param maxAuthors The maximum number of authors to write out in - * full without using etal. Set to -1 to always write out - * all authors. + * @param author Passed to {@code AuthorList.parse(author)} + * + * @param maxAuthors The maximum number of authors to write out. + * If there are more authors, then ET_AL_STRING is emitted + * to mark their omission. + * Set to -1 to write out all authors. + * + * @param andString For "A, B[ and ]C" + * @param yearSep Appended to result here. + * For example " " in default_authoryear.jstyle + * + * @return "Au[AS]Bu[AS]Cu[OXFORD_COMMA][andString]Du[yearSep]" + * or "Au[AS]Bu[AS]Cu[etAlString][yearSep]" + * + * where AS = AUTHOR_SEPARATOR + * Au, Bu, Cu, Du are last names of authors. + * + * Note: + * - The ""Au[AS]Bu[AS]Cu" part may be empty (maxAuthors==0 or nAuthors==0). + * - OXFORD_COMMA is only emitted if nAuthors is at least 3. + * - andString is only emitted if nAuthors is at least 2. + * - yearSep is always emitted */ private static String createAuthorList(OOBibStyle style, String author, @@ -415,7 +441,7 @@ private static String createAuthorList(OOBibStyle style, String authorSep = style.getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR); // The String to put after the second to last author in case - // of three or more authors + // of three or more authors: (A, B[,] and C) String oxfordComma = style.getStringCitProperty(OOBibStyle.OXFORD_COMMA); StringBuilder sb = new StringBuilder(); @@ -451,6 +477,7 @@ private static String createAuthorList(OOBibStyle style, // -1 0 "" sb.append(etAlString); } + sb.append(yearSep); return sb.toString(); } diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 0c5f7860d12..199cc366f54 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -42,7 +42,8 @@ void setUp() { @Test void testAuthorYear() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, layoutFormatterPreferences); + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, + layoutFormatterPreferences); assertTrue(style.isValid()); assertTrue(style.isInternalStyle()); assertFalse(style.isCitationKeyCiteMarkers()); @@ -55,8 +56,9 @@ void testAuthorYear() throws IOException { @Test void testAuthorYearAsFile() throws URISyntaxException, IOException { - File defFile = Path.of(OOBibStyleTest.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) - .toFile(); + File defFile = Path.of( + OOBibStyleTest.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) + .toFile(); OOBibStyle style = new OOBibStyle(defFile, layoutFormatterPreferences, StandardCharsets.UTF_8); assertTrue(style.isValid()); assertFalse(style.isInternalStyle()); @@ -282,16 +284,27 @@ void testGetCitProperty() throws IOException { @Test void testGetCitationMarker() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); BibEntry entry = new BibEntry() - .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m and Jaana W\\\"{a}yrynen and Marine Bod\\'{e}n and Konstantin Beznosov and Philippe Kruchten") + .withField(StandardField.AUTHOR, + "Gustav Bostr\\\"{o}m" + + " and Jaana W\\\"{a}yrynen" + + " and Marine Bod\\'{e}n" + + " and Konstantin Beznosov" + + " and Philippe Kruchten") .withField(StandardField.YEAR, "2006") - .withField(StandardField.BOOKTITLE, "SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems") + .withField(StandardField.BOOKTITLE, + "SESS '06: Proceedings of the 2006 international workshop" + + " on Software engineering for secure systems") .withField(StandardField.PUBLISHER, "ACM") - .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") + .withField(StandardField.TITLE, + "Extending XP practices to support security requirements engineering") .withField(StandardField.PAGES, "11--18"); + BibDatabase database = new BibDatabase(); database.insertEntry(entry); + Map entryDBMap = new HashMap<>(); entryDBMap.put(entry, database); @@ -301,19 +314,33 @@ void testGetCitationMarker() throws IOException { assertEquals("Boström et al. [2006]", style.getCitationMarker(Collections.singletonList(entry), entryDBMap, false, null, new int[]{3}, empty)); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, new int[]{5}, empty)); + style.getCitationMarker(Collections.singletonList(entry), + entryDBMap, + true, + null, + new int[]{5}, + empty)); } @Test void testLayout() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); BibEntry entry = new BibEntry() - .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m and Jaana W\\\"{a}yrynen and Marine Bod\\'{e}n and Konstantin Beznosov and Philippe Kruchten") - .withField(StandardField.YEAR, "2006") - .withField(StandardField.BOOKTITLE, "SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems") - .withField(StandardField.PUBLISHER, "ACM") - .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") + .withField(StandardField.AUTHOR, + "Gustav Bostr\\\"{o}m" + + " and Jaana W\\\"{a}yrynen" + + " and Marine Bod\\'{e}n" + + " and Konstantin Beznosov" + + " and Philippe Kruchten") + .withField(StandardField.YEAR, "2006") + .withField(StandardField.BOOKTITLE, + "SESS '06: Proceedings of the 2006 international workshop" + + " on Software engineering for secure systems") + .withField(StandardField.PUBLISHER, "ACM") + .withField(StandardField.TITLE, + "Extending XP practices to support security requirements engineering") .withField(StandardField.PAGES, "11--18"); BibDatabase database = new BibDatabase(); database.insertEntry(entry); @@ -321,19 +348,26 @@ void testLayout() throws IOException { Layout l = style.getReferenceFormat(new UnknownEntryType("default")); l.setPostFormatter(new OOPreFormatter()); assertEquals( - "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006). Extending XP practices to support security requirements engineering, : 11-18.", + "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006)." + + " Extending XP practices to support security requirements engineering," + + " : 11-18.", l.doLayout(entry, database)); l = style.getReferenceFormat(StandardEntryType.InCollection); l.setPostFormatter(new OOPreFormatter()); assertEquals( - "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006). Extending XP practices to support security requirements engineering. In: (Ed.), SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems, ACM.", - l.doLayout(entry, database)); + "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006)." + + " Extending XP practices to support security requirements engineering." + + " In: (Ed.)," + + " SESS '06: Proceedings of the 2006 international workshop" + + " on Software engineering for secure systems, ACM.", + l.doLayout(entry, database)); } @Test void testInstitutionAuthor() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); BibDatabase database = new BibDatabase(); Layout l = style.getReferenceFormat(StandardEntryType.Article); @@ -345,14 +379,16 @@ void testInstitutionAuthor() throws IOException { entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); - assertEquals("JabRef Development Team (2016). JabRef Manual, .", - l.doLayout(entry, database)); + assertEquals("JabRef Development Team" + + " (2016)." + + " JabRef Manual, .", + l.doLayout(entry, database)); } @Test void testVonAuthor() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); BibDatabase database = new BibDatabase(); Layout l = style.getReferenceFormat(StandardEntryType.Article); @@ -365,13 +401,13 @@ void testVonAuthor() throws IOException { entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); assertEquals("von Beta, A. (2016). JabRef Manual, .", - l.doLayout(entry, database)); + l.doLayout(entry, database)); } @Test void testInstitutionAuthorMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); Map entryDBMap = new HashMap<>(); List entries = new ArrayList<>(); @@ -428,7 +464,8 @@ void testNullAuthorMarker() throws IOException { entries.add(entry); entryDBMap.put(entry, database); List empty = null; - assertEquals("[, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); + assertEquals("[, 2016]", + style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); } @Test @@ -696,7 +733,8 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { @Test void testIsValidWithDefaultSectionAtTheStart() throws Exception { - OOBibStyle style = new OOBibStyle("testWithDefaultAtFirstLIne.jstyle", layoutFormatterPreferences); + OOBibStyle style = new OOBibStyle("testWithDefaultAtFirstLIne.jstyle", + layoutFormatterPreferences); assertTrue(style.isValid()); } } From 3456a3acdb0dad12e6225acf7c7e68cb2b7659ee Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 4 Apr 2021 21:58:02 +0200 Subject: [PATCH 0546/1068] attempt to clarify dependence of maxAuthors on unlimAuthors --- .../OOBibStyleGetCitationMarker.java | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 05819dfa61d..b86f4fd9b5f 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -247,8 +247,28 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, } BibDatabase currentDatabase = database.get(currentEntry); + + /* original: */ int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[j]; - int maxAuthors = unlimA > 0 ? unlimA : maxA; + int maxAuthors = (unlimA > 0) ? unlimA : maxA; + /* + * translation: + * + * if ( unlimAuthors == null ) { maxAuthors = maxA; } + * else if ( unlimAuthors[j] > 0 ) { maxAuthors = unlimAuthors[j]; } + * else { maxAuthors = maxA; } + * + * maxAuthors = (( (unlimAuthors != null) && (unlimAuthors[j] > 0) ) + * ? unlimAuthors[j] + * : maxA ) + */ + + int maxAuthors2 = (( (unlimAuthors != null) && (unlimAuthors[j] > 0) ) + ? unlimAuthors[j] + : maxA ); + if (maxAuthors2 != maxAuthors) { + throw new RuntimeException( "(maxAuthors2 != maxAuthors)" ); + } String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); From 6586b7f949b75d15f6513f4529b1ed29ab3d8161 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 4 Apr 2021 22:02:22 +0200 Subject: [PATCH 0547/1068] getVon in getAuthorLastName --- .../logic/openoffice/OOBibStyleGetCitationMarker.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index b86f4fd9b5f..2d2809c4606 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -414,7 +414,13 @@ private static String getAuthorLastName(OOBibStyle style, if (al.getNumberOfAuthors() > number) { Author a = al.getAuthor(number); - a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> sb.append(von).append(' ')); + // "von " if von exists + Optional von = a.getVon(); + if (von.isPresent() && !von.isEmpty()) { + sb.append(von.get()); + sb.append(' '); + } + // last name if it exists sb.append(a.getLast().orElse("")); } From fba9ad6d6ef85a061cedafdafa29f0544c1e8c01 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 4 Apr 2021 23:44:51 +0200 Subject: [PATCH 0548/1068] comment on why do we expect a single author in the "et al." case. --- .../logic/openoffice/OOBibStyleTest.java | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 199cc366f54..b7b171b0cac 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -308,11 +308,30 @@ void testGetCitationMarker() throws IOException { Map entryDBMap = new HashMap<>(); entryDBMap.put(entry, database); + assertEquals(3, style.getIntCitProperty("MaxAuthors")); + List empty = null; + + /* + * For in-text citations most (maybe all) styles prescribe a single + * author's name before "et al." + */ assertEquals("[Boström et al., 2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, null, empty)); + style.getCitationMarker(Collections.singletonList(entry), // List + entryDBMap, // Map + true, // inParenthesis + null, // uniquefiers + null, // unlimAuthors + empty)); // pageInfosForCitations + assertEquals("Boström et al. [2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, false, null, new int[]{3}, empty)); + style.getCitationMarker(Collections.singletonList(entry), + entryDBMap, + false, + null, + new int[]{3}, + empty)); + assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", style.getCitationMarker(Collections.singletonList(entry), entryDBMap, From d115360066cff2a9e2449ee8c7e5e7ce55d8b0a3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 4 Apr 2021 23:47:16 +0200 Subject: [PATCH 0549/1068] refactor: now createAuthorList is explicit about maxAuthorsBeforeEtAl --- .../OOBibStyleGetCitationMarker.java | 101 +++++++++++++----- 1 file changed, 76 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 2d2809c4606..1cc8673ff25 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -435,18 +435,23 @@ private static String getAuthorLastName(OOBibStyle style, * to mark their omission. * Set to -1 to write out all authors. * + * maxAuthors=0 is pointless, now throws RuntimeException + * (Earlier it behaved as maxAuthors=1) + * + * maxAuthors less than -1 : throw RuntimeException + * * @param andString For "A, B[ and ]C" * @param yearSep Appended to result here. * For example " " in default_authoryear.jstyle * * @return "Au[AS]Bu[AS]Cu[OXFORD_COMMA][andString]Du[yearSep]" - * or "Au[AS]Bu[AS]Cu[etAlString][yearSep]" + * or "Au[etAlString][yearSep]" * * where AS = AUTHOR_SEPARATOR * Au, Bu, Cu, Du are last names of authors. * * Note: - * - The ""Au[AS]Bu[AS]Cu" part may be empty (maxAuthors==0 or nAuthors==0). + * - The "Au[AS]Bu[AS]Cu" (or the "Au") part may be empty (maxAuthors==0 or nAuthors==0). * - OXFORD_COMMA is only emitted if nAuthors is at least 3. * - andString is only emitted if nAuthors is at least 2. * - yearSep is always emitted @@ -458,6 +463,19 @@ private static String createAuthorList(OOBibStyle style, String yearSep) { Objects.requireNonNull(author); + // Apparently maxAuthorsBeforeEtAl is always 1 for in-text citations. + // In reference lists can be for example 7, + // (https://www.chicagomanualofstyle.org/turabian/turabian-author-date-citation-quick-guide.html) + // but those are handled elsewhere. + // + // There is also + // https://apastyle.apa.org/style-grammar-guidelines/citations/basic-principles/same-year-first-author + // suggesting the to avoid ambiguity, we may need more than one name + // before "et al.". We do not currently do this kind of disambiguation, + // but we might, one day. + // + final int maxAuthorsBeforeEtAl = 1; + // The String to represent authors that are not mentioned, // e.g. " et al." String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); @@ -474,34 +492,67 @@ private static String createAuthorList(OOBibStyle style, AuthorList al = AuthorList.parse(author); final int nAuthors = al.getNumberOfAuthors(); - if (nAuthors > 0) { + // To reduce ambiguity, throw on unexpected values of maxAuthors + if (maxAuthors == 0) { + throw new RuntimeException("maxAuthors = 0 in createAuthorList"); + } + if (maxAuthors < -1) { + throw new RuntimeException("maxAuthors < -1 in createAuthorList"); + } + + boolean emitAllAuthors = ((nAuthors <= maxAuthors) || (maxAuthors == -1)); + + int nAuthorsToEmit = (emitAllAuthors + ? nAuthors + : Math.min(maxAuthorsBeforeEtAl, nAuthors)); + + if (!emitAllAuthors) { + // If we use "et al." maxAuthorsBeforeEtAl also limits the + // number of authors emitted. + nAuthorsToEmit = Math.min(nAuthorsToEmit, maxAuthorsBeforeEtAl); + } + + if (nAuthorsToEmit > 0) { // The first author sb.append(getAuthorLastName(style, al, 0)); } - boolean emitAllAuthors = ((nAuthors <= maxAuthors) || (maxAuthors < 0)); - if ((nAuthors >= 2) && emitAllAuthors) { - // Emit last names, except for the last author - int j = 1; - while (j < (nAuthors - 1)) { - sb.append(authorSep); - sb.append(getAuthorLastName(style, al, j)); - j++; - } - // oxfordComma if at least 3 authors - if (nAuthors >= 3) { - sb.append(oxfordComma); + if (nAuthors >= 2) { + + if (emitAllAuthors) { + // Emit last names, except for the last author + int j = 1; + while (j < (nAuthors - 1)) { + sb.append(authorSep); + sb.append(getAuthorLastName(style, al, j)); + j++; + } + // oxfordComma if at least 3 authors + if (nAuthors >= 3) { + sb.append(oxfordComma); + } + // Emit " and "+"LastAuthor" + sb.append(andString); + sb.append(getAuthorLastName(style, al, nAuthors - 1)); + + } else { + // Emit last names up to nAuthorsToEmit. + // + // The (maxAuthorsBeforeEtAl > 1) test may seem + // superfluous, and yes, it is. + // It is intended to make sure the compiler eliminates + // this block as long as maxAuthorsBeforeEtAl is fixed + // to 1. + if (maxAuthorsBeforeEtAl > 1) { + int j = 1; + while (j < nAuthorsToEmit) { + sb.append(authorSep); + sb.append(getAuthorLastName(style, al, j)); + j++; + } + } + sb.append(etAlString); } - // Emit "and LastAuthor" - sb.append(andString); - sb.append(getAuthorLastName(style, al, nAuthors - 1)); - - } else if (nAuthors > maxAuthors && nAuthors > 1) { - // maxAuthors nAuthors result - // 0 1 "Smith" - // -1 1 "Smith" - // -1 0 "" - sb.append(etAlString); } sb.append(yearSep); From 354592f8157e2431975d8af0a468533902c7bdde Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 4 Apr 2021 23:54:31 +0200 Subject: [PATCH 0550/1068] refactor: more straightforward coding of unlimAuthors effect on maxAuthors --- .../OOBibStyleGetCitationMarker.java | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 1cc8673ff25..5e1221abe6b 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -248,10 +248,11 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, BibDatabase currentDatabase = database.get(currentEntry); - /* original: */ - int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[j]; - int maxAuthors = (unlimA > 0) ? unlimA : maxA; - /* + /* original: + * + * int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[j]; + * int maxAuthors = (unlimA > 0) ? unlimA : maxA; + * * translation: * * if ( unlimAuthors == null ) { maxAuthors = maxA; } @@ -262,13 +263,9 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, * ? unlimAuthors[j] * : maxA ) */ - - int maxAuthors2 = (( (unlimAuthors != null) && (unlimAuthors[j] > 0) ) - ? unlimAuthors[j] - : maxA ); - if (maxAuthors2 != maxAuthors) { - throw new RuntimeException( "(maxAuthors2 != maxAuthors)" ); - } + int maxAuthors = (( (unlimAuthors != null) && (unlimAuthors[j] > 0) ) + ? unlimAuthors[j] + : maxA ); String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); @@ -338,8 +335,14 @@ private static String getAuthorYearInTextMarker(OOBibStyle style, BibDatabase currentDatabase = database.get(currentEntry); - int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[i]; - int maxAuthors = unlimA > 0 ? unlimA : maxA; + /* original: + * + * int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[i]; + * int maxAuthors = unlimA > 0 ? unlimA : maxA; + */ + int maxAuthors = (( (unlimAuthors != null) && (unlimAuthors[i] > 0) ) + ? unlimAuthors[i] + : maxA ); if (i > 0) { sb.append(citationSeparator); From 5f96d17f300417aa3e3bbc855ff7a740a7c2e32d Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 4 Apr 2021 23:59:11 +0200 Subject: [PATCH 0551/1068] "createNormalizedCitationMarker" marks three locations of ... ... of creating a citation marker for comparison if there is a clash. One (in OOBibBase) uses unlimAuthors=new int[] {-1} /* no limit on authors */, the others use unlimAuthors from their argument. --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 13 +++++++++---- .../openoffice/OOBibStyleGetCitationMarker.java | 8 +++++--- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8da85371e25..baaacfa2365 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -775,10 +775,15 @@ private String normalizedCitationMarkerForNormalStyle(CitedKey ck, entries.put( ce, ck.db.get().database ); // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: - return style.getCitationMarker(Collections.singletonList(ce), - entries, - true, - null, + // createNormalizedCitationMarker + return style.getCitationMarker(Collections.singletonList(ce), // List + entries, // Map + true, // inParenthesis + null, // uniqueLetters + // No limit on authors? + // TODO: Seems wrong: the actual markers + // may be shorter, with more clashes + // than we test here. new int[] {-1}, /* no limit on authors */ null /*pageInfosForCitations*/); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 5e1221abe6b..f643d772c98 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -138,14 +138,16 @@ public static String getCitationMarker(OOBibStyle style, BibEntry currentEntry = entries.get(i); if (piv == -1) { piv = i; + // createNormalizedCitationMarker tmpMarker = getAuthorYearParenthesisMarker(style, Collections.singletonList(currentEntry), - database, - null, - unlimAuthors); + database, // Map + null, // uniqueLetters + unlimAuthors /* from args!*/); } else { // See if this entry can go into a group with the previous one: + // createNormalizedCitationMarker String thisMarker = getAuthorYearParenthesisMarker(style, Collections.singletonList(currentEntry), From e6632b5ae43831280897c55e05429e5b4378c903 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 6 Apr 2021 16:33:47 +0200 Subject: [PATCH 0552/1068] format, comment --- .../org/jabref/gui/openoffice/OOBibBase.java | 34 ++++++++----------- .../OOBibStyleGetCitationMarker.java | 4 ++- 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index baaacfa2365..90c34ad282d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1096,13 +1096,12 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes uniqueLetterForCitedEntry2[0] = uniqueLetterForCitedEntry[j]; List pageInfo = pageInfosForCitations.subList(j,j+1); s = (s - + style.getCitationMarker( - cEntries, - entries, - cg.itcType == OOBibBase.AUTHORYEAR_PAR, - uniqueLetterForCitedEntry2, - firstLimAuthors2, - pageInfo)); + + style.getCitationMarker(cEntries, + entries, + cg.itcType == OOBibBase.AUTHORYEAR_PAR, + uniqueLetterForCitedEntry2, + firstLimAuthors2, + pageInfo)); } else { s = s + String.format("(Unresolved(%s))", currentKey); } @@ -1122,16 +1121,13 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes entries.put(e,d); } - citMarkers.put( cgid, - style.getCitationMarker( - cEntries, - entries, - cg.itcType == OOBibBase.AUTHORYEAR_PAR, - uniqueLetterForCitedEntry, - firstLimAuthors, - pageInfosForCitations - ) - ); + String citMarker = style.getCitationMarker(cEntries, + entries, + cg.itcType == OOBibBase.AUTHORYEAR_PAR, + uniqueLetterForCitedEntry, + firstLimAuthors, + pageInfosForCitations); + citMarkers.put(cgid, citMarker); } } @@ -1549,8 +1545,8 @@ public void insertCitation(List entries, : style.getCitationMarker(entries, databaseMap, inParenthesis, - null, - null, + null, // uniqueLetters + null, // unlimAuthors pageInfosForCitations)); if (citeText.equals("")) { diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index f643d772c98..b0ea9ffc950 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -52,7 +52,7 @@ class OOBibStyleGetCitationMarker { * @param entries The entry array. * @param uniquefiers The uniquefier array. * @param from The first index to group (inclusive) - * @param to The last index to group (inclusive) + * @param to The last index to group (inclusive) */ private static void group(OOBibStyle style, List entries, @@ -162,6 +162,8 @@ public static String getCitationMarker(OOBibStyle style, database.get(currentEntry), authorField); AuthorList al = AuthorList.parse(author); + + // assumes (unlimAuthors != null) int prevALim = unlimAuthors[i - 1]; // i always at least 1 here if (!thisMarker.equals(tmpMarker) || ((al.getNumberOfAuthors() > maxAuthors) From b32cc2f3e1e1cac2319e1368c59ba9a7c896a960 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 6 Apr 2021 16:34:41 +0200 Subject: [PATCH 0553/1068] bring utilities to the front, getAuthorLastName does not need style --- .../OOBibStyleGetCitationMarker.java | 325 +++++++++--------- 1 file changed, 163 insertions(+), 162 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index b0ea9ffc950..f8ef7dc9757 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -42,6 +42,169 @@ class OOBibStyleGetCitationMarker { + /** + * Look up the nth author and return the "proper" last name for + * citation markers. + * + * Note: "proper" in the sense that it includes the "von" part + * of the name (followed by a space) if there is one. + * + * @param al The author list. + * @param number The number of the author to return. + * @return The author name, or an empty String if inapplicable. + */ + private static String getAuthorLastName(AuthorList al, + int number) { + StringBuilder sb = new StringBuilder(); + + if (al.getNumberOfAuthors() > number) { + Author a = al.getAuthor(number); + // "von " if von exists + Optional von = a.getVon(); + if (von.isPresent() && !von.isEmpty()) { + sb.append(von.get()); + sb.append(' '); + } + // last name if it exists + sb.append(a.getLast().orElse("")); + } + + return sb.toString(); + } + + /** + * @param author Passed to {@code AuthorList.parse(author)} + * + * @param maxAuthors The maximum number of authors to write out. + * If there are more authors, then ET_AL_STRING is emitted + * to mark their omission. + * Set to -1 to write out all authors. + * + * maxAuthors=0 is pointless, now throws RuntimeException + * (Earlier it behaved as maxAuthors=1) + * + * maxAuthors less than -1 : throw RuntimeException + * + * @param andString For "A, B[ and ]C" + * @param yearSep Appended to result here. + * For example " " in default_authoryear.jstyle + * + * @return "Au[AS]Bu[AS]Cu[OXFORD_COMMA][andString]Du[yearSep]" + * or "Au[etAlString][yearSep]" + * + * where AS = AUTHOR_SEPARATOR + * Au, Bu, Cu, Du are last names of authors. + * + * Note: + * - The "Au[AS]Bu[AS]Cu" (or the "Au") part may be empty (maxAuthors==0 or nAuthors==0). + * - OXFORD_COMMA is only emitted if nAuthors is at least 3. + * - andString is only emitted if nAuthors is at least 2. + * - yearSep is always emitted + */ + private static String createAuthorList(OOBibStyle style, + String author, + int maxAuthors, + String andString, + String yearSep) { + Objects.requireNonNull(author); + + // Apparently maxAuthorsBeforeEtAl is always 1 for in-text citations. + // In reference lists can be for example 7, + // (https://www.chicagomanualofstyle.org/turabian/turabian-author-date-citation-quick-guide.html) + // but those are handled elsewhere. + // + // There is also + // https://apastyle.apa.org/style-grammar-guidelines/ ... + // ... citations/basic-principles/same-year-first-author + // suggesting the to avoid ambiguity, we may need more than one name + // before "et al.". We do not currently do this kind of disambiguation, + // but we might, one day. + // + final int maxAuthorsBeforeEtAl = 1; + + // The String to represent authors that are not mentioned, + // e.g. " et al." + String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); + + // The String to add between author names except the last two, + // e.g. ", ". + String authorSep = style.getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR); + + // The String to put after the second to last author in case + // of three or more authors: (A, B[,] and C) + String oxfordComma = style.getStringCitProperty(OOBibStyle.OXFORD_COMMA); + + StringBuilder sb = new StringBuilder(); + AuthorList al = AuthorList.parse(author); + final int nAuthors = al.getNumberOfAuthors(); + + // To reduce ambiguity, throw on unexpected values of maxAuthors + if (maxAuthors == 0) { + throw new RuntimeException("maxAuthors = 0 in createAuthorList"); + } + if (maxAuthors < -1) { + throw new RuntimeException("maxAuthors < -1 in createAuthorList"); + } + + boolean emitAllAuthors = ((nAuthors <= maxAuthors) || (maxAuthors == -1)); + + int nAuthorsToEmit = (emitAllAuthors + ? nAuthors + : Math.min(maxAuthorsBeforeEtAl, nAuthors)); + + if (!emitAllAuthors) { + // If we use "et al." maxAuthorsBeforeEtAl also limits the + // number of authors emitted. + nAuthorsToEmit = Math.min(nAuthorsToEmit, maxAuthorsBeforeEtAl); + } + + if (nAuthorsToEmit > 0) { + // The first author + sb.append(getAuthorLastName(al, 0)); + } + + if (nAuthors >= 2) { + + if (emitAllAuthors) { + // Emit last names, except for the last author + int j = 1; + while (j < (nAuthors - 1)) { + sb.append(authorSep); + sb.append(getAuthorLastName(al, j)); + j++; + } + // oxfordComma if at least 3 authors + if (nAuthors >= 3) { + sb.append(oxfordComma); + } + // Emit " and "+"LastAuthor" + sb.append(andString); + sb.append(getAuthorLastName(al, nAuthors - 1)); + + } else { + // Emit last names up to nAuthorsToEmit. + // + // The (maxAuthorsBeforeEtAl > 1) test may seem + // superfluous, and yes, it is. + // It is intended to make sure the compiler eliminates + // this block as long as maxAuthorsBeforeEtAl is fixed + // to 1. + if (maxAuthorsBeforeEtAl > 1) { + int j = 1; + while (j < nAuthorsToEmit) { + sb.append(authorSep); + sb.append(getAuthorLastName(al, j)); + j++; + } + } + sb.append(etAlString); + } + } + + sb.append(yearSep); + return sb.toString(); + } + /** * Modify entry and uniquefier arrays to facilitate a grouped * presentation of uniquefied entries. @@ -403,167 +566,5 @@ private static String getCitationMarkerField(OOBibStyle style, return ""; } - /** - * Look up the nth author and return the "proper" last name for - * citation markers. - * - * Note: "proper" in the sense that it includes the "von" part - * of the name (followed by a space) if there is one. - * - * @param al The author list. - * @param number The number of the author to return. - * @return The author name, or an empty String if inapplicable. - */ - private static String getAuthorLastName(OOBibStyle style, - AuthorList al, - int number) { - StringBuilder sb = new StringBuilder(); - - if (al.getNumberOfAuthors() > number) { - Author a = al.getAuthor(number); - // "von " if von exists - Optional von = a.getVon(); - if (von.isPresent() && !von.isEmpty()) { - sb.append(von.get()); - sb.append(' '); - } - // last name if it exists - sb.append(a.getLast().orElse("")); - } - - return sb.toString(); - } - - /** - * @param author Passed to {@code AuthorList.parse(author)} - * - * @param maxAuthors The maximum number of authors to write out. - * If there are more authors, then ET_AL_STRING is emitted - * to mark their omission. - * Set to -1 to write out all authors. - * - * maxAuthors=0 is pointless, now throws RuntimeException - * (Earlier it behaved as maxAuthors=1) - * - * maxAuthors less than -1 : throw RuntimeException - * - * @param andString For "A, B[ and ]C" - * @param yearSep Appended to result here. - * For example " " in default_authoryear.jstyle - * - * @return "Au[AS]Bu[AS]Cu[OXFORD_COMMA][andString]Du[yearSep]" - * or "Au[etAlString][yearSep]" - * - * where AS = AUTHOR_SEPARATOR - * Au, Bu, Cu, Du are last names of authors. - * - * Note: - * - The "Au[AS]Bu[AS]Cu" (or the "Au") part may be empty (maxAuthors==0 or nAuthors==0). - * - OXFORD_COMMA is only emitted if nAuthors is at least 3. - * - andString is only emitted if nAuthors is at least 2. - * - yearSep is always emitted - */ - private static String createAuthorList(OOBibStyle style, - String author, - int maxAuthors, - String andString, - String yearSep) { - Objects.requireNonNull(author); - - // Apparently maxAuthorsBeforeEtAl is always 1 for in-text citations. - // In reference lists can be for example 7, - // (https://www.chicagomanualofstyle.org/turabian/turabian-author-date-citation-quick-guide.html) - // but those are handled elsewhere. - // - // There is also - // https://apastyle.apa.org/style-grammar-guidelines/citations/basic-principles/same-year-first-author - // suggesting the to avoid ambiguity, we may need more than one name - // before "et al.". We do not currently do this kind of disambiguation, - // but we might, one day. - // - final int maxAuthorsBeforeEtAl = 1; - - // The String to represent authors that are not mentioned, - // e.g. " et al." - String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); - - // The String to add between author names except the last two, - // e.g. ", ". - String authorSep = style.getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR); - - // The String to put after the second to last author in case - // of three or more authors: (A, B[,] and C) - String oxfordComma = style.getStringCitProperty(OOBibStyle.OXFORD_COMMA); - - StringBuilder sb = new StringBuilder(); - AuthorList al = AuthorList.parse(author); - final int nAuthors = al.getNumberOfAuthors(); - - // To reduce ambiguity, throw on unexpected values of maxAuthors - if (maxAuthors == 0) { - throw new RuntimeException("maxAuthors = 0 in createAuthorList"); - } - if (maxAuthors < -1) { - throw new RuntimeException("maxAuthors < -1 in createAuthorList"); - } - - boolean emitAllAuthors = ((nAuthors <= maxAuthors) || (maxAuthors == -1)); - - int nAuthorsToEmit = (emitAllAuthors - ? nAuthors - : Math.min(maxAuthorsBeforeEtAl, nAuthors)); - - if (!emitAllAuthors) { - // If we use "et al." maxAuthorsBeforeEtAl also limits the - // number of authors emitted. - nAuthorsToEmit = Math.min(nAuthorsToEmit, maxAuthorsBeforeEtAl); - } - - if (nAuthorsToEmit > 0) { - // The first author - sb.append(getAuthorLastName(style, al, 0)); - } - - if (nAuthors >= 2) { - - if (emitAllAuthors) { - // Emit last names, except for the last author - int j = 1; - while (j < (nAuthors - 1)) { - sb.append(authorSep); - sb.append(getAuthorLastName(style, al, j)); - j++; - } - // oxfordComma if at least 3 authors - if (nAuthors >= 3) { - sb.append(oxfordComma); - } - // Emit " and "+"LastAuthor" - sb.append(andString); - sb.append(getAuthorLastName(style, al, nAuthors - 1)); - - } else { - // Emit last names up to nAuthorsToEmit. - // - // The (maxAuthorsBeforeEtAl > 1) test may seem - // superfluous, and yes, it is. - // It is intended to make sure the compiler eliminates - // this block as long as maxAuthorsBeforeEtAl is fixed - // to 1. - if (maxAuthorsBeforeEtAl > 1) { - int j = 1; - while (j < nAuthorsToEmit) { - sb.append(authorSep); - sb.append(getAuthorLastName(style, al, j)); - j++; - } - } - sb.append(etAlString); - } - } - - sb.append(yearSep); - return sb.toString(); - } } From e9fd4e45eb172424428e396641ef299fc7d68b73 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 6 Apr 2021 16:45:33 +0200 Subject: [PATCH 0554/1068] rename arg author to authorListAsString --- .../logic/openoffice/OOBibStyleGetCitationMarker.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index f8ef7dc9757..4ae8f0a929c 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -73,7 +73,7 @@ private static String getAuthorLastName(AuthorList al, } /** - * @param author Passed to {@code AuthorList.parse(author)} + * @param authorListAsString Passed to {@code AuthorList.parse(authorListAsString)} * * @param maxAuthors The maximum number of authors to write out. * If there are more authors, then ET_AL_STRING is emitted @@ -102,11 +102,11 @@ private static String getAuthorLastName(AuthorList al, * - yearSep is always emitted */ private static String createAuthorList(OOBibStyle style, - String author, + String authorListAsString, int maxAuthors, String andString, String yearSep) { - Objects.requireNonNull(author); + Objects.requireNonNull(authorListAsString); // Apparently maxAuthorsBeforeEtAl is always 1 for in-text citations. // In reference lists can be for example 7, @@ -135,7 +135,7 @@ private static String createAuthorList(OOBibStyle style, String oxfordComma = style.getStringCitProperty(OOBibStyle.OXFORD_COMMA); StringBuilder sb = new StringBuilder(); - AuthorList al = AuthorList.parse(author); + AuthorList al = AuthorList.parse(authorListAsString); final int nAuthors = al.getNumberOfAuthors(); // To reduce ambiguity, throw on unexpected values of maxAuthors From 935ee3b64a9a85a1cb95558192a56b7bf373f97a Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 6 Apr 2021 16:48:58 +0200 Subject: [PATCH 0555/1068] rerorder methods to bottom-up --- .../OOBibStyleGetCitationMarker.java | 373 ++++++++++-------- 1 file changed, 206 insertions(+), 167 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 4ae8f0a929c..2998c71dc90 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -205,157 +205,43 @@ private static String createAuthorList(OOBibStyle style, return sb.toString(); } - /** - * Modify entry and uniquefier arrays to facilitate a grouped - * presentation of uniquefied entries. - * - * entries[ (from+1 .. to) ] = null - * uniquefiers[from] = String.join( separator, uniquefiers.subList(from,to_inclusive) ) - * - * @param entries The entry array. - * @param uniquefiers The uniquefier array. - * @param from The first index to group (inclusive) - * @param to The last index to group (inclusive) - */ - private static void group(OOBibStyle style, - List entries, - String[] uniquefiers, - int from, - int to) { - - String separator = style.getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); - - StringBuilder sb = new StringBuilder(uniquefiers[from]); - for (int i = from + 1; i <= to; i++) { - sb.append(separator); - sb.append(uniquefiers[i]); - entries.set(i, null); // kill BibEntry? - } - uniquefiers[from] = sb.toString(); - } - /** - * @param entries - * @param database - * @param inParenthesis Emit "(Au, 2000)" if true, "Au (2000)" if false. - * @param uniquefiers null or of length entries.size(), with - * elements null or letter making a cited - * source unique in citations. + * This method looks up a field for an entry in a database. + * Any number of backup fields can be used if the primary field is + * empty. * - * @param unlimAuthors Can this be null? - * If not null, then its elements are ... + * @param entry The entry. + * @param database The database the entry belongs to. + * @param fields The field, or succession of fields, to look up. + * If backup fields are needed, separate + * field names by /. * - * @param pageInfosForCitations - * May be null. - * Any or of its elements can be null. + * E.g. to use "author" with "editor" as backup, + * specify StandardField.orFields(StandardField.AUTHOR, StandardField.EDITOR). + * @return The resolved field content, or an empty string if the field(s) were empty. */ - public static String getCitationMarker(OOBibStyle style, - List entries, - Map database, - boolean inParenthesis, - String[] uniquefiers, - int[] unlimAuthors, - List pageInfosForCitations - ) { - - List pageInfos = - OOBibStyle.regularizePageInfosForCitations(pageInfosForCitations, - entries.size()); - // Original: - // - // Look for groups of uniquefied entries that should be combined in the output. - // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). - // - // Now: - // - handle pageInfos - // - allow duplicate entries with same or different pageInfos. - // - // We assume entries are already sorted, all we need is to - // group consecutive entries if we can. - // - // We also assume, that identical entries have the same uniquefier. - // - // Possibilites for two consecutive entries: - // a.entry != b.entry, - // - // - int piv = -1; - - String tmpMarker = null; - - if (uniquefiers != null) { - - for (int i = 0; i < uniquefiers.length; i++) { - - if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { - // This entry has no uniquefier. - // Check if we just passed a group of more than one entry with uniquefier: - if ((piv > -1) && (i > (piv + 1))) { - // Do the grouping: - group(style, entries, uniquefiers, piv, i - 1); - } - - piv = -1; - } else { - BibEntry currentEntry = entries.get(i); - if (piv == -1) { - piv = i; - // createNormalizedCitationMarker - tmpMarker = - getAuthorYearParenthesisMarker(style, - Collections.singletonList(currentEntry), - database, // Map - null, // uniqueLetters - unlimAuthors /* from args!*/); - } else { - // See if this entry can go into a group with the previous one: - // createNormalizedCitationMarker - String thisMarker = - getAuthorYearParenthesisMarker(style, - Collections.singletonList(currentEntry), - database, - null, - unlimAuthors); + private static String getCitationMarkerField(OOBibStyle style, + BibEntry entry, + BibDatabase database, + String fields) { + Objects.requireNonNull(entry, "Entry cannot be null"); + Objects.requireNonNull(database, "database cannot be null"); - String authorField = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); - int maxAuthors = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); - String author = getCitationMarkerField(style, - currentEntry, - database.get(currentEntry), - authorField); - AuthorList al = AuthorList.parse(author); + Set authorFields = + FieldFactory.parseOrFields(style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD)); + for (Field field : FieldFactory.parseOrFields(fields)) { + Optional content = entry.getResolvedFieldOrAlias(field, database); - // assumes (unlimAuthors != null) - int prevALim = unlimAuthors[i - 1]; // i always at least 1 here - if (!thisMarker.equals(tmpMarker) - || ((al.getNumberOfAuthors() > maxAuthors) - && (unlimAuthors[i] != prevALim))) { - // No match. Update piv to exclude the previous entry. But first check if the - // previous entry was part of a group: - if ((piv > -1) && (i > (piv + 1))) { - // Do the grouping: - group(style, entries, uniquefiers, piv, i - 1); - } - tmpMarker = thisMarker; - piv = i; - } - } + if ((content.isPresent()) && !content.get().trim().isEmpty()) { + if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content.get())) { + return "{" + style.fieldFormatter.format(content.get()) + "}"; } - - } - // Finished with the loop. See if the last entries form a group: - if (piv >= 0) { - // Do the grouping: - group(style, entries, uniquefiers, piv, uniquefiers.length - 1); + return style.fieldFormatter.format(content.get()); } - } // if uniquefiers are not null - - if (inParenthesis) { - return getAuthorYearParenthesisMarker(style, entries, database, uniquefiers, unlimAuthors); - } else { - return getAuthorYearInTextMarker(style, entries, database, uniquefiers, unlimAuthors); } + // No luck? Return an empty string: + return ""; } @@ -531,39 +417,192 @@ private static String getAuthorYearInTextMarker(OOBibStyle style, } /** - * This method looks up a field for an entry in a database. Any - * number of backup fields can be used if the primary field is - * empty. + * Modify entry and uniquefier arrays to facilitate a grouped + * presentation of uniquefied entries. * - * @param entry The entry. - * @param database The database the entry belongs to. - * @param fields The field, or succession of fields, to look up. - * If backup fields are needed, separate - * field names by /. E.g. to use "author" with "editor" as backup, - * specify StandardField.orFields(StandardField.AUTHOR, StandardField.EDITOR). - * @return The resolved field content, or an empty string if the field(s) were empty. + * entries[ (from+1 .. to) ] = null + * uniquefiers[from] = String.join( separator, uniquefiers.subList(from,to_inclusive) ) + * + * @param entries The entry array. + * @param uniquefiers The uniquefier array. + * @param from The first index to group (inclusive) + * @param to The last index to group (inclusive) */ - private static String getCitationMarkerField(OOBibStyle style, - BibEntry entry, - BibDatabase database, - String fields) { - Objects.requireNonNull(entry, "Entry cannot be null"); - Objects.requireNonNull(database, "database cannot be null"); + private static void group(OOBibStyle style, + List entries, + String[] uniquefiers, + int from, + int to) { - Set authorFields = - FieldFactory.parseOrFields(style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD)); - for (Field field : FieldFactory.parseOrFields(fields)) { - Optional content = entry.getResolvedFieldOrAlias(field, database); + String separator = style.getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); - if ((content.isPresent()) && !content.get().trim().isEmpty()) { - if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content.get())) { - return "{" + style.fieldFormatter.format(content.get()) + "}"; + StringBuilder sb = new StringBuilder(uniquefiers[from]); + for (int i = from + 1; i <= to; i++) { + sb.append(separator); + sb.append(uniquefiers[i]); + entries.set(i, null); // kill BibEntry? + } + uniquefiers[from] = sb.toString(); + } + + + /** + * @param entries + * @param database + * @param inParenthesis Emit "(Au, 2000)" if true, "Au (2000)" if false. + * @param uniquefiers null or of length entries.size(), with + * elements null or letter making a cited + * source unique in citations. + * + * @param unlimAuthors Can this be null? + * If not null, then its elements are ... + * + * @param pageInfosForCitations + * May be null. + * Any or of its elements can be null. + */ + /* + * Call patterns: + * + * // normalizedCitationMarkerForNormalStyle + * return style.getCitationMarker(Collections.singletonList(ce), // List + * entries, // Map + * true, // inParenthesis + * null, // uniqueLetters + * new int[] {-1}, // no limit on authors + * null // pageInfosForCitations + * ); + * // produceCitationMarkersForNormalStyle + * // when there are unresolved entries + * style.getCitationMarker(cEntries, + * entries, + * cg.itcType == OOBibBase.AUTHORYEAR_PAR, + * uniqueLetterForCitedEntry2, + * firstLimAuthors2, + * pageInfo); + * // when there are no unresolved entries + * String citMarker = style.getCitationMarker(cEntries, + * entries, + * cg.itcType == OOBibBase.AUTHORYEAR_PAR, + * uniqueLetterForCitedEntry, + * firstLimAuthors, + * pageInfosForCitations); + * // insertCitation + * String citeText = (style.isNumberEntries() + * ? "[-]" // A dash only. Only refresh later. + * : style.getCitationMarker(entries, + * databaseMap, + * inParenthesis, + * null, // uniqueLetters + * null, // unlimAuthors + * pageInfosForCitations)); + */ + public static String getCitationMarker(OOBibStyle style, + List entries, + Map database, + boolean inParenthesis, + String[] uniquefiers, + int[] unlimAuthors, + List pageInfosForCitations + ) { + + List pageInfos = + OOBibStyle.regularizePageInfosForCitations(pageInfosForCitations, + entries.size()); + // Original: + // + // Look for groups of uniquefied entries that should be combined in the output. + // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). + // + // Now: + // - handle pageInfos + // - allow duplicate entries with same or different pageInfos. + // + // We assume entries are already sorted, all we need is to + // group consecutive entries if we can. + // + // We also assume, that identical entries have the same uniquefier. + // + // Possibilites for two consecutive entries: + // a.entry != b.entry, + // + // + int piv = -1; + + String tmpMarker = null; + + if (uniquefiers != null) { + + for (int i = 0; i < uniquefiers.length; i++) { + + if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { + // This entry has no uniquefier. + // Check if we just passed a group of more than one entry with uniquefier: + if ((piv > -1) && (i > (piv + 1))) { + // Do the grouping: + group(style, entries, uniquefiers, piv, i - 1); + } + + piv = -1; + } else { + BibEntry currentEntry = entries.get(i); + if (piv == -1) { + piv = i; + // createNormalizedCitationMarker + tmpMarker = + getAuthorYearParenthesisMarker(style, + Collections.singletonList(currentEntry), + database, // Map + null, // uniqueLetters + unlimAuthors /* from args!*/); + } else { + // See if this entry can go into a group with the previous one: + // createNormalizedCitationMarker + String thisMarker = + getAuthorYearParenthesisMarker(style, + Collections.singletonList(currentEntry), + database, + null, + unlimAuthors); + + String authorField = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); + int maxAuthors = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); + String author = getCitationMarkerField(style, + currentEntry, + database.get(currentEntry), + authorField); + AuthorList al = AuthorList.parse(author); + + // assumes (unlimAuthors != null) + int prevALim = unlimAuthors[i - 1]; // i always at least 1 here + if (!thisMarker.equals(tmpMarker) + || ((al.getNumberOfAuthors() > maxAuthors) + && (unlimAuthors[i] != prevALim))) { + // No match. Update piv to exclude the previous entry. But first check if the + // previous entry was part of a group: + if ((piv > -1) && (i > (piv + 1))) { + // Do the grouping: + group(style, entries, uniquefiers, piv, i - 1); + } + tmpMarker = thisMarker; + piv = i; + } + } } - return style.fieldFormatter.format(content.get()); + + } + // Finished with the loop. See if the last entries form a group: + if (piv >= 0) { + // Do the grouping: + group(style, entries, uniquefiers, piv, uniquefiers.length - 1); } + } // if uniquefiers are not null + + if (inParenthesis) { + return getAuthorYearParenthesisMarker(style, entries, database, uniquefiers, unlimAuthors); + } else { + return getAuthorYearInTextMarker(style, entries, database, uniquefiers, unlimAuthors); } - // No luck? Return an empty string: - return ""; } From 704ee8695f69a70fd7ea85dad1d88e8d02f38b05 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 7 Apr 2021 15:30:04 +0200 Subject: [PATCH 0556/1068] merge getAuthorYearInTextMarker into getAuthorYearParenthesisMarker --- .../OOBibStyleGetCitationMarker.java | 257 +++++++++++------- 1 file changed, 157 insertions(+), 100 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 2998c71dc90..7d2c928da69 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -32,11 +32,14 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; +import org.jabref.model.entry.field.OrFields; 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.strings.StringUtil; + + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -213,12 +216,17 @@ private static String createAuthorList(OOBibStyle style, * * @param entry The entry. * @param database The database the entry belongs to. - * @param fields The field, or succession of fields, to look up. - * If backup fields are needed, separate - * field names by /. + * + * @param fields A list of fields, to look up, using first nonempty hit. + * + * If backup fields are needed, separate field + * names by /. * * E.g. to use "author" with "editor" as backup, - * specify StandardField.orFields(StandardField.AUTHOR, StandardField.EDITOR). + * specify + * FieldFactory.serializeOrFields(StandardField.AUTHOR, + * StandardField.EDITOR) + * * @return The resolved field content, or an empty string if the field(s) were empty. */ private static String getCitationMarkerField(OOBibStyle style, @@ -228,16 +236,33 @@ private static String getCitationMarkerField(OOBibStyle style, Objects.requireNonNull(entry, "Entry cannot be null"); Objects.requireNonNull(database, "database cannot be null"); - Set authorFields = - FieldFactory.parseOrFields(style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD)); for (Field field : FieldFactory.parseOrFields(fields)) { - Optional content = entry.getResolvedFieldOrAlias(field, database); + Optional optionalContent = entry.getResolvedFieldOrAlias(field, database); + final boolean foundSomething = (optionalContent.isPresent() + && !optionalContent.get().trim().isEmpty()); + + if (foundSomething) { + String content = optionalContent.get(); + String result = style.fieldFormatter.format(content); - if ((content.isPresent()) && !content.get().trim().isEmpty()) { - if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content.get())) { - return "{" + style.fieldFormatter.format(content.get()) + "}"; + + // If the field we found is mentioned in + // OOBibStyle.AUTHOR_FIELD and content has a pair of + // braces around it, we add a pair of braces around + // the result. + + // Note: we are packing a list of strings to a string, so that we can + // store it in a style.getStringCitProperty + // And here we parse it to a OrFields, repeatedly, on each call. + // Could be more efficient to parse when the style is created. + // + final String authorFieldNames = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); + final OrFields authorFields = FieldFactory.parseOrFields(authorFieldNames); + + if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content)) { + result = "{" + result + "}"; } - return style.fieldFormatter.format(content.get()); + return result; } } // No luck? Return an empty string: @@ -246,7 +271,8 @@ private static String getCitationMarkerField(OOBibStyle style, /** - * This method produces (Author, year) style citation strings in many different forms. + * Produce (Author, year) style citation strings in many different forms. + * If inParenthesis==false, produces "Author (year)" style citation strings. * * @param entries The list of BibEntry to get fields from. * @param database A map of BibEntry-BibDatabase pairs. @@ -257,6 +283,7 @@ private static String getCitationMarkerField(OOBibStyle style, private static String getAuthorYearParenthesisMarker(OOBibStyle style, List entries, Map database, + boolean inParenthesis, String[] uniquifiers, int[] unlimAuthors) { @@ -269,7 +296,9 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, int maxA = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); // The String to separate authors from year, e.g. "; ". - String yearSep = style.getStringCitProperty(OOBibStyle.YEAR_SEPARATOR); + String yearSep = (inParenthesis + ? style.getStringCitProperty(OOBibStyle.YEAR_SEPARATOR) + : style.getStringCitProperty(OOBibStyle.IN_TEXT_YEAR_SEPARATOR)); // The opening parenthesis. String startBrace = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE); @@ -284,9 +313,20 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, String yearField = style.getStringCitProperty(OOBibStyle.YEAR_FIELD); // The String to add between the two last author names, e.g. " & ". - String andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); + String andString = (inParenthesis + ? style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR) + : style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT)); + + if (!inParenthesis && andString == null) { + // Use the default one if no explicit separator for text is defined + andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); + } + + StringBuilder sb = new StringBuilder(); + if (inParenthesis) { + sb.append(startBrace); + } - StringBuilder sb = new StringBuilder(startBrace); for (int j = 0; j < entries.size(); j++) { BibEntry currentEntry = entries.get(j); @@ -323,99 +363,115 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); sb.append(authorString); + + if (!inParenthesis) { + sb.append(startBrace); + } + String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); if (year != null) { sb.append(year); } + if ((uniquifiers != null) && (uniquifiers[j] != null)) { sb.append(uniquifiers[j]); } - } - sb.append(endBrace); - return sb.toString(); - } - - /** - * This method produces "Author (year)" style citation strings in many different forms. - * - * @param entries The list of BibEntry to get fields from. - * @param database A map of BibEntry-BibDatabase pairs. - * @param uniquefiers Optional parameters to separate similar citations. Can be null if not needed. - * @return The formatted citation. - */ - private static String getAuthorYearInTextMarker(OOBibStyle style, - List entries, - Map database, - String[] uniquefiers, - int[] unlimAuthors) { - // The bibtex field providing author names, e.g. "author" or "editor". - String authorField = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); - - // The maximum number of authors to write out in full without using etal. Set to - // -1 to always write out all authors. - int maxA = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); - - // The String to separate authors from year, e.g. "; ". - String yearSep = style.getStringCitProperty(OOBibStyle.IN_TEXT_YEAR_SEPARATOR); - - // The opening parenthesis. - String startBrace = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE); - - // The closing parenthesis. - String endBrace = style.getStringCitProperty(OOBibStyle.BRACKET_AFTER); - // The String to separate citations from each other. - String citationSeparator = style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR); - - // The bibtex field providing the year, e.g. "year". - String yearField = style.getStringCitProperty(OOBibStyle.YEAR_FIELD); - - // The String to add between the two last author names, e.g. " & ". - String andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT); - - if (andString == null) { - // Use the default one if no explicit separator for text is defined - andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < entries.size(); i++) { - BibEntry currentEntry = entries.get(i); - - // Check if this entry has been nulled due to grouping with the previous entry(ies): - if (currentEntry == null) { - continue; + if (!inParenthesis) { + sb.append(endBrace); } + } - BibDatabase currentDatabase = database.get(currentEntry); - - /* original: - * - * int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[i]; - * int maxAuthors = unlimA > 0 ? unlimA : maxA; - */ - int maxAuthors = (( (unlimAuthors != null) && (unlimAuthors[i] > 0) ) - ? unlimAuthors[i] - : maxA ); - - if (i > 0) { - sb.append(citationSeparator); - } - String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); - String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); - sb.append(authorString); - sb.append(startBrace); - String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); - if (year != null) { - sb.append(year); - } - if ((uniquefiers != null) && (uniquefiers[i] != null)) { - sb.append(uniquefiers[i]); - } + if (inParenthesis) { sb.append(endBrace); } return sb.toString(); } + // /** + // * This method produces "Author (year)" style citation strings in many different forms. + // * + // * @param entries The list of BibEntry to get fields from. + // * @param database A map of BibEntry-BibDatabase pairs. + // * @param uniquefiers Optional parameters to separate similar citations. Can be null if not needed. + // * @return The formatted citation. + // */ + // private static String getAuthorYearInTextMarker(OOBibStyle style, + // List entries, + // Map database, + // String[] uniquefiers, + // int[] unlimAuthors) { + // // The bibtex field providing author names, e.g. "author" or "editor". + // String authorField = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); + // + // // The maximum number of authors to write out in full without using etal. Set to + // // -1 to always write out all authors. + // int maxA = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); + // + // // The String to separate authors from year, e.g. "; ". + // String yearSep = style.getStringCitProperty(OOBibStyle.IN_TEXT_YEAR_SEPARATOR); + // + // // The opening parenthesis. + // String startBrace = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE); + // + // // The closing parenthesis. + // String endBrace = style.getStringCitProperty(OOBibStyle.BRACKET_AFTER); + // + // // The String to separate citations from each other. + // String citationSeparator = style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR); + // + // // The bibtex field providing the year, e.g. "year". + // String yearField = style.getStringCitProperty(OOBibStyle.YEAR_FIELD); + // + // // The String to add between the two last author names, e.g. " & ". + // String andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT); + // + // if (andString == null) { + // // Use the default one if no explicit separator for text is defined + // andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); + // } + // StringBuilder sb = new StringBuilder(); + // for (int i = 0; i < entries.size(); i++) { + // BibEntry currentEntry = entries.get(i); + // + // // Check if this entry has been nulled due to grouping with the previous entry(ies): + // if (currentEntry == null) { + // continue; + // } + // + // BibDatabase currentDatabase = database.get(currentEntry); + // + // /* original: + // * + // * int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[i]; + // * int maxAuthors = unlimA > 0 ? unlimA : maxA; + // */ + // int maxAuthors = (( (unlimAuthors != null) && (unlimAuthors[i] > 0) ) + // ? unlimAuthors[i] + // : maxA ); + // + // if (i > 0) { + // sb.append(citationSeparator); + // } + // String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); + // String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); + // sb.append(authorString); + // + // sb.append(startBrace); + // + // String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); + // if (year != null) { + // sb.append(year); + // } + // + // if ((uniquefiers != null) && (uniquefiers[i] != null)) { + // sb.append(uniquefiers[i]); + // } + // sb.append(endBrace); + // } + // return sb.toString(); + // } + /** * Modify entry and uniquefier arrays to facilitate a grouped * presentation of uniquefied entries. @@ -553,6 +609,7 @@ public static String getCitationMarker(OOBibStyle style, getAuthorYearParenthesisMarker(style, Collections.singletonList(currentEntry), database, // Map + true, // inParenthesis null, // uniqueLetters unlimAuthors /* from args!*/); } else { @@ -562,6 +619,7 @@ public static String getCitationMarker(OOBibStyle style, getAuthorYearParenthesisMarker(style, Collections.singletonList(currentEntry), database, + true, // inParenthesis null, unlimAuthors); @@ -598,12 +656,11 @@ public static String getCitationMarker(OOBibStyle style, } } // if uniquefiers are not null - if (inParenthesis) { - return getAuthorYearParenthesisMarker(style, entries, database, uniquefiers, unlimAuthors); - } else { - return getAuthorYearInTextMarker(style, entries, database, uniquefiers, unlimAuthors); - } + return getAuthorYearParenthesisMarker(style, + entries, + database, + inParenthesis, + uniquefiers, + unlimAuthors); } - - } From 167e6b7755489eda519108c94bd66fc7bdb1c641 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 7 Apr 2021 17:33:43 +0200 Subject: [PATCH 0557/1068] style.getCitPropertyMultiCiteChronological --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 3 +++ src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java | 3 ++- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 90c34ad282d..5a368c83213 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -710,7 +710,7 @@ public void applyCitationEntries( */ private Comparator comparatorForMulticite(OOBibStyle style) { - if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { + if (style.getCitPropertyMultiCiteChronological()) { return this.yearAuthorTitleComparator; } else { return this.entryComparator; diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 295f983bea1..d20eeb20981 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -521,6 +521,9 @@ public boolean getBooleanCitProperty(String key) { return (Boolean) citProperties.get(key); } + public boolean getCitPropertyMultiCiteChronological() { + return this.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL); + } public int getIntCitProperty(String key) { return (Integer) citProperties.get(key); } diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index b7b171b0cac..6f85895450e 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -275,7 +275,8 @@ void testGetCitProperty() throws IOException { layoutFormatterPreferences); assertEquals(", ", style.getStringCitProperty("AuthorSeparator")); assertEquals(3, style.getIntCitProperty("MaxAuthors")); - assertTrue(style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)); + //assertTrue(style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)); + assertTrue(style.getCitPropertyMultiCiteChronological()); assertEquals("Default", style.getCitationCharacterFormat()); assertEquals("Default [number] style file.", style.getName()); Set journals = style.getJournals(); From b1de113d1777fad6a92a90e5a8077684af13289b Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 7 Apr 2021 17:34:25 +0200 Subject: [PATCH 0558/1068] style.getCitPropertyItalicEtAl --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5a368c83213..24cc68cd39e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1181,7 +1181,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti // format it as italic. // Check if we should italicize the "et al." string in citations: - boolean italicize = style.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); + boolean italicize = style.getCitPropertyItalicEtAl(); if (italicize) { String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); Objects.requireNonNull(etAlString); diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index d20eeb20981..9e4e36ea8b7 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -524,6 +524,11 @@ public boolean getBooleanCitProperty(String key) { public boolean getCitPropertyMultiCiteChronological() { return this.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL); } + + public boolean getCitPropertyItalicEtAl() { + return this.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); + } + public int getIntCitProperty(String key) { return (Integer) citProperties.get(key); } From 3970ba07e653b5b4563dabfe1bdb80bf7a933630 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 7 Apr 2021 17:34:49 +0200 Subject: [PATCH 0559/1068] getBooleanCitProperty is pivate in OOBibStyle --- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 9e4e36ea8b7..1882a1c81ba 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -517,7 +517,7 @@ public boolean isCitationKeyCiteMarkers() { * @param key The property key * @return the value */ - public boolean getBooleanCitProperty(String key) { + private boolean getBooleanCitProperty(String key) { return (Boolean) citProperties.get(key); } From 09d926051d784d9145270fdd684e61bc19c523c3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 7 Apr 2021 17:36:43 +0200 Subject: [PATCH 0560/1068] OOBibStyle.getAuthorFieldNames, getYearFieldNames --- .../jabref/logic/openoffice/OOBibStyle.java | 17 ++++ .../OOBibStyleGetCitationMarker.java | 87 ++++++++++++------- 2 files changed, 72 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 1882a1c81ba..ec32d5e05e2 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -32,6 +32,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; +import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.EntryTypeFactory; @@ -537,6 +538,22 @@ public String getStringCitProperty(String key) { return (String) citProperties.get(key); } + /** + * @return Field containing authors, with fallback fields. + */ + protected OrFields getAuthorFieldNames() { + String authorFieldNamesString = this.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); + return FieldFactory.parseOrFields(authorFieldNamesString); + } + + /** + * @return Field containing year, with fallback fields. + */ + protected OrFields getYearFieldNames() { + String yearFieldNamesString = this.getStringCitProperty(OOBibStyle.YEAR_FIELD); + return FieldFactory.parseOrFields(yearFieldNamesString); + } + public String getCitationCharacterFormat() { return getStringCitProperty(CITATION_CHARACTER_FORMAT); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 7d2c928da69..01fab0755e3 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -208,9 +208,39 @@ private static String createAuthorList(OOBibStyle style, return sb.toString(); } + private static class FieldAndContent { + Field field; + String content; + FieldAndContent(Field field, String content) { + this.field = field; + this.content = content; + } + } + /** + * @return the field and the content of the first nonempty (after trimming) + * field (or alias) from {@code fields} found in {@code entry}, or Optional.empty() + */ + private static Optional getRawCitationMarkerField(BibEntry entry, + BibDatabase database, + OrFields fields + ) { + Objects.requireNonNull(entry, "Entry cannot be null"); + Objects.requireNonNull(database, "database cannot be null"); + + for (Field field : fields /*FieldFactory.parseOrFields(fields)*/) { + Optional optionalContent = entry.getResolvedFieldOrAlias(field, database); + final boolean foundSomething = (optionalContent.isPresent() + && !optionalContent.get().trim().isEmpty()); + if (foundSomething) { + return Optional.of(new FieldAndContent(field, optionalContent.get())); + } + } + return Optional.empty(); + } /** * This method looks up a field for an entry in a database. + * * Any number of backup fields can be used if the primary field is * empty. * @@ -232,44 +262,33 @@ private static String createAuthorList(OOBibStyle style, private static String getCitationMarkerField(OOBibStyle style, BibEntry entry, BibDatabase database, - String fields) { + OrFields fields) { Objects.requireNonNull(entry, "Entry cannot be null"); Objects.requireNonNull(database, "database cannot be null"); - for (Field field : FieldFactory.parseOrFields(fields)) { - Optional optionalContent = entry.getResolvedFieldOrAlias(field, database); - final boolean foundSomething = (optionalContent.isPresent() - && !optionalContent.get().trim().isEmpty()); + Optional optionalFieldAndContent = + getRawCitationMarkerField(entry, database, fields); - if (foundSomething) { - String content = optionalContent.get(); - String result = style.fieldFormatter.format(content); + if (optionalFieldAndContent.isEmpty()) { + // No luck? Return an empty string: + return ""; + } - // If the field we found is mentioned in - // OOBibStyle.AUTHOR_FIELD and content has a pair of - // braces around it, we add a pair of braces around - // the result. + FieldAndContent fc = optionalFieldAndContent.get(); + String result = style.fieldFormatter.format(fc.content); - // Note: we are packing a list of strings to a string, so that we can - // store it in a style.getStringCitProperty - // And here we parse it to a OrFields, repeatedly, on each call. - // Could be more efficient to parse when the style is created. - // - final String authorFieldNames = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); - final OrFields authorFields = FieldFactory.parseOrFields(authorFieldNames); + // If the field we found is mentioned in authorFieldNames and + // content has a pair of braces around it, we add a pair of + // braces around the result. - if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content)) { - result = "{" + result + "}"; - } - return result; - } + final OrFields authorFieldNames = style.getAuthorFieldNames(); + if (authorFieldNames.contains(fc.field) && StringUtil.isInCurlyBrackets(fc.content)) { + result = "{" + result + "}"; } - // No luck? Return an empty string: - return ""; + return result; } - /** * Produce (Author, year) style citation strings in many different forms. * If inParenthesis==false, produces "Author (year)" style citation strings. @@ -289,7 +308,9 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, // The bibtex field providing author names, e.g. "author" or // "editor". - String authorField = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); + // String authorFieldNamesString = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); + // OrFields authorFieldNames = FieldFactory.parseOrFields(authorFieldNamesString); + OrFields authorFieldNames = style.getAuthorFieldNames(); // The maximum number of authors to write out in full without // using etal. Set to -1 to always write out all authors. @@ -310,7 +331,9 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, String citationSeparator = style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR); // The bibtex field providing the year, e.g. "year". - String yearField = style.getStringCitProperty(OOBibStyle.YEAR_FIELD); + // String yearFieldNamesString /*yearField*/ = style.getStringCitProperty(OOBibStyle.YEAR_FIELD); + // OrFields yearFieldNames = FieldFactory.parseOrFields(yearFieldNamesString); + OrFields yearFieldNames = style.getYearFieldNames(); // The String to add between the two last author names, e.g. " & ". String andString = (inParenthesis @@ -360,7 +383,7 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, ? unlimAuthors[j] : maxA ); - String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); + String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorFieldNames); String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); sb.append(authorString); @@ -368,7 +391,7 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, sb.append(startBrace); } - String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); + String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearFieldNames); if (year != null) { sb.append(year); } @@ -628,7 +651,7 @@ public static String getCitationMarker(OOBibStyle style, String author = getCitationMarkerField(style, currentEntry, database.get(currentEntry), - authorField); + style.getAuthorFieldNames()); AuthorList al = AuthorList.parse(author); // assumes (unlimAuthors != null) From 56085d827b0e8279574c1560a463f181e86f1f32 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 7 Apr 2021 17:40:13 +0200 Subject: [PATCH 0561/1068] format, comments --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 6 ++++-- .../openoffice/OOBibStyleGetCitationMarker.java | 14 ++++++++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 24cc68cd39e..2a111f0bf1e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1096,10 +1096,12 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes uniqueLetterForCitedEntry2[0] = uniqueLetterForCitedEntry[j]; List pageInfo = pageInfosForCitations.subList(j,j+1); s = (s - + style.getCitationMarker(cEntries, + + style.getCitationMarker(cEntries, // single entry entries, cg.itcType == OOBibBase.AUTHORYEAR_PAR, uniqueLetterForCitedEntry2, + // firstLimAuthors2: firstLimAuthors[j] == + // maxAuthorsFirst or (-1) to use maxAuthors firstLimAuthors2, pageInfo)); } else { @@ -1125,7 +1127,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes entries, cg.itcType == OOBibBase.AUTHORYEAR_PAR, uniqueLetterForCitedEntry, - firstLimAuthors, + firstLimAuthors, // maxAuthorsFirst or (-1) pageInfosForCitations); citMarkers.put(cgid, citMarker); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 01fab0755e3..19700fba974 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -257,7 +257,11 @@ private static Optional getRawCitationMarkerField(BibEntry entr * FieldFactory.serializeOrFields(StandardField.AUTHOR, * StandardField.EDITOR) * - * @return The resolved field content, or an empty string if the field(s) were empty. + * @return The resolved field content, or an empty string if the + * field(s) were empty. + * + * + * */ private static String getCitationMarkerField(OOBibStyle style, BibEntry entry, @@ -297,7 +301,9 @@ private static String getCitationMarkerField(OOBibStyle style, * @param database A map of BibEntry-BibDatabase pairs. * @param uniquifiers Optional parameter to separate similar citations. * Elements can be null if not needed. + * * @return The formatted citation. + * */ private static String getAuthorYearParenthesisMarker(OOBibStyle style, List entries, @@ -379,9 +385,9 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, * ? unlimAuthors[j] * : maxA ) */ - int maxAuthors = (( (unlimAuthors != null) && (unlimAuthors[j] > 0) ) + int maxAuthors = (((unlimAuthors != null) && (unlimAuthors[j] > 0)) ? unlimAuthors[j] - : maxA ); + : maxA); String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorFieldNames); String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); @@ -557,7 +563,7 @@ private static void group(OOBibStyle style, * entries, * cg.itcType == OOBibBase.AUTHORYEAR_PAR, * uniqueLetterForCitedEntry2, - * firstLimAuthors2, + * firstLimAuthors2, // entry for a single citation * pageInfo); * // when there are no unresolved entries * String citMarker = style.getCitationMarker(cEntries, From 75e78961ba8332b889049f71bbef0a209e5bbc20 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 7 Apr 2021 17:40:40 +0200 Subject: [PATCH 0562/1068] reorganize calculation of andString --- .../logic/openoffice/OOBibStyleGetCitationMarker.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 19700fba974..43318baef48 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -344,12 +344,10 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, // The String to add between the two last author names, e.g. " & ". String andString = (inParenthesis ? style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR) - : style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT)); - - if (!inParenthesis && andString == null) { - // Use the default one if no explicit separator for text is defined - andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); - } + : Objects.requireNonNullElse( + style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT), + // Use the default one if no explicit separator for text is defined + style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR))); StringBuilder sb = new StringBuilder(); if (inParenthesis) { From 7caeabfdcce74447dffdec882a9d00cf2a79ffb7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 8 Apr 2021 22:44:33 +0200 Subject: [PATCH 0563/1068] Add interface CitationMarkerEntry, for getCitationMarker --- .../logic/openoffice/CitationMarkerEntry.java | 54 +++++++++ .../openoffice/CitationMarkerEntryImpl.java | 107 ++++++++++++++++++ 2 files changed, 161 insertions(+) create mode 100644 src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java create mode 100644 src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java new file mode 100644 index 00000000000..1e5f39c0380 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java @@ -0,0 +1,54 @@ +package org.jabref.logic.openoffice; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.function.ToIntFunction; +import java.util.regex.Pattern; + +import org.jabref.logic.layout.Layout; +import org.jabref.logic.layout.LayoutFormatter; +import org.jabref.logic.layout.LayoutFormatterPreferences; +import org.jabref.logic.layout.LayoutHelper; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.Author; +import org.jabref.model.entry.AuthorList; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; +import org.jabref.model.entry.field.FieldFactory; +import org.jabref.model.entry.field.OrFields; +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.strings.StringUtil; + + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public interface CitationMarkerEntry { + String getCitationKey(); + BibEntry getBibEntryOrNull(); + BibDatabase getDatabaseOrNull(); + String getUniqueLetterOrNull(); + String getPageInfoOrNull(); + boolean getIsFirstAppearanceOfSource(); +}; + diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java new file mode 100644 index 00000000000..4d75a3b20c1 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java @@ -0,0 +1,107 @@ +package org.jabref.logic.openoffice; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.function.ToIntFunction; +import java.util.regex.Pattern; + +import org.jabref.logic.layout.Layout; +import org.jabref.logic.layout.LayoutFormatter; +import org.jabref.logic.layout.LayoutFormatterPreferences; +import org.jabref.logic.layout.LayoutHelper; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.Author; +import org.jabref.model.entry.AuthorList; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; +import org.jabref.model.entry.field.FieldFactory; +import org.jabref.model.entry.field.OrFields; +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.strings.StringUtil; + + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CitationMarkerEntryImpl implements CitationMarkerEntry { + final String citationKey; + final BibEntry bibEntry; // should allow null + final BibDatabase database; // should allow null + final String uniqueLetter; // may be null + final String pageInfo; // null for empty + final boolean isFirstAppearanceOfSource; + + public CitationMarkerEntryImpl(String citationKey, + BibEntry bibEntry, + BibDatabase database, + String uniqueLetter, + String pageInfo, + boolean isFirstAppearanceOfSource) { + this.citationKey = citationKey; + + if (bibEntry == null && database != null) { + throw new RuntimeException("CitationMarkerEntryImpl:" + + " bibEntry == null, but database != null"); + } + if (bibEntry != null && database == null) { + throw new RuntimeException("CitationMarkerEntryImpl:" + + " bibEntry != null, but database == null"); + } + + this.bibEntry = bibEntry; + this.database = database; + this.uniqueLetter = uniqueLetter; + this.pageInfo = pageInfo; + this.isFirstAppearanceOfSource = isFirstAppearanceOfSource; + } + + @Override + public String getCitationKey() { + return citationKey; + } + + @Override + public BibEntry getBibEntryOrNull() { + return bibEntry; + } + + @Override + public BibDatabase getDatabaseOrNull() { + return database; + } + + @Override + public String getUniqueLetterOrNull() { + return uniqueLetter; + } + + @Override + public String getPageInfoOrNull() { + return pageInfo; + } + + @Override + public boolean getIsFirstAppearanceOfSource() { + return isFirstAppearanceOfSource; + } +} From 83bfd33bad98363c0437b8aaf15678ada60d726f Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 8 Apr 2021 23:53:24 +0200 Subject: [PATCH 0564/1068] refactor: getCitationMarker revised now uses CitationMarkerEntry --- .../org/jabref/gui/openoffice/OOBibBase.java | 1026 +++++++---------- .../jabref/logic/openoffice/OOBibStyle.java | 355 ++++-- .../OOBibStyleGetCitationMarker.java | 739 ++++++------ .../OOBibStyleGetNumCitationMarker.java | 12 +- .../logic/openoffice/OOBibStyleTest.java | 642 +++++++---- 5 files changed, 1506 insertions(+), 1268 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2a111f0bf1e..42a8d026776 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -33,6 +33,8 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; import org.jabref.logic.openoffice.CitationEntry; +import org.jabref.logic.openoffice.CitationMarkerEntry; +import org.jabref.logic.openoffice.CitationMarkerEntryImpl; import org.jabref.logic.openoffice.OOBibStyle; import org.jabref.logic.openoffice.OOPreFormatter; import org.jabref.logic.openoffice.OOUtil; @@ -77,7 +79,6 @@ import com.sun.star.lang.XServiceInfo; import com.sun.star.text.ReferenceFieldSource; import com.sun.star.text.ReferenceFieldPart; -// import com.sun.star.text.TextRanges; import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XFootnote; import com.sun.star.text.XReferenceMarksSupplier; @@ -91,8 +92,6 @@ import com.sun.star.text.XTextSectionsSupplier; import com.sun.star.text.XTextViewCursor; import com.sun.star.text.XTextViewCursorSupplier; -//import com.sun.star.text.textfield.GetReference; -//import com.sun.star.text.GetReference; import com.sun.star.uno.Any; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; @@ -178,25 +177,6 @@ class OOBibBase { CreationException { this.dialogService = dialogService; - - /* - FieldComparator a = new FieldComparator(StandardField.AUTHOR); - FieldComparator y = new FieldComparator(StandardField.YEAR); - FieldComparator t = new FieldComparator(StandardField.TITLE); - - List> ayt = new ArrayList<>(3); - ayt.add(a); - ayt.add(y); - ayt.add(t); - this.entryComparator = new FieldComparatorStack<>(ayt); - - List> yat = new ArrayList<>(3); - yat.add(y); - yat.add(a); - yat.add(t); - this.yearAuthorTitleComparator = new FieldComparatorStack<>(yat); - */ - this.xDesktop = simpleBootstrap(loPath); } @@ -770,22 +750,16 @@ private String normalizedCitationMarkerForNormalStyle(CitedKey ck, if (ck.db.isEmpty()){ return String.format("(Unresolved(%s))", ck.citationKey); } - BibEntry ce = ck.db.get().entry; - Map entries = new HashMap<>(); - entries.put( ce, ck.db.get().database ); // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: // createNormalizedCitationMarker - return style.getCitationMarker(Collections.singletonList(ce), // List - entries, // Map - true, // inParenthesis - null, // uniqueLetters - // No limit on authors? - // TODO: Seems wrong: the actual markers - // may be shorter, with more clashes - // than we test here. - new int[] {-1}, /* no limit on authors */ - null /*pageInfosForCitations*/); + CitationMarkerEntry ce = new CitationMarkerEntryImpl(ck.citationKey, + ck.db.get().entry, + ck.db.get().database, + null, // uniqueLetter + null, // pageInfo + false /* isFirstAppearanceOfSource */); + return style.getNormalizedCitationMarker(ce); } /** @@ -951,7 +925,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes cgs.createNumberedBibliographySortedInOrderOfAppearance(); - final int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + final int minGroupingCount = style.getMinimumGroupingCount(); Map citMarkers = new HashMap<>(); @@ -980,8 +954,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes cgs.createNumberedBibliographySortedByComparator( entryComparator ); - final int minGroupingCount = - style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + final int minGroupingCount = style.getMinimumGroupingCount(); Map citMarkers = new HashMap<>(); @@ -1026,7 +999,8 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes // Finally, go through all citation markers, and update // those referring to entries in our current list: - final int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); + final int maxAuthorsFirst = style.getMaxAuthorsFirst(); + Set seenBefore = new HashSet<>(); Map citMarkers = new HashMap<>(); @@ -1035,100 +1009,69 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List cits = cg.getSortedCitations(); final int nCitedEntries = cits.size(); - int[] firstLimAuthors = new int[nCitedEntries]; - String[] uniqueLetterForCitedEntry = new String[nCitedEntries]; - - for (int j = 0; j < nCitedEntries; j++) { - String currentKey = cits.get(j).citationKey; // nullable - - // firstLimAuthors will be (-1) except at the first - // refMark it appears at, where a positive - // maxAuthorsFirst may override. This is why: - // https://discourse.jabref.org/t/ - // number-of-authors-in-citations-style-libreoffice/747/3 - // "Some citation styles require to list the full - // names of the first 4 authors for the first - // time. Later it is sufficient to have only maybe - // (Author A and Author B 2019 et al.)" - firstLimAuthors[j] = -1; - if (maxAuthorsFirst > 0) { - if (!seenBefore.contains(currentKey)) { - firstLimAuthors[j] = maxAuthorsFirst; - } - seenBefore.add(currentKey); - } + List pageInfosForCitations = cgs.backend.getPageInfosForCitations(cg); - String uniqueLetterForKey = cits.get(j).uniqueLetter.orElse(""); - uniqueLetterForCitedEntry[j] = uniqueLetterForKey; - } + List citationMarkerEntries = new ArrayList<>(nCitedEntries); - // TODO: Cannot pass unresolved keys to style.getCitationMarker - // fall back to ungrouped citations if there is - // any unresolved. boolean hasUnresolved = false; for (int j = 0; j < nCitedEntries; j++) { - //String currentKey = cits.get(j).citationKey; - if (cits.get(j).db.isEmpty()) { + Citation cit = cits.get(j); + String currentKey = cit.citationKey; // nullable + boolean isFirst = false; + if (!seenBefore.contains(currentKey)) { + isFirst = true; + seenBefore.add(currentKey); + } + String uniqueLetterForKey = cit.uniqueLetter.orElse(null); + BibDatabase database = null; + BibEntry bibEntry = null; + if (cit.db.isEmpty()) { hasUnresolved = true; - break; + } else { + database = cit.db.get().database; + bibEntry = cit.db.get().entry; } + + CitationMarkerEntry cm = + new CitationMarkerEntryImpl(currentKey, + bibEntry, + database, + uniqueLetterForKey, + pageInfosForCitations.get(j), + isFirst); + citationMarkerEntries.add(cm); } - List pageInfosForCitations = cgs.backend.getPageInfosForCitations(cg); + // TODO: Now we can pass CitationMarkerEntry values with unresolved + // keys to style.getCitationMarker, + // maybe the fall back to ungrouped citations here is + // not needed anymore. + if ( hasUnresolved ) { /* * Some entries are unresolved. */ String s = ""; for (int j = 0; j < nCitedEntries; j++) { - List cEntries = new ArrayList<>(); - Map entries = new HashMap<>(); - int[] firstLimAuthors2 = new int[1]; - String[] uniqueLetterForCitedEntry2 = new String[1]; - - String currentKey = cits.get(j).citationKey; - if (!cits.get(j).db.isEmpty()) { - BibEntry e = cits.get(j).db.get().entry; - BibDatabase d = cits.get(j).db.get().database; - cEntries.add(e); - entries.put(e,d); - firstLimAuthors2[0] = firstLimAuthors[j]; - uniqueLetterForCitedEntry2[0] = uniqueLetterForCitedEntry[j]; - List pageInfo = pageInfosForCitations.subList(j,j+1); + + CitationMarkerEntry cm = citationMarkerEntries.get(j); + if (cm.getBibEntryOrNull() == null) { s = (s - + style.getCitationMarker(cEntries, // single entry - entries, + + style.getCitationMarker(citationMarkerEntries.subList(j,j+1), cg.itcType == OOBibBase.AUTHORYEAR_PAR, - uniqueLetterForCitedEntry2, - // firstLimAuthors2: firstLimAuthors[j] == - // maxAuthorsFirst or (-1) to use maxAuthors - firstLimAuthors2, - pageInfo)); + OOBibStyle.NonUniqueCitationMarker.THROWS)); } else { - s = s + String.format("(Unresolved(%s))", currentKey); + s = s + String.format("(Unresolved(%s))", cm.getCitationKey()); } } - citMarkers.put( cgid, s ); + citMarkers.put(cgid, s); } else { /* * All entries are resolved. */ - List cEntries = new ArrayList<>(); - Map entries = new HashMap<>(); - for (int j = 0; j < nCitedEntries; j++) { - // String currentKey = cits.get(j).citationKey - BibEntry e = cits.get(j).db.get().entry; - BibDatabase d = cits.get(j).db.get().database; - cEntries.add(e); - entries.put(e,d); - } - - String citMarker = style.getCitationMarker(cEntries, - entries, + String citMarker = style.getCitationMarker(citationMarkerEntries, cg.itcType == OOBibBase.AUTHORYEAR_PAR, - uniqueLetterForCitedEntry, - firstLimAuthors, // maxAuthorsFirst or (-1) - pageInfosForCitations); + OOBibStyle.NonUniqueCitationMarker.THROWS); citMarkers.put(cgid, citMarker); } } @@ -1157,19 +1100,9 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti Objects.requireNonNull(citationText); Objects.requireNonNull(style); - // TODO: Last minute editing: If there is "page info" for this - // citation mark, we should inject it into the citation marker - // when creating. - - String citText; - Optional pageInfo = cgs.getPageInfo(cgid); - citText = ((pageInfo.isEmpty() || pageInfo.get().equals("")) - ? citationText - : style.insertPageInfo(citationText, pageInfo.get())); - if (withText) { // setString: All styles are removed when applying this method. - cursor.setString(citText); + cursor.setString(citationText); DocumentConnection.setCharLocaleNone(cursor); if (style.isFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); @@ -1187,10 +1120,10 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti if (italicize) { String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); Objects.requireNonNull(etAlString); - Objects.requireNonNull(citText); - for (int index = citText.indexOf(etAlString); + Objects.requireNonNull(citationText); + for (int index = citationText.indexOf(etAlString); index >= 0; - index = citText.indexOf(etAlString, index + 1)) { + index = citationText.indexOf(etAlString, index + 1)) { italicizeRangeFromPosition(cursor, index, index + etAlString.length()); } } @@ -1447,6 +1380,7 @@ public void insertCitation(List entries, + Localization.lang("Select some before citing.") ); } + final int nEntries = entries.size(); DocumentConnection documentConnection = getDocumentConnectionOrThrow(); CitationGroups cgs = new CitationGroups(documentConnection); @@ -1485,12 +1419,6 @@ public void insertCitation(List entries, // sortBibEntryListForMulticite(entries, style); - /* - * String keyString = - * entries.stream() - * .map(entry -> entry.getCitationKey().orElse("")) - * .collect(Collectors.joining(",")); - */ List citationKeys = entries.stream() .map(OOBibBase::insertCitationGetCitationKey) @@ -1502,7 +1430,7 @@ public void insertCitation(List entries, // If we should store metadata for page info, do that now: // // Note: the (single) pageInfo here gets associated with - // the citation group. At presentation it is inject + // the citation group. At presentation it is injected // to before the final parenthesis, appearing to // belong to the last entry added here. // @@ -1525,87 +1453,87 @@ public void insertCitation(List entries, assertCitationCharacterFormatIsOK(cursor, style); // Insert reference mark and text - // { - // Create a BibEntry to BibDatabase map (to make - // style.getCitationMarker happy?) - Map databaseMap = new HashMap<>(); - for (BibEntry entry : entries) { - // Using the same database for each entry. - // Probably the GUI limits selection to a single database. - databaseMap.put(entry, database); - } - // JabRef53 style pageInfo list, or null - List pageInfosForCitations = - Backend52.fakePageInfosForCitations(pageInfo, - entries.size(), - true /* mayReturnNull */); - - // The text we insert - String citeText = (style.isNumberEntries() - ? "[-]" // A dash only. Only refresh later. - : style.getCitationMarker(entries, - databaseMap, - inParenthesis, - null, // uniqueLetters - null, // unlimAuthors - pageInfosForCitations)); - - if (citeText.equals("")) { - citeText = "[?]"; - } + // JabRef53 style pageInfo list, or null + List pageInfosForCitations = + Backend52.fakePageInfosForCitations(pageInfo, + nEntries, + false /* mayReturnNull */); + // Make it non-null, with a (possibly null) entry for each + // pageInfosForCitations = OOBibStyle.regularizePageInfosForCitations(pageInfosForCitations); + + List citationMarkerEntries = new ArrayList<>(entries.size()); + for (int i = 0; i < nEntries; i++) { + // Using the same database for each entry. + // Probably the GUI limits selection to a single database. + CitationMarkerEntry cm = + new CitationMarkerEntryImpl(citationKeys.get(i), + entries.get(i), + database, + null, // uniqueLetter + pageInfosForCitations.get(i), + false /* isFirstAppearanceOfSource */); + citationMarkerEntries.add(cm); + } - insertReferenceMark(cgs, - documentConnection, - citationKeys, - pageInfosForCitations, - itcType, - citeText, - cursor, - withText, - style, - true /* insertSpaceAfter */); - // } // end of scope for databaseMap, citeText - - // Move to the right of the space and remember this - // position: we will come back here in the end. - // cursor.collapseToEnd(); - // cursor.goRight((short) 1, false); - XTextRange position = cursor.getEnd(); - - if (sync) { - // To account for numbering and for uniqueLetters, we - // must refresh the cite markers: - ProduceCitationMarkersResult x = produceCitationMarkers(documentConnection, - allBases, - style); - try { - documentConnection.lockControllers(); - applyNewCitationMarkers(documentConnection, - x.cgs, - x.citMarkers, - style); - // Insert it at the current position: - rebuildBibTextSection(documentConnection, - style, - x.cgs, - x.getBibliography()); - } finally { - documentConnection.unlockControllers(); - } + // The text we insert + String citeText = (style.isNumberEntries() + ? "[-]" // A dash only. Only refresh later. + : style.getCitationMarker(citationMarkerEntries, + inParenthesis, + OOBibStyle.NonUniqueCitationMarker.FORGIVEN)); - /* - * Problem: insertEntry in bibliography - * Reference is destroyed when we want to get there. - */ - // Go back to the relevant position: - try { - cursor.gotoRange(position, false); - } catch (com.sun.star.uno.RuntimeException ex) { - LOGGER.warn("OOBibBase.insertEntry:" - + " Could not go back to end of in-text citation", ex); - } + if (citeText.equals("")) { + citeText = "[?]"; + } + + insertReferenceMark(cgs, + documentConnection, + citationKeys, + pageInfosForCitations, + itcType, + citeText, + cursor, + withText, + style, + true /* insertSpaceAfter */); + + // Remember this position: we will come back here in the + // end. + XTextRange position = cursor.getEnd(); + + if (sync) { + // To account for numbering and for uniqueLetters, we + // must refresh the cite markers: + ProduceCitationMarkersResult x = + produceCitationMarkers(documentConnection, allBases, style); + try { + documentConnection.lockControllers(); + applyNewCitationMarkers(documentConnection, + x.cgs, + x.citMarkers, + style); + // Insert it at the current position: + rebuildBibTextSection(documentConnection, + style, + x.cgs, + x.getBibliography()); + } finally { + documentConnection.unlockControllers(); } + + /* + * Problem: insertEntry in bibliography + * Reference is destroyed when we want to get there. + */ + // Go back to the relevant position: + try { + cursor.gotoRange(position, false); + } catch (com.sun.star.uno.RuntimeException ex) { + LOGGER.warn("OOBibBase.insertEntry:" + + " Could not go back to end of in-text citation", ex); + } + } } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference @@ -1654,13 +1582,6 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, WrappedTargetException, PropertyVetoException { - // CitationGroupsV001 cgs = new CitationGroupsV001(documentConnection); - // CitationGroupsV001 cgs = x.cgs; - - // final int nRefMarks = referenceMarkNames.size(); - // assert (citMarkers.length == nRefMarks); - // assert (types.length == nRefMarks); - final boolean hadBibSection = (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) != null); @@ -1711,9 +1632,8 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { // Overwriting text already there is too harsh. // I am making it an error, to see if we ever get here. - throw new RuntimeException( - "OOBibBase.applyNewCitationMarkers:" - + " just overwrote the bibliography section marker. Sorry."); + throw new RuntimeException("OOBibBase.applyNewCitationMarkers:" + + " just overwrote the bibliography section marker. Sorry."); } } } @@ -1733,16 +1653,16 @@ static class ProduceCitationMarkersResult { this.cgs = cgs; this.citMarkers = citMarkers; if ( cgs.getBibliography().isEmpty() ) { - throw new RuntimeException( - "ProduceCitationMarkersResult.constructor: cgs does not have a bibliography"); + throw new RuntimeException("ProduceCitationMarkersResult.constructor:" + + " cgs does not have a bibliography"); } } public CitedKeys getBibliography() { if ( cgs.getBibliography().isEmpty() ) { - throw new RuntimeException( - "ProduceCitationMarkersResult.getBibliography: cgs does not have a bibliography"); + throw new RuntimeException("ProduceCitationMarkersResult.getBibliography:" + + " cgs does not have a bibliography"); } return cgs.getBibliography().get(); } @@ -1751,7 +1671,7 @@ public List getUnresolvedKeys() { CitedKeys bib = getBibliography(); List unresolvedKeys = new ArrayList<>(); for (CitedKey ck : bib.values()) { - if ( ck.db.isEmpty() ) { + if (ck.db.isEmpty()) { unresolvedKeys.add(ck.citationKey); } } @@ -1801,25 +1721,21 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d } // localOrder and globalOrder together gives us order-of-appearance of citations - // citMarkers[i] = what goes in the text at referenceMark[i] - // String[] citMarkers; Map citMarkers; // fill citMarkers Map uniqueLetters = new HashMap<>(); if (style.isCitationKeyCiteMarkers()) { - citMarkers = - produceCitationMarkersForIsCitationKeyCiteMarkers(cgs, style); + citMarkers = produceCitationMarkersForIsCitationKeyCiteMarkers(cgs, style); } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { - citMarkers = - produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); + citMarkers = produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); } else { - citMarkers = - produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); + citMarkers = produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); } - } else /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ { + } else { + /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ citMarkers = produceCitationMarkersForNormalStyle(cgs, style); } @@ -1893,7 +1809,6 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, style); } - /** * Insert body of bibliography at `cursor`. * @@ -1922,22 +1837,6 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, final boolean debugThisFun = false; - /* - * Map entries; - * - * if (style.isSortByPosition()) { - * // We need to sort the entries according to their order of appearance: - * entries = - * sortEntriesByRefMarkNames( - * jabRefReferenceMarkNamesSortedByPosition, - * fce.citeKeyToBibEntry, - * fce.entries - * ); - * } else { - * entries = sortEntriesByComparator(fce.entries, entryComparator); - * } - */ - if (debugThisFun) { System.out.printf("Ref isSortByPosition %s\n", style.isSortByPosition()); System.out.printf("Ref isNumberEntries %s\n", style.isNumberEntries()); @@ -1945,7 +1844,6 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, for (CitedKey ck : bibliography.values()) { - if (debugThisFun) { System.out.printf("Ref cit %-20s ck.number %7s%n", String.format("'%s'",ck.citationKey), @@ -1964,12 +1862,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, "insertFullReferenceAtCursor: numbered style, but found unnumbered entry"); } - // Note: minGroupingCount is pointless here, we are - // formatting a single entry. - // int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); - // int minGroupingCount = 2; int number = ck.number.get(); - // List pageInfosForCitations = null; // no pageInfo for the bibliography String marker = style.getNumCitationMarkerForBibliography(number); OOUtil.insertTextAtCurrentLocation(documentConnection.xText, @@ -1982,7 +1875,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, } if ( ck.db.isEmpty() ) { - // skip unresolved entries + // Unresolved entry OOUtil.insertTextAtCurrentLocation(documentConnection.xText, cursor, String.format("Unresolved(%s)", ck.citationKey), @@ -2020,22 +1913,21 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, ")", Collections.emptyList()); } - } else { + } else { + // Resolved entry BibEntry bibentry = ck.db.get().entry; // insert the actual details. Layout layout = style.getReferenceFormat(bibentry.getType()); layout.setPostFormatter(POSTFORMATTER); - OOUtil.insertFullReferenceAtCurrentLocation( - documentConnection.xText, - cursor, - layout, - parFormat, - bibentry, - ck.db.get().database, - ck.uniqueLetter.orElse(null) - ); + OOUtil.insertFullReferenceAtCurrentLocation(documentConnection.xText, + cursor, + layout, + parFormat, + bibentry, + ck.db.get().database, + ck.uniqueLetter.orElse(null)); } } } @@ -2057,11 +1949,9 @@ private void createBibTextSection2(DocumentConnection documentConnection) OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); - documentConnection.insertTextSection( - OOBibBase.BIB_SECTION_NAME, - textCursor, - false - ); + documentConnection.insertTextSection(OOBibBase.BIB_SECTION_NAME, + textCursor, + false); } /** @@ -2088,8 +1978,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) XTextSection section = (XTextSection) a.getObject(); // Clear it: - XTextCursor cursor = - documentConnection.xText.createTextCursorByRange(section.getAnchor()); + XTextCursor cursor = documentConnection.xText.createTextCursorByRange(section.getAnchor()); cursor.gotoRange(section.getAnchor(), false); cursor.setString(""); @@ -2128,35 +2017,24 @@ private void populateBibTextSection(DocumentConnection documentConnection, XTextSection section = documentConnection.getTextSectionByName(OOBibBase.BIB_SECTION_NAME); - XTextCursor cursor = - documentConnection.xText - .createTextCursorByRange(section.getAnchor()); - - OOUtil.insertTextAtCurrentLocation( - documentConnection.xText, - cursor, - (String) style.getProperty(OOBibStyle.TITLE), - (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT) - ); - - String refParaFormat = - (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); - - insertFullReferenceAtCursor( - documentConnection, - cursor, - cgs, - bibliography, - // entries, - style, - refParaFormat - // uniqueLetters - ); - - documentConnection.insertBookmark( - OOBibBase.BIB_SECTION_END_NAME, - cursor, - true); + XTextCursor cursor = (documentConnection.xText + .createTextCursorByRange(section.getAnchor())); + + OOUtil.insertTextAtCurrentLocation(documentConnection.xText, + cursor, + style.getTitle(), + style.getReferenceHeaderParagraphFormat()); + + insertFullReferenceAtCursor(documentConnection, + cursor, + cgs, + bibliography, + style, + style.getReferenceParagraphFormat()); + + documentConnection.insertBookmark(OOBibBase.BIB_SECTION_END_NAME, + cursor, + true); cursor.collapseToEnd(); } @@ -2207,326 +2085,319 @@ public void combineCiteMarkers(List databases, boolean madeModifications = false; - - List - referenceMarkNames = + List referenceMarkNames = cgs.getCitationGroupIDsSortedWithinPartitions(documentConnection, false /* mapFootnotesToFootnoteMarks */); final int nRefMarks = referenceMarkNames.size(); - try { + try { - if (useLockControllers) { - documentConnection.lockControllers(); - } + if (useLockControllers) { + documentConnection.lockControllers(); + } - /* - * joinableGroups collects lists of CitationGroup values - * that we think are joinable. - * - * joinableGroupsCursors provides the range for each group - */ - List> joinableGroups = new ArrayList<>(); - List joinableGroupsCursors = new ArrayList<>(); - - // Since we only join groups with identical itcTypes, we - // can get itcType from the first element of each - // joinableGroup. - // - // List itcTypes = new ArrayList<>(); + /* + * joinableGroups collects lists of CitationGroup values + * that we think are joinable. + * + * joinableGroupsCursors provides the range for each group + */ + List> joinableGroups = new ArrayList<>(); + List joinableGroupsCursors = new ArrayList<>(); - if (referenceMarkNames.size() > 0) { - // current group of CitationGroup values - List currentGroup = new ArrayList<>(); - XTextCursor currentGroupCursor = null; - XTextCursor cursorBetween = null; - CitationGroup prev = null; - XTextRange prevRange = null; + // Since we only join groups with identical itcTypes, we + // can get itcType from the first element of each + // joinableGroup. + // + // List itcTypes = new ArrayList<>(); - for (CitationGroupID cgid : referenceMarkNames) { - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + if (referenceMarkNames.size() > 0) { + // current group of CitationGroup values + List currentGroup = new ArrayList<>(); + XTextCursor currentGroupCursor = null; + XTextCursor cursorBetween = null; + CitationGroup prev = null; + XTextRange prevRange = null; - XTextRange currentRange = cgs.getMarkRangeOrNull(documentConnection, cgid); - Objects.requireNonNull(currentRange); + for (CitationGroupID cgid : referenceMarkNames) { + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - boolean addToGroup = true; - /* - * Decide if we add cg to the group - */ + XTextRange currentRange = cgs.getMarkRangeOrNull(documentConnection, cgid); + Objects.requireNonNull(currentRange); - // Only combine (Author 2000) type citations - if (cg.itcType != OOBibBase.AUTHORYEAR_PAR - // allow "Author (2000)" - // && itcTypes[i] != OOBibBase.AUTHORYEAR_INTEXT - ) { - addToGroup = false; - } + boolean addToGroup = true; + /* + * Decide if we add cg to the group + */ - // Even if we combine AUTHORYEAR_INTEXT citations, we - // would not mix them with AUTHORYEAR_PAR - if (addToGroup && (prev != null)) { - if (cg.itcType != prev.itcType) { + // Only combine (Author 2000) type citations + if (cg.itcType != OOBibBase.AUTHORYEAR_PAR + // allow "Author (2000)" + // && itcTypes[i] != OOBibBase.AUTHORYEAR_INTEXT + ) { addToGroup = false; } - } - if (addToGroup && prev != null) { - Objects.requireNonNull(prevRange); - Objects.requireNonNull(currentRange); - if (!DocumentConnection.comparableRanges(prevRange, currentRange)) { + // Even if we combine AUTHORYEAR_INTEXT citations, we + // would not mix them with AUTHORYEAR_PAR + if (addToGroup && (prev != null)) { + if (cg.itcType != prev.itcType) { addToGroup = false; - } else { - - int textOrder = - DocumentConnection.javaCompareRegionStarts( - prevRange, - currentRange); - - if (textOrder != (-1)) { - String msg = String.format( - "combineCiteMarkers: \"%s\" supposed to be followed by \"%s\", but %s", - prevRange.getString(), - currentRange.getString(), - ((textOrder == 0) - ? "they start at the same position" - : "the start of the latter precedes the start of the first") - ); - LOGGER.warn(msg); - addToGroup = false; } } - } - if (addToGroup && (cursorBetween != null)) { - Objects.requireNonNull(currentGroupCursor); - // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() - if (DocumentConnection.javaCompareRegionEnds( - cursorBetween, currentGroupCursor) != 0) { - throw new RuntimeException( - "combineCiteMarkers: cursorBetween.end != currentGroupCursor.end"); + if (addToGroup && prev != null) { + Objects.requireNonNull(prevRange); + Objects.requireNonNull(currentRange); + if (!DocumentConnection.comparableRanges(prevRange, currentRange)) { + addToGroup = false; + } else { + + int textOrder = + DocumentConnection.javaCompareRegionStarts(prevRange, + currentRange); + + if (textOrder != (-1)) { + String msg = String.format( + "combineCiteMarkers:" + + " \"%s\" supposed to be followed by \"%s\", but %s", + prevRange.getString(), + currentRange.getString(), + ((textOrder == 0) + ? "they start at the same position" + : "the start of the latter precedes the start of the first")); + LOGGER.warn(msg); + addToGroup = false; + } + } } - XTextRange rangeStart = currentRange.getStart(); - - boolean couldExpand = true; - XTextCursor thisCharCursor = - currentRange.getText() - .createTextCursorByRange(cursorBetween.getEnd()); - while (couldExpand && - (DocumentConnection.javaCompareRegionEnds( - cursorBetween, rangeStart) < 0)) { - couldExpand = cursorBetween.goRight((short) 1, true); - currentGroupCursor.goRight((short) 1, true); - // - thisCharCursor.goRight((short) 1, true); - String thisChar = thisCharCursor.getString(); - thisCharCursor.collapseToEnd(); - if (thisChar.isEmpty() - || thisChar.equals("\n") - || !thisChar.trim().isEmpty()) { - couldExpand = false; - } - if (DocumentConnection.javaCompareRegionEnds( - cursorBetween, currentGroupCursor) != 0) { + if (addToGroup && (cursorBetween != null)) { + Objects.requireNonNull(currentGroupCursor); + // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() + if (DocumentConnection + .javaCompareRegionEnds(cursorBetween, currentGroupCursor) != 0) { throw new RuntimeException( "combineCiteMarkers:" - + " cursorBetween.end != currentGroupCursor.end" - + " (during expand)"); + + " cursorBetween.end != currentGroupCursor.end"); } - } - if (!couldExpand) { - addToGroup = false; + XTextRange rangeStart = currentRange.getStart(); + + boolean couldExpand = true; + + XTextCursor thisCharCursor = + (currentRange.getText() + .createTextCursorByRange(cursorBetween.getEnd())); + + while (couldExpand && + (DocumentConnection + .javaCompareRegionEnds(cursorBetween, rangeStart) < 0)) { + couldExpand = cursorBetween.goRight((short) 1, true); + currentGroupCursor.goRight((short) 1, true); + // + thisCharCursor.goRight((short) 1, true); + String thisChar = thisCharCursor.getString(); + thisCharCursor.collapseToEnd(); + if (thisChar.isEmpty() + || thisChar.equals("\n") + || !thisChar.trim().isEmpty()) { + couldExpand = false; + } + if (DocumentConnection.javaCompareRegionEnds( + cursorBetween, currentGroupCursor) != 0) { + throw new RuntimeException( + "combineCiteMarkers:" + + " cursorBetween.end != currentGroupCursor.end" + + " (during expand)"); + } + } // while + + if (!couldExpand) { + addToGroup = false; + } } - } - /* - * Even if we do not add it to an existing group, - * we might use it to start a new group. - * - * Can it start a new group? - */ - boolean canStartGroup = (cg.itcType == OOBibBase.AUTHORYEAR_PAR); - - if (!addToGroup) { - // close currentGroup - if (currentGroup.size() > 1) { - joinableGroups.add(currentGroup); - joinableGroupsCursors.add(currentGroupCursor); + /* + * Even if we do not add it to an existing group, + * we might use it to start a new group. + * + * Can it start a new group? + */ + boolean canStartGroup = (cg.itcType == OOBibBase.AUTHORYEAR_PAR); + + if (!addToGroup) { + // close currentGroup + if (currentGroup.size() > 1) { + joinableGroups.add(currentGroup); + joinableGroupsCursors.add(currentGroupCursor); + } + // Start a new, empty group + currentGroup = new ArrayList<>(); + currentGroupCursor = null; + cursorBetween = null; + prev = null; + prevRange = null; } - // Start a new, empty group - currentGroup = new ArrayList<>(); - currentGroupCursor = null; - cursorBetween = null; - prev = null; - prevRange = null; - } - if (addToGroup || canStartGroup) { - // Add the current entry to a group. - currentGroup.add(cg); - // ... and start new cursorBetween - // Set up cursorBetween - // - XTextRange rangeEnd = currentRange.getEnd(); - cursorBetween = - currentRange.getText().createTextCursorByRange(rangeEnd); - // If new group, create currentGroupCursor - if (currentGroupCursor == null) { - currentGroupCursor = - currentRange.getText() - .createTextCursorByRange(currentRange.getStart()); - } - // include self in currentGroupCursor - currentGroupCursor.goRight( - (short) (currentRange.getString().length()), true); - - if (DocumentConnection.javaCompareRegionEnds( - cursorBetween, currentGroupCursor) != 0) { - /* - * A problem discovered using this check: - * when viewing the document in - * two-pages-side-by-side mode, our visual - * firstAppearanceOrder follows the visual - * ordering on the screen. The problem - * this caused: it sees a citation on the - * 2nd line of the 1st page as appearing - * after one at the 1st line of 2nd - * page. Since we create cursorBetween at - * the end of range1Full (on 1st page), it - * is now BEFORE currentGroupCursor (on - * 2nd page). - */ - throw new RuntimeException( - "combineCiteMarkers: " - + "cursorBetween.end != currentGroupCursor.end" - + String.format( - " (after %s)", addToGroup ? "addToGroup" : "startGroup") - + (addToGroup - ? String.format( - " comparisonResult: %d\n" - + "cursorBetween: '%s'\n" - + "currentRange: '%s'\n" - + "currentGroupCursor: '%s'\n", - DocumentConnection.javaCompareRegionEnds( - cursorBetween, currentGroupCursor), - cursorBetween.getString(), - currentRange.getString(), - currentGroupCursor.getString() - ) - : "") - ); + if (addToGroup || canStartGroup) { + // Add the current entry to a group. + currentGroup.add(cg); + // ... and start new cursorBetween + // Set up cursorBetween + // + XTextRange rangeEnd = currentRange.getEnd(); + cursorBetween = + currentRange.getText().createTextCursorByRange(rangeEnd); + // If new group, create currentGroupCursor + if (currentGroupCursor == null) { + currentGroupCursor = (currentRange.getText() + .createTextCursorByRange(currentRange.getStart())); + } + // include self in currentGroupCursor + currentGroupCursor.goRight((short) (currentRange.getString().length()), true); + + if (DocumentConnection + .javaCompareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + /* + * A problem discovered using this check: + * when viewing the document in + * two-pages-side-by-side mode, our visual + * firstAppearanceOrder follows the visual + * ordering on the screen. The problem + * this caused: it sees a citation on the + * 2nd line of the 1st page as appearing + * after one at the 1st line of 2nd + * page. Since we create cursorBetween at + * the end of range1Full (on 1st page), it + * is now BEFORE currentGroupCursor (on + * 2nd page). + */ + throw new RuntimeException( + "combineCiteMarkers: " + + "cursorBetween.end != currentGroupCursor.end" + + String.format(" (after %s)", + addToGroup ? "addToGroup" : "startGroup") + + (addToGroup + ? String.format(" comparisonResult: %d\n" + + "cursorBetween: '%s'\n" + + "currentRange: '%s'\n" + + "currentGroupCursor: '%s'\n", + DocumentConnection + .javaCompareRegionEnds(cursorBetween, + currentGroupCursor), + cursorBetween.getString(), + currentRange.getString(), + currentGroupCursor.getString()) + : "")); + } + prev = cg; + prevRange = currentRange; } - prev = cg; - prevRange = currentRange; + } // for cgid + + // close currentGroup + if (currentGroup.size() > 1) { + joinableGroups.add(currentGroup); + joinableGroupsCursors.add(currentGroupCursor); } - } + } // if (referenceMarkNames.size() > 0) - // close currentGroup - if (currentGroup.size() > 1) { - joinableGroups.add(currentGroup); - joinableGroupsCursors.add(currentGroupCursor); + if (joinableGroups.size() > 0) { + XTextCursor textCursor = joinableGroupsCursors.get(0); + assertCitationCharacterFormatIsOK(textCursor, style); } - } - - if (joinableGroups.size() > 0) { - XTextCursor textCursor = joinableGroupsCursors.get(0); - assertCitationCharacterFormatIsOK(textCursor, style); - } - /* - * Now we can process the joinable groups - */ - for (int gi = 0; gi < joinableGroups.size(); gi++) { - - List joinableGroup = joinableGroups.get(gi); /* - * Join those in joinableGroups.get(gi) + * Now we can process the joinable groups */ + for (int gi = 0; gi < joinableGroups.size(); gi++) { - // - // Note: we are taking ownership of the citations (by - // adding to newGroupCitations, then removing - // the original CitationGroup values) - // - // cgPageInfos currently belong to the CitationGroup, - // but it is not clear how should handle them here. - // - List newGroupCitations = new ArrayList<>(); - for (CitationGroup rk : joinableGroup) { - newGroupCitations.addAll(rk.citations); - } + List joinableGroup = joinableGroups.get(gi); + /* + * Join those in joinableGroups.get(gi) + */ - int itcType = joinableGroup.get(0).itcType; + // + // Note: we are taking ownership of the citations (by + // adding to newGroupCitations, then removing + // the original CitationGroup values) - List pageInfosForCitations = - cgs.backend.combinePageInfos(joinableGroup); + List newGroupCitations = new ArrayList<>(); + for (CitationGroup rk : joinableGroup) { + newGroupCitations.addAll(rk.citations); + } - // Remove the old citation groups from the document. - // We might want to do this via backends. - for (int gj = 0; gj < joinableGroup.size(); gj++) { - cgs.removeCitationGroups( joinableGroup, documentConnection ); - } + int itcType = joinableGroup.get(0).itcType; - XTextCursor textCursor = joinableGroupsCursors.get(gi); - // Also remove the spaces between. - textCursor.setString(""); - - List citationKeys = - newGroupCitations.stream() - .map(cit -> cit.citationKey) - .collect(Collectors.toList()); - - // Insert reference mark: - insertReferenceMark(cgs, - documentConnection, - citationKeys, - pageInfosForCitations, - itcType, // OOBibBase.AUTHORYEAR_PAR - "tmp", - textCursor, - true, // withText - style, - false /* insertSpaceAfter: no, it - * is already there (or - * could be) */); - } // for gi + // cgPageInfos belong to the CitationGroup (DataModel JabRef52), + // but it is not clear how should we handle them here. + // We delegate the problem to the backend. + List pageInfosForCitations = + cgs.backend.combinePageInfos(joinableGroup); - madeModifications = (joinableGroups.size() > 0); + // Remove the old citation groups from the document. + for (int gj = 0; gj < joinableGroup.size(); gj++) { + cgs.removeCitationGroups( joinableGroup, documentConnection ); + } - } finally { - if (useLockControllers) { - documentConnection.unlockControllers(); - } - } + XTextCursor textCursor = joinableGroupsCursors.get(gi); + // Also remove the spaces between. + textCursor.setString(""); + + List citationKeys = (newGroupCitations.stream() + .map(cit -> cit.citationKey) + .collect(Collectors.toList())); + + // Insert reference mark: + + /* insertSpaceAfter: no, it is already there (or could + * be) + */ + boolean insertSpaceAfter = false; + insertReferenceMark(cgs, + documentConnection, + citationKeys, + pageInfosForCitations, + itcType, // OOBibBase.AUTHORYEAR_PAR + "tmp", + textCursor, + true, // withText + style, + insertSpaceAfter); + } // for gi + + madeModifications = (joinableGroups.size() > 0); - if (madeModifications) { - ProduceCitationMarkersResult x = - produceCitationMarkers( - // cgs, - documentConnection, - databases, - style - ); - try { - if (useLockControllers) { - documentConnection.lockControllers(); - } - applyNewCitationMarkers(documentConnection, - x.cgs, - x.citMarkers, - style); } finally { if (useLockControllers) { documentConnection.unlockControllers(); } } - } + + if (madeModifications) { + ProduceCitationMarkersResult x = produceCitationMarkers(documentConnection, + databases, + style); + try { + if (useLockControllers) { + documentConnection.lockControllers(); + } + applyNewCitationMarkers(documentConnection, + x.cgs, + x.citMarkers, + style); + } finally { + if (useLockControllers) { + documentConnection.unlockControllers(); + } + } + } } finally { documentConnection.leaveUndoContext(); } - } + } // combineCiteMarkers /** * GUI action "Separate citations". @@ -2642,17 +2513,12 @@ public void unCombineCiteMarkers(List databases, if (madeModifications) { ProduceCitationMarkersResult x = - produceCitationMarkers(documentConnection, - databases, - style); + produceCitationMarkers(documentConnection, databases, style); try { if (useLockControllers) { documentConnection.lockControllers(); } - applyNewCitationMarkers(documentConnection, - x.cgs, - x.citMarkers, - style); + applyNewCitationMarkers(documentConnection, x.cgs, x.citMarkers, style); } finally { if (useLockControllers) { documentConnection.unlockControllers(); @@ -2779,12 +2645,10 @@ public ExportCitedHelperResult exportCitedHelper(List databases, void styleIsRequired(OOBibStyle style) throws JabRefException { if (style == null) { - throw new JabRefException( - "This operation requires a style", - Localization.lang("This operation requires a style.") - + "\n" - + Localization.lang("Please select one.") - ); + throw new JabRefException("This operation requires a style", + Localization.lang("This operation requires a style.") + + "\n" + + Localization.lang("Please select one.")); } } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index ec32d5e05e2..53ea336f8c3 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -73,8 +73,8 @@ */ public class OOBibStyle implements Comparable { - public static final String ITALIC_ET_AL = "ItalicEtAl"; - public static final String MULTI_CITE_CHRONOLOGICAL = "MultiCiteChronological"; + private static final String ITALIC_ET_AL = "ItalicEtAl"; + private static final String MULTI_CITE_CHRONOLOGICAL = "MultiCiteChronological"; public static final String MINIMUM_GROUPING_COUNT = "MinimumGroupingCount"; public static final String ET_AL_STRING = "EtAlString"; public static final String MAX_AUTHORS_FIRST = "MaxAuthorsFirst"; @@ -115,6 +115,7 @@ public class OOBibStyle implements Comparable { private static final String FORMAT_CITATIONS = "FormatCitations"; private static final String IS_NUMBER_ENTRIES = "IsNumberEntries"; private static final String IS_SORT_BY_POSITION = "IsSortByPosition"; + private static final String SORT_ALGORITHM = "SortAlgorithm"; private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); @@ -176,11 +177,17 @@ public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) throws private void setDefaultProperties() { // Set default property values: properties.put(TITLE, "Bibliography"); - properties.put(SORT_ALGORITHM, "alphanumeric"); + + /* TODO: unused */ properties.put(SORT_ALGORITHM, "alphanumeric"); + properties.put(IS_SORT_BY_POSITION, Boolean.FALSE); properties.put(IS_NUMBER_ENTRIES, Boolean.FALSE); - properties.put(BRACKET_BEFORE, "["); - properties.put(BRACKET_AFTER, "]"); + + // BRACKET_BEFORE and BRACKET_AFTER appears both in + // properties and citProperties + /* TODO: unused */ properties.put(BRACKET_BEFORE, "["); + /* TODO: unused */ properties.put(BRACKET_AFTER, "]"); + properties.put(REFERENCE_PARAGRAPH_FORMAT, "Default"); properties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1"); @@ -197,8 +204,10 @@ private void setDefaultProperties() { citProperties.put(ET_AL_STRING, " et al."); citProperties.put(YEAR_SEPARATOR, ", "); citProperties.put(IN_TEXT_YEAR_SEPARATOR, " "); + citProperties.put(BRACKET_BEFORE, "("); citProperties.put(BRACKET_AFTER, ")"); + citProperties.put(CITATION_SEPARATOR, "; "); citProperties.put(PAGE_INFO_SEPARATOR, "; "); citProperties.put(GROUPED_NUMBERS_SEPARATOR, "-"); @@ -401,60 +410,152 @@ public String getNumCitationMarkerForBibliography(int number) { number); } + public String getNormalizedCitationMarker(CitationMarkerEntry ce) { + return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this,ce, Optional.empty()); + } + + + /** + * What should getCitationMarker do if it discovers that + * uniqueLetters provided are not sufficient for unique presentation? + */ + public enum NonUniqueCitationMarker { + /** Give an insufficient representation anyway. */ + FORGIVEN, + /** Throw a RuntimeException */ + THROWS + } + /** - * Format the marker for the in-text citation according to this - * BIB style. Uniquefier letters are added as provided by the - * uniquefiers argument. If successive entries within the citation - * are uniquefied from each other, this method will perform a - * grouping of these entries. + * Format the marker for an the in-text citation according to + * this style. + * + * Uniquefier letters are added as provided by the + * CitationMarkerEntry.getUniqueLetterOrNull(). + * + * If successive entries within the citation are uniquefied from + * each other, this method will perform a grouping of these + * entries. + * + * @param citationMarkerEntries The list of entries providing the + * data. + * + * @param inParenthesis Signals whether a parenthesized citation + * or an in-text citation is wanted. + * + * @param nonUniqueCitationMarkerHandling + * + * THROWS : Should throw if finds that uniqueLetters + * provided do not make the entries unique. + * + * FORGIVEN : is needed to allow preliminary markers + * for freshly inserted citations without + * going throw the uniquification process. * - * @param entries The list of JabRef BibEntry providing the data. - * @param database A map of BibEntry-BibDatabase pairs. - * @param inParenthesis Signals whether a parenthesized citation or an in-text citation is wanted. - * @param uniquefiers Strings to add behind the year for each entry in case it's needed - * to separate similar entries. - * @param unlimAuthors Boolean for each entry. If true, we should not use "et al" formatting - * regardless of the number of authors. - * Can be null to indicate that no entries should have unlimited names. - * @param pageInfosForCitations Null for "none", or a list with - * pageInfo for each citation. These can be null as well. * @return The formatted citation. */ - public String getCitationMarker(List entries, - Map database, + public String getCitationMarker(List citationMarkerEntries, boolean inParenthesis, - String[] uniquefiers, - int[] unlimAuthors, - List pageInfosForCitations - ) { - - OOBibStyle style = this; - return OOBibStyleGetCitationMarker.getCitationMarker(style, - entries, - database, + NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { + return OOBibStyleGetCitationMarker.getCitationMarker(this, + citationMarkerEntries, inParenthesis, - uniquefiers, - unlimAuthors, - pageInfosForCitations); + nonUniqueCitationMarkerHandling); } /** - * Take a finished citation and insert a string at the end (but - * inside the end bracket) separated by "PageInfoSeparator" + * Indicate if it is an internal style * - * @param citation A formatted citation probably ending with BRACKET_AFTER. - * @param pageInfo Text to be inserted. - * @return The modified citation. + * @return True if an internal style */ - public String insertPageInfo(String citation, String pageInfo) { - String bracketAfter = getStringCitProperty(BRACKET_AFTER); - if (citation.endsWith(bracketAfter)) { - String first = citation.substring(0, citation.length() - bracketAfter.length()); - return first + getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo + bracketAfter; - } else { - return citation + getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo; + public boolean isInternalStyle() { + return fromResource; + } + + public String getLocalCopy() { + return localCopy; + } + + @Override + public int compareTo(OOBibStyle other) { + return getName().compareTo(other.getName()); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } + if (o instanceof OOBibStyle) { + OOBibStyle otherStyle = (OOBibStyle) o; + return Objects.equals(path, otherStyle.path) + && Objects.equals(name, otherStyle.name) + && Objects.equals(citProperties, otherStyle.citProperties) + && Objects.equals(properties, otherStyle.properties); + } + return false; + } + + @Override + public int hashCode() { + return Objects.hash(path, name, citProperties, properties); + } + + + /* + * + * Property getters + * + */ + + /** + * Get a style property. + * + * @param propName The property name. + * @return The property value, or null if it doesn't exist. + */ + private Object getProperty(String propName) { + return properties.get(propName); + } + + private boolean getBooleanProperty(String propName) { + return (Boolean) properties.get(propName); + } + + private String getStringProperty(String propName) { + return (String) properties.get(propName); + } + + private int getIntProperty(String key) { + return (Integer) properties.get(key); + } + + + /** + * Get boolean property. + * + * @param key The property key + * @return the value + */ + private boolean getBooleanCitProperty(String key) { + return (Boolean) citProperties.get(key); + } + + private int getIntCitProperty(String key) { + return (Integer) citProperties.get(key); + } + + public String getStringCitProperty(String key) { + return (String) citProperties.get(key); + } + + /** + * Minimal number of consecutive citation numbers needed to start + * replacing with an "i-j" range. + */ + public int getMinimumGroupingCount() { + return getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); } /** @@ -464,7 +565,7 @@ public String insertPageInfo(String citation, String pageInfo) { * @return true if we use numbered citations, false otherwise. */ public boolean isNumberEntries() { - return (Boolean) getProperty(IS_NUMBER_ENTRIES); + return getBooleanProperty(IS_NUMBER_ENTRIES); } /** @@ -474,7 +575,7 @@ public boolean isNumberEntries() { * @return true to sort by appearance, false to sort alphabetically. */ public boolean isSortByPosition() { - return (Boolean) getProperty(IS_SORT_BY_POSITION); + return getBooleanProperty(IS_SORT_BY_POSITION); } /** @@ -484,7 +585,7 @@ public boolean isSortByPosition() { * @return true to indicate that citations should be in italics. */ public boolean isItalicCitations() { - return (Boolean) citProperties.get(ITALIC_CITATIONS); + return getBooleanCitProperty(ITALIC_CITATIONS); } /** @@ -512,16 +613,6 @@ public boolean isCitationKeyCiteMarkers() { return (Boolean) citProperties.get(CITATION_KEY_CITATIONS); } - /** - * Get boolean property. - * - * @param key The property key - * @return the value - */ - private boolean getBooleanCitProperty(String key) { - return (Boolean) citProperties.get(key); - } - public boolean getCitPropertyMultiCiteChronological() { return this.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL); } @@ -530,14 +621,6 @@ public boolean getCitPropertyItalicEtAl() { return this.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); } - public int getIntCitProperty(String key) { - return (Integer) citProperties.get(key); - } - - public String getStringCitProperty(String key) { - return (String) citProperties.get(key); - } - /** * @return Field containing authors, with fallback fields. */ @@ -558,51 +641,117 @@ public String getCitationCharacterFormat() { return getStringCitProperty(CITATION_CHARACTER_FORMAT); } - /** - * Get a style property. - * - * @param propName The property name. - * @return The property value, or null if it doesn't exist. - */ - public Object getProperty(String propName) { - return properties.get(propName); + // The String to add between the two last author names, e.g. " & ". + protected String getAuthorLastSeparator() { + return getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); } - /** - * Indicate if it is an internal style - * - * @return True if an internal style - */ - public boolean isInternalStyle() { - return fromResource; + protected String getAuthorLastSeparatorInText() { + return Objects.requireNonNullElse( + getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT), + // Use the default one if no explicit separator for text is defined + getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR)); } - public String getLocalCopy() { - return localCopy; + protected String getPageInfoSeparator() { + return getStringCitProperty(OOBibStyle.PAGE_INFO_SEPARATOR); } - @Override - public int compareTo(OOBibStyle other) { - return getName().compareTo(other.getName()); + protected String getUniquefierSeparator() { + return getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o instanceof OOBibStyle) { - OOBibStyle otherStyle = (OOBibStyle) o; - return Objects.equals(path, otherStyle.path) - && Objects.equals(name, otherStyle.name) - && Objects.equals(citProperties, otherStyle.citProperties) - && Objects.equals(properties, otherStyle.properties); - } - return false; + protected String getCitationSeparator() { + return getStringCitProperty(OOBibStyle.CITATION_SEPARATOR); } - @Override - public int hashCode() { - return Objects.hash(path, name, citProperties, properties); + protected String getYearSeparator() { + return getStringCitProperty(OOBibStyle.YEAR_SEPARATOR); + } + + protected String getYearSeparatorInText() { + return getStringCitProperty(OOBibStyle.IN_TEXT_YEAR_SEPARATOR); + } + + // The maximum number of authors to write out in full without + // using etal. Set to -1 to always write out all authors. + protected int getMaxAuthors() { + return getIntCitProperty(OOBibStyle.MAX_AUTHORS); + } + + public int getMaxAuthorsFirst() { + return getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); + } + + // Opening parenthesis before citation (or year, for in-text) + protected String getBracketBefore() { + return getStringCitProperty(OOBibStyle.BRACKET_BEFORE); + } + + // Closing parenthesis after citation + protected String getBracketAfter() { + return getStringCitProperty(OOBibStyle.BRACKET_AFTER); + } + + // Opening parenthesis before citation marker in the bibliography + protected String getBracketBeforeInList() { + return getStringCitProperty(OOBibStyle.BRACKET_BEFORE_IN_LIST); + } + + // Closing parenthesis after citation marker in the bibliography + protected String getBracketAfterInList() { + return getStringCitProperty(OOBibStyle.BRACKET_AFTER_IN_LIST); } + + protected String getBracketBeforeInListWithFallBack() { + return Objects.requireNonNullElse(getBracketBeforeInList(), + getBracketBefore() ); + } + + protected String getBracketAfterInListWithFallBack() { + return Objects.requireNonNullElse(getBracketAfterInList(), + getBracketAfter() ); + } + + // The String to represent authors that are not mentioned, + // e.g. " et al." + protected String getEtAlString() { + return getStringCitProperty(OOBibStyle.ET_AL_STRING); + } + + // The String to add between author names except the last two, + // e.g. ", ". + protected String getAuthorSeparator() { + return getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR); + } + + // The String to put after the second to last author in case + // of three or more authors: (A, B[,] and C) + protected String getOxfordComma() { + return getStringCitProperty(OOBibStyle.OXFORD_COMMA); + } + + /** + * Title for the bibliography. + */ + public String getTitle() { + return getStringProperty(OOBibStyle.TITLE); + } + + /** + * Name of paragraph format (within OO/LO) to be used for + * the title of the bibliography. + */ + public String getReferenceHeaderParagraphFormat() { + return getStringProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT); + } + + /** + * Name of paragraph format (within OO/LO) to be used for + * the entries in the bibliography. + */ + public String getReferenceParagraphFormat() { + return getStringProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); + } + } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 43318baef48..088d2ffcf41 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -76,7 +76,7 @@ private static String getAuthorLastName(AuthorList al, } /** - * @param authorListAsString Passed to {@code AuthorList.parse(authorListAsString)} + * @param authorList * * @param maxAuthors The maximum number of authors to write out. * If there are more authors, then ET_AL_STRING is emitted @@ -102,14 +102,13 @@ private static String getAuthorLastName(AuthorList al, * - The "Au[AS]Bu[AS]Cu" (or the "Au") part may be empty (maxAuthors==0 or nAuthors==0). * - OXFORD_COMMA is only emitted if nAuthors is at least 3. * - andString is only emitted if nAuthors is at least 2. - * - yearSep is always emitted */ - private static String createAuthorList(OOBibStyle style, - String authorListAsString, + private static String formatAuthorList(OOBibStyle style, + AuthorList authorList, int maxAuthors, - String andString, - String yearSep) { - Objects.requireNonNull(authorListAsString); + String andString) { + + Objects.requireNonNull(authorList); // Apparently maxAuthorsBeforeEtAl is always 1 for in-text citations. // In reference lists can be for example 7, @@ -127,26 +126,26 @@ private static String createAuthorList(OOBibStyle style, // The String to represent authors that are not mentioned, // e.g. " et al." - String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); + String etAlString = style.getEtAlString(); // The String to add between author names except the last two, // e.g. ", ". - String authorSep = style.getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR); + String authorSep = style.getAuthorSeparator(); // The String to put after the second to last author in case // of three or more authors: (A, B[,] and C) - String oxfordComma = style.getStringCitProperty(OOBibStyle.OXFORD_COMMA); + String oxfordComma = style.getOxfordComma(); StringBuilder sb = new StringBuilder(); - AuthorList al = AuthorList.parse(authorListAsString); - final int nAuthors = al.getNumberOfAuthors(); + + final int nAuthors = authorList.getNumberOfAuthors(); // To reduce ambiguity, throw on unexpected values of maxAuthors - if (maxAuthors == 0) { - throw new RuntimeException("maxAuthors = 0 in createAuthorList"); + if (maxAuthors == 0 && nAuthors != 0) { + throw new RuntimeException("maxAuthors = 0 in formatAuthorList"); } if (maxAuthors < -1) { - throw new RuntimeException("maxAuthors < -1 in createAuthorList"); + throw new RuntimeException("maxAuthors < -1 in formatAuthorList"); } boolean emitAllAuthors = ((nAuthors <= maxAuthors) || (maxAuthors == -1)); @@ -163,7 +162,7 @@ private static String createAuthorList(OOBibStyle style, if (nAuthorsToEmit > 0) { // The first author - sb.append(getAuthorLastName(al, 0)); + sb.append(getAuthorLastName(authorList, 0)); } if (nAuthors >= 2) { @@ -173,7 +172,7 @@ private static String createAuthorList(OOBibStyle style, int j = 1; while (j < (nAuthors - 1)) { sb.append(authorSep); - sb.append(getAuthorLastName(al, j)); + sb.append(getAuthorLastName(authorList, j)); j++; } // oxfordComma if at least 3 authors @@ -182,21 +181,19 @@ private static String createAuthorList(OOBibStyle style, } // Emit " and "+"LastAuthor" sb.append(andString); - sb.append(getAuthorLastName(al, nAuthors - 1)); + sb.append(getAuthorLastName(authorList, nAuthors - 1)); } else { // Emit last names up to nAuthorsToEmit. // - // The (maxAuthorsBeforeEtAl > 1) test may seem - // superfluous, and yes, it is. - // It is intended to make sure the compiler eliminates - // this block as long as maxAuthorsBeforeEtAl is fixed - // to 1. + // The (maxAuthorsBeforeEtAl > 1) test is intended to + // make sure the compiler eliminates this block as + // long as maxAuthorsBeforeEtAl is fixed to 1. if (maxAuthorsBeforeEtAl > 1) { int j = 1; while (j < nAuthorsToEmit) { sb.append(authorSep); - sb.append(getAuthorLastName(al, j)); + sb.append(getAuthorLastName(authorList, j)); j++; } } @@ -204,10 +201,16 @@ private static String createAuthorList(OOBibStyle style, } } - sb.append(yearSep); return sb.toString(); } + /** + * On success, getRawCitationMarkerField returns content, + * but we also need to know which field matched, because + * for some fields (actually: for author names) we need to + * reproduce the surrounding braces to inform AuthorList.parse + * not to split up teh content. + */ private static class FieldAndContent { Field field; String content; @@ -216,14 +219,15 @@ private static class FieldAndContent { this.content = content; } } + /** * @return the field and the content of the first nonempty (after trimming) - * field (or alias) from {@code fields} found in {@code entry}, or Optional.empty() + * field (or alias) from {@code fields} found in {@code entry}. + * Return {@code Optional.empty()} if found nothing. */ private static Optional getRawCitationMarkerField(BibEntry entry, BibDatabase database, - OrFields fields - ) { + OrFields fields) { Objects.requireNonNull(entry, "Entry cannot be null"); Objects.requireNonNull(database, "database cannot be null"); @@ -284,81 +288,161 @@ private static String getCitationMarkerField(OOBibStyle style, // If the field we found is mentioned in authorFieldNames and // content has a pair of braces around it, we add a pair of - // braces around the result. - - final OrFields authorFieldNames = style.getAuthorFieldNames(); - if (authorFieldNames.contains(fc.field) && StringUtil.isInCurlyBrackets(fc.content)) { + // braces around the result, so that AuthorList.parse does not split + // the content. + final OrFields fieldsToRebrace = style.getAuthorFieldNames(); + if (fieldsToRebrace.contains(fc.field) && StringUtil.isInCurlyBrackets(fc.content)) { result = "{" + result + "}"; } return result; } + private static AuthorList getAuthorList(OOBibStyle style, + BibEntry entry, + BibDatabase database) { + + // The bibtex fields providing author names, e.g. "author" or + // "editor". + OrFields authorFieldNames = style.getAuthorFieldNames(); + + String authorListAsString = getCitationMarkerField(style, + entry, + database, + authorFieldNames); + return AuthorList.parse(authorListAsString); + } + + private enum AuthorYearMarkerPurpose { + IN_PARENTHESIS, + IN_TEXT, + NORMALIZED + }; + + /** + * How many authors would be emitted for ce, considering + * style and ce.getIsFirstAppearanceOfSource() + * + * If ce is unresolved, return 0. + */ + private static int calculateNAuthorsToEmit(OOBibStyle style, + CitationMarkerEntry ce) { + + int maxAuthors = (ce.getIsFirstAppearanceOfSource() + ? style.getMaxAuthorsFirst() + : style.getMaxAuthors()); + + BibEntry bibEntry = ce.getBibEntryOrNull(); + BibDatabase database = ce.getDatabaseOrNull(); + boolean isUnresolved = (bibEntry == null) || (database == null); + if (isUnresolved) { + return 0; + } + + AuthorList authorList = getAuthorList(style, bibEntry, database); + int nAuthors = authorList.getNumberOfAuthors(); + + if (maxAuthors == -1) { + return nAuthors; + } else { + return Integer.min(nAuthors,maxAuthors); + } + } + /** - * Produce (Author, year) style citation strings in many different forms. - * If inParenthesis==false, produces "Author (year)" style citation strings. + * Produce (Author, year) or "Author (year)" style citation strings. + * + * @param purpose IN_PARENTHESIS and NORMALIZED puts parentheses around the whole, + * IN_TEXT around each (year,uniqueLetter,pageInfo) part. + * + * NORMALIZED omits uniqueLetter and pageInfo, + * ignores isFirstAppearanceOfSource (always + * style.getMaxAuthors, not getMaxAuthorsFirst) and + * probably assumes a single CitationMarkerEntry. * - * @param entries The list of BibEntry to get fields from. - * @param database A map of BibEntry-BibDatabase pairs. - * @param uniquifiers Optional parameter to separate similar citations. - * Elements can be null if not needed. + * @param ces The list of CitationMarkerEntry values to process. + * + * Here we do not check for duplicate entries: those + * are handled by {@code getCitationMarker} by + * omitting them from the list. + * + * Unresolved citations recognized by + * ce.getBibEntryOrNull() and/or + * ce.getDatabaseOrNull() returning null, and + * emitted as "Unresolved${citationKey}". + * + * Neither uniqueLetter nor pageInfo are emitted + * for unresolved citations. + * + * @param startsNewGroup Should have the same length as {@code ces}, and + * contain true for entries starting a new group, + * false for those that only add a uniqueLetter to + * the grouped presentation. + * + * @param maxAuthorsOverride If not empty, always show this number of authors. + * Added to allow NORMALIZED to use maxAuthors value that differs from + * style.getMaxAuthors() * * @return The formatted citation. * */ private static String getAuthorYearParenthesisMarker(OOBibStyle style, - List entries, - Map database, - boolean inParenthesis, - String[] uniquifiers, - int[] unlimAuthors) { + AuthorYearMarkerPurpose purpose, + List ces, + boolean[] startsNewGroup, + Optional maxAuthorsOverride) { - // The bibtex field providing author names, e.g. "author" or - // "editor". - // String authorFieldNamesString = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); - // OrFields authorFieldNames = FieldFactory.parseOrFields(authorFieldNamesString); - OrFields authorFieldNames = style.getAuthorFieldNames(); + boolean inParenthesis = (purpose == AuthorYearMarkerPurpose.IN_PARENTHESIS + || purpose == AuthorYearMarkerPurpose.NORMALIZED); - // The maximum number of authors to write out in full without - // using etal. Set to -1 to always write out all authors. - int maxA = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); // The String to separate authors from year, e.g. "; ". String yearSep = (inParenthesis - ? style.getStringCitProperty(OOBibStyle.YEAR_SEPARATOR) - : style.getStringCitProperty(OOBibStyle.IN_TEXT_YEAR_SEPARATOR)); + ? style.getYearSeparator() + : style.getYearSeparatorInText()); // The opening parenthesis. - String startBrace = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE); + String startBrace = style.getBracketBefore(); // The closing parenthesis. - String endBrace = style.getStringCitProperty(OOBibStyle.BRACKET_AFTER); + String endBrace = style.getBracketAfter(); // The String to separate citations from each other. - String citationSeparator = style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR); + String citationSeparator = style.getCitationSeparator(); // The bibtex field providing the year, e.g. "year". - // String yearFieldNamesString /*yearField*/ = style.getStringCitProperty(OOBibStyle.YEAR_FIELD); - // OrFields yearFieldNames = FieldFactory.parseOrFields(yearFieldNamesString); OrFields yearFieldNames = style.getYearFieldNames(); // The String to add between the two last author names, e.g. " & ". String andString = (inParenthesis - ? style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR) - : Objects.requireNonNullElse( - style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT), - // Use the default one if no explicit separator for text is defined - style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR))); + ? style.getAuthorLastSeparator() + : style.getAuthorLastSeparatorInText()); + + String pageInfoSeparator = style.getPageInfoSeparator(); + String uniquefierSeparator = style.getUniquefierSeparator(); + StringBuilder sb = new StringBuilder(); if (inParenthesis) { sb.append(startBrace); } - for (int j = 0; j < entries.size(); j++) { - BibEntry currentEntry = entries.get(j); + for (int j = 0; j < ces.size(); j++) { + CitationMarkerEntry ce = ces.get(j); + boolean startingNewGroup = startsNewGroup[j]; + boolean endingAGroup = (j + 1 == ces.size()) || startsNewGroup[j+1] ; + + if (!startingNewGroup) { + // Just add our uniqueLetter + String uniqueLetter = ce.getUniqueLetterOrNull(); + if (uniqueLetter != null) { + sb.append( uniquefierSeparator ); + sb.append( uniqueLetter ); + } - // Check if this entry has been nulled due to grouping with the previous entry(ies): - if (currentEntry == null) { + // And close the brace, if we are the last in the group. + if (!inParenthesis && endingAGroup) { + sb.append(endBrace); + } continue; } @@ -366,48 +450,60 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, sb.append(citationSeparator); } - BibDatabase currentDatabase = database.get(currentEntry); - - /* original: - * - * int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[j]; - * int maxAuthors = (unlimA > 0) ? unlimA : maxA; - * - * translation: - * - * if ( unlimAuthors == null ) { maxAuthors = maxA; } - * else if ( unlimAuthors[j] > 0 ) { maxAuthors = unlimAuthors[j]; } - * else { maxAuthors = maxA; } - * - * maxAuthors = (( (unlimAuthors != null) && (unlimAuthors[j] > 0) ) - * ? unlimAuthors[j] - * : maxA ) - */ - int maxAuthors = (((unlimAuthors != null) && (unlimAuthors[j] > 0)) - ? unlimAuthors[j] - : maxA); - - String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorFieldNames); - String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); - sb.append(authorString); - - if (!inParenthesis) { - sb.append(startBrace); - } + BibDatabase currentDatabase = ce.getDatabaseOrNull(); + BibEntry currentEntry = ce.getBibEntryOrNull(); - String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearFieldNames); - if (year != null) { - sb.append(year); - } + boolean isUnresolved = (currentEntry == null) || (currentDatabase == null); - if ((uniquifiers != null) && (uniquifiers[j] != null)) { - sb.append(uniquifiers[j]); - } + if (isUnresolved) { + sb.append(String.format("Unresolved(%s)", ce.getCitationKey())); + } else { + + int maxAuthors = (purpose == AuthorYearMarkerPurpose.NORMALIZED + ? style.getMaxAuthors() + : calculateNAuthorsToEmit(style,ce)); + + if ( maxAuthorsOverride.isPresent() ) { + maxAuthors = maxAuthorsOverride.get(); + } + + AuthorList authorList = getAuthorList(style, + currentEntry, + currentDatabase); + String authorString = formatAuthorList(style, authorList, maxAuthors, andString); + sb.append(authorString); + sb.append(yearSep); + + if (!inParenthesis) { + sb.append(startBrace); + } + + String year = getCitationMarkerField(style, + currentEntry, + currentDatabase, + yearFieldNames); + if (year != null) { + sb.append(year); + } + + if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { + String uniqueLetter = ce.getUniqueLetterOrNull(); + if (uniqueLetter != null) { + sb.append(uniqueLetter); + } - if (!inParenthesis) { - sb.append(endBrace); + String pageInfo = OOBibStyle.regularizePageInfo(ce.getPageInfoOrNull()); + if (pageInfo != null) { + sb.append(pageInfoSeparator); + sb.append(pageInfo); + } + } + + if (!inParenthesis && endingAGroup) { + sb.append(endBrace); + } } - } + } // for j if (inParenthesis) { sb.append(endBrace); @@ -415,183 +511,70 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, return sb.toString(); } - // /** - // * This method produces "Author (year)" style citation strings in many different forms. - // * - // * @param entries The list of BibEntry to get fields from. - // * @param database A map of BibEntry-BibDatabase pairs. - // * @param uniquefiers Optional parameters to separate similar citations. Can be null if not needed. - // * @return The formatted citation. - // */ - // private static String getAuthorYearInTextMarker(OOBibStyle style, - // List entries, - // Map database, - // String[] uniquefiers, - // int[] unlimAuthors) { - // // The bibtex field providing author names, e.g. "author" or "editor". - // String authorField = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); - // - // // The maximum number of authors to write out in full without using etal. Set to - // // -1 to always write out all authors. - // int maxA = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); - // - // // The String to separate authors from year, e.g. "; ". - // String yearSep = style.getStringCitProperty(OOBibStyle.IN_TEXT_YEAR_SEPARATOR); - // - // // The opening parenthesis. - // String startBrace = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE); - // - // // The closing parenthesis. - // String endBrace = style.getStringCitProperty(OOBibStyle.BRACKET_AFTER); - // - // // The String to separate citations from each other. - // String citationSeparator = style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR); - // - // // The bibtex field providing the year, e.g. "year". - // String yearField = style.getStringCitProperty(OOBibStyle.YEAR_FIELD); - // - // // The String to add between the two last author names, e.g. " & ". - // String andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT); - // - // if (andString == null) { - // // Use the default one if no explicit separator for text is defined - // andString = style.getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); - // } - // StringBuilder sb = new StringBuilder(); - // for (int i = 0; i < entries.size(); i++) { - // BibEntry currentEntry = entries.get(i); - // - // // Check if this entry has been nulled due to grouping with the previous entry(ies): - // if (currentEntry == null) { - // continue; - // } - // - // BibDatabase currentDatabase = database.get(currentEntry); - // - // /* original: - // * - // * int unlimA = (unlimAuthors == null) ? -1 : unlimAuthors[i]; - // * int maxAuthors = unlimA > 0 ? unlimA : maxA; - // */ - // int maxAuthors = (( (unlimAuthors != null) && (unlimAuthors[i] > 0) ) - // ? unlimAuthors[i] - // : maxA ); - // - // if (i > 0) { - // sb.append(citationSeparator); - // } - // String author = getCitationMarkerField(style, currentEntry, currentDatabase, authorField); - // String authorString = createAuthorList(style, author, maxAuthors, andString, yearSep); - // sb.append(authorString); - // - // sb.append(startBrace); - // - // String year = getCitationMarkerField(style, currentEntry, currentDatabase, yearField); - // if (year != null) { - // sb.append(year); - // } - // - // if ((uniquefiers != null) && (uniquefiers[i] != null)) { - // sb.append(uniquefiers[i]); - // } - // sb.append(endBrace); - // } - // return sb.toString(); - // } + // "" is more convenient to compare for equality than null-or-String + private static String nullToEmptyString(String s) { + if (s == null) { + return ""; + } + return s; + } /** - * Modify entry and uniquefier arrays to facilitate a grouped - * presentation of uniquefied entries. + * @param ce A citation to process. * - * entries[ (from+1 .. to) ] = null - * uniquefiers[from] = String.join( separator, uniquefiers.subList(from,to_inclusive) ) + * @return A normalized citation marker for deciding which + * citations need uniqueLetters. * - * @param entries The entry array. - * @param uniquefiers The uniquefier array. - * @param from The first index to group (inclusive) - * @param to The last index to group (inclusive) + * For details of what "normalized" means: {@see getAuthorYearParenthesisMarker} */ - private static void group(OOBibStyle style, - List entries, - String[] uniquefiers, - int from, - int to) { - - String separator = style.getStringCitProperty(OOBibStyle.UNIQUEFIER_SEPARATOR); - - StringBuilder sb = new StringBuilder(uniquefiers[from]); - for (int i = from + 1; i <= to; i++) { - sb.append(separator); - sb.append(uniquefiers[i]); - entries.set(i, null); // kill BibEntry? - } - uniquefiers[from] = sb.toString(); + public static String getNormalizedCitationMarker(OOBibStyle style, + CitationMarkerEntry ce, + Optional maxAuthorsOverride) { + boolean[] startsNewGroup = {true}; + return getAuthorYearParenthesisMarker(style, + AuthorYearMarkerPurpose.NORMALIZED, + Collections.singletonList(ce), + startsNewGroup, + maxAuthorsOverride); } - /** - * @param entries - * @param database - * @param inParenthesis Emit "(Au, 2000)" if true, "Au (2000)" if false. - * @param uniquefiers null or of length entries.size(), with - * elements null or letter making a cited - * source unique in citations. - * - * @param unlimAuthors Can this be null? - * If not null, then its elements are ... - * - * @param pageInfosForCitations - * May be null. - * Any or of its elements can be null. - */ - /* - * Call patterns: - * - * // normalizedCitationMarkerForNormalStyle - * return style.getCitationMarker(Collections.singletonList(ce), // List - * entries, // Map - * true, // inParenthesis - * null, // uniqueLetters - * new int[] {-1}, // no limit on authors - * null // pageInfosForCitations - * ); - * // produceCitationMarkersForNormalStyle - * // when there are unresolved entries - * style.getCitationMarker(cEntries, - * entries, - * cg.itcType == OOBibBase.AUTHORYEAR_PAR, - * uniqueLetterForCitedEntry2, - * firstLimAuthors2, // entry for a single citation - * pageInfo); - * // when there are no unresolved entries - * String citMarker = style.getCitationMarker(cEntries, - * entries, - * cg.itcType == OOBibBase.AUTHORYEAR_PAR, - * uniqueLetterForCitedEntry, - * firstLimAuthors, - * pageInfosForCitations); - * // insertCitation - * String citeText = (style.isNumberEntries() - * ? "[-]" // A dash only. Only refresh later. - * : style.getCitationMarker(entries, - * databaseMap, - * inParenthesis, - * null, // uniqueLetters - * null, // unlimAuthors - * pageInfosForCitations)); + * Produce citation marker for a citation group. + * + * Attempts to join consecutive citations: if normalized citations + * markers match and no pageInfo is present, the second entry + * can be presented by appending its uniqueLetter to the + * previous. + * + * If either entry has pageInfo, join is inhibited. + * If the previous entry has more names than we need + * we check with extended normalizedMarkers if they match. + * + * For consecutive identical entries, the second one is omitted. + * Identical requires same pageInfo here, we do not try to merge them. + * Note: notifying the user about them would be nice. + * + * @param citationMarkerEntries A group of citations to process. + * + * @param inParenthesis If true, put parenthesis around the whole group, + * otherwise around each (year,uniqueLetter,pageInfo) part. + * + * @param nonUniqueCitationMarkerHandling What should happen if we + * stumble upon citations with identical normalized + * citation markers which cite different sources and + * are not distinguished by uniqueLetters. + * + * Note: only consecutive citations are checked. + * */ - public static String getCitationMarker(OOBibStyle style, - List entries, - Map database, - boolean inParenthesis, - String[] uniquefiers, - int[] unlimAuthors, - List pageInfosForCitations - ) { - - List pageInfos = - OOBibStyle.regularizePageInfosForCitations(pageInfosForCitations, - entries.size()); + public static String getCitationMarker( + OOBibStyle style, + List citationMarkerEntries, + boolean inParenthesis, + OOBibStyle.NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { + + final int nEntries = citationMarkerEntries.size(); + // Original: // // Look for groups of uniquefied entries that should be combined in the output. @@ -606,88 +589,164 @@ public static String getCitationMarker(OOBibStyle style, // // We also assume, that identical entries have the same uniquefier. // - // Possibilites for two consecutive entries: - // a.entry != b.entry, - // - // - int piv = -1; - String tmpMarker = null; + List normalizedMarkers = new ArrayList<>(nEntries); + for (int i = 0; i < nEntries; i++){ + String nm = getNormalizedCitationMarker(style, + citationMarkerEntries.get(i), + Optional.empty()); + normalizedMarkers.add(nm); + } - if (uniquefiers != null) { + // How many authors would be emitted without grouping. + // Later overwritten for group members with value for + // first of the group. + int[] nAuthorsToEmit = new int[nEntries]; + int[] nAuthorsToEmitRevised = new int[nEntries]; + for (int i = 0; i < nEntries; i++){ + CitationMarkerEntry ce = citationMarkerEntries.get(i); + nAuthorsToEmit[i] = calculateNAuthorsToEmit(style, ce); + nAuthorsToEmitRevised[i] = calculateNAuthorsToEmit(style, ce); + } - for (int i = 0; i < uniquefiers.length; i++) { + boolean[] startsNewGroup = new boolean[nEntries]; + List filteredCitationMarkerEntries = new ArrayList<>(nEntries); + int i_out = 0; - if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { - // This entry has no uniquefier. - // Check if we just passed a group of more than one entry with uniquefier: - if ((piv > -1) && (i > (piv + 1))) { - // Do the grouping: - group(style, entries, uniquefiers, piv, i - 1); - } + if ( nEntries > 0) { + filteredCitationMarkerEntries.add(citationMarkerEntries.get(0)); + startsNewGroup[i_out] = true; + i_out++; + } + + for (int i = 1; i < nEntries; i++){ + CitationMarkerEntry ce1 = citationMarkerEntries.get(i - 1); + CitationMarkerEntry ce2 = citationMarkerEntries.get(i); + String nm1 = normalizedMarkers.get(i - 1); + String nm2 = normalizedMarkers.get(i); + + BibEntry bibEntry1 = ce1.getBibEntryOrNull(); + BibEntry bibEntry2 = ce2.getBibEntryOrNull(); + + BibDatabase database1 = ce1.getDatabaseOrNull(); + BibDatabase database2 = ce2.getDatabaseOrNull(); - piv = -1; + boolean isUnresolved1 = (bibEntry1 == null) || (database1 == null); + boolean isUnresolved2 = (bibEntry2 == null) || (database2 == null); + + boolean startingNewGroup; + boolean sameAsPrev; + if (isUnresolved2) { + startingNewGroup = true; + sameAsPrev = false; // keep it visible + } else { + // Does the number of authors to be shown differ? + // Since we compared normalizedMarkers, the difference + // between maxAuthors and maxAuthorsFirst may invalidate + // our expectation that adding uniqueLetter is valid. + + boolean firstAppearanceInhibitsJoin; + if ( isUnresolved1 ) { + firstAppearanceInhibitsJoin = true; // no join for unresolved } else { - BibEntry currentEntry = entries.get(i); - if (piv == -1) { - piv = i; - // createNormalizedCitationMarker - tmpMarker = - getAuthorYearParenthesisMarker(style, - Collections.singletonList(currentEntry), - database, // Map - true, // inParenthesis - null, // uniqueLetters - unlimAuthors /* from args!*/); + boolean isFirst1 = ce1.getIsFirstAppearanceOfSource(); + boolean isFirst2 = ce2.getIsFirstAppearanceOfSource(); + + // nAuthorsToEmitRevised[i-1] may have been indirectly increased, + // we have to check that too. + if (!isFirst1 && !isFirst2 && (nAuthorsToEmitRevised[i-1] == nAuthorsToEmit[i-1])){ + // we can rely on normalizedMarkers + firstAppearanceInhibitsJoin = false; + } else if (style.getMaxAuthors() == style.getMaxAuthorsFirst()) { + // we can rely on normalizedMarkers + firstAppearanceInhibitsJoin = false; } else { - // See if this entry can go into a group with the previous one: - // createNormalizedCitationMarker - String thisMarker = - getAuthorYearParenthesisMarker(style, - Collections.singletonList(currentEntry), - database, - true, // inParenthesis - null, - unlimAuthors); - - String authorField = style.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); - int maxAuthors = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS); - String author = getCitationMarkerField(style, - currentEntry, - database.get(currentEntry), - style.getAuthorFieldNames()); - AuthorList al = AuthorList.parse(author); - - // assumes (unlimAuthors != null) - int prevALim = unlimAuthors[i - 1]; // i always at least 1 here - if (!thisMarker.equals(tmpMarker) - || ((al.getNumberOfAuthors() > maxAuthors) - && (unlimAuthors[i] != prevALim))) { - // No match. Update piv to exclude the previous entry. But first check if the - // previous entry was part of a group: - if ((piv > -1) && (i > (piv + 1))) { - // Do the grouping: - group(style, entries, uniquefiers, piv, i - 1); + int prevShown = nAuthorsToEmitRevised[i-1]; + int need = nAuthorsToEmit[i]; + + if ( prevShown < need ) { + // We do not retrospectively change the number of authors shown + // at the previous entry, take that as decided. + firstAppearanceInhibitsJoin = true; + } else { + // prevShown >= need + // Check with extended normalizedMarkers. + String nmx1 = getNormalizedCitationMarker(style, ce1, Optional.of(prevShown)); + String nmx2 = getNormalizedCitationMarker(style, ce2, Optional.of(prevShown)); + if (nmx2.equals(nmx1)) { + firstAppearanceInhibitsJoin = false; + } else { + firstAppearanceInhibitsJoin = true; } - tmpMarker = thisMarker; - piv = i; } } } + String pi2 = nullToEmptyString(OOBibStyle.regularizePageInfo(ce2.getPageInfoOrNull())); + String pi1 = nullToEmptyString(OOBibStyle.regularizePageInfo(ce1.getPageInfoOrNull())); + + String ul2 = ce2.getUniqueLetterOrNull(); + String ul1 = ce1.getUniqueLetterOrNull(); + + boolean uniqLetterPresenceChanged = (ul2 == null) != (ul1 == null); + + String xul2 = nullToEmptyString(ul2); + String xul1 = nullToEmptyString(ul1); + + String k2 = ce2.getCitationKey(); + String k1 = ce1.getCitationKey(); + + boolean uniqLetterDoesNotMakeUnique = (nm2.equals(nm1) + && xul2.equals(xul1) + && !k2.equals(k1)); + + if (uniqLetterDoesNotMakeUnique && + nonUniqueCitationMarkerHandling == OOBibStyle.NonUniqueCitationMarker.THROWS) { + throw new RuntimeException("different citation keys," + + " but same normalizedMarker and uniqueLetter"); + } + + boolean pageInfoInhibitsJoin; + if (pi1.equals("") && pi2.equals("")) { + pageInfoInhibitsJoin = false; + } else if (k2.equals(k1) && pi2.equals(pi1)) { + pageInfoInhibitsJoin = false; + } else { + pageInfoInhibitsJoin = true; + } + + boolean normalizedMarkerChanged = !nm2.equals(nm1); + startingNewGroup = ( + normalizedMarkerChanged + || firstAppearanceInhibitsJoin + || pageInfoInhibitsJoin + || uniqLetterPresenceChanged + || uniqLetterDoesNotMakeUnique); + + if (!startingNewGroup) { + // inherit from first of group. Used at next i. + nAuthorsToEmitRevised[i] = nAuthorsToEmitRevised[i-1]; + } + + sameAsPrev = (!startingNewGroup + && xul2.equals(xul1) + && k2.equals(k1) + && pi2.equals(pi1)); } - // Finished with the loop. See if the last entries form a group: - if (piv >= 0) { - // Do the grouping: - group(style, entries, uniquefiers, piv, uniquefiers.length - 1); + + if (!sameAsPrev) { + filteredCitationMarkerEntries.add(ce2); + startsNewGroup[i_out] = startingNewGroup; + i_out++; } - } // if uniquefiers are not null + } return getAuthorYearParenthesisMarker(style, - entries, - database, - inParenthesis, - uniquefiers, - unlimAuthors); + (inParenthesis + ? AuthorYearMarkerPurpose.IN_PARENTHESIS + : AuthorYearMarkerPurpose.IN_TEXT), + filteredCitationMarkerEntries, + startsNewGroup, + Optional.empty()); } } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java index e6c07825a66..1efd334c3a3 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java @@ -167,8 +167,8 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, */ final boolean strictPurpose = true; - String bracketBefore = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE); - String bracketAfter = style.getStringCitProperty(OOBibStyle.BRACKET_AFTER); + String bracketBefore = style.getBracketBefore(); + String bracketAfter = style.getBracketAfter(); /* * purpose == BIBLIOGRAPHY means: we are formatting for the @@ -176,12 +176,8 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, */ if (purpose == CitationMarkerPurpose.BIBLIOGRAPHY) { // prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST - if (style.citProperties.containsKey(OOBibStyle.BRACKET_BEFORE_IN_LIST)) { - bracketBefore = style.getStringCitProperty(OOBibStyle.BRACKET_BEFORE_IN_LIST); - } - if (style.citProperties.containsKey(OOBibStyle.BRACKET_AFTER_IN_LIST)) { - bracketAfter = style.getStringCitProperty(OOBibStyle.BRACKET_AFTER_IN_LIST); - } + bracketBefore = style.getBracketBeforeInListWithFallBack(); + bracketAfter = style.getBracketAfterInListWithFallBack(); if (strictPurpose) { // If (purpose==BIBLIOGRAPHY), then diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 6f85895450e..dcd7bf1822c 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -10,7 +10,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; -import java.util.Optional; import java.util.Map; import java.util.Set; @@ -42,8 +41,7 @@ void setUp() { @Test void testAuthorYear() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, - layoutFormatterPreferences); + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, layoutFormatterPreferences); assertTrue(style.isValid()); assertTrue(style.isInternalStyle()); assertFalse(style.isCitationKeyCiteMarkers()); @@ -56,9 +54,8 @@ void testAuthorYear() throws IOException { @Test void testAuthorYearAsFile() throws URISyntaxException, IOException { - File defFile = Path.of( - OOBibStyleTest.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) - .toFile(); + File defFile = Path.of(OOBibStyleTest.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) + .toFile(); OOBibStyle style = new OOBibStyle(defFile, layoutFormatterPreferences, StandardCharsets.UTF_8); assertTrue(style.isValid()); assertFalse(style.isInternalStyle()); @@ -212,21 +209,12 @@ void testGetNumCitationMarkerForInText() throws IOException { assertEquals("[1] ", style.getNumCitationMarkerForBibliography(1)); - /* - * test insertPageInfo - */ - if (true) { - String citation = style.getNumCitationMarkerForInText(Arrays.asList(1), - -1, - empty); - assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); - } } @Test void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); List empty = null; // unresolved citations look like [??] @@ -274,8 +262,7 @@ void testGetCitProperty() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); assertEquals(", ", style.getStringCitProperty("AuthorSeparator")); - assertEquals(3, style.getIntCitProperty("MaxAuthors")); - //assertTrue(style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)); + assertEquals(3, style.getMaxAuthors()); assertTrue(style.getCitPropertyMultiCiteChronological()); assertEquals("Default", style.getCitationCharacterFormat()); assertEquals("Default [number] style file.", style.getName()); @@ -285,82 +272,283 @@ void testGetCitProperty() throws IOException { @Test void testGetCitationMarker() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); BibEntry entry = new BibEntry() - .withField(StandardField.AUTHOR, - "Gustav Bostr\\\"{o}m" - + " and Jaana W\\\"{a}yrynen" - + " and Marine Bod\\'{e}n" - + " and Konstantin Beznosov" - + " and Philippe Kruchten") + .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m and Jaana W\\\"{a}yrynen and Marine Bod\\'{e}n and Konstantin Beznosov and Philippe Kruchten") .withField(StandardField.YEAR, "2006") - .withField(StandardField.BOOKTITLE, - "SESS '06: Proceedings of the 2006 international workshop" - + " on Software engineering for secure systems") + .withField(StandardField.BOOKTITLE, "SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems") .withField(StandardField.PUBLISHER, "ACM") - .withField(StandardField.TITLE, - "Extending XP practices to support security requirements engineering") + .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") .withField(StandardField.PAGES, "11--18"); - BibDatabase database = new BibDatabase(); database.insertEntry(entry); - Map entryDBMap = new HashMap<>(); - entryDBMap.put(entry, database); - - assertEquals(3, style.getIntCitProperty("MaxAuthors")); + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm = + new CitationMarkerEntryImpl("Bostrom2006", entry, database, null, null, false); + citationMarkerEntries.add(cm); - List empty = null; + assertEquals(3, style.getMaxAuthors()); + assertEquals(-1, style.getMaxAuthorsFirst()); /* * For in-text citations most (maybe all) styles prescribe a single * author's name before "et al." */ assertEquals("[Boström et al., 2006]", - style.getCitationMarker(Collections.singletonList(entry), // List - entryDBMap, // Map - true, // inParenthesis - null, // uniquefiers - null, // unlimAuthors - empty)); // pageInfosForCitations + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); assertEquals("Boström et al. [2006]", - style.getCitationMarker(Collections.singletonList(entry), - entryDBMap, + style.getCitationMarker(citationMarkerEntries, false, - null, - new int[]{3}, - empty)); + OOBibStyle.NonUniqueCitationMarker.THROWS)); + + /* + * Currently there is no override for MAX_AUTHORS, except + * cm.isFirstAppearanceOfSource, which asks for MAX_AUTHORS_FIRST + */ + citationMarkerEntries.clear(); + cm = new CitationMarkerEntryImpl("Bostrom2006", entry, database, null, null, true); + citationMarkerEntries.add(cm); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", - style.getCitationMarker(Collections.singletonList(entry), - entryDBMap, + style.getCitationMarker(citationMarkerEntries, true, - null, - new int[]{5}, - empty)); + OOBibStyle.NonUniqueCitationMarker.THROWS)); } @Test - void testLayout() throws IOException { + void testGetCitationMarkerJoinFirst() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + // Question: What should happen if some of the sources is + // marked as isFirstAppearanceOfSource? + // This test documents what is happening now, + // but it is possible this is not what should. + + // Two entries with identical normalizedMarkers and many authors. + BibEntry entry1 = new BibEntry() + .withField(StandardField.AUTHOR, + "Gustav Bostr\\\"{o}m" + + " and Jaana W\\\"{a}yrynen" + + " and Marine Bod\\'{e}n" + + " and Konstantin Beznosov" + + " and Philippe Kruchten") + .withField(StandardField.YEAR, "2006") + .withField(StandardField.BOOKTITLE, "A book 1") + .withField(StandardField.PUBLISHER, "ACM") + .withField(StandardField.TITLE, "Title 1") + .withField(StandardField.PAGES, "11--18"); + + BibEntry entry2 = new BibEntry() + .withField(StandardField.AUTHOR, + "Gustav Bostr\\\"{o}m" + + " and Jaana W\\\"{a}yrynen" + + " and Marine Bod\\'{e}n" + + " and Konstantin Beznosov" + + " and Philippe Kruchten") + .withField(StandardField.YEAR, "2006") + .withField(StandardField.BOOKTITLE, "A book 2") + .withField(StandardField.PUBLISHER, "ACM") + .withField(StandardField.TITLE, "title2") + .withField(StandardField.PAGES, "11--18"); + + // Last Author differs. + BibEntry entry3 = new BibEntry() + .withField(StandardField.AUTHOR, + "Gustav Bostr\\\"{o}m" + + " and Jaana W\\\"{a}yrynen" + + " and Marine Bod\\'{e}n" + + " and Konstantin Beznosov" + + " and Philippe NotKruchten") + .withField(StandardField.YEAR, "2006") + .withField(StandardField.BOOKTITLE, "A book 3") + .withField(StandardField.PUBLISHER, "ACM") + .withField(StandardField.TITLE, "title3") + .withField(StandardField.PAGES, "11--18"); + + BibDatabase database = new BibDatabase(); + database.insertEntry(entry1); + database.insertEntry(entry2); + database.insertEntry(entry3); + + // Without pageInfo, two isFirstAppearanceOfSource may be joined. + // The third is NotKruchten, should not be joined. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", null, true); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + new CitationMarkerEntryImpl("b2", entry2, database, "b", null, true); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + new CitationMarkerEntryImpl("b3", entry3, database, "c", null, true); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" + +"; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); + + assertEquals("Boström, Wäyrynen, Bodén, Beznosov & Kruchten [2006a,b]" + + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten [2006c]", + style.getCitationMarker(citationMarkerEntries, + false, + OOBibStyle.NonUniqueCitationMarker.THROWS)); + } + + // Without pageInfo, only the first is isFirstAppearanceOfSource. + // The second may be joined, based on expanded normalizedMarkers. + // The third is NotKruchten, should not be joined. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", null, true); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + new CitationMarkerEntryImpl("b2", entry2, database, "b", null, false); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + new CitationMarkerEntryImpl("b3", entry3, database, "c", null, false); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" + +"; Boström et al., 2006c]", + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); + + } + // Without pageInfo, only the second is isFirstAppearanceOfSource. + // The second is not joined, because it is a first appearance, thus + // requires more names to be shown. + // The third is NotKruchten, should not be joined. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", null, false); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + new CitationMarkerEntryImpl("b2", entry2, database, "b", null, true); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + new CitationMarkerEntryImpl("b3", entry3, database, "c", null, false); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström et al., 2006a" + + "; Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006b" + + "; Boström et al., 2006c]", + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); + } + + // Without pageInfo, only the neither is isFirstAppearanceOfSource. + // The second is joined. + // The third is NotKruchten, but is joined because NotKruchten is not among the names shown. + // Is this the correct behaviour? + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", null, false); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + new CitationMarkerEntryImpl("b2", entry2, database, "b", null, false); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + new CitationMarkerEntryImpl("b3", entry3, database, "c", null, false); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström et al., 2006a,b,c]", + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); + } + + // With pageInfo: different entries with identical non-null pageInfo: not joined. + // XY [2000a,b,c; p1] whould be confusing. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", "p1", false); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + new CitationMarkerEntryImpl("b2", entry2, database, "b", "p1", false); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + new CitationMarkerEntryImpl("b3", entry3, database, "c", "p1", false); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström et al., 2006a; p1" + + "; Boström et al., 2006b; p1" + + "; Boström et al., 2006c; p1]", + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); + } + + // With pageInfo: same entries with identical non-null pageInfo: collapsed. + // Note: "same" here looks at the visible parts and citation key only, + // but ignores the rest. Normally the citation key should distinguish. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", "p1", false); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", "p1", false); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", "p1", false); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström et al., 2006a; p1]", + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); + } + // With pageInfo: same entries with different pageInfo: kept separate. + // Empty ("") and null pageInfos considered equal her, collapsed. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", "p1", false); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", "p2", false); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", "", false); + citationMarkerEntries.add(cm3); + CitationMarkerEntry cm4 = + new CitationMarkerEntryImpl("b1", entry1, database, "a", null, false); + citationMarkerEntries.add(cm4); + + assertEquals("[Boström et al., 2006a; p1" + + "; Boström et al., 2006a; p2" + + "; Boström et al., 2006a]", + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); + } + } + + + @Test + void testLayout() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + BibEntry entry = new BibEntry() - .withField(StandardField.AUTHOR, - "Gustav Bostr\\\"{o}m" - + " and Jaana W\\\"{a}yrynen" - + " and Marine Bod\\'{e}n" - + " and Konstantin Beznosov" - + " and Philippe Kruchten") - .withField(StandardField.YEAR, "2006") - .withField(StandardField.BOOKTITLE, - "SESS '06: Proceedings of the 2006 international workshop" - + " on Software engineering for secure systems") - .withField(StandardField.PUBLISHER, "ACM") - .withField(StandardField.TITLE, - "Extending XP practices to support security requirements engineering") + .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m and Jaana W\\\"{a}yrynen and Marine Bod\\'{e}n and Konstantin Beznosov and Philippe Kruchten") + .withField(StandardField.YEAR, "2006") + .withField(StandardField.BOOKTITLE, "SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems") + .withField(StandardField.PUBLISHER, "ACM") + .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") .withField(StandardField.PAGES, "11--18"); BibDatabase database = new BibDatabase(); database.insertEntry(entry); @@ -368,26 +556,19 @@ void testLayout() throws IOException { Layout l = style.getReferenceFormat(new UnknownEntryType("default")); l.setPostFormatter(new OOPreFormatter()); assertEquals( - "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006)." - + " Extending XP practices to support security requirements engineering," - + " : 11-18.", + "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006). Extending XP practices to support security requirements engineering, : 11-18.", l.doLayout(entry, database)); l = style.getReferenceFormat(StandardEntryType.InCollection); l.setPostFormatter(new OOPreFormatter()); assertEquals( - "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006)." - + " Extending XP practices to support security requirements engineering." - + " In: (Ed.)," - + " SESS '06: Proceedings of the 2006 international workshop" - + " on Software engineering for secure systems, ACM.", - l.doLayout(entry, database)); + "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006). Extending XP practices to support security requirements engineering. In: (Ed.), SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems, ACM.", + l.doLayout(entry, database)); } @Test void testInstitutionAuthor() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); BibDatabase database = new BibDatabase(); Layout l = style.getReferenceFormat(StandardEntryType.Article); @@ -399,16 +580,14 @@ void testInstitutionAuthor() throws IOException { entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); - assertEquals("JabRef Development Team" - + " (2016)." - + " JabRef Manual, .", - l.doLayout(entry, database)); + assertEquals("JabRef Development Team (2016). JabRef Manual, .", + l.doLayout(entry, database)); } @Test void testVonAuthor() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); BibDatabase database = new BibDatabase(); Layout l = style.getReferenceFormat(StandardEntryType.Article); @@ -421,16 +600,14 @@ void testVonAuthor() throws IOException { entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); assertEquals("von Beta, A. (2016). JabRef Manual, .", - l.doLayout(entry, database)); + l.doLayout(entry, database)); } @Test void testInstitutionAuthorMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); - Map entryDBMap = new HashMap<>(); - List entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); @@ -439,11 +616,15 @@ void testInstitutionAuthorMarker() throws IOException { entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); - entries.add(entry); - entryDBMap.put(entry, database); - List empty = null; + + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm = + new CitationMarkerEntryImpl("JabRef2016", entry, database, null, null, false); + citationMarkerEntries.add(cm); assertEquals("[JabRef Development Team, 2016]", - style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); } @Test @@ -451,8 +632,6 @@ void testVonAuthorMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - Map entryDBMap = new HashMap<>(); - List entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); @@ -461,11 +640,16 @@ void testVonAuthorMarker() throws IOException { entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); - entries.add(entry); - entryDBMap.put(entry, database); - List empty = null; + + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm = + new CitationMarkerEntryImpl("vonBeta2016", entry, database, null, null, false); + citationMarkerEntries.add(cm); + assertEquals("[von Beta, 2016]", - style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); } @Test @@ -473,19 +657,22 @@ void testNullAuthorMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - Map entryDBMap = new HashMap<>(); - List entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); - entries.add(entry); - entryDBMap.put(entry, database); - List empty = null; + + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm = + new CitationMarkerEntryImpl("anon2016", entry, database, null, null, false); + citationMarkerEntries.add(cm); + assertEquals("[, 2016]", - style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); } @Test @@ -493,19 +680,22 @@ void testNullYearMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - Map entryDBMap = new HashMap<>(); - List entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Alpha von Beta"); database.insertEntry(entry); - entries.add(entry); - entryDBMap.put(entry, database); - List empty = null; + + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm = + new CitationMarkerEntryImpl("vonBetaNNNN", entry, database, null, null, false); + citationMarkerEntries.add(cm); + assertEquals("[von Beta, ]", - style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); } @Test @@ -513,192 +703,169 @@ void testEmptyEntryMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - Map entryDBMap = new HashMap<>(); - List entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); database.insertEntry(entry); - entries.add(entry); - entryDBMap.put(entry, database); - List empty = null; - assertEquals("[, ]", style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); + + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm = + new CitationMarkerEntryImpl("Empty", entry, database, null, null, false); + citationMarkerEntries.add(cm); + + assertEquals("[, ]", style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); } @Test - void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { + void testGetCitationMarkerUniquefiers() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - Map entryDBMap = new HashMap<>(); - List entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); + // Three different entries, the first two having the same + // normalized citation marks. BibEntry entry1 = new BibEntry(); entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); - entries.add(entry1); database.insertEntry(entry1); + BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); - entries.add(entry3); database.insertEntry(entry3); + BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); - entries.add(entry2); database.insertEntry(entry2); - for (BibEntry entry : database.getEntries()) { - entryDBMap.put(entry, database); + + + // Without uniquefiers this is a problem, getCitationMarker cannot + // solve, since it does not see the whole picture (citations outside its scope). + // It can throw a RuntimeException or forgive and provide a flawed presentation. + // + // This latter is used for providing a temporary citation mark + // for newly inserted citations. + CitationMarkerEntry cm1a = + new CitationMarkerEntryImpl("Beta2000a", entry1, database, null, null, false); + CitationMarkerEntry cm3a = + new CitationMarkerEntryImpl("Beta2000b", entry3, database, null, null, false); + CitationMarkerEntry cm2 = + new CitationMarkerEntryImpl("Epsilon2001", entry2, database, null, null, false); + + List citationMarkerEntriesA = new ArrayList<>(); + citationMarkerEntriesA.add(cm1a); + citationMarkerEntriesA.add(cm3a); + citationMarkerEntriesA.add(cm2); + + // Consecutive, different source without distinguishing uniquefiers + // can throw a RuntimeException. + boolean doesItThrow = false; + try { + style.getCitationMarker(citationMarkerEntriesA, + false, + OOBibStyle.NonUniqueCitationMarker.THROWS); + } catch (RuntimeException ex) { + doesItThrow = true; } + assertEquals(true, doesItThrow); - List empty = null; + // Or can just emit a presentation with repeated marks. assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", - style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); - assertEquals("[Beta, 2000a,b; Epsilon, 2001]", - style.getCitationMarker(entries, - entryDBMap, + style.getCitationMarker(citationMarkerEntriesA, true, - new String[]{"a", "b", ""}, - new int[]{1, 1, 1}, - empty)); - } + OOBibStyle.NonUniqueCitationMarker.FORGIVEN)); - @Test - void testGetCitationMarkerInTextUniquefiers() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", + style.getCitationMarker(citationMarkerEntriesA, + false, + OOBibStyle.NonUniqueCitationMarker.FORGIVEN)); - Map entryDBMap = new HashMap<>(); - List entries = new ArrayList<>(); - BibDatabase database = new BibDatabase(); - BibEntry entry1 = new BibEntry(); - entry1.setField(StandardField.AUTHOR, "Alpha Beta"); - entry1.setField(StandardField.TITLE, "Paper 1"); - entry1.setField(StandardField.YEAR, "2000"); - entries.add(entry1); - database.insertEntry(entry1); - BibEntry entry3 = new BibEntry(); - entry3.setField(StandardField.AUTHOR, "Alpha Beta"); - entry3.setField(StandardField.TITLE, "Paper 2"); - entry3.setField(StandardField.YEAR, "2000"); - entries.add(entry3); - database.insertEntry(entry3); - BibEntry entry2 = new BibEntry(); - entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); - entry2.setField(StandardField.YEAR, "2001"); - entries.add(entry2); - database.insertEntry(entry2); - for (BibEntry entry : database.getEntries()) { - entryDBMap.put(entry, database); - } + // With uniquefiers + CitationMarkerEntry cm1b = + new CitationMarkerEntryImpl("Beta2000a", entry1, database, "a", null, false); + CitationMarkerEntry cm3b = + new CitationMarkerEntryImpl("Beta2000b", entry3, database, "b", null, false); + + List citationMarkerEntriesB = new ArrayList<>(); + citationMarkerEntriesB.add(cm1b); + citationMarkerEntriesB.add(cm3b); + citationMarkerEntriesB.add(cm2); + + assertEquals("[Beta, 2000a,b; Epsilon, 2001]", + style.getCitationMarker(citationMarkerEntriesB, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); - List empty = null; - assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", - style.getCitationMarker(entries, entryDBMap, false, null, null, empty)); assertEquals("Beta [2000a,b]; Epsilon [2001]", - style.getCitationMarker(entries, - entryDBMap, + style.getCitationMarker(citationMarkerEntriesB, false, - new String[]{"a", "b", ""}, - new int[]{1, 1, 1}, - empty)); + OOBibStyle.NonUniqueCitationMarker.THROWS)); } + @Test - void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOException { + void testGetCitationMarkerUniquefiersThreeSameAuthor() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - Map entryDBMap = new HashMap<>(); - List entries = new ArrayList<>(); BibDatabase database = new BibDatabase(); BibEntry entry1 = new BibEntry(); entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); - entries.add(entry1); database.insertEntry(entry1); + BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); - entries.add(entry2); database.insertEntry(entry2); + BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); - entries.add(entry3); database.insertEntry(entry3); - for (BibEntry entry : database.getEntries()) { - entryDBMap.put(entry, database); - } - - List empty = null; - assertEquals("[Beta, 2000a,b,c]", - style.getCitationMarker(entries, - entryDBMap, - true, - new String[]{"a", "b", "c"}, - new int[]{1, 1, 1}, - empty)); - } - @Test - void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + CitationMarkerEntry cm1 = + new CitationMarkerEntryImpl("v1", entry1, database, "a", null, false); + CitationMarkerEntry cm2 = + new CitationMarkerEntryImpl("v2", entry2, database, "b", null, false); + CitationMarkerEntry cm3 = + new CitationMarkerEntryImpl("v3", entry3, database, "c", null, false); - Map entryDBMap = new HashMap<>(); - List entries = new ArrayList<>(); - BibDatabase database = new BibDatabase(); + List citationMarkerEntries = new ArrayList<>(); + citationMarkerEntries.add(cm1); + citationMarkerEntries.add(cm2); + citationMarkerEntries.add(cm3); - BibEntry entry1 = new BibEntry(); - entry1.setField(StandardField.AUTHOR, "Alpha Beta"); - entry1.setField(StandardField.TITLE, "Paper 1"); - entry1.setField(StandardField.YEAR, "2000"); - entries.add(entry1); - database.insertEntry(entry1); - BibEntry entry2 = new BibEntry(); - entry2.setField(StandardField.AUTHOR, "Alpha Beta"); - entry2.setField(StandardField.TITLE, "Paper 2"); - entry2.setField(StandardField.YEAR, "2000"); - entries.add(entry2); - database.insertEntry(entry2); - BibEntry entry3 = new BibEntry(); - entry3.setField(StandardField.AUTHOR, "Alpha Beta"); - entry3.setField(StandardField.TITLE, "Paper 3"); - entry3.setField(StandardField.YEAR, "2000"); - entries.add(entry3); - database.insertEntry(entry3); - for (BibEntry entry : database.getEntries()) { - entryDBMap.put(entry, database); - } + assertEquals("[Beta, 2000a,b,c]", + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); - List empty = null; assertEquals("Beta [2000a,b,c]", - style.getCitationMarker(entries, - entryDBMap, + style.getCitationMarker(citationMarkerEntries, false, - new String[]{"a", "b", "c"}, - new int[]{1, 1, 1}, - empty)); + OOBibStyle.NonUniqueCitationMarker.THROWS)); } @Test // TODO: equals only work when initialized from file, not from reader void testEquals() throws IOException { OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); assertEquals(style1, style2); } @@ -706,36 +873,36 @@ void testEquals() throws IOException { // TODO: equals only work when initialized from file, not from reader void testNotEquals() throws IOException { OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); assertNotEquals(style1, style2); } @Test void testCompareToEqual() throws IOException { OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); assertEquals(0, style1.compareTo(style2)); } @Test void testCompareToNotEqual() throws IOException { OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); assertTrue(style1.compareTo(style2) > 0); assertFalse(style2.compareTo(style1) > 0); } @Test void testEmptyStringPropertyAndOxfordComma() throws Exception { + OOBibStyle style = new OOBibStyle("test.jstyle", layoutFormatterPreferences); - Map entryDBMap = new HashMap<>(); - List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); @@ -744,17 +911,20 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); database.insertEntry(entry); - entries.add(entry); - entryDBMap.put(entry, database); - List empty = null; + + List citationMarkerEntries = new ArrayList<>(); + citationMarkerEntries.add( + new CitationMarkerEntryImpl("Beta2016", entry, database, null, null, false)); + assertEquals("von Beta, Epsilon, & Tau, 2016", - style.getCitationMarker(entries, entryDBMap, true, null, null, empty)); + style.getCitationMarker(citationMarkerEntries, + true, + OOBibStyle.NonUniqueCitationMarker.THROWS)); } @Test void testIsValidWithDefaultSectionAtTheStart() throws Exception { - OOBibStyle style = new OOBibStyle("testWithDefaultAtFirstLIne.jstyle", - layoutFormatterPreferences); + OOBibStyle style = new OOBibStyle("testWithDefaultAtFirstLIne.jstyle", layoutFormatterPreferences); assertTrue(style.isValid()); } } From 479155555fae20f9b37512f30e653b1b8566b37b Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 14:25:40 +0200 Subject: [PATCH 0565/1068] comment --- .../logic/openoffice/CitationMarkerEntry.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java index 1e5f39c0380..02ab60daf1a 100644 --- a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java @@ -43,6 +43,23 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * This is what we need for getCitationMarker. + * + * Details of BibEntry are accessed via getBibEntryOrNull() + * + * org/jabref/gui/openoffice.Citation and org/jabref/gui/openoffice.CitedKey + * + * are used as actual sources. + * + * Citation misses two things + * - isFirstAppearanceOfSource : could be extended to provide this. + * - pageInfo under DataModel JabRef52 needs CitationGroup + * + * CitedKey is used for creating normalizedCitationMarker, so we do + * not need pageInfo, uniqueLetter and isFirstAppearanceOfSource. + * + */ public interface CitationMarkerEntry { String getCitationKey(); BibEntry getBibEntryOrNull(); From 8335cedc099ddd5f790d3cd3bc5ff280c2e56817 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 14:29:22 +0200 Subject: [PATCH 0566/1068] cleanup, format, comments --- .../jabref/logic/openoffice/OOBibStyle.java | 38 +++++++------------ .../logic/openoffice/OOBibStyleTest.java | 4 +- 2 files changed, 15 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 53ea336f8c3..cc3da354ab1 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -6,7 +6,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; -import java.io.StringReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -19,24 +18,14 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; -import java.util.function.ToIntFunction; -import java.util.regex.Pattern; import org.jabref.logic.layout.Layout; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.logic.layout.LayoutFormatterPreferences; -import org.jabref.logic.layout.LayoutHelper; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.Author; -import org.jabref.model.entry.AuthorList; -import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.OrFields; 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.strings.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -321,7 +310,7 @@ public Layout getReferenceFormat(EntryType type) { } } - public static String regularizePageInfo( String p ) { + public static String regularizePageInfo(String p) { if (p == null) { return null; } @@ -463,7 +452,6 @@ public String getCitationMarker(List citationMarkerEntries, nonUniqueCitationMarkerHandling); } - /** * Indicate if it is an internal style * @@ -502,7 +490,6 @@ public int hashCode() { return Objects.hash(path, name, citProperties, properties); } - /* * * Property getters @@ -569,18 +556,18 @@ public boolean isNumberEntries() { } /** - * Convenience method for checking the property for whether we sort the bibliography - * according to their order of appearance in the text. + * Shall we sort the bibliography entries according to their order + * of first appearance in the text. * - * @return true to sort by appearance, false to sort alphabetically. + * @return true to sort by order of appearance, false to sort alphabetically. */ public boolean isSortByPosition() { return getBooleanProperty(IS_SORT_BY_POSITION); } /** - * Convenience method for checking whether citation markers should be italicized. - * Will only be relevant if isFormatCitations() returns true. + * Should citation markers be italicized? + * Only relevant if isFormatCitations() returns true. * * @return true to indicate that citations should be in italics. */ @@ -589,8 +576,8 @@ public boolean isItalicCitations() { } /** - * Convenience method for checking whether citation markers should be bold. - * Will only be relevant if isFormatCitations() returns true. + * Should citation markers be bold? + * Only relevant if isFormatCitations() returns true. * * @return true to indicate that citations should be in bold. */ @@ -599,11 +586,11 @@ public boolean isBoldCitations() { } /** - * Convenience method for checking whether citation markers formatted + * Should citation markers be formatted * according to the results of the isItalicCitations() and - * isBoldCitations() methods. + * isBoldCitations() methods? * - * @return true to indicate that citations should be in italics. + * @return true to indicate that citations should be in italics (or bold). */ public boolean isFormatCitations() { return (Boolean) citProperties.get(FORMAT_CITATIONS); @@ -622,7 +609,8 @@ public boolean getCitPropertyItalicEtAl() { } /** - * @return Field containing authors, with fallback fields. + * @return Names of fields containing authors: the first + * non-empty field is will be used. */ protected OrFields getAuthorFieldNames() { String authorFieldNamesString = this.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index dcd7bf1822c..50cd211f352 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -89,8 +89,8 @@ void testGetNumCitationMarkerForInText() throws IOException { // Unfortunately these two are both "; " in // jabref/src/main/resources/resource/openoffice/default_numerical.jstyle // We might want to change one of them - // style.getStringCitProperty(OOBibStyle.PAGE_INFO_SEPARATOR); - // style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR); + // style.getPageInfoSeparator(); + // style.getCitationSeparator(); /* The default numerical style uses "[1]", no space after "]" for in-text, * but "[1] " with space after "]" for the bibliography. From 4b3c350e2f4c80d19a95142df8b87467053add8a Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 17:18:59 +0200 Subject: [PATCH 0567/1068] sortBibEntryListForMulticite is not used, commented out --- .../org/jabref/gui/openoffice/OOBibBase.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 42a8d026776..1c1214104c4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -702,14 +702,14 @@ public void applyCitationEntries( * * Note: the sort is in-place, modifies the argument. */ - private void - sortBibEntryListForMulticite(List entries, - OOBibStyle style) { - if (entries.size() <= 1) { - return; - } - entries.sort(comparatorForMulticite(style)); - } + // private void + // sortBibEntryListForMulticite(List entries, + // OOBibStyle style) { + // if (entries.size() <= 1) { + // return; + // } + // entries.sort(comparatorForMulticite(style)); + // } /* *************************************** * From 7d8714bd05c2bb8efa2ed7f4d306eb9a866f93fe Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 17:21:23 +0200 Subject: [PATCH 0568/1068] OOBibStyle property-name constants and generic property-getters are private --- .../org/jabref/gui/openoffice/OOBibBase.java | 2 +- .../jabref/logic/openoffice/OOBibStyle.java | 226 ++++++++++++------ .../OOBibStyleGetCitationMarker.java | 2 +- .../OOBibStyleGetNumCitationMarker.java | 10 +- .../logic/openoffice/OOBibStyleTest.java | 4 +- 5 files changed, 164 insertions(+), 80 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1c1214104c4..7b9e54df1f8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1118,7 +1118,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti // Check if we should italicize the "et al." string in citations: boolean italicize = style.getCitPropertyItalicEtAl(); if (italicize) { - String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); + String etAlString = style.getEtAlString(); Objects.requireNonNull(etAlString); Objects.requireNonNull(citationText); for (int index = citationText.indexOf(etAlString); diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index cc3da354ab1..cad3bf54521 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -61,57 +61,141 @@ * */ public class OOBibStyle implements Comparable { + // Variable access definition in wrong order - private static final String ITALIC_ET_AL = "ItalicEtAl"; - private static final String MULTI_CITE_CHRONOLOGICAL = "MultiCiteChronological"; - public static final String MINIMUM_GROUPING_COUNT = "MinimumGroupingCount"; - public static final String ET_AL_STRING = "EtAlString"; - public static final String MAX_AUTHORS_FIRST = "MaxAuthorsFirst"; - public static final String REFERENCE_HEADER_PARAGRAPH_FORMAT = "ReferenceHeaderParagraphFormat"; - public static final String REFERENCE_PARAGRAPH_FORMAT = "ReferenceParagraphFormat"; - - public static final String TITLE = "Title"; + // Unlike many others beolow, UNDEFINED_CITATION_MARKER is not a + // key to properties or citProperties public static final String UNDEFINED_CITATION_MARKER = "??"; - // These are used in OOBibStyleGetNumCitationMarker - protected static final String BRACKET_AFTER = "BracketAfter"; - protected static final String BRACKET_BEFORE = "BracketBefore"; - protected static final String BRACKET_AFTER_IN_LIST = "BracketAfterInList"; - protected static final String BRACKET_BEFORE_IN_LIST = "BracketBeforeInList"; - protected static final String GROUPED_NUMBERS_SEPARATOR = "GroupedNumbersSeparator"; - protected static final String PAGE_INFO_SEPARATOR = "PageInfoSeparator"; - protected static final String CITATION_SEPARATOR = "CitationSeparator"; - - // These are used in OOBibStyleGetCitationMarker - protected static final String AUTHOR_FIELD = "AuthorField"; - protected static final String MAX_AUTHORS = "MaxAuthors"; - protected static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; - protected static final String YEAR_SEPARATOR = "YearSeparator"; - protected static final String AUTHOR_LAST_SEPARATOR = "AuthorLastSeparator"; - protected static final String IN_TEXT_YEAR_SEPARATOR = "InTextYearSeparator"; - protected static final String YEAR_FIELD = "YearField"; - protected static final String AUTHOR_LAST_SEPARATOR_IN_TEXT = "AuthorLastSeparatorInText"; - protected static final String OXFORD_COMMA = "OxfordComma"; - protected static final String AUTHOR_SEPARATOR = "AuthorSeparator"; + /* + * Keys for the PROPERTIES section of a *.jstyle file. + */ + private static final String TITLE = "Title"; + // TODO: unused SORT_ALGORITHM + private static final String SORT_ALGORITHM = "SortAlgorithm"; + private static final String IS_SORT_BY_POSITION = "IsSortByPosition"; + private static final String IS_NUMBER_ENTRIES = "IsNumberEntries"; + private static final String REFERENCE_HEADER_PARAGRAPH_FORMAT = "ReferenceHeaderParagraphFormat"; + private static final String REFERENCE_PARAGRAPH_FORMAT = "ReferenceParagraphFormat"; + + /* + * Keys for the CITATION section of a *.jstyle file. + */ + + /* + * general + */ private static final String CITATION_KEY_CITATIONS = "BibTeXKeyCitations"; + private static final String MULTI_CITE_CHRONOLOGICAL = "MultiCiteChronological"; + + // general / formatting citations + private static final String FORMAT_CITATIONS = "FormatCitations"; + private static final String CITATION_CHARACTER_FORMAT = "CitationCharacterFormat"; + + // TODO: unused ITALIC_CITATIONS, BOLD_CITATIONS + private static final String ITALIC_CITATIONS = "ItalicCitations"; + private static final String BOLD_CITATIONS = "BoldCitations"; + + // TODO: unused SUBSCRIPT_CITATIONS, SUPERSCRIPT_CITATIONS private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations"; private static final String SUPERSCRIPT_CITATIONS = "SuperscriptCitations"; - private static final String BOLD_CITATIONS = "BoldCitations"; - private static final String ITALIC_CITATIONS = "ItalicCitations"; - private static final String CITATION_CHARACTER_FORMAT = "CitationCharacterFormat"; - private static final String FORMAT_CITATIONS = "FormatCitations"; - private static final String IS_NUMBER_ENTRIES = "IsNumberEntries"; - private static final String IS_SORT_BY_POSITION = "IsSortByPosition"; - private static final String SORT_ALGORITHM = "SortAlgorithm"; + /* + * common (numeric and authoryear) + */ + + /** "{[}Smith 2000]" "Smith {[}2000]" "{[}1]" */ + private static final String BRACKET_BEFORE = "BracketBefore"; + + /** "[Smith 2000{]}" "Smith [2000{]}" "[1{]}" */ + private static final String BRACKET_AFTER = "BracketAfter"; + + /** Entry labels in bibliography: "{[}1]" */ + private static final String BRACKET_BEFORE_IN_LIST = "BracketBeforeInList"; + + /** Entry labels in bibliography: "[1{]}" */ + private static final String BRACKET_AFTER_IN_LIST = "BracketAfterInList"; + + /** "[Smith 2000a{; }pp 10-13]" "Smith [2000a{; }pp 10-13]" "[1{; }pp 10-13]" */ + private static final String PAGE_INFO_SEPARATOR = "PageInfoSeparator"; + + /** "[Smith 2000{; }Jones 2001]" "Smith [2000{; }Jones [2001]" "[1{; }2]" */ + private static final String CITATION_SEPARATOR = "CitationSeparator"; + + /* + * numeric + */ + + /** How many consecutive numbers in "[1; 2; 3]" allows grouping to "[1-3]" */ + private static final String MINIMUM_GROUPING_COUNT = "MinimumGroupingCount"; + + /** "[1{-}3]" */ + private static final String GROUPED_NUMBERS_SEPARATOR = "GroupedNumbersSeparator"; + + /* + * author-year + */ + + /** Name of field that contains the authors. May be a list: "author/editor" */ + private static final String AUTHOR_FIELD = "AuthorField"; + + /** How many authors to show before swithing to "et al." */ + private static final String MAX_AUTHORS = "MaxAuthors"; + + /** The first appearance of a source may have a higher limit. */ + private static final String MAX_AUTHORS_FIRST = "MaxAuthorsFirst"; + + /** "[Smith{, }Jones, and Brown 2000]" */ + private static final String AUTHOR_SEPARATOR = "AuthorSeparator"; + + /** "[Smith, Jones{,} and Brown 2000]" */ + private static final String OXFORD_COMMA = "OxfordComma"; + + /** "[Smith, Jones,{ and }Brown 2000]" */ + private static final String AUTHOR_LAST_SEPARATOR = "AuthorLastSeparator"; + + /** "Smith, Jones,{ and }Brown [2000]" */ + private static final String AUTHOR_LAST_SEPARATOR_IN_TEXT = "AuthorLastSeparatorInText"; + + private static final String ITALIC_ET_AL = "ItalicEtAl"; + /** "[Smith{ et al.} 2000]" */ + private static final String ET_AL_STRING = "EtAlString"; + + /** "[Smith et al.{ }2000]" */ + private static final String YEAR_SEPARATOR = "YearSeparator"; + + /** "Smith et al.{ }[2000]" */ + private static final String IN_TEXT_YEAR_SEPARATOR = "InTextYearSeparator"; + + /** Name of field that contains the year. May be a list "year/anotherFieldWithYear" */ + private static final String YEAR_FIELD = "YearField"; + + /** "[Smith et al. 2000a{,}b; pp 10-13]" */ + private static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; + // end of keys private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); // Formatter to be run on fields before they are used as part of citation marker: protected final LayoutFormatter fieldFormatter = new OOPreFormatter(); + /* + * Used or modified in OOBibStyleParser.readFormatFile() + */ + String name = ""; + String localCopy; + final LayoutFormatterPreferences prefs; + Layout defaultBibLayout; + boolean isDefaultLayoutPresent; + // reference layout mapped from entry type: + final Map bibLayout = new HashMap<>(); + final Map properties = new HashMap<>(); + final Map citProperties = new HashMap<>(); + boolean valid; + final SortedSet journals = new TreeSet<>(); + private final boolean fromResource; private final String path; @@ -120,21 +204,6 @@ public class OOBibStyle implements Comparable { private File styleFile; private long styleFileModificationTime = Long.MIN_VALUE; - /* - * Used or modified in OOBibStyleParser.readFormatFile() - */ - protected String name = ""; - protected String localCopy; - protected final LayoutFormatterPreferences prefs; - protected Layout defaultBibLayout; - protected boolean isDefaultLayoutPresent; - // reference layout mapped from entry type: - protected final Map bibLayout = new HashMap<>(); - protected final Map properties = new HashMap<>(); - protected final Map citProperties = new HashMap<>(); - protected boolean valid; - protected final SortedSet journals = new TreeSet<>(); - /** * Construct from user-provided style file. */ @@ -539,15 +608,21 @@ public String getStringCitProperty(String key) { /** * Minimal number of consecutive citation numbers needed to start - * replacing with an "i-j" range. + * replacing with an range like "10-13". */ public int getMinimumGroupingCount() { return getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); } /** - * Convenience method for checking the property for whether we use number citations or - * author-year citations. + * Used in number ranges like "10-13" in numbered citations. + */ + public String getGroupedNumbersSeparator() { + return getStringCitProperty(OOBibStyle.GROUPED_NUMBERS_SEPARATOR); + } + + /** + * Shall we use number citations or author-year citations. * * @return true if we use numbered citations, false otherwise. */ @@ -565,11 +640,32 @@ public boolean isSortByPosition() { return getBooleanProperty(IS_SORT_BY_POSITION); } + /** + * Should citation markers be formatted + * according to the results of the + * - isItalicCitations() // no, isItalicCitations() is not used at all + * - isBoldCitations() // no, isBoldCitations() is not used at all + * - getCitationCharacterFormat() // yes + * methods? + * + * @return true to indicate that citations should be formatted to getCitationCharacterFormat() + * in italics (or bold). + */ + public boolean isFormatCitations() { + return (Boolean) citProperties.get(FORMAT_CITATIONS); + } + + public String getCitationCharacterFormat() { + return getStringCitProperty(CITATION_CHARACTER_FORMAT); + } + /** * Should citation markers be italicized? * Only relevant if isFormatCitations() returns true. * * @return true to indicate that citations should be in italics. + * + * TODO: unused */ public boolean isItalicCitations() { return getBooleanCitProperty(ITALIC_CITATIONS); @@ -580,21 +676,13 @@ public boolean isItalicCitations() { * Only relevant if isFormatCitations() returns true. * * @return true to indicate that citations should be in bold. + * + * TODO: unused */ public boolean isBoldCitations() { return (Boolean) citProperties.get(BOLD_CITATIONS); } - /** - * Should citation markers be formatted - * according to the results of the isItalicCitations() and - * isBoldCitations() methods? - * - * @return true to indicate that citations should be in italics (or bold). - */ - public boolean isFormatCitations() { - return (Boolean) citProperties.get(FORMAT_CITATIONS); - } public boolean isCitationKeyCiteMarkers() { return (Boolean) citProperties.get(CITATION_KEY_CITATIONS); @@ -625,16 +713,12 @@ protected OrFields getYearFieldNames() { return FieldFactory.parseOrFields(yearFieldNamesString); } - public String getCitationCharacterFormat() { - return getStringCitProperty(CITATION_CHARACTER_FORMAT); - } - // The String to add between the two last author names, e.g. " & ". protected String getAuthorLastSeparator() { return getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); } - protected String getAuthorLastSeparatorInText() { + protected String getAuthorLastSeparatorInTextWithFallBack() { return Objects.requireNonNullElse( getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT), // Use the default one if no explicit separator for text is defined @@ -703,12 +787,12 @@ protected String getBracketAfterInListWithFallBack() { // The String to represent authors that are not mentioned, // e.g. " et al." - protected String getEtAlString() { + public String getEtAlString() { return getStringCitProperty(OOBibStyle.ET_AL_STRING); } // The String to add between author names except the last two, - // e.g. ", ". + // e.g. ", " in "[Smith, Jones and Brown]" protected String getAuthorSeparator() { return getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 088d2ffcf41..21b333973bf 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -415,7 +415,7 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, // The String to add between the two last author names, e.g. " & ". String andString = (inParenthesis ? style.getAuthorLastSeparator() - : style.getAuthorLastSeparatorInText()); + : style.getAuthorLastSeparatorInTextWithFallBack()); String pageInfoSeparator = style.getPageInfoSeparator(); String uniquefierSeparator = style.getUniquefierSeparator(); diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java index 1efd334c3a3..e817e36615a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java @@ -278,7 +278,7 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, // Emit pageInfo String pageInfo = block.get(0).pageInfo; if (pageInfo != null) { - sb.append(style.getStringCitProperty(OOBibStyle.PAGE_INFO_SEPARATOR) + pageInfo); + sb.append(style.getPageInfoSeparator() + pageInfo); } } else { @@ -324,13 +324,13 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, } // Emit: "first-last" sb.append(first); - sb.append(style.getStringCitProperty(OOBibStyle.GROUPED_NUMBERS_SEPARATOR)); + sb.append(style.getGroupedNumbersSeparator()); sb.append(last); } else { // Emit: first,first+1,...,last for (int j = 0; j < blockSize; j++) { if (j > 0) { - sb.append(style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR)); + sb.append(style.getCitationSeparator()); } sb.append(block.get(j).num); } @@ -388,7 +388,7 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, // emit current block // We are emitting a block if (blocksEmitted > 0) { - sb.append(style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR)); + sb.append(style.getCitationSeparator()); } int emittedNow = emitBlock.applyAsInt(currentBlock); if (emittedNow > 0) { @@ -407,7 +407,7 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, if (currentBlock.size() > 0) { // We are emitting a block if (blocksEmitted > 0) { - sb.append(style.getStringCitProperty(OOBibStyle.CITATION_SEPARATOR)); + sb.append(style.getCitationSeparator()); } emitBlock.applyAsInt(currentBlock); } diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 50cd211f352..1d0000f704f 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -306,8 +306,8 @@ void testGetCitationMarker() throws IOException { OOBibStyle.NonUniqueCitationMarker.THROWS)); /* - * Currently there is no override for MAX_AUTHORS, except - * cm.isFirstAppearanceOfSource, which asks for MAX_AUTHORS_FIRST + * Currently there is no way override for getMaxAuthors(), except + * cm.isFirstAppearanceOfSource, which asks for getMaxAuthorsFirst() */ citationMarkerEntries.clear(); cm = new CitationMarkerEntryImpl("Bostrom2006", entry, database, null, null, true); From b9353b5e048aaa0de9a968852a02c7f03b9775e3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 19:52:03 +0200 Subject: [PATCH 0569/1068] CitationMarkerEntry : doc, cleanup --- .../logic/openoffice/CitationMarkerEntry.java | 80 +++++++++---------- 1 file changed, 37 insertions(+), 43 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java index 02ab60daf1a..3d5e8f14ab6 100644 --- a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java @@ -1,50 +1,11 @@ package org.jabref.logic.openoffice; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.function.ToIntFunction; -import java.util.regex.Pattern; - -import org.jabref.logic.layout.Layout; -import org.jabref.logic.layout.LayoutFormatter; -import org.jabref.logic.layout.LayoutFormatterPreferences; -import org.jabref.logic.layout.LayoutHelper; import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.Author; -import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.Field; -import org.jabref.model.entry.field.FieldFactory; -import org.jabref.model.entry.field.OrFields; -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.strings.StringUtil; - - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** - * This is what we need for getCitationMarker. + * This is what we need for getCitationMarker to produce author-year + * citation markers. * * Details of BibEntry are accessed via getBibEntryOrNull() * @@ -61,11 +22,44 @@ * */ public interface CitationMarkerEntry { + + /** Citation key. This is what we usually get from the document. + * + * Used if getBibEntryOrNull() and/or getDatabaseOrNull() returns + * null, which indicates failure to lookup in the databases. + * The marker created is "Unresolved({citationKey})". + * + */ String getCitationKey(); + + /** Bibliography entry looked up from databases. + * + * May be null if not found. In this case getDatabaseOrNull() + * should also return null. + */ BibEntry getBibEntryOrNull(); + + /** + * The database where BibEntry was found. + * May be null, if not found (otherwise not). + */ BibDatabase getDatabaseOrNull(); + + /** + * uniqueLetter or null if not needed. + */ String getUniqueLetterOrNull(); + + /** + * pageInfo for this citation, provided by the user. + * May be null, for none. + */ String getPageInfoOrNull(); - boolean getIsFirstAppearanceOfSource(); -}; + /** + * @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(); +} From 21aad1688593b80d9f17c01676b1d463b1cf38f0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 19:52:47 +0200 Subject: [PATCH 0570/1068] format --- .../logic/openoffice/OOBibStyleGetNumCitationMarker.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java index e817e36615a..102f4bea10b 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java @@ -41,7 +41,8 @@ import org.slf4j.LoggerFactory; class OOBibStyleGetNumCitationMarker { - /* + + /* * Helper class for sorting citation numbers while * maintaining their correspondance to pageInfos. */ From 1b514c119d14df315fc438f24130df4c4387dc96 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 19:53:34 +0200 Subject: [PATCH 0571/1068] OOBibStyle.java passes checkstyle --- .../jabref/logic/openoffice/OOBibStyle.java | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index cad3bf54521..536446c997d 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -61,10 +61,10 @@ * */ public class OOBibStyle implements Comparable { - // Variable access definition in wrong order - // Unlike many others beolow, UNDEFINED_CITATION_MARKER is not a - // key to properties or citProperties + /** Unlike many others below, UNDEFINED_CITATION_MARKER is not a + * key to properties or citProperties + */ public static final String UNDEFINED_CITATION_MARKER = "??"; /* @@ -178,7 +178,18 @@ public class OOBibStyle implements Comparable { private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); - // Formatter to be run on fields before they are used as part of citation marker: + /** Formatter to be run on fields before they are used as part of citation marker. + * + * Usage: String output = fieldFormatter.format(input); + * + * Input: LaTeX, output: unicode with a small set of HTML tags + * indicating character formatting. + * + * Note: OOPreFormatter is stateless, the above call is equivalent to + * + * String output = OOPreFormatter.latexToUnicodeWithHtmlTags(input); + * + */ protected final LayoutFormatter fieldFormatter = new OOPreFormatter(); /* @@ -417,7 +428,6 @@ public static List regularizePageInfosForCitations(List pageInfo } } - /** * Defines sort order for pageInfo strings. * @@ -469,10 +479,9 @@ public String getNumCitationMarkerForBibliography(int number) { } public String getNormalizedCitationMarker(CitationMarkerEntry ce) { - return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this,ce, Optional.empty()); + return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, ce, Optional.empty()); } - /** * What should getCitationMarker do if it discovers that * uniqueLetters provided are not sufficient for unique presentation? @@ -587,7 +596,6 @@ private int getIntProperty(String key) { return (Integer) properties.get(key); } - /** * Get boolean property. * @@ -683,7 +691,6 @@ public boolean isBoldCitations() { return (Boolean) citProperties.get(BOLD_CITATIONS); } - public boolean isCitationKeyCiteMarkers() { return (Boolean) citProperties.get(CITATION_KEY_CITATIONS); } @@ -777,12 +784,12 @@ protected String getBracketAfterInList() { protected String getBracketBeforeInListWithFallBack() { return Objects.requireNonNullElse(getBracketBeforeInList(), - getBracketBefore() ); + getBracketBefore()); } protected String getBracketAfterInListWithFallBack() { return Objects.requireNonNullElse(getBracketAfterInList(), - getBracketAfter() ); + getBracketAfter()); } // The String to represent authors that are not mentioned, From 32a3efb90764805bd7d8b5ed64c3f066d286f85b Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 19:58:06 +0200 Subject: [PATCH 0572/1068] CitationMarkerEntryImpl.java : checkstyle, cleanup, describe --- .../openoffice/CitationMarkerEntryImpl.java | 54 ++++--------------- 1 file changed, 10 insertions(+), 44 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java index 4d75a3b20c1..986880760cc 100644 --- a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java +++ b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java @@ -1,54 +1,20 @@ package org.jabref.logic.openoffice; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.function.ToIntFunction; -import java.util.regex.Pattern; - -import org.jabref.logic.layout.Layout; -import org.jabref.logic.layout.LayoutFormatter; -import org.jabref.logic.layout.LayoutFormatterPreferences; -import org.jabref.logic.layout.LayoutHelper; import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.Author; -import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.Field; -import org.jabref.model.entry.field.FieldFactory; -import org.jabref.model.entry.field.OrFields; -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.strings.StringUtil; - - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +/** + * Implement CitationMarkerEntry by containing the data needed. + * + * {@see CitationMarkerEntry} for description. + * + */ public class CitationMarkerEntryImpl implements CitationMarkerEntry { final String citationKey; - final BibEntry bibEntry; // should allow null - final BibDatabase database; // should allow null - final String uniqueLetter; // may be null - final String pageInfo; // null for empty + final BibEntry bibEntry; + final BibDatabase database; + final String uniqueLetter; + final String pageInfo; final boolean isFirstAppearanceOfSource; public CitationMarkerEntryImpl(String citationKey, From 8031753761cbb8d46219b9a94443a350e692af6d Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 20:08:01 +0200 Subject: [PATCH 0573/1068] OOBibStyleGetCitationMarker cleanup, checkstyle --- .../OOBibStyleGetCitationMarker.java | 80 ++++++------------- 1 file changed, 24 insertions(+), 56 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 21b333973bf..3db94c2cc91 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -1,48 +1,19 @@ package org.jabref.logic.openoffice; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.function.ToIntFunction; -import java.util.regex.Pattern; - -import org.jabref.logic.layout.Layout; -import org.jabref.logic.layout.LayoutFormatter; -import org.jabref.logic.layout.LayoutFormatterPreferences; -import org.jabref.logic.layout.LayoutHelper; + import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.Author; import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; -import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.OrFields; -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.strings.StringUtil; - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - class OOBibStyleGetCitationMarker { /** @@ -89,8 +60,6 @@ private static String getAuthorLastName(AuthorList al, * maxAuthors less than -1 : throw RuntimeException * * @param andString For "A, B[ and ]C" - * @param yearSep Appended to result here. - * For example " " in default_authoryear.jstyle * * @return "Au[AS]Bu[AS]Cu[OXFORD_COMMA][andString]Du[yearSep]" * or "Au[etAlString][yearSep]" @@ -231,7 +200,7 @@ private static Optional getRawCitationMarkerField(BibEntry entr Objects.requireNonNull(entry, "Entry cannot be null"); Objects.requireNonNull(database, "database cannot be null"); - for (Field field : fields /*FieldFactory.parseOrFields(fields)*/) { + for (Field field : fields /* FieldFactory.parseOrFields(fields)*/) { Optional optionalContent = entry.getResolvedFieldOrAlias(field, database); final boolean foundSomething = (optionalContent.isPresent() && !optionalContent.get().trim().isEmpty()); @@ -277,7 +246,6 @@ private static String getCitationMarkerField(OOBibStyle style, Optional optionalFieldAndContent = getRawCitationMarkerField(entry, database, fields); - if (optionalFieldAndContent.isEmpty()) { // No luck? Return an empty string: return ""; @@ -292,7 +260,7 @@ private static String getCitationMarkerField(OOBibStyle style, // the content. final OrFields fieldsToRebrace = style.getAuthorFieldNames(); if (fieldsToRebrace.contains(fc.field) && StringUtil.isInCurlyBrackets(fc.content)) { - result = "{" + result + "}"; + result = "{" + result + "}"; } return result; } @@ -316,7 +284,7 @@ private enum AuthorYearMarkerPurpose { IN_PARENTHESIS, IN_TEXT, NORMALIZED - }; + } /** * How many authors would be emitted for ce, considering @@ -344,7 +312,7 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, if (maxAuthors == -1) { return nAuthors; } else { - return Integer.min(nAuthors,maxAuthors); + return Integer.min(nAuthors, maxAuthors); } } @@ -394,7 +362,6 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, boolean inParenthesis = (purpose == AuthorYearMarkerPurpose.IN_PARENTHESIS || purpose == AuthorYearMarkerPurpose.NORMALIZED); - // The String to separate authors from year, e.g. "; ". String yearSep = (inParenthesis ? style.getYearSeparator() @@ -420,7 +387,6 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, String pageInfoSeparator = style.getPageInfoSeparator(); String uniquefierSeparator = style.getUniquefierSeparator(); - StringBuilder sb = new StringBuilder(); if (inParenthesis) { sb.append(startBrace); @@ -429,14 +395,14 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, for (int j = 0; j < ces.size(); j++) { CitationMarkerEntry ce = ces.get(j); boolean startingNewGroup = startsNewGroup[j]; - boolean endingAGroup = (j + 1 == ces.size()) || startsNewGroup[j+1] ; + boolean endingAGroup = (j + 1 == ces.size()) || startsNewGroup[j + 1]; if (!startingNewGroup) { // Just add our uniqueLetter String uniqueLetter = ce.getUniqueLetterOrNull(); if (uniqueLetter != null) { - sb.append( uniquefierSeparator ); - sb.append( uniqueLetter ); + sb.append(uniquefierSeparator); + sb.append(uniqueLetter); } // And close the brace, if we are the last in the group. @@ -461,9 +427,9 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, int maxAuthors = (purpose == AuthorYearMarkerPurpose.NORMALIZED ? style.getMaxAuthors() - : calculateNAuthorsToEmit(style,ce)); + : calculateNAuthorsToEmit(style, ce)); - if ( maxAuthorsOverride.isPresent() ) { + if (maxAuthorsOverride.isPresent()) { maxAuthors = maxAuthorsOverride.get(); } @@ -587,11 +553,11 @@ public static String getCitationMarker( // We assume entries are already sorted, all we need is to // group consecutive entries if we can. // - // We also assume, that identical entries have the same uniquefier. + // We also assume, that identical entries have the same uniqueLetters. // List normalizedMarkers = new ArrayList<>(nEntries); - for (int i = 0; i < nEntries; i++){ + for (int i = 0; i < nEntries; i++) { String nm = getNormalizedCitationMarker(style, citationMarkerEntries.get(i), Optional.empty()); @@ -603,23 +569,23 @@ public static String getCitationMarker( // first of the group. int[] nAuthorsToEmit = new int[nEntries]; int[] nAuthorsToEmitRevised = new int[nEntries]; - for (int i = 0; i < nEntries; i++){ + for (int i = 0; i < nEntries; i++) { CitationMarkerEntry ce = citationMarkerEntries.get(i); nAuthorsToEmit[i] = calculateNAuthorsToEmit(style, ce); nAuthorsToEmitRevised[i] = calculateNAuthorsToEmit(style, ce); } boolean[] startsNewGroup = new boolean[nEntries]; - List filteredCitationMarkerEntries = new ArrayList<>(nEntries); + List filteredCitationMarkerEntries = new ArrayList<>(nEntries); int i_out = 0; - if ( nEntries > 0) { + if (nEntries > 0) { filteredCitationMarkerEntries.add(citationMarkerEntries.get(0)); startsNewGroup[i_out] = true; i_out++; } - for (int i = 1; i < nEntries; i++){ + for (int i = 1; i < nEntries; i++) { CitationMarkerEntry ce1 = citationMarkerEntries.get(i - 1); CitationMarkerEntry ce2 = citationMarkerEntries.get(i); String nm1 = normalizedMarkers.get(i - 1); @@ -646,7 +612,7 @@ public static String getCitationMarker( // our expectation that adding uniqueLetter is valid. boolean firstAppearanceInhibitsJoin; - if ( isUnresolved1 ) { + if (isUnresolved1) { firstAppearanceInhibitsJoin = true; // no join for unresolved } else { boolean isFirst1 = ce1.getIsFirstAppearanceOfSource(); @@ -654,17 +620,19 @@ public static String getCitationMarker( // nAuthorsToEmitRevised[i-1] may have been indirectly increased, // we have to check that too. - if (!isFirst1 && !isFirst2 && (nAuthorsToEmitRevised[i-1] == nAuthorsToEmit[i-1])){ + if (!isFirst1 && + !isFirst2 && + (nAuthorsToEmitRevised[i - 1] == nAuthorsToEmit[i - 1])) { // we can rely on normalizedMarkers firstAppearanceInhibitsJoin = false; } else if (style.getMaxAuthors() == style.getMaxAuthorsFirst()) { // we can rely on normalizedMarkers firstAppearanceInhibitsJoin = false; } else { - int prevShown = nAuthorsToEmitRevised[i-1]; - int need = nAuthorsToEmit[i]; + int prevShown = nAuthorsToEmitRevised[i - 1]; + int need = nAuthorsToEmit[i]; - if ( prevShown < need ) { + if (prevShown < need) { // We do not retrospectively change the number of authors shown // at the previous entry, take that as decided. firstAppearanceInhibitsJoin = true; @@ -725,7 +693,7 @@ public static String getCitationMarker( if (!startingNewGroup) { // inherit from first of group. Used at next i. - nAuthorsToEmitRevised[i] = nAuthorsToEmitRevised[i-1]; + nAuthorsToEmitRevised[i] = nAuthorsToEmitRevised[i - 1]; } sameAsPrev = (!startingNewGroup From da0f2f76ba0fa73cda269fd82d455fe12b3ee969 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 22:20:45 +0200 Subject: [PATCH 0574/1068] idea suggestions --- .../OOBibStyleGetCitationMarker.java | 51 ++++++++----------- 1 file changed, 21 insertions(+), 30 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 3db94c2cc91..82cb38f9e0d 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -35,7 +35,7 @@ private static String getAuthorLastName(AuthorList al, Author a = al.getAuthor(number); // "von " if von exists Optional von = a.getVon(); - if (von.isPresent() && !von.isEmpty()) { + if (von.isPresent() && !von.get().isEmpty()) { sb.append(von.get()); sb.append(' '); } @@ -47,7 +47,7 @@ private static String getAuthorLastName(AuthorList al, } /** - * @param authorList + * @param authorList Parsed list of authors. * * @param maxAuthors The maximum number of authors to write out. * If there are more authors, then ET_AL_STRING is emitted @@ -117,18 +117,15 @@ private static String formatAuthorList(OOBibStyle style, throw new RuntimeException("maxAuthors < -1 in formatAuthorList"); } + // emitAllAuthors == false means use "et al." boolean emitAllAuthors = ((nAuthors <= maxAuthors) || (maxAuthors == -1)); int nAuthorsToEmit = (emitAllAuthors ? nAuthors + // If we use "et al." maxAuthorsBeforeEtAl also limits the + // number of authors emitted. : Math.min(maxAuthorsBeforeEtAl, nAuthors)); - if (!emitAllAuthors) { - // If we use "et al." maxAuthorsBeforeEtAl also limits the - // number of authors emitted. - nAuthorsToEmit = Math.min(nAuthorsToEmit, maxAuthorsBeforeEtAl); - } - if (nAuthorsToEmit > 0) { // The first author sb.append(getAuthorLastName(authorList, 0)); @@ -533,11 +530,11 @@ public static String getNormalizedCitationMarker(OOBibStyle style, * Note: only consecutive citations are checked. * */ - public static String getCitationMarker( - OOBibStyle style, - List citationMarkerEntries, - boolean inParenthesis, - OOBibStyle.NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { + public static String + getCitationMarker(OOBibStyle style, + List citationMarkerEntries, + boolean inParenthesis, + OOBibStyle.NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { final int nEntries = citationMarkerEntries.size(); @@ -557,9 +554,9 @@ public static String getCitationMarker( // List normalizedMarkers = new ArrayList<>(nEntries); - for (int i = 0; i < nEntries; i++) { + for (CitationMarkerEntry citationMarkerEntry : citationMarkerEntries) { String nm = getNormalizedCitationMarker(style, - citationMarkerEntries.get(i), + citationMarkerEntry, Optional.empty()); normalizedMarkers.add(nm); } @@ -641,11 +638,7 @@ public static String getCitationMarker( // Check with extended normalizedMarkers. String nmx1 = getNormalizedCitationMarker(style, ce1, Optional.of(prevShown)); String nmx2 = getNormalizedCitationMarker(style, ce2, Optional.of(prevShown)); - if (nmx2.equals(nmx1)) { - firstAppearanceInhibitsJoin = false; - } else { - firstAppearanceInhibitsJoin = true; - } + firstAppearanceInhibitsJoin = !nmx2.equals(nmx1); } } } @@ -656,7 +649,7 @@ public static String getCitationMarker( String ul2 = ce2.getUniqueLetterOrNull(); String ul1 = ce1.getUniqueLetterOrNull(); - boolean uniqLetterPresenceChanged = (ul2 == null) != (ul1 == null); + boolean uniqueLetterPresenceChanged = (ul2 == null) != (ul1 == null); String xul2 = nullToEmptyString(ul2); String xul1 = nullToEmptyString(ul1); @@ -664,11 +657,11 @@ public static String getCitationMarker( String k2 = ce2.getCitationKey(); String k1 = ce1.getCitationKey(); - boolean uniqLetterDoesNotMakeUnique = (nm2.equals(nm1) - && xul2.equals(xul1) - && !k2.equals(k1)); + boolean uniqueLetterDoesNotMakeUnique = (nm2.equals(nm1) + && xul2.equals(xul1) + && !k2.equals(k1)); - if (uniqLetterDoesNotMakeUnique && + if (uniqueLetterDoesNotMakeUnique && nonUniqueCitationMarkerHandling == OOBibStyle.NonUniqueCitationMarker.THROWS) { throw new RuntimeException("different citation keys," + " but same normalizedMarker and uniqueLetter"); @@ -677,10 +670,8 @@ public static String getCitationMarker( boolean pageInfoInhibitsJoin; if (pi1.equals("") && pi2.equals("")) { pageInfoInhibitsJoin = false; - } else if (k2.equals(k1) && pi2.equals(pi1)) { - pageInfoInhibitsJoin = false; } else { - pageInfoInhibitsJoin = true; + pageInfoInhibitsJoin = !(k2.equals(k1) && pi2.equals(pi1)); } boolean normalizedMarkerChanged = !nm2.equals(nm1); @@ -688,8 +679,8 @@ public static String getCitationMarker( normalizedMarkerChanged || firstAppearanceInhibitsJoin || pageInfoInhibitsJoin - || uniqLetterPresenceChanged - || uniqLetterDoesNotMakeUnique); + || uniqueLetterPresenceChanged + || uniqueLetterDoesNotMakeUnique); if (!startingNewGroup) { // inherit from first of group. Used at next i. From 1ecfbbeac08fb587591ac7c72de6aae9dc35ea67 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 22:33:10 +0200 Subject: [PATCH 0575/1068] OOBibStyleGetNumCitationMarker.java cleanup, checkstyle --- .../OOBibStyleGetNumCitationMarker.java | 59 ++++--------------- 1 file changed, 11 insertions(+), 48 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java index 102f4bea10b..13f7547ed37 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java @@ -1,50 +1,15 @@ package org.jabref.logic.openoffice; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; import java.util.function.ToIntFunction; -import java.util.regex.Pattern; - -import org.jabref.logic.layout.Layout; -import org.jabref.logic.layout.LayoutFormatter; -import org.jabref.logic.layout.LayoutFormatterPreferences; -import org.jabref.logic.layout.LayoutHelper; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.Author; -import org.jabref.model.entry.AuthorList; -import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.Field; -import org.jabref.model.entry.field.FieldFactory; -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.strings.StringUtil; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; class OOBibStyleGetNumCitationMarker { /* * Helper class for sorting citation numbers while - * maintaining their correspondance to pageInfos. + * maintaining their correspondence to pageInfos. */ private static class NumberWithPageInfo { int num; @@ -63,7 +28,7 @@ private static class NumberWithPageInfo { private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPageInfo b) { int res = Integer.compare(a.num, b.num); if (res == 0) { - res = OOBibStyle.comparePageInfo( a.pageInfo, b.pageInfo ); + res = OOBibStyle.comparePageInfo(a.pageInfo, b.pageInfo); } return res; } @@ -93,7 +58,7 @@ public static String getNumCitationMarkerForInText(OOBibStyle style, * Create a numeric marker for use in the bibliography as label for the entry. * * To support for example numbers in superscript without brackets for the text, - * but "[1]" form for the bibliogaphy, the style can provide + * but "[1]" form for the bibliography, the style can provide * the optional "BracketBeforeInList" and "BracketAfterInList" strings * to be used in the bibliography instead of "BracketBefore" and "BracketAfter" * @@ -213,17 +178,18 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, * pageInfos with null values. */ List pageInfos = - OOBibStyle.regularizePageInfosForCitations((purpose == CitationMarkerPurpose.BIBLIOGRAPHY - ? null - : pageInfosForCitations), - numbers.size()); + OOBibStyle.regularizePageInfosForCitations( + (purpose == CitationMarkerPurpose.BIBLIOGRAPHY + ? null + : pageInfosForCitations), + numbers.size()); // Sort the numbers, together with the corresponding pageInfo values List nps = new ArrayList<>(); for (int i = 0; i < nCitations; i++) { nps.add(new NumberWithPageInfo(numbers.get(i), pageInfos.get(i))); } - Collections.sort(nps, OOBibStyleGetNumCitationMarker::compareNumberWithPageInfo); + nps.sort(OOBibStyleGetNumCitationMarker::compareNumberWithPageInfo); // "[" StringBuilder sb = new StringBuilder(bracketBefore); @@ -282,15 +248,12 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, sb.append(style.getPageInfoSeparator() + pageInfo); } } else { + // block has at least 2 elements /* * Check assumptions */ - // block has at least 2 elements - if (blockSize < 2) { - throw new RuntimeException("impossible: (blockSize < 2)"); - } // None of these elements has a pageInfo, // because if it had, we would not join. for (NumberWithPageInfo x : block) { @@ -328,7 +291,7 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, sb.append(style.getGroupedNumbersSeparator()); sb.append(last); } else { - // Emit: first,first+1,...,last + // Emit: first, first+1,..., last for (int j = 0; j < blockSize; j++) { if (j > 0) { sb.append(style.getCitationSeparator()); From 82b6c0c045eae8dee1dbab3e416d4ead1d1f48ae Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 22:54:07 +0200 Subject: [PATCH 0576/1068] OOBibStyle.java : checkstyle --- .../jabref/logic/openoffice/OOBibStyle.java | 88 +++++++++---------- 1 file changed, 43 insertions(+), 45 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 536446c997d..40cfd99d90a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -27,9 +27,6 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * * This class embodies bibliography formatting for OpenOffice, which @@ -103,7 +100,7 @@ public class OOBibStyle implements Comparable { private static final String SUPERSCRIPT_CITATIONS = "SuperscriptCitations"; /* - * common (numeric and authoryear) + * common (numeric and author-year) */ /** "{[}Smith 2000]" "Smith {[}2000]" "{[}1]" */ @@ -141,7 +138,7 @@ public class OOBibStyle implements Comparable { /** Name of field that contains the authors. May be a list: "author/editor" */ private static final String AUTHOR_FIELD = "AuthorField"; - /** How many authors to show before swithing to "et al." */ + /** How many authors to show before switching to "et al." */ private static final String MAX_AUTHORS = "MaxAuthors"; /** The first appearance of a source may have a higher limit. */ @@ -176,7 +173,7 @@ public class OOBibStyle implements Comparable { private static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; // end of keys - private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); + // private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); /** Formatter to be run on fields before they are used as part of citation marker. * @@ -293,9 +290,9 @@ private void setDefaultProperties() { citProperties.put(OXFORD_COMMA, ""); } - public Layout getDefaultBibLayout() { - return defaultBibLayout; - } + // public Layout getDefaultBibLayout() { + // return defaultBibLayout; + // } public String getName() { return name; @@ -347,8 +344,6 @@ private boolean isUpToDate() { /** * If this style was initialized from a file on disk, reload the style * if the file has been modified since it was read. - * - * @throws IOException */ public void ensureUpToDate() throws IOException { if (!isUpToDate()) { @@ -359,8 +354,6 @@ public void ensureUpToDate() throws IOException { /** * If this style was initialized from a file on disk, reload the style * information. - * - * @throws IOException */ private void reload() throws IOException { if (styleFile != null) { @@ -464,7 +457,7 @@ public String getNumCitationMarkerForInText(List numbers, * Create a numeric marker for use in the bibliography as label for the entry. * * To support for example numbers in superscript without brackets for the text, - * but "[1]" form for the bibliogaphy, the style can provide + * but "[1]" form for the bibliography, the style can provide * the optional "BracketBeforeInList" and "BracketAfterInList" strings * to be used in the bibliography instead of "BracketBefore" and "BracketAfter" * @@ -517,7 +510,7 @@ public enum NonUniqueCitationMarker { * * FORGIVEN : is needed to allow preliminary markers * for freshly inserted citations without - * going throw the uniquification process. + * going throw the uniquefication process. * * @return The formatted citation. */ @@ -574,15 +567,15 @@ public int hashCode() { * */ - /** - * Get a style property. - * - * @param propName The property name. - * @return The property value, or null if it doesn't exist. - */ - private Object getProperty(String propName) { - return properties.get(propName); - } + // /** + // * Get a style property. + // * + // * @param propName The property name. + // * @return The property value, or null if it doesn't exist. + // */ + // private Object getProperty(String propName) { + // return properties.get(propName); + // } private boolean getBooleanProperty(String propName) { return (Boolean) properties.get(propName); @@ -592,9 +585,9 @@ private String getStringProperty(String propName) { return (String) properties.get(propName); } - private int getIntProperty(String key) { - return (Integer) properties.get(key); - } + // private int getIntProperty(String key) { + // return (Integer) properties.get(key); + // } /** * Get boolean property. @@ -720,11 +713,12 @@ protected OrFields getYearFieldNames() { return FieldFactory.parseOrFields(yearFieldNamesString); } - // The String to add between the two last author names, e.g. " & ". + /* The String to add between the two last author names, e.g. " & ". */ protected String getAuthorLastSeparator() { return getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); } + /* As getAuthorLastSeparator, for in-text citation. */ protected String getAuthorLastSeparatorInTextWithFallBack() { return Objects.requireNonNullElse( getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT), @@ -752,8 +746,9 @@ protected String getYearSeparatorInText() { return getStringCitProperty(OOBibStyle.IN_TEXT_YEAR_SEPARATOR); } - // The maximum number of authors to write out in full without - // using etal. Set to -1 to always write out all authors. + /** The maximum number of authors to write out in full without + * using "et al." Set to -1 to always write out all authors. + */ protected int getMaxAuthors() { return getIntCitProperty(OOBibStyle.MAX_AUTHORS); } @@ -762,50 +757,53 @@ public int getMaxAuthorsFirst() { return getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); } - // Opening parenthesis before citation (or year, for in-text) + /** Opening parenthesis before citation (or year, for in-text) */ protected String getBracketBefore() { return getStringCitProperty(OOBibStyle.BRACKET_BEFORE); } - // Closing parenthesis after citation + /** Closing parenthesis after citation */ protected String getBracketAfter() { return getStringCitProperty(OOBibStyle.BRACKET_AFTER); } - // Opening parenthesis before citation marker in the bibliography - protected String getBracketBeforeInList() { + /** Opening parenthesis before citation marker in the bibliography. */ + private String getBracketBeforeInList() { return getStringCitProperty(OOBibStyle.BRACKET_BEFORE_IN_LIST); } - // Closing parenthesis after citation marker in the bibliography - protected String getBracketAfterInList() { - return getStringCitProperty(OOBibStyle.BRACKET_AFTER_IN_LIST); - } - protected String getBracketBeforeInListWithFallBack() { return Objects.requireNonNullElse(getBracketBeforeInList(), getBracketBefore()); } + /** Closing parenthesis after citation marker in the bibliography */ + private String getBracketAfterInList() { + return getStringCitProperty(OOBibStyle.BRACKET_AFTER_IN_LIST); + } + protected String getBracketAfterInListWithFallBack() { return Objects.requireNonNullElse(getBracketAfterInList(), getBracketAfter()); } - // The String to represent authors that are not mentioned, - // e.g. " et al." + /** The String to represent authors that are not mentioned, + * e.g. " et al." + */ public String getEtAlString() { return getStringCitProperty(OOBibStyle.ET_AL_STRING); } - // The String to add between author names except the last two, - // e.g. ", " in "[Smith, Jones and Brown]" + /** The String to add between author names except the last two: + * "[Smith{, }Jones and Brown]" + */ protected String getAuthorSeparator() { return getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR); } - // The String to put after the second to last author in case - // of three or more authors: (A, B[,] and C) + /** The String to put after the second to last author in case + * of three or more authors: (A, B{,} and C) + */ protected String getOxfordComma() { return getStringCitProperty(OOBibStyle.OXFORD_COMMA); } From 7a76a7d9968e3934a3a0862dc18ef565b5bc4008 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Apr 2021 23:32:25 +0200 Subject: [PATCH 0577/1068] drop unused property: SORT_ALGORITHM = "SortAlgorithm" --- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 40cfd99d90a..8624c4bf64a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -69,9 +69,6 @@ public class OOBibStyle implements Comparable { */ private static final String TITLE = "Title"; - // TODO: unused SORT_ALGORITHM - private static final String SORT_ALGORITHM = "SortAlgorithm"; - private static final String IS_SORT_BY_POSITION = "IsSortByPosition"; private static final String IS_NUMBER_ENTRIES = "IsNumberEntries"; private static final String REFERENCE_HEADER_PARAGRAPH_FORMAT = "ReferenceHeaderParagraphFormat"; @@ -244,8 +241,6 @@ private void setDefaultProperties() { // Set default property values: properties.put(TITLE, "Bibliography"); - /* TODO: unused */ properties.put(SORT_ALGORITHM, "alphanumeric"); - properties.put(IS_SORT_BY_POSITION, Boolean.FALSE); properties.put(IS_NUMBER_ENTRIES, Boolean.FALSE); From e849a67fefdb0d38f68ab0cb9f7a51f8c0b71b8e Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 10 Apr 2021 14:39:24 +0200 Subject: [PATCH 0578/1068] add DocumentConnection.setParagraphStyle --- .../gui/openoffice/DocumentConnection.java | 35 ++++++++++++++----- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java index 16fd8de0506..d32cab045b2 100644 --- a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java @@ -33,7 +33,7 @@ // import org.jabref.logic.openoffice.OOPreFormatter; import org.jabref.logic.openoffice.OOUtil; // import org.jabref.logic.openoffice.UndefinedBibtexEntry; -// import org.jabref.logic.openoffice.UndefinedParagraphFormatException; +import org.jabref.logic.openoffice.UndefinedParagraphFormatException; // import org.jabref.model.database.BibDatabase; // import org.jabref.model.entry.BibEntry; // import org.jabref.model.entry.field.StandardField; @@ -74,6 +74,7 @@ import com.sun.star.text.ReferenceFieldPart; import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XFootnote; +import com.sun.star.text.XParagraphCursor; import com.sun.star.text.XReferenceMarksSupplier; import com.sun.star.text.XText; import com.sun.star.text.XTextContent; @@ -104,8 +105,8 @@ class DocumentConnection { * "CharStyleName" is an OpenOffice Property name. */ private static final String CHAR_STYLE_NAME = "CharStyleName"; - private static final Logger LOGGER = - LoggerFactory.getLogger(DocumentConnection.class); + private static final String PARA_STYLE_NAME = "ParaStyleName"; + private static final Logger LOGGER = LoggerFactory.getLogger(DocumentConnection.class); public XTextDocument mxDoc; @@ -979,11 +980,10 @@ public XNamed insertReferenceMark(String name, * @param charStyle Name of the character style as known by Openoffice. */ public static void - setCharStyle( - XTextCursor position, // TODO: maybe an XTextRange is sufficient here - String charStyle - ) - throws UndefinedCharacterFormatException { + setCharStyle(XTextCursor position, // TODO: maybe an XTextRange is sufficient here + String charStyle) + throws + UndefinedCharacterFormatException { XPropertySet xCursorProps = unoQI(XPropertySet.class, position); @@ -999,6 +999,25 @@ public XNamed insertReferenceMark(String name, } } + public static void setParagraphStyle(XTextCursor cursor, + String parStyle) + throws + UndefinedParagraphFormatException { + XParagraphCursor parCursor = unoQI(XParagraphCursor.class, cursor); + + // Access the property set of the cursor, and set the currently selected text + // (which is the string we just inserted) to be bold + XPropertySet props = unoQI(XPropertySet.class, parCursor); + try { + props.setPropertyValue(PARA_STYLE_NAME, parStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + throw new UndefinedParagraphFormatException(parStyle); + } + } + /** * Apply direct character format "Italic" to a range of text. * From 27dd533a6ebb633d8a7517da02b7800b411c17e3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 10 Apr 2021 14:52:49 +0200 Subject: [PATCH 0579/1068] feature: do not throw on setParagraphStyle It is better to have a bibliography without the requested paragraph formats than an empty one. Warning the user should be done in a better way than the current based on LOGGER.warn() --- .../org/jabref/gui/openoffice/OOBibBase.java | 64 +++++++++++++----- .../org/jabref/logic/openoffice/OOUtil.java | 67 ++++++++++--------- 2 files changed, 83 insertions(+), 48 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7b9e54df1f8..8401cbd2cb6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1816,7 +1816,6 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, * @param cursor Where to * @param entries Its iteration order defines order in bibliography. * @param style Style. - * @param parFormat Passed to OOUtil.insertFullReferenceAtCurrentLocation * @param uniqueLetters * * Only called from populateBibTextSection (and that from rebuildBibTextSection) @@ -1825,10 +1824,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, XTextCursor cursor, CitationGroups cgs, CitedKeys bibliography, - OOBibStyle style, - String parFormat) + OOBibStyle style) throws - UndefinedParagraphFormatException, IllegalArgumentException, UnknownPropertyException, PropertyVetoException, @@ -1842,6 +1839,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, System.out.printf("Ref isNumberEntries %s\n", style.isNumberEntries()); } + String parStyle = style.getReferenceParagraphFormat(); + for (CitedKey ck : bibliography.values()) { if (debugThisFun) { @@ -1852,6 +1851,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, : String.format("%02d",ck.number.get()))); } + // this is where we create the paragraph. OOUtil.insertParagraphBreak(documentConnection.xText, cursor); // insert marker "[1]" @@ -1921,13 +1921,30 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // insert the actual details. Layout layout = style.getReferenceFormat(bibentry.getType()); layout.setPostFormatter(POSTFORMATTER); - OOUtil.insertFullReferenceAtCurrentLocation(documentConnection.xText, - cursor, - layout, - parFormat, - bibentry, - ck.db.get().database, - ck.uniqueLetter.orElse(null)); + + String formattedText = OOUtil.formatFullReference(layout, + bibentry, + ck.db.get().database, + ck.uniqueLetter.orElse(null)); + + // format the paragraph + try { + if (parStyle != null) { + DocumentConnection.setParagraphStyle(cursor, + parStyle); + } + } catch ( UndefinedParagraphFormatException ex ) { + // TODO: precheck or remember if we already emitted this message. + String message = + String.format("Could not apply paragraph format '%s' to bibliography entry", + parStyle); + // LOGGER.warn(message, ex); + LOGGER.warn(message); // no stack trace + } + // Insert the formatted text: + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection.xText, + cursor, + formattedText); } } } @@ -2020,17 +2037,30 @@ private void populateBibTextSection(DocumentConnection documentConnection, XTextCursor cursor = (documentConnection.xText .createTextCursorByRange(section.getAnchor())); - OOUtil.insertTextAtCurrentLocation(documentConnection.xText, - cursor, - style.getTitle(), - style.getReferenceHeaderParagraphFormat()); + // emit header + documentConnection.xText.insertString(cursor, + style.getTitle(), + true); + String parStyle = style.getReferenceHeaderParagraphFormat(); + try { + if (parStyle != null) { + DocumentConnection.setParagraphStyle(cursor, parStyle); + } + } catch ( UndefinedParagraphFormatException ex ) { + String message = + String.format("Could not apply paragraph format '%s' to bibliography header", + parStyle); + // LOGGER.warn(message, ex); + LOGGER.warn(message); // No stack trace. + } + cursor.collapseToEnd(); + // emit body insertFullReferenceAtCursor(documentConnection, cursor, cgs, bibliography, - style, - style.getReferenceParagraphFormat()); + style); documentConnection.insertBookmark(OOBibBase.BIB_SECTION_END_NAME, cursor, diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 7273e6580ca..863424c5a5a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -58,20 +58,32 @@ private OOUtil() { } /** - * Insert a reference, formatted using a Layout, at the position of a given cursor. + * Format the reference part of a bibliography entry using a Layout. + * + * The label (if any) and paragraph style are not added here. + * + * param parStyle The name of the paragraph style to use. + * + * Not used here, for now we leave application of + * the paragraph style to the caller. * - * @param text The text to insert in. - * @param cursor The cursor giving the insert location. * @param layout The Layout to format the reference with. - * @param parStyle The name of the paragraph style to use. * @param entry The entry to insert. * @param database The database the entry belongs to. * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. + * + * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation() */ - public static void insertFullReferenceAtCurrentLocation(XText text, XTextCursor cursor, - Layout layout, String parStyle, BibEntry entry, BibDatabase database, String uniquefier) - throws UndefinedParagraphFormatException, UnknownPropertyException, PropertyVetoException, - WrappedTargetException, IllegalArgumentException { + public static String formatFullReference(Layout layout, + BibEntry entry, + BibDatabase database, + String uniquefier) + throws + // TODO: are any of these thrown? + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException { // Backup the value of the uniq field, just in case the entry already has it: Optional oldUniqVal = entry.getField(UNIQUEFIER_FIELD); @@ -92,43 +104,37 @@ public static void insertFullReferenceAtCurrentLocation(XText text, XTextCursor } else { entry.clearField(UNIQUEFIER_FIELD); } - - // Insert the formatted text: - OOUtil.insertOOFormattedTextAtCurrentLocation(text, cursor, formattedText, parStyle); + return formattedText; } /** - * Insert a text with formatting indicated by HTML-like tags, into - * a text at the position given by a cursor. + * Insert a text in OOFormattedText + * (where character formatting is indicated by HTML-like tags), into + * an {@code XText} at the position given by an {@code XTextCursor}. * - * Set {@code parStyle}, process {@code ltext} in chunks between - * HTML-tags, while updating current formatting state at HTML-tags. + * Process {@code ltext} in chunks between HTML-tags, while + * updating current formatting state at HTML-tags. * * Finally: {@code cursor.collapseToEnd()} * + * Note: Leaves setting the paragraph style to the caller. + * * @param text The text to insert in. * @param cursor The cursor giving the insert location. * @param lText The marked-up text to insert. - * @param parStyle The name of the paragraph style to use. * @throws WrappedTargetException * @throws PropertyVetoException * @throws UnknownPropertyException * @throws IllegalArgumentException */ - public static void insertOOFormattedTextAtCurrentLocation(XText text, XTextCursor cursor, String lText, - String parStyle) throws UndefinedParagraphFormatException, UnknownPropertyException, PropertyVetoException, - WrappedTargetException, IllegalArgumentException { - - XParagraphCursor parCursor = UnoRuntime.queryInterface( - XParagraphCursor.class, cursor); - XPropertySet props = UnoRuntime.queryInterface( - XPropertySet.class, parCursor); - - try { - props.setPropertyValue(PARA_STYLE_NAME, parStyle); - } catch (com.sun.star.lang.IllegalArgumentException ex) { - throw new UndefinedParagraphFormatException(parStyle); - } + public static void insertOOFormattedTextAtCurrentLocation(XText text, + XTextCursor cursor, + String lText) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException { List formatting = new ArrayList<>(); // We need to extract formatting. Use a simple regexp search iteration: @@ -181,7 +187,6 @@ public static void insertOOFormattedTextAtCurrentLocation(XText text, XTextCurso if (piv < lText.length()) { OOUtil.insertTextAtCurrentLocation(text, cursor, lText.substring(piv), formatting); } - cursor.collapseToEnd(); } From 8da054819645f7c31a784240ca8a4794494e0056 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 10 Apr 2021 14:59:11 +0200 Subject: [PATCH 0580/1068] format --- .../gui/openoffice/OpenOfficePanel.java | 31 ++++++++++++------- .../org/jabref/logic/openoffice/OOUtil.java | 14 ++++++--- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index b4d04abc97d..d4d716a5b7a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -163,24 +163,31 @@ private void initPanel() { setStyleFile.setMaxWidth(Double.MAX_VALUE); setStyleFile.setOnAction(event -> { - - dialogService.showCustomDialogAndWait(new StyleSelectDialogView(loader)).ifPresent(selectedStyle -> { - style = selectedStyle; - try { - style.ensureUpToDate(); - } catch (IOException e) { - LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", e); - } - dialogService.notify(Localization.lang("Current style is '%0'", style.getName())); + dialogService.showCustomDialogAndWait(new StyleSelectDialogView(loader)) + .ifPresent(selectedStyle -> { + style = selectedStyle; + try { + style.ensureUpToDate(); + } catch (IOException e) { + LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", e); + } + dialogService.notify(Localization.lang("Current style is '%0'", + style.getName())); + }); }); - }); - pushEntries.setTooltip(new Tooltip(Localization.lang("Cite selected entries between parenthesis"))); + pushEntries.setTooltip( + new Tooltip(Localization.lang("Cite selected entries between parenthesis"))); + pushEntries.setOnAction(e -> pushEntries(true, true, false)); pushEntries.setMaxWidth(Double.MAX_VALUE); - pushEntriesInt.setTooltip(new Tooltip(Localization.lang("Cite selected entries with in-text citation"))); + + pushEntriesInt.setTooltip( + new Tooltip(Localization.lang("Cite selected entries with in-text citation"))); + pushEntriesInt.setOnAction(e -> pushEntries(false, true, false)); pushEntriesInt.setMaxWidth(Double.MAX_VALUE); + pushEntriesEmpty.setTooltip(new Tooltip(Localization.lang("Insert a citation without text (the entry will appear in the reference list)"))); pushEntriesEmpty.setOnAction(e -> pushEntries(false, false, false)); pushEntriesEmpty.setMaxWidth(Double.MAX_VALUE); diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 863424c5a5a..64c2ccf6971 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -190,7 +190,9 @@ public static void insertOOFormattedTextAtCurrentLocation(XText text, cursor.collapseToEnd(); } - public static void insertParagraphBreak(XText text, XTextCursor cursor) throws IllegalArgumentException { + public static void insertParagraphBreak(XText text, XTextCursor cursor) + throws + IllegalArgumentException { text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); cursor.collapseToEnd(); } @@ -202,8 +204,8 @@ public static void insertParagraphBreak(XText text, XTextCursor cursor) throws I * Insert {@code string} into {@code text} at {@code cursor}, while removing the content * of the cursor's range. The cursor's content is {@code string} now. * - * Apply character direct formatting from {@code - * formatting}. Features not in {@code formatting} are removed by setting to NONE. + * Apply character direct formatting from {@code formatting}. + * Features not in {@code formatting} are removed by setting to NONE. * * Finally: {@code cursor.collapseToEnd();} */ @@ -211,11 +213,12 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S List formatting) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException { + text.insertString(cursor, string, true); // Access the property set of the cursor, and set the currently selected text // (which is the string we just inserted) to be bold - XPropertySet xCursorProps = UnoRuntime.queryInterface( - XPropertySet.class, cursor); + XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); + if (formatting.contains(Formatting.BOLD)) { xCursorProps.setPropertyValue(CHAR_WEIGHT, com.sun.star.awt.FontWeight.BOLD); @@ -250,6 +253,7 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S xCursorProps.setPropertyValue("CharFontPitch", com.sun.star.awt.FontPitch.VARIABLE); } */ + if (formatting.contains(Formatting.SUBSCRIPT)) { xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (byte) -101); From 14fa5442fc3251df9012caf0913f5eee0d345d67 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 10 Apr 2021 15:01:20 +0200 Subject: [PATCH 0581/1068] drop insertTextAtCurrentLocation (old implementation) --- .../org/jabref/logic/openoffice/OOUtil.java | 29 ------------------- 1 file changed, 29 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 64c2ccf6971..8f2167c7537 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -285,35 +285,6 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S cursor.collapseToEnd(); } - /** - * Set cursor range content to {@code string}, apply {@code - * parStyle} to it, {@code cursor.collapseToEnd()}. - * - * Insert {@code string} into {@code text} at {@code cursor}, while removing the content - * of the cursor's range. The cursor's content is {@code string} now. - * - * Set paragraph style to {@code parStyle} - * - * Finally: {@code cursor.collapseToEnd();} - */ - public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, String string, String parStyle) - throws WrappedTargetException, PropertyVetoException, UnknownPropertyException, - UndefinedParagraphFormatException { - text.insertString(cursor, string, true); - XParagraphCursor parCursor = UnoRuntime.queryInterface( - XParagraphCursor.class, cursor); - // Access the property set of the cursor, and set the currently selected text - // (which is the string we just inserted) to be bold - XPropertySet props = UnoRuntime.queryInterface( - XPropertySet.class, parCursor); - try { - props.setPropertyValue(PARA_STYLE_NAME, parStyle); - } catch (IllegalArgumentException ex) { - throw new UndefinedParagraphFormatException(parStyle); - } - cursor.collapseToEnd(); - } - public static Object getProperty(Object o, String property) throws UnknownPropertyException, WrappedTargetException { XPropertySet props = UnoRuntime.queryInterface( From e5122ea17ece7800c392890df16d9b99817a5e01 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 10 Apr 2021 15:38:44 +0200 Subject: [PATCH 0582/1068] drop properties BRACKET_BEFORE BRACKET_AFTER --- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 8624c4bf64a..9414f9672b1 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -244,11 +244,6 @@ private void setDefaultProperties() { properties.put(IS_SORT_BY_POSITION, Boolean.FALSE); properties.put(IS_NUMBER_ENTRIES, Boolean.FALSE); - // BRACKET_BEFORE and BRACKET_AFTER appears both in - // properties and citProperties - /* TODO: unused */ properties.put(BRACKET_BEFORE, "["); - /* TODO: unused */ properties.put(BRACKET_AFTER, "]"); - properties.put(REFERENCE_PARAGRAPH_FORMAT, "Default"); properties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1"); From 310f8abbe7148892d973cbb16a7d29e5bffe5573 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 11 Apr 2021 18:14:12 +0200 Subject: [PATCH 0583/1068] OOBibStyleParser has more checks, returns ParseLog Need a way to show it in the GUI. Currently showInformationDialogAndWait and showErrorDialogAndWait, but these are not wide enough, and they do not allow the messages to be copied out. --- .../StyleSelectDialogViewModel.java | 30 +- .../jabref/logic/openoffice/OOBibStyle.java | 186 +++-- .../logic/openoffice/OOBibStyleParser.java | 650 +++++++++++++++--- .../jabref/logic/openoffice/StyleLoader.java | 42 +- .../openoffice/default_authoryear.jstyle | 34 +- .../openoffice/default_numerical.jstyle | 32 +- .../org/jabref/logic/openoffice/test.jstyle | 8 +- .../testWithDefaultAtFirstLIne.jstyle | 8 +- 8 files changed, 769 insertions(+), 221 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java index 80c7b97c8de..3d884d013b8 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java @@ -23,6 +23,7 @@ import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.OOBibStyle; +import org.jabref.logic.openoffice.OOBibStyleParser; import org.jabref.logic.openoffice.OpenOfficePreferences; import org.jabref.logic.openoffice.StyleLoader; import org.jabref.logic.util.StandardFileType; @@ -66,14 +67,27 @@ public void addStyleFile() { .build(); Optional path = dialogService.showFileOpenDialog(fileDialogConfiguration); path.map(Path::toAbsolutePath).map(Path::toString).ifPresent(stylePath -> { - if (loader.addStyleIfValid(stylePath)) { - preferences.setCurrentStyle(stylePath); - styles.setAll(loadStyles()); - selectedItem.setValue(getStyleOrDefault(stylePath)); - } else { - dialogService.showErrorDialogAndWait(Localization.lang("Invalid style selected"), Localization.lang("You must select a valid style file. Your style is probably missing a line for the type \"default\".")); - } - }); + OOBibStyleParser.ParseLog parseLog = loader.addStyleIfValid(stylePath); + if ( !parseLog.hasError() ) { + preferences.setCurrentStyle(stylePath); + styles.setAll(loadStyles()); + selectedItem.setValue(getStyleOrDefault(stylePath)); + if (!parseLog.isEmpty()) { + // showInformationDialogAndWait shows a non-resizable window, + // not wide enough. + dialogService.showInformationDialogAndWait("Parse log", parseLog.format()); + } + } else { + dialogService.showErrorDialogAndWait( + Localization.lang("Invalid style selected"), + Localization.lang( + "You must select a valid style file." + +" Your style is probably missing a line for the type \"default\".") + + "\n" + + parseLog.format() + ); + } + }); } public List loadStyles() { diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 9414f9672b1..3c2bb2af06c 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -88,11 +88,18 @@ public class OOBibStyle implements Comparable { private static final String FORMAT_CITATIONS = "FormatCitations"; private static final String CITATION_CHARACTER_FORMAT = "CitationCharacterFormat"; - // TODO: unused ITALIC_CITATIONS, BOLD_CITATIONS + // TODO: ITALIC_CITATIONS ItalicCitations is not implemented + // status: + // - jstyles.jabref.org-master : 4 styles mention it, value is false in all of them. + // - getter: isItalicCitations() exists, but only called from tests, to assert it is false. + // - default: citProperties.put(ITALIC_CITATIONS, Boolean.FALSE); + // private static final String ITALIC_CITATIONS = "ItalicCitations"; + + // TODO: BOLD_CITATIONS is not implemented private static final String BOLD_CITATIONS = "BoldCitations"; - // TODO: unused SUBSCRIPT_CITATIONS, SUPERSCRIPT_CITATIONS + // TODO: SUBSCRIPT_CITATIONS, SUPERSCRIPT_CITATIONS are not implemented private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations"; private static final String SUPERSCRIPT_CITATIONS = "SuperscriptCitations"; @@ -189,17 +196,28 @@ public class OOBibStyle implements Comparable { /* * Used or modified in OOBibStyleParser.readFormatFile() */ - String name = ""; String localCopy; - final LayoutFormatterPreferences prefs; - Layout defaultBibLayout; - boolean isDefaultLayoutPresent; + + String obsName = ""; + final SortedSet journals = new TreeSet<>(); + + final Map obsProperties = new HashMap<>(); + final Map obsCitProperties = new HashMap<>(); + // reference layout mapped from entry type: final Map bibLayout = new HashMap<>(); - final Map properties = new HashMap<>(); - final Map citProperties = new HashMap<>(); + Layout defaultBibLayout; + boolean isDefaultLayoutPresent; + + final LayoutFormatterPreferences prefs; boolean valid; - final SortedSet journals = new TreeSet<>(); + + /** Messages from that parser. + * + * Since we are parsing from the constructor, there is no way to + * return it to the caller there. + */ + OOBibStyleParser.ParseLog parseLog; private final boolean fromResource; @@ -218,7 +236,7 @@ public OOBibStyle(File styleFile, this.prefs = Objects.requireNonNull(prefs); this.styleFile = Objects.requireNonNull(styleFile); this.encoding = Objects.requireNonNull(encoding); - setDefaultProperties(); + // setDefaultProperties(); // moved into initialize() reload(); fromResource = false; path = styleFile.getPath(); @@ -231,53 +249,53 @@ public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) throws this.prefs = Objects.requireNonNull(prefs); Objects.requireNonNull(resourcePath); this.encoding = StandardCharsets.UTF_8; - setDefaultProperties(); - initialize(OOBibStyle.class.getResourceAsStream(resourcePath)); + // setDefaultProperties(); // moved into initialize() + initialize(OOBibStyle.class.getResourceAsStream(resourcePath), resourcePath); fromResource = true; path = resourcePath; } private void setDefaultProperties() { // Set default property values: - properties.put(TITLE, "Bibliography"); + obsProperties.put(TITLE, "Bibliography"); - properties.put(IS_SORT_BY_POSITION, Boolean.FALSE); - properties.put(IS_NUMBER_ENTRIES, Boolean.FALSE); + obsProperties.put(IS_SORT_BY_POSITION, Boolean.FALSE); + obsProperties.put(IS_NUMBER_ENTRIES, Boolean.FALSE); - properties.put(REFERENCE_PARAGRAPH_FORMAT, "Default"); - properties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1"); + obsProperties.put(REFERENCE_PARAGRAPH_FORMAT, "Default"); + obsProperties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1"); - // Set default properties for the citation marker: - citProperties.put(AUTHOR_FIELD, + // Set default obsCitProperties for the citation marker: + obsCitProperties.put(AUTHOR_FIELD, FieldFactory.serializeOrFields(StandardField.AUTHOR, StandardField.EDITOR)); - citProperties.put(YEAR_FIELD, StandardField.YEAR.getName()); - citProperties.put(MAX_AUTHORS, 3); - citProperties.put(MAX_AUTHORS_FIRST, -1); - citProperties.put(AUTHOR_SEPARATOR, ", "); - citProperties.put(AUTHOR_LAST_SEPARATOR, " & "); - citProperties.put(AUTHOR_LAST_SEPARATOR_IN_TEXT, null); - citProperties.put(ET_AL_STRING, " et al."); - citProperties.put(YEAR_SEPARATOR, ", "); - citProperties.put(IN_TEXT_YEAR_SEPARATOR, " "); - - citProperties.put(BRACKET_BEFORE, "("); - citProperties.put(BRACKET_AFTER, ")"); - - citProperties.put(CITATION_SEPARATOR, "; "); - citProperties.put(PAGE_INFO_SEPARATOR, "; "); - citProperties.put(GROUPED_NUMBERS_SEPARATOR, "-"); - citProperties.put(MINIMUM_GROUPING_COUNT, 3); - citProperties.put(FORMAT_CITATIONS, Boolean.FALSE); - citProperties.put(CITATION_CHARACTER_FORMAT, "Default"); - citProperties.put(ITALIC_CITATIONS, Boolean.FALSE); - citProperties.put(BOLD_CITATIONS, Boolean.FALSE); - citProperties.put(SUPERSCRIPT_CITATIONS, Boolean.FALSE); - citProperties.put(SUBSCRIPT_CITATIONS, Boolean.FALSE); - citProperties.put(MULTI_CITE_CHRONOLOGICAL, Boolean.TRUE); - citProperties.put(CITATION_KEY_CITATIONS, Boolean.FALSE); - citProperties.put(ITALIC_ET_AL, Boolean.FALSE); - citProperties.put(OXFORD_COMMA, ""); + obsCitProperties.put(YEAR_FIELD, StandardField.YEAR.getName()); + obsCitProperties.put(MAX_AUTHORS, 3); + obsCitProperties.put(MAX_AUTHORS_FIRST, -1); + obsCitProperties.put(AUTHOR_SEPARATOR, ", "); + obsCitProperties.put(AUTHOR_LAST_SEPARATOR, " & "); + obsCitProperties.put(AUTHOR_LAST_SEPARATOR_IN_TEXT, null); + obsCitProperties.put(ET_AL_STRING, " et al."); + obsCitProperties.put(YEAR_SEPARATOR, ", "); + obsCitProperties.put(IN_TEXT_YEAR_SEPARATOR, " "); + + obsCitProperties.put(BRACKET_BEFORE, "("); + obsCitProperties.put(BRACKET_AFTER, ")"); + + obsCitProperties.put(CITATION_SEPARATOR, "; "); + obsCitProperties.put(PAGE_INFO_SEPARATOR, "; "); + obsCitProperties.put(GROUPED_NUMBERS_SEPARATOR, "-"); + obsCitProperties.put(MINIMUM_GROUPING_COUNT, 3); + obsCitProperties.put(FORMAT_CITATIONS, Boolean.FALSE); + obsCitProperties.put(CITATION_CHARACTER_FORMAT, "Default"); + obsCitProperties.put(ITALIC_CITATIONS, Boolean.FALSE); + obsCitProperties.put(BOLD_CITATIONS, Boolean.FALSE); + obsCitProperties.put(SUPERSCRIPT_CITATIONS, Boolean.FALSE); + obsCitProperties.put(SUBSCRIPT_CITATIONS, Boolean.FALSE); + obsCitProperties.put(MULTI_CITE_CHRONOLOGICAL, Boolean.TRUE); + obsCitProperties.put(CITATION_KEY_CITATIONS, Boolean.FALSE); //"BibTeXKeyCitations" + obsCitProperties.put(ITALIC_ET_AL, Boolean.FALSE); + obsCitProperties.put(OXFORD_COMMA, ""); } // public Layout getDefaultBibLayout() { @@ -285,7 +303,7 @@ private void setDefaultProperties() { // } public String getName() { - return name; + return obsName; } public String getPath() { @@ -305,15 +323,30 @@ public Set getJournals() { * earlier versions of the input. This may be confusing for the * user (modified file until it works, but next time it fails again). */ - private void initialize(InputStream stream) throws IOException { + private void initialize(InputStream stream, String filename) throws IOException { Objects.requireNonNull(stream); + + // remove data from a previous parse + localCopy = null; + obsName = ""; + journals.clear(); + obsProperties.clear(); + obsCitProperties.clear(); + bibLayout.clear(); + defaultBibLayout = null; + isDefaultLayoutPresent = false; + valid = false; + setDefaultProperties(); + this.parseLog = null; + // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html // // The try-with-resources Statement // try (Reader reader = new InputStreamReader(stream, encoding)) { - OOBibStyleParser.readFormatFile(reader, this); + this.parseLog = OOBibStyleParser.readFormatFile(reader, this, filename); + // System.out.print(pp.format()); } } @@ -349,7 +382,7 @@ private void reload() throws IOException { if (styleFile != null) { this.styleFileModificationTime = styleFile.lastModified(); try (InputStream stream = new FileInputStream(styleFile)) { - initialize(stream); + initialize(stream, styleFile.getAbsolutePath()); } } } @@ -364,6 +397,13 @@ public boolean isValid() { return valid; } + /** + * May return null. + */ + public OOBibStyleParser.ParseLog getParseLog() { + return parseLog; + } + public Layout getReferenceFormat(EntryType type) { Layout l = bibLayout.get(type); if (l == null) { @@ -531,6 +571,9 @@ public int compareTo(OOBibStyle other) { return getName().compareTo(other.getName()); } + private String nullToEmpty(String s) { + return ( s == null ? "" : s ); + } @Override public boolean equals(Object o) { if (this == o) { @@ -538,17 +581,22 @@ public boolean equals(Object o) { } if (o instanceof OOBibStyle) { OOBibStyle otherStyle = (OOBibStyle) o; - return Objects.equals(path, otherStyle.path) - && Objects.equals(name, otherStyle.name) - && Objects.equals(citProperties, otherStyle.citProperties) - && Objects.equals(properties, otherStyle.properties); + return (Objects.equals(path, otherStyle.path) + && (nullToEmpty(localCopy) + .equals(nullToEmpty(otherStyle.localCopy)))); + // return (Objects.equals(path, otherStyle.path) + // && Objects.equals(obsName, otherStyle.obsName) + // && Objects.equals(obsCitProperties, otherStyle.obsCitProperties) + // && Objects.equals(obsProperties, otherStyle.obsProperties) + // // bibLayout does no count? + // ); } return false; } @Override public int hashCode() { - return Objects.hash(path, name, citProperties, properties); + return Objects.hash(path, obsName, obsCitProperties, obsProperties); } /* @@ -564,19 +612,19 @@ public int hashCode() { // * @return The property value, or null if it doesn't exist. // */ // private Object getProperty(String propName) { - // return properties.get(propName); + // return obsProperties.get(propName); // } private boolean getBooleanProperty(String propName) { - return (Boolean) properties.get(propName); + return (Boolean) obsProperties.get(propName); } private String getStringProperty(String propName) { - return (String) properties.get(propName); + return (String) obsProperties.get(propName); } // private int getIntProperty(String key) { - // return (Integer) properties.get(key); + // return (Integer) obsProperties.get(key); // } /** @@ -586,15 +634,15 @@ private String getStringProperty(String propName) { * @return the value */ private boolean getBooleanCitProperty(String key) { - return (Boolean) citProperties.get(key); + return (Boolean) obsCitProperties.get(key); } private int getIntCitProperty(String key) { - return (Integer) citProperties.get(key); + return (Integer) obsCitProperties.get(key); } public String getStringCitProperty(String key) { - return (String) citProperties.get(key); + return (String) obsCitProperties.get(key); } /** @@ -634,16 +682,18 @@ public boolean isSortByPosition() { /** * Should citation markers be formatted * according to the results of the - * - isItalicCitations() // no, isItalicCitations() is not used at all - * - isBoldCitations() // no, isBoldCitations() is not used at all + * - isItalicCitations() // not implemented + * - isBoldCitations() // not implemented * - getCitationCharacterFormat() // yes * methods? * + * There is also SUPERSCRIPT_CITATIONS, SUBSCRIPT_CITATIONS + * * @return true to indicate that citations should be formatted to getCitationCharacterFormat() * in italics (or bold). */ public boolean isFormatCitations() { - return (Boolean) citProperties.get(FORMAT_CITATIONS); + return (Boolean) obsCitProperties.get(FORMAT_CITATIONS); } public String getCitationCharacterFormat() { @@ -671,11 +721,13 @@ public boolean isItalicCitations() { * TODO: unused */ public boolean isBoldCitations() { - return (Boolean) citProperties.get(BOLD_CITATIONS); + return (Boolean) obsCitProperties.get(BOLD_CITATIONS); } + + public boolean isCitationKeyCiteMarkers() { - return (Boolean) citProperties.get(CITATION_KEY_CITATIONS); + return (Boolean) obsCitProperties.get(CITATION_KEY_CITATIONS); } public boolean getCitPropertyMultiCiteChronological() { diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java index b97c3dcf38e..057cb1129f2 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -3,7 +3,12 @@ import java.io.IOException; import java.io.Reader; import java.io.StringReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Set; import java.util.SortedSet; import java.util.regex.Pattern; @@ -19,26 +24,341 @@ * Parse a "*.jstyle" file */ -class OOBibStyleParser { +public class OOBibStyleParser { - private static final String LAYOUT_MRK = "LAYOUT"; - private static final String PROPERTIES_MARK = "PROPERTIES"; - private static final String CITATION_MARK = "CITATION"; + // Emit warning instead of error if possible. + private static boolean patient = true; + + // Section names private static final String NAME_MARK = "NAME"; private static final String JOURNALS_MARK = "JOURNALS"; + private static final String PROPERTIES_MARK = "PROPERTIES"; + private static final String CITATION_MARK = "CITATION"; + private static final String LAYOUT_MARK = "LAYOUT"; + + // name of default layout private static final String DEFAULT_MARK = "default"; private static final Pattern QUOTED = Pattern.compile("\".*\""); private static final Pattern NUM_PATTERN = Pattern.compile("-?\\d+"); + private static final Set SECTION_NAMES = + Set.of(NAME_MARK, JOURNALS_MARK, PROPERTIES_MARK, CITATION_MARK, LAYOUT_MARK); + + /* + * Keys in the PROPERTIES section that we warn about. + */ + private static final Map PROPERTY_WARNINGS = Map.of( + // Appeared in setDefaultProperties, otherwise unknown. + "SortAlgorithm", "SortAlgorithm is not used" + ); + + /* + * Keys in the CITATION section we warn about. + */ + private static final Map CITATION_PROPERTY_WARNINGS = makeCitationPropertyWarnings(); + private static final Map KNOWN_PROPERTIES = makeKnownProperties(); + private static final Map KNOWN_CITATION_PROPERTIES = + makeKnownCitationProperties(); + + enum PropertyType { + BOOL, + INT, + STRING, + IGNORE // ignore silently, unless also in WARNINGS + } + + private static boolean hasQuotes(String s) { + return (s.length() >= 2) && QUOTED.matcher(s).matches(); + } + + private static String dropQuotes(String s) { + if (hasQuotes(s)){ + return s.substring(1, s.length()-1); + } + return s; + } + + /** + * Add property with name {@code propertyName} to {@code destProperties} + * + * @param type The expected type of the value. Directs decoding + * from the string {@code value}. The {@code IGNORE} type directs to silently skip + * decoding and assignment. + * + * @param whatIsIt "property" or "citation property".. + */ + private static ParseLogLevel addProperty(String propertyName, + String value, // already trimmed + PropertyType type, + Map destProperties, + String fileName, + int lineNumber, + ParseLog logger, + String whatIsIt) { + final String quotedTrue = "\"true\""; + final String quotedFalse = "\"false\""; + + switch (type) { + case IGNORE: + return ParseLogLevel.OK; + case BOOL: + switch (value) { + case "true": + destProperties.put(propertyName, Boolean.TRUE ); + return ParseLogLevel.OK; + case "false": + destProperties.put(propertyName, Boolean.FALSE ); + return ParseLogLevel.OK; + default: + String msg = String.format("Boolean %s '%s'" + + " expects true or false as value, got '%s'", + whatIsIt, + propertyName, value); + if (patient) { + if (value.equals(quotedTrue)){ + destProperties.put(propertyName, Boolean.TRUE ); + logger.warn(fileName, lineNumber, msg); + return ParseLogLevel.WARN; + } + if (value.equals(quotedFalse)){ + destProperties.put(propertyName, Boolean.FALSE ); + logger.warn(fileName, lineNumber, msg); + return ParseLogLevel.WARN; + } + } + logger.error(fileName, lineNumber, msg); + return ParseLogLevel.ERROR; + } + + case INT: + if (NUM_PATTERN.matcher(value).matches()) { + destProperties.put(propertyName, Integer.parseInt(value)); + return ParseLogLevel.OK; + } else { + String msg = String.format("Integer %s '%s'" + + " expects number matching '-?[0-9]+' as value, got '%s'", + whatIsIt, + propertyName, value); + if (patient) { + if (NUM_PATTERN.matcher(dropQuotes(value)).matches()) { + destProperties.put(propertyName, Integer.parseInt(dropQuotes(value))); + logger.warn(fileName, lineNumber, msg); + return ParseLogLevel.WARN; + } + } + logger.error(fileName, lineNumber, msg); + return ParseLogLevel.ERROR; + } + + case STRING: + ParseLogLevel res = ParseLogLevel.OK; + boolean isQuoted = hasQuotes(value); + if (!isQuoted) { + String msg = String.format("String %s '%s'" + + " expects double quotes around value, got '%s'", + whatIsIt, + propertyName, value); + if (patient) { + destProperties.put(propertyName, dropQuotes(value)); + logger.warn(fileName, lineNumber, msg); + return ParseLogLevel.WARN; + } else { + logger.error(fileName, lineNumber, msg); + return ParseLogLevel.ERROR; + } + } + return res; + } + throw new RuntimeException(""); + } + + private static Map makeKnownProperties() { + Map res = new HashMap(); + res.put("Title", PropertyType.STRING); + res.put("IsNumberEntries", PropertyType.BOOL); + res.put("IsSortByPosition", PropertyType.BOOL); + res.put("ReferenceHeaderParagraphFormat", PropertyType.STRING); + res.put("ReferenceParagraphFormat", PropertyType.STRING); + return Collections.unmodifiableMap(res); + } + + private static Map makeCitationPropertyWarnings() { + + Map res = new HashMap(); + /* ItalicCitations was only recognized, but not used in JabRef5.2. */ + res.put("ItalicCitations", "ItalicCitations is not implemented"); + res.put("BoldCitations", "BoldCitations is not implemented"); + res.put("SuperscriptCitations", "SuperscriptCitations is not implemented"); + res.put("SubscriptCitations", "SubscriptCitations is not implemented"); + res.put("BibtexKeyCitations", "Found 'BibtexKeyCitations' instead of 'BibTeXKeyCitations'"); + return Collections.unmodifiableMap(res); + } + + private static Map makeKnownCitationProperties() { + + Map res = new HashMap(); + res.put("AuthorField", PropertyType.STRING); + res.put("YearField", PropertyType.STRING); + res.put("MaxAuthors", PropertyType.INT); + res.put("MaxAuthorsFirst", PropertyType.INT); + res.put("AuthorSeparator", PropertyType.STRING); + res.put("AuthorLastSeparator", PropertyType.STRING); + res.put("AuthorLastSeparatorInText", PropertyType.STRING); + res.put("EtAlString", PropertyType.STRING); + res.put("YearSeparator", PropertyType.STRING); + res.put("InTextYearSeparator", PropertyType.STRING); + res.put("BracketBefore", PropertyType.STRING); + res.put("BracketAfter", PropertyType.STRING); + res.put("BracketBeforeInList", PropertyType.STRING); + res.put("BracketAfterInList", PropertyType.STRING); + res.put("CitationSeparator", PropertyType.STRING); + res.put("PageInfoSeparator", PropertyType.STRING); + res.put("GroupedNumbersSeparator", PropertyType.STRING); + res.put("MinimumGroupingCount", PropertyType.INT); + res.put("FormatCitations", PropertyType.BOOL); + res.put("CitationCharacterFormat", PropertyType.STRING); + res.put("ItalicCitations", PropertyType.BOOL); + res.put("BoldCitations", PropertyType.BOOL); + res.put("SuperscriptCitations", PropertyType.BOOL); + res.put("SubscriptCitations", PropertyType.BOOL); + res.put("MultiCiteChronological", PropertyType.BOOL); + res.put("BibTeXKeyCitations", PropertyType.BOOL); // CITATION_KEY_CITATIONS + res.put("ItalicEtAl", PropertyType.BOOL); + res.put("OxfordComma", PropertyType.STRING); + res.put("UniquefierSeparator", PropertyType.STRING); + return Collections.unmodifiableMap(res); + } + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyleParser.class); + private static boolean endsWithCharacter(String s, char c){ + return !s.isEmpty() && (s.charAt(s.length() - 1) == c); + } + + private static String dropLastCharacter(String s) { + return s.substring(0, s.length() - 1); + } + + private static enum BibStyleMode { + BEFORE_NAME_SECTION, + IN_NAME_SECTION, + BEFORE_JOURNALS_SECTION, + IN_JOURNALS_SECTION, + IN_PROPERTIES_SECTION, + IN_CITATION_SECTION, + IN_LAYOUT_SECTION + } + + + /** Also used as return code */ + static enum ParseLogLevel { + ERROR, + WARN, + INFO, + OK // no message + } + + static class ParseLogEntry { + public final ParseLogLevel level; + public final String fileName; + public final int lineNumber; + public final String message; + ParseLogEntry(ParseLogLevel level, String fileName, int lineNumber, String message) { + this.level = level; + this.fileName = fileName; + this.lineNumber = lineNumber; + this.message = message; + } + public String format() { + StringBuilder sb = new StringBuilder(); + ParseLogEntry e = this; + sb.append(e.fileName); + sb.append(":"); + sb.append(e.lineNumber); + sb.append(":"); + switch (e.level) { + case ERROR: + sb.append("error:"); + break; + case WARN: + sb.append("warning:"); + break; + case INFO: + sb.append("info:"); + break; + case OK: + sb.append("unexpected 'OK'"); + break; + } + sb.append(e.message); + sb.append("\n"); + return sb.toString(); + } + } + + public static class ParseLog { + List entries; + ParseLog() { + this.entries = new ArrayList<>(); + } + void log( ParseLogLevel level, String fileName, int lineNumber, String message) { + this.entries.add(new ParseLogEntry(level, fileName, lineNumber, message)); + } + void error(String fileName, int lineNumber, String message) { + this.entries.add(new ParseLogEntry(ParseLogLevel.ERROR, fileName, lineNumber, message)); + } + void warn(String fileName, int lineNumber, String message) { + this.entries.add(new ParseLogEntry(ParseLogLevel.WARN, fileName, lineNumber, message)); + } + + public int size() { + return entries.size(); + } + + public boolean isEmpty() { + return entries.isEmpty(); + } + + public String format(){ + StringBuilder sb = new StringBuilder(); + for (ParseLogEntry e : entries) { + sb.append(e.format()); + } + return sb.toString(); + } + + public boolean hasError() { + for (ParseLogEntry e : entries) { + if (e.level == ParseLogLevel.ERROR) { + return true; + } + } + return false; + } + } + /** * Parse a *.jstyle file from {@code in}. * * - Does not reset style, only adds things. + * + * - Expects a fixed order of sections (NAME,JOURNALS,PROPERTIES,CITATION,LAYOUT) + * + * - Only known properties and citation properties are accepted, and only with the + * type defined in KNOWN_PROPERTIES and KNOWN_CITATION_PROPERTIES. + * - boolean and integer values must not be quoted, strings must. + * - Unparsable lines are not ignored. + * + * - To reduce friction, (OOBibStyleParser.patient == true) turns + * "unparsable lines", "extra quotes", "missing quotes", "unknown property" + * into a warning (instead of error). */ - public static void readFormatFile(Reader in, OOBibStyle style) throws IOException { + public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileName) + throws + IOException { + + ParseLog logger = new ParseLog(); // First read all the contents of the file: StringBuilder sb = new StringBuilder(); @@ -52,71 +372,228 @@ public static void readFormatFile(Reader in, OOBibStyle style) throws IOExceptio // Break into separate lines: String[] lines = sb.toString().split("\n"); - BibStyleMode mode = BibStyleMode.NONE; + BibStyleMode mode = BibStyleMode.BEFORE_NAME_SECTION; + int lineNumber = 0; for (String line1 : lines) { String line = line1; + lineNumber++; // Drop "\r" from end of line - if (!line.isEmpty() - && (line.charAt(line.length() - 1) == '\r')) { - line = line.substring(0, line.length() - 1); + if (endsWithCharacter(line, '\r')) { + line = dropLastCharacter(line); + } + + final String trimmedLine = line.trim(); + + // Skip empty lines: + if (trimmedLine.isEmpty()) { + continue; } - // Skip empty line or comment: - if (line.trim().isEmpty() || (line.charAt(0) == '#')) { + // Skip comment: + if (line.charAt(0) == '#') { continue; } - // Check if we should change mode: - switch (line) { + /* We only get here if we do have something (not empty line or comment) */ + switch (mode) { + + case BEFORE_NAME_SECTION: + switch (trimmedLine) { case NAME_MARK: - mode = BibStyleMode.NAME; - continue; - case LAYOUT_MRK: - mode = BibStyleMode.LAYOUT; - continue; - case PROPERTIES_MARK: - mode = BibStyleMode.PROPERTIES; + mode = BibStyleMode.IN_NAME_SECTION; continue; - case CITATION_MARK: - mode = BibStyleMode.CITATION; + default: + logger.error(fileName, lineNumber, + String.format("Expected \"%s\", got \"%s\"", NAME_MARK, line)); + return logger; + } + + case IN_NAME_SECTION: + if (SECTION_NAMES.contains(trimmedLine)) { + logger.error( fileName, lineNumber, + "Expected name of style, found section name" + + String.format("'%s'", trimmedLine )); + return logger; + } else { + // ok + style.obsName = trimmedLine; + mode = BibStyleMode.BEFORE_JOURNALS_SECTION; continue; + } + + case BEFORE_JOURNALS_SECTION: + switch (trimmedLine) { case JOURNALS_MARK: - mode = BibStyleMode.JOURNALS; + mode = BibStyleMode.IN_JOURNALS_SECTION; continue; default: - break; - } + String msg = String.format("Expected \"%s\", got \"%s\"", JOURNALS_MARK, line); + if (patient) { + logger.warn(fileName, lineNumber, msg); + style.obsName = trimmedLine; // mimic old behaviour + continue; + } else { + logger.error(fileName, lineNumber, + String.format("Expected \"%s\", got \"%s\"", JOURNALS_MARK, line)); + return logger; + } + } - switch (mode) { - case NAME: - if (!line.trim().isEmpty()) { - style.name = line.trim(); + case IN_JOURNALS_SECTION: + if (SECTION_NAMES.contains(trimmedLine)) { + if (trimmedLine.equals(PROPERTIES_MARK)) { + mode = BibStyleMode.IN_PROPERTIES_SECTION; + continue; + } else { + logger.error(fileName, lineNumber, + String.format("Expected journal name or '%s'," + + " found section name '%s'", + PROPERTIES_MARK, + trimmedLine)); + return logger; } - break; - case LAYOUT: - handleLayoutLine(line, style); - break; - case PROPERTIES: - handlePropertiesLine(line, style.properties); - break; - case CITATION: - handlePropertiesLine(line, style.citProperties); - break; - case JOURNALS: - handleJournalsLine(line, style.journals); - break; - default: - break; + } else { + style.journals.add( trimmedLine ); + continue; + } + + case IN_PROPERTIES_SECTION: + if (SECTION_NAMES.contains(trimmedLine)) { + if (trimmedLine.equals(CITATION_MARK)) { + mode = BibStyleMode.IN_CITATION_SECTION; + continue; + } else { + logger.error(fileName, lineNumber, + String.format("Expected property setting or '%s'," + + " found section name '%s'", + CITATION_MARK, + trimmedLine)); + return logger; + } + } else { + ParseLogLevel res = handlePropertiesLine(trimmedLine, + fileName, + lineNumber, + style.obsProperties, + PROPERTY_WARNINGS, + KNOWN_PROPERTIES, + logger, + "property"); + if (res == ParseLogLevel.ERROR) { + return logger; + } else { + continue; + } + } + + case IN_CITATION_SECTION: + if (SECTION_NAMES.contains(trimmedLine)) { + if (trimmedLine.equals(LAYOUT_MARK)) { + mode = BibStyleMode.IN_LAYOUT_SECTION; + continue; + } else { + logger.error(fileName, lineNumber, + String.format("Expected citation property setting or '%s'," + + " found section name '%s'", + LAYOUT_MARK, + trimmedLine)); + return logger; + } + } else { + ParseLogLevel res = handlePropertiesLine(trimmedLine, + fileName, + lineNumber, + style.obsCitProperties, + CITATION_PROPERTY_WARNINGS, + KNOWN_CITATION_PROPERTIES, + logger, + "citation property"); + if (res == ParseLogLevel.ERROR) { + return logger; + } else { + continue; + } + } + + case IN_LAYOUT_SECTION: + ParseLogLevel res = handleLayoutLine(line, style, fileName, lineNumber, logger); + if (res == ParseLogLevel.ERROR) { + return logger; + } else { + continue; + } + + default: + throw new RuntimeException("Unexpected mode in OOBibStyleParser.readFormatFile"); } } - // Set validity boolean based on whether we found anything interesting - // in the file: - if ((mode != BibStyleMode.NONE) && style.isDefaultLayoutPresent) { + // Set validity boolean based on whether we found every section + // in the file. + if ((mode == BibStyleMode.IN_LAYOUT_SECTION) && style.isDefaultLayoutPresent) { style.valid = true; } + return logger; + } + + /** + * Parse a line providing a property name and value. + * + * @param line The line containing the formatter names. + * + * Format: "{propertyName}={value}" + */ + private static ParseLogLevel handlePropertiesLine(String trimmedLine, + String fileName, + int lineNumber, + Map properties, + Map WARNINGS, + Map KNOWN, + ParseLog logger, + String whatIsIt) { + int index = trimmedLine.indexOf('='); + ParseLogLevel softError = (patient ? ParseLogLevel.WARN : ParseLogLevel.ERROR); + if (index < 0) { + logger.log(softError, + fileName, lineNumber, + String.format("Expected %s setting," + + " but the line does not contain '='", + whatIsIt)); + return softError; + } + + String propertyName = trimmedLine.substring(0, index).trim(); + String value = trimmedLine.substring(index + 1).trim(); + + if ("".equals(propertyName)){ + logger.log(softError, fileName, lineNumber, + String.format("Empty %s name", whatIsIt)); + return softError; + } + + if (WARNINGS.containsKey(propertyName)) { + String msg = WARNINGS.get(propertyName); + // LOGGER.warn(msg); + logger.warn(fileName, lineNumber, msg); + // Do not return yet. Warning does not preclude using the value. + // return ParseLogLevel.WARN; + } + + PropertyType type = KNOWN.get(propertyName); + if (type == null) { + String msg = String.format("Unknown %s: '%s'", whatIsIt, propertyName); + logger.log(softError, fileName, lineNumber, msg); + return softError; + } else { + ParseLogLevel res = addProperty(propertyName, + value, + type, + properties, + fileName, lineNumber, logger, whatIsIt); + return res; + } } /** @@ -130,8 +607,14 @@ public static void readFormatFile(Reader in, OOBibStyle style) throws IOExceptio * The "name" part is passed to {@code EntryTypeFactory.parse(name);} * The "RHS" part is passed to {@code new LayoutHelper( ..., style.prefs).getLayoutFromText();} * + * See https://docs.jabref.org/collaborative-work/export/customexports for a description of what can go + * into the RHS. */ - private static void handleLayoutLine(String line, OOBibStyle style) { + private static ParseLogLevel handleLayoutLine(String line, + OOBibStyle style, + String fileName, + int lineNumber, + ParseLog logger) { /* * uses: * style.prefs @@ -150,11 +633,25 @@ private static void handleLayoutLine(String line, OOBibStyle style) { * */ int index = line.indexOf('='); - if (index <= 0) { - return; /* No "=" or line[0] == "=" */ + if (index < 0) { + logger.error(fileName, lineNumber, + "Expected format definition," + + " but the line does not contain '='"); + return ParseLogLevel.ERROR; + } + + if (index == 0) { + logger.error(fileName, lineNumber, + "Expected entry type name or default," + + " but the line is empty before '='"); + return ParseLogLevel.ERROR; } + if (index >= (line.length() - 1)) { - return; /* First "=" is at the last character. */ + logger.error(fileName, lineNumber, + "Expected entry layout definition," + + " but the line is empty after '='"); + return ParseLogLevel.ERROR; } String name = line.substring(0, index); @@ -170,8 +667,10 @@ private static void handleLayoutLine(String line, OOBibStyle style) { try { layout = new LayoutHelper(reader, style.prefs).getLayoutFromText(); } catch (IOException ex) { - LOGGER.warn("Cannot parse bibliography structure", ex); - return; + // LOGGER.warn("Cannot parse bibliography structure", ex); + String msg = String.format("Cannot parse bibliography structure. %s", ex.getMessage()); + logger.error(fileName, lineNumber, msg); + return ParseLogLevel.ERROR; } /* At the first DEFAULT_MARK, put into defaultBibLayout, otherwise @@ -186,49 +685,6 @@ private static void handleLayoutLine(String line, OOBibStyle style) { } else { style.bibLayout.put(type, layout); } + return ParseLogLevel.OK; } - - /** - * Parse a line providing a property name and value. - * - * @param line The line containing the formatter names. - */ - private static void handlePropertiesLine(String line, Map map) { - int index = line.indexOf('='); - if ((index > 0) && (index <= (line.length() - 1))) { - String propertyName = line.substring(0, index).trim(); - String value = line.substring(index + 1); - if ((value.trim().length() > 1) && QUOTED.matcher(value.trim()).matches()) { - value = value.trim().substring(1, value.trim().length() - 1); - } - Object toSet = value; - if (NUM_PATTERN.matcher(value).matches()) { - toSet = Integer.parseInt(value); - } else if ("true".equalsIgnoreCase(value.trim())) { - toSet = Boolean.TRUE; - } else if ("false".equalsIgnoreCase(value.trim())) { - toSet = Boolean.FALSE; - } - map.put(propertyName, toSet); - } - } - - /** - * Parse a line providing a journal name for which this style is valid. - */ - private static void handleJournalsLine(String line, SortedSet journals) { - if (!line.trim().isEmpty()) { - journals.add(line.trim()); - } - } - - enum BibStyleMode { - NONE, - LAYOUT, - PROPERTIES, - CITATION, - NAME, - JOURNALS - } - } diff --git a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java b/src/main/java/org/jabref/logic/openoffice/StyleLoader.java index 4d3b30537db..da7842f90f0 100644 --- a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java +++ b/src/main/java/org/jabref/logic/openoffice/StyleLoader.java @@ -53,28 +53,54 @@ public List getStyles() { * Adds the given style to the list of styles * * @param filename The filename of the style - * @return True if the added style is valid, false otherwise + * @return parse log. result.hasError() is false if the style is added, true otherwise. + * // was: True if the added style is valid, false otherwise */ - public boolean addStyleIfValid(String filename) { + public OOBibStyleParser.ParseLog addStyleIfValid(String filename) { Objects.requireNonNull(filename); try { - OOBibStyle newStyle = new OOBibStyle(new File(filename), layoutFormatterPreferences, encoding); + OOBibStyle newStyle = new OOBibStyle(new File(filename), + layoutFormatterPreferences, + encoding); + + OOBibStyleParser.ParseLog parseLog = newStyle.getParseLog(); + if ( parseLog == null ) { + parseLog = new OOBibStyleParser.ParseLog(); + parseLog.error(filename, 0, + "OOBibStyle constructor returned with no parseLog"); + } + if (externalStyles.contains(newStyle)) { LOGGER.info("External style file " + filename + " already existing."); - } else if (newStyle.isValid()) { + parseLog.error(filename, 0, + "An external style file with the same content," + + " including its path" + + " is already known (not adding)" ); + return parseLog; + } else if (newStyle.isValid() && !parseLog.hasError()) { externalStyles.add(newStyle); storeExternalStyles(); - return true; + return parseLog; } else { - LOGGER.error(String.format("Style with filename %s is invalid", filename)); + String msg = String.format("Style with filename %s is invalid", filename); + LOGGER.error(msg); + parseLog.error(filename, 0, msg); + return parseLog; } } catch (FileNotFoundException e) { // The file couldn't be found... should we tell anyone? - LOGGER.info("Cannot find external style file " + filename, e); + String msg = "Cannot find external style file " + filename; + LOGGER.info(msg, e); + OOBibStyleParser.ParseLog parseLog = new OOBibStyleParser.ParseLog(); + parseLog.error( filename, 0, msg ); + return parseLog; } catch (IOException e) { LOGGER.info("Problem reading external style file " + filename, e); + OOBibStyleParser.ParseLog parseLog = new OOBibStyleParser.ParseLog(); + String msg = "Problem (IOException) reading external style file " + filename; + parseLog.error( filename, 0, msg ); + return parseLog; } - return false; } private void loadExternalStyles() { diff --git a/src/main/resources/resource/openoffice/default_authoryear.jstyle b/src/main/resources/resource/openoffice/default_authoryear.jstyle index e0c5b2443d3..3656f6a9a20 100644 --- a/src/main/resources/resource/openoffice/default_authoryear.jstyle +++ b/src/main/resources/resource/openoffice/default_authoryear.jstyle @@ -9,36 +9,36 @@ Journal name 2 PROPERTIES Title="References" -IsSortByPosition="false" -IsNumberEntries="false" +IsSortByPosition = false +IsNumberEntries = false ReferenceParagraphFormat="Text body" ReferenceHeaderParagraphFormat="Heading 2" CITATION -BibtexKeyCitations=false +BibTeXKeyCitations=false AuthorField="author/editor" YearField="year" -MaxAuthors="2" -MaxAuthorsFirst="6" +MaxAuthors=2 +MaxAuthorsFirst=6 AuthorSeparator="," -AuthorLastSeparator=" & " -AuthorLastSeparatorInText=" and " +AuthorLastSeparator = " & " +AuthorLastSeparatorInText = " and " EtAlString=" et al." -ItalicEtAl="false" +ItalicEtAl=false YearSeparator=" " InTextYearSeparator=" " BracketBefore="[" BracketAfter="]" -BracketBeforeInList="[" -BracketAfterInList="] " -CitationSeparator="; " -UniquefierSeparator="," +BracketBeforeInList = "[" +BracketAfterInList = "] " +CitationSeparator = "; " +UniquefierSeparator = "," GroupedNumbersSeparator="-" -MinimumGroupingCount="3" -FormatCitations="false" -CitationCharacterFormat="Default" -MultiCiteChronological="true" -PageInfoSeparator="; " +MinimumGroupingCount=3 +FormatCitations = false +CitationCharacterFormat = "Default" +MultiCiteChronological = true +PageInfoSeparator = "; " LAYOUT article=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. diff --git a/src/main/resources/resource/openoffice/default_numerical.jstyle b/src/main/resources/resource/openoffice/default_numerical.jstyle index 047caee3be8..0442d080e26 100644 --- a/src/main/resources/resource/openoffice/default_numerical.jstyle +++ b/src/main/resources/resource/openoffice/default_numerical.jstyle @@ -8,24 +8,24 @@ Journal name 1 Journal name 2 PROPERTIES -Title="References" -IsSortByPosition="true" -IsNumberEntries="true" -ReferenceParagraphFormat="Text body" -ReferenceHeaderParagraphFormat="Heading 2" +Title = "References" +IsSortByPosition = true +IsNumberEntries = true +ReferenceParagraphFormat = "Text body" +ReferenceHeaderParagraphFormat = "Heading 2" CITATION -BracketBefore="[" -BracketAfter="]" -BracketBeforeInList="[" -BracketAfterInList="] " -CitationSeparator="; " -UniquefierSeparator="," -GroupedNumbersSeparator="-" -MinimumGroupingCount="3" -FormatCitations="false" -CitationCharacterFormat="Default" -PageInfoSeparator="; " +BracketBefore = "[" +BracketAfter = "]" +BracketBeforeInList = "[" +BracketAfterInList = "] " +CitationSeparator = "; " +UniquefierSeparator = "," +GroupedNumbersSeparator = "-" +MinimumGroupingCount = 3 +FormatCitations = false +CitationCharacterFormat = "Default" +PageInfoSeparator = "; " LAYOUT article=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. diff --git a/src/test/resources/org/jabref/logic/openoffice/test.jstyle b/src/test/resources/org/jabref/logic/openoffice/test.jstyle index 3ecd9bfbf08..7d803ea026f 100644 --- a/src/test/resources/org/jabref/logic/openoffice/test.jstyle +++ b/src/test/resources/org/jabref/logic/openoffice/test.jstyle @@ -9,8 +9,8 @@ Journal name 2 PROPERTIES Title="References" -IsSortByPosition="true" -IsNumberEntries="true" +IsSortByPosition=true +IsNumberEntries=true ReferenceParagraphFormat="Text body" ReferenceHeaderParagraphFormat="Heading 2" @@ -22,8 +22,8 @@ BracketAfterInList="] " CitationSeparator="; " UniquefierSeparator="," GroupedNumbersSeparator="-" -MinimumGroupingCount="3" -FormatCitations="false" +MinimumGroupingCount=3 +FormatCitations=false CitationCharacterFormat="Default" PageInfoSeparator="; " OxfordComma="," diff --git a/src/test/resources/org/jabref/logic/openoffice/testWithDefaultAtFirstLIne.jstyle b/src/test/resources/org/jabref/logic/openoffice/testWithDefaultAtFirstLIne.jstyle index 2a4dcf7a697..0c146f679db 100644 --- a/src/test/resources/org/jabref/logic/openoffice/testWithDefaultAtFirstLIne.jstyle +++ b/src/test/resources/org/jabref/logic/openoffice/testWithDefaultAtFirstLIne.jstyle @@ -9,8 +9,8 @@ Journal name 2 PROPERTIES Title="References" -IsSortByPosition="true" -IsNumberEntries="true" +IsSortByPosition=true +IsNumberEntries=true ReferenceParagraphFormat="Text body" ReferenceHeaderParagraphFormat="Heading 2" @@ -22,8 +22,8 @@ BracketAfterInList="] " CitationSeparator="; " UniquefierSeparator="," GroupedNumbersSeparator="-" -MinimumGroupingCount="3" -FormatCitations="false" +MinimumGroupingCount=3 +FormatCitations=false CitationCharacterFormat="Default" PageInfoSeparator="; " OxfordComma="," From be2504dde27a7bf6021b439d57c4556584a93dc6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 11 Apr 2021 20:44:05 +0200 Subject: [PATCH 0584/1068] Correction: OOBibStyleParser now adds value when it is correctly formed --- .../java/org/jabref/logic/openoffice/OOBibStyleParser.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java index 057cb1129f2..0e796e193f2 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -152,9 +152,11 @@ private static ParseLogLevel addProperty(String propertyName, } case STRING: - ParseLogLevel res = ParseLogLevel.OK; boolean isQuoted = hasQuotes(value); - if (!isQuoted) { + if (isQuoted) { + destProperties.put(propertyName, dropQuotes(value)); + return ParseLogLevel.OK; + } else { String msg = String.format("String %s '%s'" + " expects double quotes around value, got '%s'", whatIsIt, @@ -168,7 +170,6 @@ private static ParseLogLevel addProperty(String propertyName, return ParseLogLevel.ERROR; } } - return res; } throw new RuntimeException(""); } From 61c6ba009aa12c8d35fa5d08eb4f087965d2692f Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 11 Apr 2021 20:45:26 +0200 Subject: [PATCH 0585/1068] omit file path from dialog, to fit in the window --- .../StyleSelectDialogViewModel.java | 11 +++--- .../logic/openoffice/OOBibStyleParser.java | 35 +++++++++++++++++++ 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java index 3d884d013b8..45fc2630879 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java @@ -73,18 +73,15 @@ public void addStyleFile() { styles.setAll(loadStyles()); selectedItem.setValue(getStyleOrDefault(stylePath)); if (!parseLog.isEmpty()) { - // showInformationDialogAndWait shows a non-resizable window, - // not wide enough. - dialogService.showInformationDialogAndWait("Parse log", parseLog.format()); + dialogService.showInformationDialogAndWait("Parse log", + parseLog.formatShort()); } } else { dialogService.showErrorDialogAndWait( Localization.lang("Invalid style selected"), - Localization.lang( - "You must select a valid style file." - +" Your style is probably missing a line for the type \"default\".") + Localization.lang("You must select a valid style file.") + "\n" - + parseLog.format() + + parseLog.formatShort() ); } }); diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java index 0e796e193f2..4f4683b51d1 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -296,6 +296,32 @@ public String format() { sb.append("\n"); return sb.toString(); } + + public String formatShort() { + StringBuilder sb = new StringBuilder(); + ParseLogEntry e = this; + sb.append("line"); + sb.append(":"); + sb.append(e.lineNumber); + sb.append(":"); + switch (e.level) { + case ERROR: + sb.append("error:"); + break; + case WARN: + sb.append("warning:"); + break; + case INFO: + sb.append("info:"); + break; + case OK: + sb.append("unexpected 'OK'"); + break; + } + sb.append(e.message); + sb.append("\n"); + return sb.toString(); + } } public static class ParseLog { @@ -329,6 +355,15 @@ public String format(){ return sb.toString(); } + // omits file path + public String formatShort(){ + StringBuilder sb = new StringBuilder(); + for (ParseLogEntry e : entries) { + sb.append(e.formatShort()); + } + return sb.toString(); + } + public boolean hasError() { for (ParseLogEntry e : entries) { if (e.level == ParseLogLevel.ERROR) { From bd1954ec43fba7e691101730b9181a7bb9dce18e Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 11 Apr 2021 20:46:40 +0200 Subject: [PATCH 0586/1068] Missing default layout is reported in parseLog, no "probably" about it --- .../org/jabref/logic/openoffice/OOBibStyleParser.java | 10 ++++++++-- src/main/resources/l10n/JabRef_en.properties | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java index 4f4683b51d1..849a30f0382 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -568,9 +568,15 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa // Set validity boolean based on whether we found every section // in the file. - if ((mode == BibStyleMode.IN_LAYOUT_SECTION) && style.isDefaultLayoutPresent) { - style.valid = true; + if (mode != BibStyleMode.IN_LAYOUT_SECTION) { + logger.error(fileName, lineNumber, "Did not reach LAYOUT section at EOF"); + return logger; } + if (!style.isDefaultLayoutPresent) { + logger.error(fileName, lineNumber, "File did not provide a \"default\" layout."); + return logger; + } + style.valid = true; return logger; } diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 260bf1ba070..0c494820b6b 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1384,7 +1384,7 @@ Internal\ style=Internal style Add\ style\ file=Add style file Current\ style\ is\ '%0'=Current style is '%0' Remove\ style=Remove style -You\ must\ select\ a\ valid\ style\ file.\ Your\ style\ is\ probably\ missing\ a\ line\ for\ the\ type\ "default".=You must select a valid style file. Your style is probably missing a line for the type "default". +You\ must\ select\ a\ valid\ style\ file.=You must select a valid style file. Invalid\ style\ selected=Invalid style selected Reload=Reload From 1dad9d910ce7f3b4bee9b6655df0aa12cfe9f2ce Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 11 Apr 2021 20:48:00 +0200 Subject: [PATCH 0587/1068] comment on info about LAYOUT --- .../java/org/jabref/logic/openoffice/OOBibStyleParser.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java index 849a30f0382..0d11528ac48 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -649,8 +649,9 @@ private static ParseLogLevel handlePropertiesLine(String trimmedLine, * The "name" part is passed to {@code EntryTypeFactory.parse(name);} * The "RHS" part is passed to {@code new LayoutHelper( ..., style.prefs).getLayoutFromText();} * - * See https://docs.jabref.org/collaborative-work/export/customexports for a description of what can go - * into the RHS. + * See + * https://docs.jabref.org/collaborative-work/export/customexports + * for a description of what can go into the RHS. */ private static ParseLogLevel handleLayoutLine(String line, OOBibStyle style, From 6525179313b54797826ff2b9f150cedc192ccb4b Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 11 Apr 2021 20:54:35 +0200 Subject: [PATCH 0588/1068] test, why did I get "()", not "[]" --- .../java/org/jabref/logic/openoffice/OOBibStyleTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 1d0000f704f..6acacb9ee2d 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -703,6 +703,11 @@ void testEmptyEntryMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + OOBibStyleParser.ParseLog pl = style.getParseLog(); + assertTrue( pl != null ); + assertTrue( !pl.hasError() ); + assertTrue( "[".equals(style.getBracketBefore()) ); + BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); From 0083ce6f95096a7e441c0c0b42e4de87abb8bea3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 11 Apr 2021 23:45:12 +0200 Subject: [PATCH 0589/1068] add getInternalNameOfParagraphStyleOrNull, getInternalNameOfCharacterStyleOrNull --- .../gui/openoffice/DocumentConnection.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java index d32cab045b2..ac2580ddfc2 100644 --- a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java @@ -53,6 +53,7 @@ // import com.sun.star.container.XEnumeration; // import com.sun.star.container.XEnumerationAccess; import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNameContainer; import com.sun.star.container.XNamed; import com.sun.star.document.XDocumentPropertiesSupplier; import com.sun.star.document.XUndoManager; @@ -70,6 +71,8 @@ // import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XServiceInfo; +import com.sun.star.style.XStyle; +import com.sun.star.style.XStyleFamiliesSupplier; import com.sun.star.text.ReferenceFieldSource; import com.sun.star.text.ReferenceFieldPart; import com.sun.star.text.XBookmarksSupplier; @@ -150,6 +153,68 @@ class DocumentConnection { this.propertySet = unoQI(XPropertySet.class, userProperties); } + private XStyle getStyleFromFamilyOrNull(String familyName, String styleName) + throws + NoSuchElementException, + WrappedTargetException { + + XStyleFamiliesSupplier xFamiliesSupplier = unoQI(XStyleFamiliesSupplier.class, mxDoc); + XNameAccess xFamilies = (XNameAccess) unoQI(XNameAccess.class, + xFamiliesSupplier.getStyleFamilies()); + + // Access the 'ParagraphStyles' Family + XNameContainer xFamily = (XNameContainer) unoQI(XNameContainer.class, + xFamilies.getByName(familyName)); + + try { + Object s = xFamily.getByName(styleName); + XStyle xs = (XStyle) unoQI( XStyle.class, s ); + return xs; + } catch (NoSuchElementException ex) { + return null; + } + } + + private XStyle getParagraphStyleOrNull(String styleName) + throws + NoSuchElementException, + WrappedTargetException { + return getStyleFromFamilyOrNull("ParagraphStyles", styleName ); + } + + private XStyle getCharacterStyleOrNull(String styleName) + throws + NoSuchElementException, + WrappedTargetException { + return getStyleFromFamilyOrNull("CharacterStyles", styleName ); + } + + public String getInternalNameOfParagraphStyleOrNull(String name) + throws + NoSuchElementException, + WrappedTargetException { + + XStyle xs = getParagraphStyleOrNull(name); + if (xs == null) { + return null; + } else { + return xs.getName(); + } + } + + public String getInternalNameOfCharacterStyleOrNull(String name) + throws + NoSuchElementException, + WrappedTargetException { + + XStyle xs = getCharacterStyleOrNull(name); + if (xs == null) { + return null; + } else { + return xs.getName(); + } + } + /** * @param An uno object, hopefully implementing XServiceInfo */ From 64603c3502ba03b427ca064182ec0de228993a30 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 11 Apr 2021 23:46:18 +0200 Subject: [PATCH 0590/1068] add checkStylesExistInTheDocument Now called from "refresh bibliography" --- .../org/jabref/gui/openoffice/OOBibBase.java | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8401cbd2cb6..862835bcc67 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2682,6 +2682,103 @@ void styleIsRequired(OOBibStyle style) } } + public void checkParagraphStyleExistsInTheDocument(String styleName, + DocumentConnection documentConnection, + String labelInJstyleFile, + String pathToStyleFile) + throws + JabRefException, + NoSuchElementException, + WrappedTargetException { + + String internalName = documentConnection.getInternalNameOfParagraphStyleOrNull(styleName); + if (internalName == null) { + throw new JabRefException(Localization.lang( + "The %0 paragraph style '%1'" + + " is missing from the document", + labelInJstyleFile, + styleName) + + "\n" + + Localization.lang( + "Please create it in the document or change in the file:") + + "\n" + pathToStyleFile); + } + if (!internalName.equals(styleName)) { + throw new JabRefException(Localization.lang( + "The %0 paragraph style '%1'" + + " is a display name for '%2'.", + labelInJstyleFile, + styleName, + internalName) + + "\n" + + Localization.lang( + "Please use the latter in the style file below" + + " to avoid localization problems.") + + "\n" + pathToStyleFile); + } + } + + public void checkCharacterStyleExistsInTheDocument(String styleName, + DocumentConnection documentConnection, + String labelInJstyleFile, + String pathToStyleFile) + throws + JabRefException, + NoSuchElementException, + WrappedTargetException { + + String internalName = documentConnection.getInternalNameOfCharacterStyleOrNull(styleName); + if (internalName == null) { + throw new JabRefException(Localization.lang( + "The %0 character style '%1'" + + " is missing from the document", + labelInJstyleFile, + styleName) + + "\n" + + Localization.lang( + "Please create it in the document or change in the file:") + + "\n" + pathToStyleFile); + } + if (!internalName.equals(styleName)) { + throw new JabRefException(Localization.lang( + "The %0 character style '%1'" + + " is a display name for '%2'.", + labelInJstyleFile, + styleName, + internalName) + + "\n" + + Localization.lang( + "Please use the latter in the style file below" + + " to avoid localization problems.") + + "\n" + pathToStyleFile); + } + } + + public void checkStylesExistInTheDocument( OOBibStyle style, DocumentConnection documentConnection ) + throws + JabRefException, + NoSuchElementException, + WrappedTargetException { + + String pathToStyleFile = style.getPath(); + + checkParagraphStyleExistsInTheDocument(style.getReferenceHeaderParagraphFormat(), + documentConnection, + "ReferenceHeaderParagraphFormat", + pathToStyleFile); + + checkParagraphStyleExistsInTheDocument(style.getReferenceParagraphFormat(), + documentConnection, + "ReferenceParagraphFormat", + pathToStyleFile); + if (style.isFormatCitations()) { + checkCharacterStyleExistsInTheDocument(style.getCitationCharacterFormat(), + documentConnection, + "CitationCharacterFormat", + pathToStyleFile); + } + } + /** * GUI action, refreshes citation markers and bibliography. * @@ -2710,6 +2807,8 @@ public List updateDocumentActionHelper(List databases, styleIsRequired(style); DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + checkStylesExistInTheDocument(style, documentConnection); + try { documentConnection.enterUndoContext("Refresh bibliography"); From 4315de013194d22656962158226d9e76e9ddf13f Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 08:20:54 +0200 Subject: [PATCH 0591/1068] rename isFormatCitations to getFormatCitations --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++---- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 6 +++--- .../java/org/jabref/logic/openoffice/OOBibStyleTest.java | 6 +++--- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 862835bcc67..e285bc7f912 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1104,7 +1104,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti // setString: All styles are removed when applying this method. cursor.setString(citationText); DocumentConnection.setCharLocaleNone(cursor); - if (style.isFormatCitations()) { + if (style.getFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); DocumentConnection.setCharStyle(cursor, charStyle); } @@ -1234,7 +1234,7 @@ void assertCitationCharacterFormatIsOK( OOBibStyle style ) throws UndefinedCharacterFormatException { - if (!style.isFormatCitations()) { + if (!style.getFormatCitations()) { return; } @@ -1591,7 +1591,7 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, // doesn't exist, we end up deleting the markers before the // process crashes due to a the missing format, with // catastrophic consequences for the user. - boolean mustTestCharFormat = style.isFormatCitations(); + boolean mustTestCharFormat = style.getFormatCitations(); for (Map.Entry kv : citMarkers.entrySet() ) { @@ -2771,7 +2771,7 @@ public void checkStylesExistInTheDocument( OOBibStyle style, DocumentConnection documentConnection, "ReferenceParagraphFormat", pathToStyleFile); - if (style.isFormatCitations()) { + if (style.getFormatCitations()) { checkCharacterStyleExistsInTheDocument(style.getCitationCharacterFormat(), documentConnection, "CitationCharacterFormat", diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 3c2bb2af06c..f7a0f714cf6 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -692,7 +692,7 @@ public boolean isSortByPosition() { * @return true to indicate that citations should be formatted to getCitationCharacterFormat() * in italics (or bold). */ - public boolean isFormatCitations() { + public boolean getFormatCitations() { return (Boolean) obsCitProperties.get(FORMAT_CITATIONS); } @@ -702,7 +702,7 @@ public String getCitationCharacterFormat() { /** * Should citation markers be italicized? - * Only relevant if isFormatCitations() returns true. + * Only relevant if getFormatCitations() returns true. * * @return true to indicate that citations should be in italics. * @@ -714,7 +714,7 @@ public boolean isItalicCitations() { /** * Should citation markers be bold? - * Only relevant if isFormatCitations() returns true. + * Only relevant if getFormatCitations() returns true. * * @return true to indicate that citations should be in bold. * diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 6acacb9ee2d..a7f194c32dd 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -46,7 +46,7 @@ void testAuthorYear() throws IOException { assertTrue(style.isInternalStyle()); assertFalse(style.isCitationKeyCiteMarkers()); assertFalse(style.isBoldCitations()); - assertFalse(style.isFormatCitations()); + assertFalse(style.getFormatCitations()); assertFalse(style.isItalicCitations()); assertFalse(style.isNumberEntries()); assertFalse(style.isSortByPosition()); @@ -61,7 +61,7 @@ void testAuthorYearAsFile() throws URISyntaxException, IOException { assertFalse(style.isInternalStyle()); assertFalse(style.isCitationKeyCiteMarkers()); assertFalse(style.isBoldCitations()); - assertFalse(style.isFormatCitations()); + assertFalse(style.getFormatCitations()); assertFalse(style.isItalicCitations()); assertFalse(style.isNumberEntries()); assertFalse(style.isSortByPosition()); @@ -74,7 +74,7 @@ void testNumerical() throws IOException { assertTrue(style.isValid()); assertFalse(style.isCitationKeyCiteMarkers()); assertFalse(style.isBoldCitations()); - assertFalse(style.isFormatCitations()); + assertFalse(style.getFormatCitations()); assertFalse(style.isItalicCitations()); assertTrue(style.isNumberEntries()); assertTrue(style.isSortByPosition()); From bf90852ad77ddfe817d0ef3b9b284007b4927ee9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 08:21:51 +0200 Subject: [PATCH 0592/1068] REFERENCE_HEADER_PARAGRAPH_FORMAT defaults to "Standard" --- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index f7a0f714cf6..2fc1ff4fb90 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -258,12 +258,14 @@ public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) throws private void setDefaultProperties() { // Set default property values: obsProperties.put(TITLE, "Bibliography"); + obsProperties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1"); + + // Note: was default, but that is not known to LO + obsProperties.put(REFERENCE_PARAGRAPH_FORMAT, "Standard"); - obsProperties.put(IS_SORT_BY_POSITION, Boolean.FALSE); obsProperties.put(IS_NUMBER_ENTRIES, Boolean.FALSE); + obsProperties.put(IS_SORT_BY_POSITION, Boolean.FALSE); - obsProperties.put(REFERENCE_PARAGRAPH_FORMAT, "Default"); - obsProperties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1"); // Set default obsCitProperties for the citation marker: obsCitProperties.put(AUTHOR_FIELD, From 28272f1026a237ba204dbea49f8af600aff46fc9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 08:22:35 +0200 Subject: [PATCH 0593/1068] CITATION_CHARACTER_FORMAT defaults to "Standard" --- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 2fc1ff4fb90..5b9eb760e55 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -289,7 +289,9 @@ private void setDefaultProperties() { obsCitProperties.put(GROUPED_NUMBERS_SEPARATOR, "-"); obsCitProperties.put(MINIMUM_GROUPING_COUNT, 3); obsCitProperties.put(FORMAT_CITATIONS, Boolean.FALSE); - obsCitProperties.put(CITATION_CHARACTER_FORMAT, "Default"); + + // was "Default", but that is not knowm to LO + obsCitProperties.put(CITATION_CHARACTER_FORMAT, "Standard"); obsCitProperties.put(ITALIC_CITATIONS, Boolean.FALSE); obsCitProperties.put(BOLD_CITATIONS, Boolean.FALSE); obsCitProperties.put(SUPERSCRIPT_CITATIONS, Boolean.FALSE); From 700c2290124511c4231f922388a743a27fa1066e Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 08:23:41 +0200 Subject: [PATCH 0594/1068] decl order --- .../java/org/jabref/logic/openoffice/OOBibStyle.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 5b9eb760e55..3af6eedb3e4 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -68,12 +68,12 @@ public class OOBibStyle implements Comparable { * Keys for the PROPERTIES section of a *.jstyle file. */ private static final String TITLE = "Title"; - - private static final String IS_SORT_BY_POSITION = "IsSortByPosition"; - private static final String IS_NUMBER_ENTRIES = "IsNumberEntries"; private static final String REFERENCE_HEADER_PARAGRAPH_FORMAT = "ReferenceHeaderParagraphFormat"; private static final String REFERENCE_PARAGRAPH_FORMAT = "ReferenceParagraphFormat"; + private static final String IS_NUMBER_ENTRIES = "IsNumberEntries"; + private static final String IS_SORT_BY_POSITION = "IsSortByPosition"; + /* * Keys for the CITATION section of a *.jstyle file. */ @@ -728,9 +728,8 @@ public boolean isBoldCitations() { return (Boolean) obsCitProperties.get(BOLD_CITATIONS); } - - public boolean isCitationKeyCiteMarkers() { + // "BibTeXKeyCitations" return (Boolean) obsCitProperties.get(CITATION_KEY_CITATIONS); } From a9212cc237b1ce0dc25ca157fa0fb3af4791085a Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 08:26:57 +0200 Subject: [PATCH 0595/1068] reload rnamed obsReload, returns true if reloaded --- .../java/org/jabref/logic/openoffice/OOBibStyle.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 3af6eedb3e4..bbd77cf194b 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -237,7 +237,7 @@ public OOBibStyle(File styleFile, this.styleFile = Objects.requireNonNull(styleFile); this.encoding = Objects.requireNonNull(encoding); // setDefaultProperties(); // moved into initialize() - reload(); + obsReload(); fromResource = false; path = styleFile.getPath(); } @@ -374,20 +374,25 @@ private boolean isUpToDate() { */ public void ensureUpToDate() throws IOException { if (!isUpToDate()) { - reload(); + obsReload(); } } /** * If this style was initialized from a file on disk, reload the style * information. + * + * @return true if reloaded */ - private void reload() throws IOException { + private boolean obsReload() throws IOException { if (styleFile != null) { this.styleFileModificationTime = styleFile.lastModified(); try (InputStream stream = new FileInputStream(styleFile)) { initialize(stream, styleFile.getAbsolutePath()); } + return true; + } else { + return false; } } From 853efa02e9fa8dfe4fec661d01fd4b4a84d4a87d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 09:04:31 +0200 Subject: [PATCH 0596/1068] add localization messages --- src/main/resources/l10n/JabRef_en.properties | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 0c494820b6b..60db86380aa 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -2330,5 +2330,18 @@ I\ cannot\ insert\ to\ the\ cursors\ current\ location.=I\ cannot\ insert\ to\ t Please\ move\ the\ cursor\ to\ the\ location\ for\ the\ new\ citation.=Please\ move\ the\ cursor\ to\ the\ location\ for\ the\ new\ citation. +Please\ create\ it\ in\ the\ document\ or\ change\ in\ the\ file\:=Please create it in the document or change in the file: + +Please\ use\ the\ latter\ in\ the\ style\ file\ below\ to\ avoid\ localization\ problems.=Please use the latter in the style file below to avoid localization problems. + +The\ %0\ character\ style\ '%1'\ is\ a\ display\ name\ for\ '%2'.=The %0 character style '%1' is a display name for '%2'. + +The\ %0\ character\ style\ '%1'\ is\ missing\ from\ the\ document=The %0 character style '%1' is missing from the document + +The\ %0\ paragraph\ style\ '%1'\ is\ a\ display\ name\ for\ '%2'.=The %0 paragraph style '%1' is a display name for '%2'. + +The\ %0\ paragraph\ style\ '%1'\ is\ missing\ from\ the\ document=The %0 paragraph style '%1' is missing from the document + Unable\ to\ find\ valid\ certification\ path\ to\ requested\ target(%0),\ download\ anyway?=Unable to find valid certification path to requested target(%0), download anyway? Download\ operation\ canceled.=Download operation canceled. + From f328d62ec4778676fe20a6c036830bb30595359c Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 09:05:52 +0200 Subject: [PATCH 0597/1068] rename getTitle to getReferenceHeaderText --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e285bc7f912..3dab460ab27 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -2039,7 +2039,7 @@ private void populateBibTextSection(DocumentConnection documentConnection, // emit header documentConnection.xText.insertString(cursor, - style.getTitle(), + style.getReferenceHeaderText(), true); String parStyle = style.getReferenceHeaderParagraphFormat(); try { diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index bbd77cf194b..bb58b727ac6 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -67,7 +67,7 @@ public class OOBibStyle implements Comparable { /* * Keys for the PROPERTIES section of a *.jstyle file. */ - private static final String TITLE = "Title"; + private static final String REFERENCE_HEADER_TEXT = "Title"; // getReferenceHeaderText private static final String REFERENCE_HEADER_PARAGRAPH_FORMAT = "ReferenceHeaderParagraphFormat"; private static final String REFERENCE_PARAGRAPH_FORMAT = "ReferenceParagraphFormat"; @@ -257,7 +257,7 @@ public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) throws private void setDefaultProperties() { // Set default property values: - obsProperties.put(TITLE, "Bibliography"); + obsProperties.put(REFERENCE_HEADER_TEXT, "Bibliography"); obsProperties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1"); // Note: was default, but that is not known to LO @@ -861,8 +861,8 @@ protected String getOxfordComma() { /** * Title for the bibliography. */ - public String getTitle() { - return getStringProperty(OOBibStyle.TITLE); + public String getReferenceHeaderText() { + return getStringProperty(OOBibStyle.REFERENCE_HEADER_TEXT); } /** From ac42cf67581b8a3988f0d9873e073778610b66c0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 09:16:16 +0200 Subject: [PATCH 0598/1068] isNumberEntries, isSortByPosition renamed to getI... --- .../org/jabref/gui/openoffice/OOBibBase.java | 35 ++++++++++--------- .../jabref/logic/openoffice/OOBibStyle.java | 8 +++-- .../logic/openoffice/OOBibStyleTest.java | 12 +++---- 3 files changed, 29 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3dab460ab27..62feb7c01b8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -920,8 +920,8 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes throws BibEntryNotFoundException { - assert style.isNumberEntries(); - assert style.isSortByPosition(); + assert style.getIsNumberEntries(); + assert style.getIsSortByPosition(); cgs.createNumberedBibliographySortedInOrderOfAppearance(); @@ -949,8 +949,8 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes private Map produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, OOBibStyle style) { - assert style.isNumberEntries(); - assert !style.isSortByPosition(); + assert style.getIsNumberEntries(); + assert !style.getIsSortByPosition(); cgs.createNumberedBibliographySortedByComparator( entryComparator ); @@ -972,7 +972,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes /** * Produce citMarkers for normal - * (!isCitationKeyCiteMarkers && !isNumberEntries) styles. + * (!isCitationKeyCiteMarkers && !IsNumberEntries) styles. * * @param referenceMarkNames Names of reference marks. * @param bibtexKeysIn Bibtex citation keys. @@ -988,7 +988,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes BibEntryNotFoundException { assert !style.isCitationKeyCiteMarkers(); - assert !style.isNumberEntries(); + assert !style.getIsNumberEntries(); // Citations in (Au1, Au2 2000) form CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); @@ -1477,7 +1477,7 @@ public void insertCitation(List entries, } // The text we insert - String citeText = (style.isNumberEntries() + String citeText = (style.getIsNumberEntries() ? "[-]" // A dash only. Only refresh later. : style.getCitationMarker(citationMarkerEntries, inParenthesis, @@ -1708,8 +1708,9 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d // Question: is there a case when we do not need order-of-appearance? // // style.isCitationKeyCiteMarkers() : ??? - // style.isNumberEntries() && style.isSortByPosition() : needs order-of-appearance for numbering - // style.isNumberEntries() && !style.isSortByPosition() : ??? + // style.getIsNumberEntries() && style.getIsSortByPosition() : + // needs order-of-appearance for numbering + // style.getIsNumberEntries() && !style.getIsSortByPosition() : ??? // produceCitationMarkersForNormalStyle : needs order-of-appearance for uniqueLetters // { @@ -1728,14 +1729,14 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d if (style.isCitationKeyCiteMarkers()) { citMarkers = produceCitationMarkersForIsCitationKeyCiteMarkers(cgs, style); - } else if (style.isNumberEntries()) { - if (style.isSortByPosition()) { + } else if (style.getIsNumberEntries()) { + if (style.getIsSortByPosition()) { citMarkers = produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); } else { citMarkers = produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); } } else { - /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ + /* Normal case, (!isCitationKeyCiteMarkers && !IsNumberEntries) */ citMarkers = produceCitationMarkersForNormalStyle(cgs, style); } @@ -1786,7 +1787,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d * Rebuilds the bibliography. * * Note: assumes fresh `jabRefReferenceMarkNamesSortedByPosition` - * if `style.isSortByPosition()` + * if `style.getIsSortByPosition()` */ private void rebuildBibTextSection(DocumentConnection documentConnection, OOBibStyle style, @@ -1835,8 +1836,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, final boolean debugThisFun = false; if (debugThisFun) { - System.out.printf("Ref isSortByPosition %s\n", style.isSortByPosition()); - System.out.printf("Ref isNumberEntries %s\n", style.isNumberEntries()); + System.out.printf("Ref IsSortByPosition %s\n", style.getIsSortByPosition()); + System.out.printf("Ref IsNumberEntries %s\n", style.getIsNumberEntries()); } String parStyle = style.getReferenceParagraphFormat(); @@ -1855,7 +1856,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, OOUtil.insertParagraphBreak(documentConnection.xText, cursor); // insert marker "[1]" - if (style.isNumberEntries()) { + if (style.getIsNumberEntries()) { if ( ck.number.isEmpty() ) { throw new RuntimeException( @@ -1870,7 +1871,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, marker, Collections.emptyList()); } else { - // !style.isNumberEntries() : emit no prefix + // !style.getIsNumberEntries() : emit no prefix // TODO: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index bb58b727ac6..2d2edeeb13a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -67,7 +67,9 @@ public class OOBibStyle implements Comparable { /* * Keys for the PROPERTIES section of a *.jstyle file. */ - private static final String REFERENCE_HEADER_TEXT = "Title"; // getReferenceHeaderText + + // getReferenceHeaderText + private static final String REFERENCE_HEADER_TEXT = "Title"; private static final String REFERENCE_HEADER_PARAGRAPH_FORMAT = "ReferenceHeaderParagraphFormat"; private static final String REFERENCE_PARAGRAPH_FORMAT = "ReferenceParagraphFormat"; @@ -674,7 +676,7 @@ public String getGroupedNumbersSeparator() { * * @return true if we use numbered citations, false otherwise. */ - public boolean isNumberEntries() { + public boolean getIsNumberEntries() { return getBooleanProperty(IS_NUMBER_ENTRIES); } @@ -684,7 +686,7 @@ public boolean isNumberEntries() { * * @return true to sort by order of appearance, false to sort alphabetically. */ - public boolean isSortByPosition() { + public boolean getIsSortByPosition() { return getBooleanProperty(IS_SORT_BY_POSITION); } diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index a7f194c32dd..a3b4a461f86 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -48,8 +48,8 @@ void testAuthorYear() throws IOException { assertFalse(style.isBoldCitations()); assertFalse(style.getFormatCitations()); assertFalse(style.isItalicCitations()); - assertFalse(style.isNumberEntries()); - assertFalse(style.isSortByPosition()); + assertFalse(style.getIsNumberEntries()); + assertFalse(style.getIsSortByPosition()); } @Test @@ -63,8 +63,8 @@ void testAuthorYearAsFile() throws URISyntaxException, IOException { assertFalse(style.isBoldCitations()); assertFalse(style.getFormatCitations()); assertFalse(style.isItalicCitations()); - assertFalse(style.isNumberEntries()); - assertFalse(style.isSortByPosition()); + assertFalse(style.getIsNumberEntries()); + assertFalse(style.getIsSortByPosition()); } @Test @@ -76,8 +76,8 @@ void testNumerical() throws IOException { assertFalse(style.isBoldCitations()); assertFalse(style.getFormatCitations()); assertFalse(style.isItalicCitations()); - assertTrue(style.isNumberEntries()); - assertTrue(style.isSortByPosition()); + assertTrue(style.getIsNumberEntries()); + assertTrue(style.getIsSortByPosition()); } @Test From ccbf1744b20bcccd8edac87ce7e3857d0dbf4b4f Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 09:24:55 +0200 Subject: [PATCH 0599/1068] isCitationKeyCiteMarkers renamed to getBibTeXKeyCitations --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 14 +++++++------- .../org/jabref/logic/openoffice/OOBibStyle.java | 8 ++++---- .../jabref/logic/openoffice/OOBibStyleParser.java | 2 +- .../jabref/logic/openoffice/OOBibStyleTest.java | 6 +++--- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 62feb7c01b8..197e5649acf 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -880,7 +880,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes throws BibEntryNotFoundException { - assert style.isCitationKeyCiteMarkers(); + assert style.getBibTeXKeyCitations(); cgs.createPlainBibliographySortedByComparator(OOBibBase.entryComparator); @@ -972,7 +972,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes /** * Produce citMarkers for normal - * (!isCitationKeyCiteMarkers && !IsNumberEntries) styles. + * (!getBibTeXKeyCitations && !getIsNumberEntries) styles. * * @param referenceMarkNames Names of reference marks. * @param bibtexKeysIn Bibtex citation keys. @@ -987,7 +987,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes throws BibEntryNotFoundException { - assert !style.isCitationKeyCiteMarkers(); + assert !style.getBibTeXKeyCitations(); assert !style.getIsNumberEntries(); // Citations in (Au1, Au2 2000) form @@ -1707,7 +1707,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d // // Question: is there a case when we do not need order-of-appearance? // - // style.isCitationKeyCiteMarkers() : ??? + // style.getBibTeXKeyCitations() : ??? // style.getIsNumberEntries() && style.getIsSortByPosition() : // needs order-of-appearance for numbering // style.getIsNumberEntries() && !style.getIsSortByPosition() : ??? @@ -1727,7 +1727,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d // fill citMarkers Map uniqueLetters = new HashMap<>(); - if (style.isCitationKeyCiteMarkers()) { + if (style.getBibTeXKeyCitations()) { citMarkers = produceCitationMarkersForIsCitationKeyCiteMarkers(cgs, style); } else if (style.getIsNumberEntries()) { if (style.getIsSortByPosition()) { @@ -1736,7 +1736,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d citMarkers = produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); } } else { - /* Normal case, (!isCitationKeyCiteMarkers && !IsNumberEntries) */ + /* Normal case, (!getBibTeXKeyCitations && !getIsNumberEntries) */ citMarkers = produceCitationMarkersForNormalStyle(cgs, style); } @@ -1872,7 +1872,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, Collections.emptyList()); } else { // !style.getIsNumberEntries() : emit no prefix - // TODO: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); + // TODO: We might want [citationKey] prefix for style.getBibTeXKeyCitations(); } if ( ck.db.isEmpty() ) { diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 2d2edeeb13a..1e84a35be76 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -83,7 +83,7 @@ public class OOBibStyle implements Comparable { /* * general */ - private static final String CITATION_KEY_CITATIONS = "BibTeXKeyCitations"; + private static final String BIBTEX_KEY_CITATIONS = "BibTeXKeyCitations"; private static final String MULTI_CITE_CHRONOLOGICAL = "MultiCiteChronological"; // general / formatting citations @@ -299,7 +299,7 @@ private void setDefaultProperties() { obsCitProperties.put(SUPERSCRIPT_CITATIONS, Boolean.FALSE); obsCitProperties.put(SUBSCRIPT_CITATIONS, Boolean.FALSE); obsCitProperties.put(MULTI_CITE_CHRONOLOGICAL, Boolean.TRUE); - obsCitProperties.put(CITATION_KEY_CITATIONS, Boolean.FALSE); //"BibTeXKeyCitations" + obsCitProperties.put(BIBTEX_KEY_CITATIONS, Boolean.FALSE); //"BibTeXKeyCitations" obsCitProperties.put(ITALIC_ET_AL, Boolean.FALSE); obsCitProperties.put(OXFORD_COMMA, ""); } @@ -735,9 +735,9 @@ public boolean isBoldCitations() { return (Boolean) obsCitProperties.get(BOLD_CITATIONS); } - public boolean isCitationKeyCiteMarkers() { + public boolean getBibTeXKeyCitations() { // "BibTeXKeyCitations" - return (Boolean) obsCitProperties.get(CITATION_KEY_CITATIONS); + return (Boolean) obsCitProperties.get(BIBTEX_KEY_CITATIONS); } public boolean getCitPropertyMultiCiteChronological() { diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java index 0d11528ac48..a87f974fb08 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -224,7 +224,7 @@ private static Map makeKnownCitationProperties() { res.put("SuperscriptCitations", PropertyType.BOOL); res.put("SubscriptCitations", PropertyType.BOOL); res.put("MultiCiteChronological", PropertyType.BOOL); - res.put("BibTeXKeyCitations", PropertyType.BOOL); // CITATION_KEY_CITATIONS + res.put("BibTeXKeyCitations", PropertyType.BOOL); // BIBTEX_KEY_CITATIONS res.put("ItalicEtAl", PropertyType.BOOL); res.put("OxfordComma", PropertyType.STRING); res.put("UniquefierSeparator", PropertyType.STRING); diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index a3b4a461f86..55d1753249a 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -44,7 +44,7 @@ void testAuthorYear() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, layoutFormatterPreferences); assertTrue(style.isValid()); assertTrue(style.isInternalStyle()); - assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.getBibTeXKeyCitations()); assertFalse(style.isBoldCitations()); assertFalse(style.getFormatCitations()); assertFalse(style.isItalicCitations()); @@ -59,7 +59,7 @@ void testAuthorYearAsFile() throws URISyntaxException, IOException { OOBibStyle style = new OOBibStyle(defFile, layoutFormatterPreferences, StandardCharsets.UTF_8); assertTrue(style.isValid()); assertFalse(style.isInternalStyle()); - assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.getBibTeXKeyCitations()); assertFalse(style.isBoldCitations()); assertFalse(style.getFormatCitations()); assertFalse(style.isItalicCitations()); @@ -72,7 +72,7 @@ void testNumerical() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); assertTrue(style.isValid()); - assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.getBibTeXKeyCitations()); assertFalse(style.isBoldCitations()); assertFalse(style.getFormatCitations()); assertFalse(style.isItalicCitations()); From aa9a404dee6dfe7a6662fb424a1441f2ab85ca3c Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 09:27:56 +0200 Subject: [PATCH 0600/1068] getCitPropertyMultiCiteChronological renamed to getMultiCiteChronological --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 3 ++- src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 197e5649acf..8fcd22d6026 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -690,7 +690,7 @@ public void applyCitationEntries( */ private Comparator comparatorForMulticite(OOBibStyle style) { - if (style.getCitPropertyMultiCiteChronological()) { + if (style.getMultiCiteChronological()) { return this.yearAuthorTitleComparator; } else { return this.entryComparator; diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 1e84a35be76..642d66b894b 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -740,7 +740,8 @@ public boolean getBibTeXKeyCitations() { return (Boolean) obsCitProperties.get(BIBTEX_KEY_CITATIONS); } - public boolean getCitPropertyMultiCiteChronological() { + public boolean getMultiCiteChronological() { + // "MultiCiteChronological" return this.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL); } diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 55d1753249a..d676249d048 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -263,7 +263,7 @@ void testGetCitProperty() throws IOException { layoutFormatterPreferences); assertEquals(", ", style.getStringCitProperty("AuthorSeparator")); assertEquals(3, style.getMaxAuthors()); - assertTrue(style.getCitPropertyMultiCiteChronological()); + assertTrue(style.getMultiCiteChronological()); assertEquals("Default", style.getCitationCharacterFormat()); assertEquals("Default [number] style file.", style.getName()); Set journals = style.getJournals(); From 0de5b7988dd645b0d9d923986262b238edf2cb0d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 09:31:48 +0200 Subject: [PATCH 0601/1068] getCitPropertyItalicEtAl rnamed getItalicEtAl --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8fcd22d6026..06b96c332a3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1116,7 +1116,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti // format it as italic. // Check if we should italicize the "et al." string in citations: - boolean italicize = style.getCitPropertyItalicEtAl(); + boolean italicize = style.getItalicEtAl(); if (italicize) { String etAlString = style.getEtAlString(); Objects.requireNonNull(etAlString); diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 642d66b894b..dd374ad0d00 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -745,7 +745,8 @@ public boolean getMultiCiteChronological() { return this.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL); } - public boolean getCitPropertyItalicEtAl() { + public boolean getItalicEtAl() { + // "ItalicEtAl" return this.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); } From 61e800e2fa1befb5fe92e32fa057dfc8e5d447d8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 09:43:47 +0200 Subject: [PATCH 0602/1068] isItalicCitations rnamed getItalicCitations --- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 6 +++--- .../java/org/jabref/logic/openoffice/OOBibStyleTest.java | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index dd374ad0d00..7591933264f 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -93,7 +93,7 @@ public class OOBibStyle implements Comparable { // TODO: ITALIC_CITATIONS ItalicCitations is not implemented // status: // - jstyles.jabref.org-master : 4 styles mention it, value is false in all of them. - // - getter: isItalicCitations() exists, but only called from tests, to assert it is false. + // - getter: getItalicCitations() exists, but only called from tests, to assert it is false. // - default: citProperties.put(ITALIC_CITATIONS, Boolean.FALSE); // private static final String ITALIC_CITATIONS = "ItalicCitations"; @@ -693,7 +693,7 @@ public boolean getIsSortByPosition() { /** * Should citation markers be formatted * according to the results of the - * - isItalicCitations() // not implemented + * - getItalicCitations() // not implemented * - isBoldCitations() // not implemented * - getCitationCharacterFormat() // yes * methods? @@ -719,7 +719,7 @@ public String getCitationCharacterFormat() { * * TODO: unused */ - public boolean isItalicCitations() { + public boolean getItalicCitations() { return getBooleanCitProperty(ITALIC_CITATIONS); } diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index d676249d048..1d6e6913096 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -47,7 +47,7 @@ void testAuthorYear() throws IOException { assertFalse(style.getBibTeXKeyCitations()); assertFalse(style.isBoldCitations()); assertFalse(style.getFormatCitations()); - assertFalse(style.isItalicCitations()); + assertFalse(style.getItalicCitations()); assertFalse(style.getIsNumberEntries()); assertFalse(style.getIsSortByPosition()); } @@ -62,7 +62,7 @@ void testAuthorYearAsFile() throws URISyntaxException, IOException { assertFalse(style.getBibTeXKeyCitations()); assertFalse(style.isBoldCitations()); assertFalse(style.getFormatCitations()); - assertFalse(style.isItalicCitations()); + assertFalse(style.getItalicCitations()); assertFalse(style.getIsNumberEntries()); assertFalse(style.getIsSortByPosition()); } @@ -75,7 +75,7 @@ void testNumerical() throws IOException { assertFalse(style.getBibTeXKeyCitations()); assertFalse(style.isBoldCitations()); assertFalse(style.getFormatCitations()); - assertFalse(style.isItalicCitations()); + assertFalse(style.getItalicCitations()); assertTrue(style.getIsNumberEntries()); assertTrue(style.getIsSortByPosition()); } From c9f2e5897b32aa731d16948b472d3d4763148fa3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 10:11:36 +0200 Subject: [PATCH 0603/1068] add getSuperscriptCitations, getSubscriptCitations --- .../jabref/logic/openoffice/OOBibStyle.java | 34 ++++++++++++------- .../logic/openoffice/OOBibStyleTest.java | 6 ++-- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 7591933264f..913aa594b59 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -101,10 +101,12 @@ public class OOBibStyle implements Comparable { // TODO: BOLD_CITATIONS is not implemented private static final String BOLD_CITATIONS = "BoldCitations"; - // TODO: SUBSCRIPT_CITATIONS, SUPERSCRIPT_CITATIONS are not implemented - private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations"; + // TODO: SUPERSCRIPT_CITATIONS is not implemented private static final String SUPERSCRIPT_CITATIONS = "SuperscriptCitations"; + // TODO: SUBSCRIPT_CITATIONS is not implemented + private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations"; + /* * common (numeric and author-year) */ @@ -690,18 +692,16 @@ public boolean getIsSortByPosition() { return getBooleanProperty(IS_SORT_BY_POSITION); } + /* + * Character formatting + */ + /** * Should citation markers be formatted - * according to the results of the - * - getItalicCitations() // not implemented - * - isBoldCitations() // not implemented - * - getCitationCharacterFormat() // yes - * methods? - * - * There is also SUPERSCRIPT_CITATIONS, SUBSCRIPT_CITATIONS + * according to getCitationCharacterFormat()? * - * @return true to indicate that citations should be formatted to getCitationCharacterFormat() - * in italics (or bold). + * @return true to indicate that citations should be formatted to + * getCitationCharacterFormat(). */ public boolean getFormatCitations() { return (Boolean) obsCitProperties.get(FORMAT_CITATIONS); @@ -731,9 +731,19 @@ public boolean getItalicCitations() { * * TODO: unused */ - public boolean isBoldCitations() { + public boolean getBoldCitations() { return (Boolean) obsCitProperties.get(BOLD_CITATIONS); } + public boolean getSuperscriptCitations() { + return (Boolean) obsCitProperties.get(SUPERSCRIPT_CITATIONS); + } + public boolean getSubscriptCitations() { + return (Boolean) obsCitProperties.get(SUBSCRIPT_CITATIONS); + } + + /* + * + */ public boolean getBibTeXKeyCitations() { // "BibTeXKeyCitations" diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 1d6e6913096..4dd5dc303f1 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -45,7 +45,7 @@ void testAuthorYear() throws IOException { assertTrue(style.isValid()); assertTrue(style.isInternalStyle()); assertFalse(style.getBibTeXKeyCitations()); - assertFalse(style.isBoldCitations()); + assertFalse(style.getBoldCitations()); assertFalse(style.getFormatCitations()); assertFalse(style.getItalicCitations()); assertFalse(style.getIsNumberEntries()); @@ -60,7 +60,7 @@ void testAuthorYearAsFile() throws URISyntaxException, IOException { assertTrue(style.isValid()); assertFalse(style.isInternalStyle()); assertFalse(style.getBibTeXKeyCitations()); - assertFalse(style.isBoldCitations()); + assertFalse(style.getBoldCitations()); assertFalse(style.getFormatCitations()); assertFalse(style.getItalicCitations()); assertFalse(style.getIsNumberEntries()); @@ -73,7 +73,7 @@ void testNumerical() throws IOException { layoutFormatterPreferences); assertTrue(style.isValid()); assertFalse(style.getBibTeXKeyCitations()); - assertFalse(style.isBoldCitations()); + assertFalse(style.getBoldCitations()); assertFalse(style.getFormatCitations()); assertFalse(style.getItalicCitations()); assertTrue(style.getIsNumberEntries()); From 7798b4d4de2d1c3325846b88914f503f0d053440 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 12:38:14 +0200 Subject: [PATCH 0604/1068] comments, format --- .../jabref/logic/openoffice/OOBibStyle.java | 62 ++++++++++++------- 1 file changed, 40 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 913aa594b59..7b9bce0b733 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -146,6 +146,9 @@ public class OOBibStyle implements Comparable { /** Name of field that contains the authors. May be a list: "author/editor" */ private static final String AUTHOR_FIELD = "AuthorField"; + /** Name of field that contains the year. May be a list "year/anotherFieldWithYear" */ + private static final String YEAR_FIELD = "YearField"; + /** How many authors to show before switching to "et al." */ private static final String MAX_AUTHORS = "MaxAuthors"; @@ -174,8 +177,6 @@ public class OOBibStyle implements Comparable { /** "Smith et al.{ }[2000]" */ private static final String IN_TEXT_YEAR_SEPARATOR = "InTextYearSeparator"; - /** Name of field that contains the year. May be a list "year/anotherFieldWithYear" */ - private static final String YEAR_FIELD = "YearField"; /** "[Smith et al. 2000a{,}b; pp 10-13]" */ private static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; @@ -272,9 +273,21 @@ private void setDefaultProperties() { // Set default obsCitProperties for the citation marker: + + /* + * Character formatting. + */ + obsCitProperties.put(FORMAT_CITATIONS, Boolean.FALSE); + // was "Default", but that is not knowm to LO + obsCitProperties.put(CITATION_CHARACTER_FORMAT, "Standard"); + obsCitProperties.put(ITALIC_CITATIONS, Boolean.FALSE); + obsCitProperties.put(BOLD_CITATIONS, Boolean.FALSE); + obsCitProperties.put(SUPERSCRIPT_CITATIONS, Boolean.FALSE); + obsCitProperties.put(SUBSCRIPT_CITATIONS, Boolean.FALSE); + obsCitProperties.put(AUTHOR_FIELD, - FieldFactory.serializeOrFields(StandardField.AUTHOR, - StandardField.EDITOR)); + FieldFactory.serializeOrFields(StandardField.AUTHOR, + StandardField.EDITOR)); obsCitProperties.put(YEAR_FIELD, StandardField.YEAR.getName()); obsCitProperties.put(MAX_AUTHORS, 3); obsCitProperties.put(MAX_AUTHORS_FIRST, -1); @@ -292,14 +305,7 @@ private void setDefaultProperties() { obsCitProperties.put(PAGE_INFO_SEPARATOR, "; "); obsCitProperties.put(GROUPED_NUMBERS_SEPARATOR, "-"); obsCitProperties.put(MINIMUM_GROUPING_COUNT, 3); - obsCitProperties.put(FORMAT_CITATIONS, Boolean.FALSE); - // was "Default", but that is not knowm to LO - obsCitProperties.put(CITATION_CHARACTER_FORMAT, "Standard"); - obsCitProperties.put(ITALIC_CITATIONS, Boolean.FALSE); - obsCitProperties.put(BOLD_CITATIONS, Boolean.FALSE); - obsCitProperties.put(SUPERSCRIPT_CITATIONS, Boolean.FALSE); - obsCitProperties.put(SUBSCRIPT_CITATIONS, Boolean.FALSE); obsCitProperties.put(MULTI_CITE_CHRONOLOGICAL, Boolean.TRUE); obsCitProperties.put(BIBTEX_KEY_CITATIONS, Boolean.FALSE); //"BibTeXKeyCitations" obsCitProperties.put(ITALIC_ET_AL, Boolean.FALSE); @@ -713,24 +719,36 @@ public String getCitationCharacterFormat() { /** * Should citation markers be italicized? - * Only relevant if getFormatCitations() returns true. * * @return true to indicate that citations should be in italics. * - * TODO: unused + * TODO: unused getItalicCitations, getBoldCitations, + * getSuperscriptCitations, getSubscriptCitations + * + * May be worth implementing, because only getItalicCitations has + * a corresponding predefined character style in LibreOffice + * (Emphasis), and asking the user to create a style complicates + * usage. + * + * (a) Alternatively, we could have a character style, for example + * JR_citation that we always apply, and modify according to the + * current style. But that might interact with other uses of + * styles: I think a character can only have a single character + * style applied: if we are doing that, then a style applied by the + * user, for example a change in the font-size is going to be + * overwritten. Is it possible to create partial styles, that + * only override some, but not all character properties? Probably not. + * + * (b) Considering ItalicEtAl, we may want to switch to citation + * marks generated as OOFormattedText instead of plain + * text. If we do so, getItalicCitations et al could be + * replaced by BracketBefore="[" BracketAfter="]". + * + * Probably this is the way to go. */ public boolean getItalicCitations() { return getBooleanCitProperty(ITALIC_CITATIONS); } - - /** - * Should citation markers be bold? - * Only relevant if getFormatCitations() returns true. - * - * @return true to indicate that citations should be in bold. - * - * TODO: unused - */ public boolean getBoldCitations() { return (Boolean) obsCitProperties.get(BOLD_CITATIONS); } From 54fc1458701a635548168d4f12ef5b56911ab4fe Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 15:46:31 +0200 Subject: [PATCH 0605/1068] feature: Allow multiline rules in *.jstyle --- .../logic/openoffice/OOBibStyleParser.java | 103 ++++- .../logic/openoffice/OOBibStyleTest.java | 37 ++ .../openoffice/example_style_file.jstyle | 377 ++++++++++++++++ .../openoffice/multilineLayoutRule.jstyle | 417 ++++++++++++++++++ .../jabref/logic/openoffice/parseError.jstyle | 6 + .../logic/openoffice/parserWarning.jstyle | 44 ++ 6 files changed, 975 insertions(+), 9 deletions(-) create mode 100644 src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle create mode 100644 src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle create mode 100644 src/test/resources/org/jabref/logic/openoffice/parseError.jstyle create mode 100644 src/test/resources/org/jabref/logic/openoffice/parserWarning.jstyle diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java index a87f974fb08..86dafd40751 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -10,6 +10,7 @@ import java.util.Map; import java.util.Set; import java.util.SortedSet; +import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.logic.layout.Layout; @@ -41,6 +42,9 @@ public class OOBibStyleParser { private static final Pattern QUOTED = Pattern.compile("\".*\""); private static final Pattern NUM_PATTERN = Pattern.compile("-?\\d+"); + private static final Pattern LAYOUT_MULTILINE_STARTER = + Pattern.compile("^\\s*([^\\s=]+)\\s*[=]\\s*[|](.*)[|]\\s*$"); + private static final Pattern LAYOUT_MULTILINE_CONTINUATION = Pattern.compile("^\\s*[|](.*)[|]\\s*$"); private static final Set SECTION_NAMES = Set.of(NAME_MARK, JOURNALS_MARK, PROPERTIES_MARK, CITATION_MARK, LAYOUT_MARK); @@ -248,7 +252,8 @@ private static enum BibStyleMode { IN_JOURNALS_SECTION, IN_PROPERTIES_SECTION, IN_CITATION_SECTION, - IN_LAYOUT_SECTION + IN_LAYOUT_SECTION, + IN_LAYOUT_SECTION_MULTILINE } @@ -338,6 +343,9 @@ void error(String fileName, int lineNumber, String message) { void warn(String fileName, int lineNumber, String message) { this.entries.add(new ParseLogEntry(ParseLogLevel.WARN, fileName, lineNumber, message)); } + void info(String fileName, int lineNumber, String message) { + this.entries.add(new ParseLogEntry(ParseLogLevel.INFO, fileName, lineNumber, message)); + } public int size() { return entries.size(); @@ -389,6 +397,14 @@ public boolean hasError() { * - To reduce friction, (OOBibStyleParser.patient == true) turns * "unparsable lines", "extra quotes", "missing quotes", "unknown property" * into a warning (instead of error). + * + * - To avoid the necessity of long lines in the LAYOUT section, + * if the RHS matches "|.*|", than we switch to multiline LAYOUT mode + * for the given entry, and collect lines matching to "|.*|" into the value. + * We expect an empty line to terminate the multiline rule. + * The "|" characters are stripped and the rest are concatenated before + * using the value. + * */ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileName) throws @@ -406,11 +422,21 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa // Store a local copy for viewing style.localCopy = sb.toString(); + // Add EOL and a fake an empty line at the end. In case + // IN_LAYOUT_SECTION_MULTILINE is terminated by EOF, + // this will trigger closing. // Break into separate lines: + sb.append("\n \n "); String[] lines = sb.toString().split("\n"); - BibStyleMode mode = BibStyleMode.BEFORE_NAME_SECTION; + BibStyleMode mode = BibStyleMode.BEFORE_NAME_SECTION; int lineNumber = 0; + + // For multiline LAYOUT rules + int layoutLineCollectorStartLine = -1; + String layoutLineCollectorName = "***"; + List layoutLineCollectorValue = new ArrayList<>(); + for (String line1 : lines) { String line = line1; lineNumber++; @@ -422,13 +448,13 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa final String trimmedLine = line.trim(); - // Skip empty lines: - if (trimmedLine.isEmpty()) { + // Skip empty lines, unless we are in IN_LAYOUT_SECTION_MULTILINE + if (trimmedLine.isEmpty() && (mode != BibStyleMode.IN_LAYOUT_SECTION_MULTILINE) ) { continue; } // Skip comment: - if (line.charAt(0) == '#') { + if (line.length() > 0 && line.charAt(0) == '#') { continue; } @@ -554,11 +580,52 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa } case IN_LAYOUT_SECTION: - ParseLogLevel res = handleLayoutLine(line, style, fileName, lineNumber, logger); - if (res == ParseLogLevel.ERROR) { - return logger; + Matcher ms = LAYOUT_MULTILINE_STARTER.matcher(line); + if (ms.find()) { + layoutLineCollectorStartLine = lineNumber; + layoutLineCollectorName = ms.group(1); + layoutLineCollectorValue = new ArrayList<>(); + layoutLineCollectorValue.add(ms.group(2)); + mode = BibStyleMode.IN_LAYOUT_SECTION_MULTILINE; + continue; } else { + ParseLogLevel res = handleLayoutLine(line, style, fileName, lineNumber, logger); + if (res == ParseLogLevel.ERROR) { + return logger; + } else { + continue; + } + } + case IN_LAYOUT_SECTION_MULTILINE: + Matcher mc = LAYOUT_MULTILINE_CONTINUATION.matcher(line); + if (mc.find()) { + layoutLineCollectorValue.add(mc.group(1)); continue; + } else if (trimmedLine.equals("")) { + ParseLogLevel res = handleLayoutLineParts(layoutLineCollectorName, + String.join("", layoutLineCollectorValue), + style, + fileName, + layoutLineCollectorStartLine, + logger ); + + layoutLineCollectorName = "***"; + layoutLineCollectorValue = new ArrayList<>(); + layoutLineCollectorStartLine = -1; + + mode = BibStyleMode.IN_LAYOUT_SECTION; + + if (res == ParseLogLevel.ERROR) { + return logger; + } else { + continue; + } + } else { + logger.error(fileName, + lineNumber, + "line is neither empty, nor |.*|" + + " while expecting multiline LAYOUT rule continuation."); + return logger; } default: @@ -568,7 +635,11 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa // Set validity boolean based on whether we found every section // in the file. - if (mode != BibStyleMode.IN_LAYOUT_SECTION) { + if (mode == BibStyleMode.IN_LAYOUT_SECTION_MULTILINE) { + logger.error(fileName, lineNumber, "Reached end of file inside a multiline LAYOUT rule."); + return logger; + } + if (mode != BibStyleMode.IN_LAYOUT_SECTION && mode != BibStyleMode.IN_LAYOUT_SECTION_MULTILINE) { logger.error(fileName, lineNumber, "Did not reach LAYOUT section at EOF"); return logger; } @@ -699,6 +770,20 @@ private static ParseLogLevel handleLayoutLine(String line, String name = line.substring(0, index); String formatString = line.substring(index + 1); + return handleLayoutLineParts(name, + formatString, + style, + fileName, + lineNumber, + logger ); + } + + private static ParseLogLevel handleLayoutLineParts(String name, + String formatString, + OOBibStyle style, + String fileName, + int lineNumber, + ParseLog logger) { // Parse name: actually look up in a closed list, or // return {@code new UnknownEntryType(typeName)} diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 4dd5dc303f1..2db21938f8d 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -932,4 +932,41 @@ void testIsValidWithDefaultSectionAtTheStart() throws Exception { OOBibStyle style = new OOBibStyle("testWithDefaultAtFirstLIne.jstyle", layoutFormatterPreferences); assertTrue(style.isValid()); } + + @Test + void testParseError() throws Exception { + OOBibStyle style = new OOBibStyle("parseError.jstyle", + layoutFormatterPreferences); + assertFalse(style.isValid()); + OOBibStyleParser.ParseLog pl = style.getParseLog(); + assertTrue(pl.hasError()); + } + + @Test + void testParserWarning() throws Exception { + OOBibStyle style = new OOBibStyle("parserWarning.jstyle", + layoutFormatterPreferences); + assertTrue(style.isValid()); + OOBibStyleParser.ParseLog pl = style.getParseLog(); + assertFalse(pl.hasError()); + } + + @Test + void testParseMultilineRules() throws Exception { + OOBibStyle style = new OOBibStyle("multilineLayoutRule.jstyle", + layoutFormatterPreferences); + assertTrue(style.isValid()); + OOBibStyleParser.ParseLog pl = style.getParseLog(); + assertFalse(pl.hasError()); + } + + @Test + void testParseExample() throws Exception { + OOBibStyle style = new OOBibStyle("example_style_file.jstyle", + layoutFormatterPreferences); + assertTrue(style.isValid()); + OOBibStyleParser.ParseLog pl = style.getParseLog(); + assertFalse(pl.hasError()); + } } + diff --git a/src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle b/src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle new file mode 100644 index 00000000000..e00ab23d1dd --- /dev/null +++ b/src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle @@ -0,0 +1,377 @@ +# +# This is an example style file for the OpenOffice integration part of +# JabRef. +# +# The format of *.jstyle files are describe here: +# https://docs.jabref.org/cite/openofficeintegration#the-style-file +# +# The format of the rules in teh LAYOUT section is detailed here: +# https://docs.jabref.org/collaborative-work/export/customexports +# +# +# This is a comment, due to # at the beginning of the line. +# Comments and empty lines are ignored. +# +# Definitions: +# "citation" : reference to a source in the text +# +# "citation group" : one or more citations grouped together, +# typically in a pair or parentheses. +# +# Technically each citation is in a group, +# single citations are in their own +# single-element groups. +# +# in-text in-parenthesis and hidden citations: +# +# JabRef allows to mark individual citation groups as +# +# in-parenthesis: "[Smith et al. 2000]" (this is the default form), or +# in-text: "Smith et al. [2000]" form. +# These two are only relevant for author-year citation styles. +# +# hidden citations are not shown in the text, but appear in +# the bibliography. They can be used to type your own +# citations in the text, but still get help in +# building the bibliography. +# +# Some settings below allow a different value to be set for +# in-text citations. +# +# Implementation note: +# +# The "Merge" button in the GUI only merges +# in-parenthesis citation groups. +# +# However selecting multiple sources and clicking "Cite in-text" +# will create a group of multiple in-text citations. +# +# Even a group of multiple hidden citations can be created by +# "Insert empty citation". +# +# Note on paragraph and character styles in LibreOffice: +# +# This concerns ReferenceHeaderParagraphFormat, +# ReferenceParagraphFormat and, if FormatCitations is true, +# CitationCharacterFormat below. +# +# (1) JabRef does not manipulate named styles in LibreOffice. +# +# If the jstyle file refers to a style that does not exist in the +# document, the user has to create the style in LibreOffice or +# edit the the name in jstyle file. +# +# (2) Styles in LibreOffice have two names. One is the "Display name" +# shown to users, the other is the "internal name". +# +# Locally one could use either, but the "Display name" depends on +# the locale, thus would fail for other users. +# +# The "Refresh bibliography" now checks if the jstyle asks to +# apply a style by display name, and asks to change it. It will +# show the corresponding internal name, which otherwise I +# do not know how to get. +# +# +NAME +# The NAME section provides a name for the style. +# It consists of a single (non-empty, non-comment) line. + +Example style file for JabRef-oo plugin. + +JOURNALS +# The JOURNALS section lists journal names, one per line. +Journal name 1 +Journal name 2 + +PROPERTIES + +## The PROPERTIES and CITATION sections provide name=value pairs. +## The names are fixed, also the type of the corresponding values. + +## There are three value types: +## boolean: true or false +## integer: like -1 or 113 +## string: like "Hello there" + +## Title: string, the title of the bibliography. +## default: "Bibliography" +Title = "References" + +## ReferenceHeaderParagraphFormat : string. +## The paragraph style for the title of the bibliography. +## Should name a paragraph style known by OpenOffice/LibreOffice +## default: "Heading 1" +## example: ReferenceHeaderParagraphFormat = "Heading 2" + +## ReferenceParagraphFormat : string. +## The paragraph style for the bibliography entries. +## default: "Standard" +## example: ReferenceParagraphFormat="Text body" +ReferenceParagraphFormat="Text body" + +## IsNumberEntries : boolean, default: false +## If true, than this style uses numbered citations. +## If false, author-year style. +## +## Since numbered citations have different parts than +## author-year citations, the value of IsNumberEntries +## affects which properties are relevant. +## +## Note: if BibTeXKeyCitations is true (below, in the CITATION +## section), then IsNumberEntries is irrelevant. +## +IsNumberEntries = false + +## IsSortByPosition : boolean, default: false. +## +## Determines how the bibliography is sorted. +## +## If true, the entries will be sorted according to the order in which +## they are cited. Note: within a citation group +## +## If false, the entries will be sorted alphabetically by authors. +## +## Only relevant for numbered citations. +## +IsSortByPosition = false + +CITATION + +## This section contains settings related to individual citations and +## citation groups. + +## BibTeXKeyCitations : boolean, default: false +## If true, citations are represented by their BibTex keys. +## In this case IsNumberEntries is irrelevant. +# BibTeXKeyCitations=false + +## MultiCiteChronological: boolean, default: true +## If true, citations in a citation group are +## sorted by (year,author,title), otherwise by (author,year,title). +## +## Relevant with author-year and BibTeXKeyCitations. +## +## Its relevance for numbered citations is less obviuous, because just +## before we emit a citaion group, we sort the numbers appearing in +## the group. +## +## For IsNumberEntries + IsSortByPosition, it affects the citations +## position within citation groups, which may be observable in the +## numbering. +## +## For IsNumberEntries + !IsSortByPosition, the numbering comes from +## sorting the bibliography, thus MultiCiteChronological does not have +## an effect. +## +MultiCiteChronological=true + +## Character formatting of citation groups. + +## FormatCitations: boolean, default: false +## Decides if CitationCharacterFormat below should be applied. +## +## Note: when switching from a style with FormatCitations==true to one +## with FormatCitations==false, the character style established +## by the first is not removed from the citations. Applying a +## style with CitationCharacterFormat = "Standard" might help to +## avoid doing by hand. +## +FormatCitations = false + +## CitationCharacterFormat : string. +## default: "Standard" +## +## A character format to apply to citation groups, as known to +## LibreOffice. +## +## example: CitationCharacterFormat = "Standard" +## example: CitationCharacterFormat = "Emphasis" +## example: CitationCharacterFormat = "Example" +# CitationCharacterFormat = "Standard" +# CitationCharacterFormat="JR_citation" + +## +## The following correspond to direct character formatting. +## They are not controlled by FormatCitations. +## + +## ItalicCitations : boolean, default: false. +## Not implemented. +# ItalicCitations = false + +## BoldCitations : boolean, default: false. +## Not implemented. +# BoldCitations = false + +## SuperscriptCitations : boolean, default: false. +## Not implemented. +# SuperscriptCitations = false + +## SubscriptCitations : boolean, default: false. +## Not implemented. +# SubscriptCitations = false + +## +## For text fragments below, examples show the location +## by bracketing the relevant part with "{}" +## + +## BracketBefore : string, default: "(" +## Location: "{[}Smith 2000]" "Smith {[}2000]" "{[}1]" "{[}bibtextkey]" +BracketBefore="[" + +## BracketAfter : string, default: ")" +## Location: "[Smith 2000{]}" "Smith [2000{]}" "[1{]}" "[bibtextkey{]}" +BracketAfter="]" + +## BracketBeforeInList : string, default: not set. +## If not set, BracketBefore is used instead. +## Purpose: for numbered styles, used in the entry labels in the bibliography. +## Location: "{[}1]" +## Not relevant for BibTeXKeyCitations and author-year. +BracketBeforeInList="[" + +## BracketAfterInList : string, default: not set. +## If not set, BracketAfter is used instead. +## Purpose: for numbered styles, used in the entry labels in the bibliography. +## Location: "[1{]}" +## Not relevant for BibTeXKeyCitations and author-year. +BracketAfterInList="] " + +## PageInfoSeparator : string, default: "; " +## Location: "[Smith 2000a{; }pp 10-13]" "Smith [2000a{; }pp 10-13]" "[1{; }pp 10-13]" +## Not used for BibTeXKeyCitations (maybe it should be) +PageInfoSeparator = "; " + +## CitationSeparator : string, default: "; " +## Location: between citations in the same citation group. +## "[Smith 2000{; }Jones 2001]" "Smith [2000{; }Jones [2001]" "[1{; }2]" +CitationSeparator="; " + +## +## Settings that only apply to numeric citation style. +## + +## MinimumGroupingCount : int, default: 3 +## Purpose: How many consecutive numbers in "[1; 2; 3]" allows grouping to "[1-3]" +MinimumGroupingCount=3 + +## GroupedNumbersSeparator : string, default: "-" +## Purpose: for numeric style, when consecutive numbers collapsed to a +## range, this is used as the separator between range start +## and range end. +## Location: "[1{-}3]" +GroupedNumbersSeparator="-" + +## +## Settings that only apply to author-year style. +## + +## AuthorField : string, default: "author/editor" +## +## Purpose: When looking for authors, which bibtex fields to look in? +## +## The field names are separated by "/", the first field that +## exists and is not empty applies. +AuthorField="author/editor" + +## YearField : string, default: "year" +## +## Purpose: When looking for the year, which bibtex fields to look in? +## +## The field names are separated by "/", the first field that +## exists and is not empty applies. +## +YearField="year" + +## MaxAuthors : int, default: 3 +## Purpose: How many author names to show in citations? +## If there are more, "FirstAuthor et al." will be used instead. +## Special value: -1 encodes "unlimited" +MaxAuthors=2 + +## MaxAuthorsFirst : int, default: -1 +## Purpose: some styles require a different value of MaxAuthors for +## the first appearance of a source. +## Special value: -1 encodes "unlimited" +## +MaxAuthorsFirst=6 + +## AuthorSeparator : string, default: ", " +## Location: "[Smith{, }Jones, and Brown 2000]" +AuthorSeparator=", " + +## OxfordComma : string, default: "" +## Location: "[Smith, Jones{,} and Brown 2000]" +# example: OxfordComma = "," + +## AuthorLastSeparator : string default: " & " +## Location: "[Smith, Jones,{ and }Brown 2000]" */ +AuthorLastSeparator=" & " + +## AuthorLastSeparatorInText : string, default: not set. +## If not set, AuthorLastSeparator is used instead. +## Purpose: for in-text "Author (year)" citations, +## allows alternative value for AuthorLastSeparator. +## Location: "Smith, Jones,{ and }Brown [2000]" +AuthorLastSeparatorInText=" and " + +## EtAlString : string, default: "et al." +## Location: "[Smith{ et al.} 2000]" "Smith{ et al.} [2000]" +## Purpose: if there are more authors than allowed by MaxAuthors, +## only the first author name is shown. EtAlString indicates +## the omission of the other names. +EtAlString=" et al." + +## YearSeparator : string, default: ", " +## Location: just after the authors, for in-parenthesis citations: "[Smith et al.{ }2000]" +YearSeparator=" " + +## InTextYearSeparator : string, default: " " +## Location: "Smith et al.{ }[2000]" +InTextYearSeparator=" " + +## UniquefierSeparator : string, default: "," +## Location: "[Smith et al. 2000a{,}b; pp 10-13]" +UniquefierSeparator="," + +LAYOUT +## +## The LAYOUT section provides formatting rules for the bibliography entries. +## +## In the name=value pairs below, "name" is either a bibtex entry type (article, ...) +## or "default" (fallback in case there is no formatting provided for a bibtex entry type. +## +## The default entry is required. +## +## Note: +## (1) White spaces are significant in the rules. +## +## (2) You can split the value to multiple lines. +## Each part must be between two "|" characters. +## Each part (except the first) has its own line. +## An empty line terminates the rule. +## See below at the book and incollection rules. +## +article=\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. + +book = |\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| + |\begin{editor}| + |\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.)| + |\end{editor},| + | \year\uniq. \title. \publisher, \address.| + +incollection = || +|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| +# We can add comments between the lines (still has to start at the first column). +| (\year\uniq). \title.| +| In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.),| +| \booktitle, \publisher.| + +inbook=\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author} (\year\uniq). \chapter. In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.), \title, \publisher. + +phdthesis=\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author} (\year\uniq). \title, \school. + +default=\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. + diff --git a/src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle b/src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle new file mode 100644 index 00000000000..8e6c1f5a552 --- /dev/null +++ b/src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle @@ -0,0 +1,417 @@ +# +# This is an example style file for the OpenOffice integration part of +# JabRef. +# +# The format of *.jstyle files are describe here: +# https://docs.jabref.org/cite/openofficeintegration#the-style-file +# +# The format of the rules in teh LAYOUT section is detailed here: +# https://docs.jabref.org/collaborative-work/export/customexports +# +# +# This is a comment, due to # at the beginning of the line. +# Comments and empty lines are ignored. +# +# Definitions: +# "citation" : reference to a source in the text +# +# "citation group" : one or more citations grouped together, +# typically in a pair or parentheses. +# +# Technically each citation is in a group, +# single citations are in their own +# single-element groups. +# +# in-text in-parenthesis and hidden citations: +# +# JabRef allows to mark individual citation groups as +# +# in-parenthesis: "[Smith et al. 2000]" (this is the default form), or +# in-text: "Smith et al. [2000]" form. +# These two are only relevant for author-year citation styles. +# +# hidden citations are not shown in the text, but appear in +# the bibliography. They can be used to type your own +# citations in the text, but still get help in +# building the bibliography. +# +# Some settings below allow a different value to be set for +# in-text citations. +# +# Implementation note: +# +# The "Merge" button in the GUI only merges +# in-parenthesis citation groups. +# +# However selecting multiple sources and clicking "Cite in-text" +# will create a group of multiple in-text citations. +# +# Even a group of multiple hidden citations can be created by +# "Insert empty citation". +# +# Note on paragraph and character styles in LibreOffice: +# +# This concerns ReferenceHeaderParagraphFormat, +# ReferenceParagraphFormat and, if FormatCitations is true, +# CitationCharacterFormat below. +# +# (1) JabRef does not manipulate named styles in LibreOffice. +# +# If the jstyle file refers to a style that does not exist in the +# document, the user has to create the style in LibreOffice or +# edit the the name in jstyle file. +# +# (2) Styles in LibreOffice have two names. One is the "Display name" +# shown to users, the other is the "internal name". +# +# Locally one could use either, but the "Display name" depends on +# the locale, thus would fail for other users. +# +# The "Refresh bibliography" now checks if the jstyle asks to +# apply a style by display name, and asks to change it. It will +# show the corresponding internal name, which otherwise I +# do not know how to get. +# +# +NAME +# The NAME section provides a name for the style. +# It consists of a single (non-empty, non-comment) line. + +Multiline LAYOUT rule example. + +JOURNALS +# The JOURNALS section lists journal names, one per line. +Journal name 1 +Journal name 2 + +PROPERTIES + +## The PROPERTIES and CITATION sections provide name=value pairs. +## The names are fixed, also the type of the corresponding values. + +## There are three value types: +## boolean: true or false +## integer: like -1 or 113 +## string: like "Hello there" + +## Title: string, the title of the bibliography. +## default: "Bibliography" +Title = "References" + +## ReferenceHeaderParagraphFormat : string. +## The paragraph style for the title of the bibliography. +## Should name a paragraph style known by OpenOffice/LibreOffice +## default: "Heading 1" +## example: ReferenceHeaderParagraphFormat = "Heading 2" + +## ReferenceParagraphFormat : string. +## The paragraph style for the bibliography entries. +## default: "Standard" +## example: ReferenceParagraphFormat="Text body" +ReferenceParagraphFormat="Text body" + +## IsNumberEntries : boolean, default: false +## If true, than this style uses numbered citations. +## If false, author-year style. +## +## Since numbered citations have different parts than +## author-year citations, the value of IsNumberEntries +## affects which properties are relevant. +## +## Note: if BibTeXKeyCitations is true (below, in the CITATION +## section), then IsNumberEntries is irrelevant. +## +IsNumberEntries = false + +## IsSortByPosition : boolean, default: false. +## +## Determines how the bibliography is sorted. +## +## If true, the entries will be sorted according to the order in which +## they are cited. Note: within a citation group +## +## If false, the entries will be sorted alphabetically by authors. +## +## Only relevant for numbered citations. +## +IsSortByPosition = false + +CITATION + +## This section contains settings related to individual citations and +## citation groups. + +## BibTeXKeyCitations : boolean, default: false +## If true, citations are represented by their BibTex keys. +## In this case IsNumberEntries is irrelevant. +# BibTeXKeyCitations=false + +## MultiCiteChronological: boolean, default: true +## If true, citations in a citation group are +## sorted by (year,author,title), otherwise by (author,year,title). +## +## Relevant with author-year and BibTeXKeyCitations. +## +## Its relevance for numbered citations is less obviuous, because just +## before we emit a citaion group, we sort the numbers appearing in +## the group. +## +## For IsNumberEntries + IsSortByPosition, it affects the citations +## position within citation groups, which may be observable in the +## numbering. +## +## For IsNumberEntries + !IsSortByPosition, the numbering comes from +## sorting the bibliography, thus MultiCiteChronological does not have +## an effect. +## +MultiCiteChronological=true + +## Character formatting of citation groups. + +## FormatCitations: boolean, default: false +## Decides if CitationCharacterFormat below should be applied. +## +## Note: when switching from a style with FormatCitations==true to one +## with FormatCitations==false, the character style established +## by the first is not removed from the citations. Applying a +## style with CitationCharacterFormat = "Standard" might help to +## avoid doing by hand. +## +FormatCitations = false + +## CitationCharacterFormat : string. +## default: "Standard" +## +## A character format to apply to citation groups, as known to +## LibreOffice. +## +## example: CitationCharacterFormat = "Standard" +## example: CitationCharacterFormat = "Emphasis" +## example: CitationCharacterFormat = "Example" +# CitationCharacterFormat = "Standard" +# CitationCharacterFormat="JR_citation" + +## +## The following correspond to direct character formatting. +## They are not controlled by FormatCitations. +## + +## ItalicCitations : boolean, default: false. +## Not implemented. +# ItalicCitations = false + +## BoldCitations : boolean, default: false. +## Not implemented. +# BoldCitations = false + +## SuperscriptCitations : boolean, default: false. +## Not implemented. +# SuperscriptCitations = false + +## SubscriptCitations : boolean, default: false. +## Not implemented. +# SubscriptCitations = false + +## +## For text fragments below, examples show the location +## by bracketing the relevant part with "{}" +## + +## BracketBefore : string, default: "(" +## Location: "{[}Smith 2000]" "Smith {[}2000]" "{[}1]" "{[}bibtextkey]" +BracketBefore="[" + +## BracketAfter : string, default: ")" +## Location: "[Smith 2000{]}" "Smith [2000{]}" "[1{]}" "[bibtextkey{]}" +BracketAfter="]" + +## BracketBeforeInList : string, default: not set. +## If not set, BracketBefore is used instead. +## Purpose: for numbered styles, used in the entry labels in the bibliography. +## Location: "{[}1]" +## Not relevant for BibTeXKeyCitations and author-year. +BracketBeforeInList="[" + +## BracketAfterInList : string, default: not set. +## If not set, BracketAfter is used instead. +## Purpose: for numbered styles, used in the entry labels in the bibliography. +## Location: "[1{]}" +## Not relevant for BibTeXKeyCitations and author-year. +BracketAfterInList="] " + +## PageInfoSeparator : string, default: "; " +## Location: "[Smith 2000a{; }pp 10-13]" "Smith [2000a{; }pp 10-13]" "[1{; }pp 10-13]" +## Not used for BibTeXKeyCitations (maybe it should be) +PageInfoSeparator = "; " + +## CitationSeparator : string, default: "; " +## Location: between citations in the same citation group. +## "[Smith 2000{; }Jones 2001]" "Smith [2000{; }Jones [2001]" "[1{; }2]" +CitationSeparator="; " + +## +## Settings that only apply to numeric citation style. +## + +## MinimumGroupingCount : int, default: 3 +## Purpose: How many consecutive numbers in "[1; 2; 3]" allows grouping to "[1-3]" +MinimumGroupingCount=3 + +## GroupedNumbersSeparator : string, default: "-" +## Purpose: for numeric style, when consecutive numbers collapsed to a +## range, this is used as the separator between range start +## and range end. +## Location: "[1{-}3]" +GroupedNumbersSeparator="-" + +## +## Settings that only apply to author-year style. +## + +## AuthorField : string, default: "author/editor" +## +## Purpose: When looking for authors, which bibtex fields to look in? +## +## The field names are separated by "/", the first field that +## exists and is not empty applies. +AuthorField="author/editor" + +## YearField : string, default: "year" +## +## Purpose: When looking for the year, which bibtex fields to look in? +## +## The field names are separated by "/", the first field that +## exists and is not empty applies. +## +YearField="year" + +## MaxAuthors : int, default: 3 +## Purpose: How many author names to show in citations? +## If there are more, "FirstAuthor et al." will be used instead. +## Special value: -1 encodes "unlimited" +MaxAuthors=2 + +## MaxAuthorsFirst : int, default: -1 +## Purpose: some styles require a different value of MaxAuthors for +## the first appearance of a source. +## Special value: -1 encodes "unlimited" +## +MaxAuthorsFirst=6 + +## AuthorSeparator : string, default: ", " +## Location: "[Smith{, }Jones, and Brown 2000]" +AuthorSeparator=", " + +## OxfordComma : string, default: "" +## Location: "[Smith, Jones{,} and Brown 2000]" +# example: OxfordComma = "," + +## AuthorLastSeparator : string default: " & " +## Location: "[Smith, Jones,{ and }Brown 2000]" */ +AuthorLastSeparator=" & " + +## AuthorLastSeparatorInText : string, default: not set. +## If not set, AuthorLastSeparator is used instead. +## Purpose: for in-text "Author (year)" citations, +## allows alternative value for AuthorLastSeparator. +## Location: "Smith, Jones,{ and }Brown [2000]" +AuthorLastSeparatorInText=" and " + +## EtAlString : string, default: "et al." +## Location: "[Smith{ et al.} 2000]" "Smith{ et al.} [2000]" +## Purpose: if there are more authors than allowed by MaxAuthors, +## only the first author name is shown. EtAlString indicates +## the omission of the other names. +EtAlString=" et al." + +## YearSeparator : string, default: ", " +## Location: just after the authors, for in-parenthesis citations: "[Smith et al.{ }2000]" +YearSeparator=" " + +## InTextYearSeparator : string, default: " " +## Location: "Smith et al.{ }[2000]" +InTextYearSeparator=" " + +## UniquefierSeparator : string, default: "," +## Location: "[Smith et al. 2000a{,}b; pp 10-13]" +UniquefierSeparator="," + +LAYOUT +## +## The LAYOUT section provides formatting rules for the bibliography entries. +## +## In the name=value pairs below, "name" is either a bibtex entry type (article, ...) +## or "default" (fallback in case there is no formatting provided for a bibtex entry type. +## +## The default entry is required. +## +## Note: no line breaks are allowed within a rule. +## +## We could relax this like below. If value starts with "|", +## then line breaks are allowed. An empty line ends the entry. +## Each line, after trimming must be surrounded by "|" and "|". +## As with strings in property values: we only care about the first and last +## characters: within the line "|" may appear, does not need quoting. +## The main purpose of the "|" marks is to make the spaces within visible +## and separable from those used for indentation. +## +## Conversion from old style: +## (1) put || around the value +## (2) Wherever you want a line break, insert || and a linebreak between. +## +## Conversion to old style: +## (1) collect value from RHS and following lines, +## until an empty line occurs. +## (2) Trim each line, check and remove || around, concatenate. +## +## Detection: after trimming RHS starts and ends with | +## Ambiguity: when the RHS would start and end with | anyway. +## Solution: an extra pair of | around converts to new style. +## +article=|| +# We can add comments between the lines (still has to start at the first column). +# This could be a place to describe what AuthorAndsReplacer does, +# and https://docs.jabref.org/collaborative-work/export/customexports +# does not explain. +# http://www.massapi.com/class/au/AuthorAndsReplacer.html explains. +|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| +| (\year\uniq).| +| \title,| +| \journal| +| \volume| +# Does FormatPagesForHTML include some HTML tags? +# https://docs.jabref.org/collaborative-work/export/customexports +# says: FormatPagesForHTML : replaces "--" with "-". +|\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}.| + +book=|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| + |\begin{editor}| + |\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.)| + |\end{editor},| + | \year\uniq.| + | \title.| + | \publisher,| + | \address.| + +incollection=|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| + | (\year\uniq).| + | \title.| + | In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.),| + | \booktitle,| + | \publisher.| + +inbook=|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| + | (\year\uniq).| + | \chapter.| + | In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.),| + | \title, \publisher.| + +phdthesis=|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| + | (\year\uniq).| + | \title, \school.| + +default=|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| + | (\year\uniq).| + | \title,| + | \journal \volume| + |\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}.| diff --git a/src/test/resources/org/jabref/logic/openoffice/parseError.jstyle b/src/test/resources/org/jabref/logic/openoffice/parseError.jstyle new file mode 100644 index 00000000000..928ea6e7736 --- /dev/null +++ b/src/test/resources/org/jabref/logic/openoffice/parseError.jstyle @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: MIT + +NAME +A style to provoke a parsing error. + + diff --git a/src/test/resources/org/jabref/logic/openoffice/parserWarning.jstyle b/src/test/resources/org/jabref/logic/openoffice/parserWarning.jstyle new file mode 100644 index 00000000000..242ce6f277d --- /dev/null +++ b/src/test/resources/org/jabref/logic/openoffice/parserWarning.jstyle @@ -0,0 +1,44 @@ +# SPDX-License-Identifier: MIT + +NAME +A style provoking a parser warning. + +JOURNALS +Journal name 1 +Journal name 2 + +PROPERTIES +Title = "References" + +# warning: do not quote boolean values. +IsSortByPosition = "true" + +IsNumberEntries = true +ReferenceParagraphFormat = "Text body" +ReferenceHeaderParagraphFormat = "Heading 2" + +CITATION +BracketBefore = "[" +BracketAfter = "]" +BracketBeforeInList = "[" +BracketAfterInList = "] " +CitationSeparator = "; " +UniquefierSeparator = "," +GroupedNumbersSeparator = "-" +MinimumGroupingCount = 3 +FormatCitations = false +CitationCharacterFormat = "Default" +PageInfoSeparator = "; " + +LAYOUT +article=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. + +book=\format[Authors(LastFirst,Semicolon)]{\author}\begin{editor}\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.)\end{editor}, \year\uniq. \title. \publisher, \address. + +incollection=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title. In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.), \booktitle, \publisher. + +inbook=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \chapter. In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.), \title, \publisher. + +phdthesis=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title, \school. + +default=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. From a9c125722bbeea610afbe4e8741a311f96b3d773 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 18:52:50 +0200 Subject: [PATCH 0606/1068] citation marks are now inserted as OOFormattedText This means ... are interpreted. Note: the intervening text is NOT escaped, we just hope it does not contain stuff looking like html tags. --- .../org/jabref/gui/openoffice/OOBibBase.java | 9 ++++++-- .../org/jabref/logic/openoffice/OOUtil.java | 22 ++++++++++++++----- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 06b96c332a3..da1ce0d2f28 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1102,7 +1102,11 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti if (withText) { // setString: All styles are removed when applying this method. - cursor.setString(citationText); + // cursor.setString(citationText); + OOUtil.insertOOFormattedTextAtCurrentLocation( + cursor, + citationText); + DocumentConnection.setCharLocaleNone(cursor); if (style.getFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); @@ -1943,9 +1947,10 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, LOGGER.warn(message); // no stack trace } // Insert the formatted text: - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection.xText, + OOUtil.insertOOFormattedTextAtCurrentLocation(//documentConnection.xText, cursor, formattedText); + cursor.collapseToEnd(); } } } diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 8f2167c7537..7e39b2d851f 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -115,19 +115,23 @@ public static String formatFullReference(Layout layout, * Process {@code ltext} in chunks between HTML-tags, while * updating current formatting state at HTML-tags. * - * Finally: {@code cursor.collapseToEnd()} + * // removed: Finally: {@code cursor.collapseToEnd()} + * Works with a copy of the cursor passed in. * * Note: Leaves setting the paragraph style to the caller. * - * @param text The text to insert in. + * param text The text to insert into. (taken from the cursor) + * * @param cursor The cursor giving the insert location. * @param lText The marked-up text to insert. + * //param keepTheCursor If true, use a copy of the cursor, do not modify. + * // If false the cursor is collapsed at the end. * @throws WrappedTargetException * @throws PropertyVetoException * @throws UnknownPropertyException * @throws IllegalArgumentException */ - public static void insertOOFormattedTextAtCurrentLocation(XText text, + public static void insertOOFormattedTextAtCurrentLocation(//XText text, XTextCursor cursor, String lText) throws @@ -136,6 +140,12 @@ public static void insertOOFormattedTextAtCurrentLocation(XText text, WrappedTargetException, IllegalArgumentException { + // boolean keepTheCursor = true; + XText text = cursor.getText(); + // copy the cursor + XTextCursor cursor3 = cursor.getText().createTextCursorByRange(cursor); + // XTextCursor cursor3 = keepTheCursor ? cursor2 : cursor ; + List formatting = new ArrayList<>(); // We need to extract formatting. Use a simple regexp search iteration: int piv = 0; @@ -143,7 +153,7 @@ public static void insertOOFormattedTextAtCurrentLocation(XText text, while (m.find()) { String currentSubstring = lText.substring(piv, m.start()); if (!currentSubstring.isEmpty()) { - OOUtil.insertTextAtCurrentLocation(text, cursor, currentSubstring, formatting); + OOUtil.insertTextAtCurrentLocation(text, cursor3, currentSubstring, formatting); } String tag = m.group(); // Handle tags: @@ -185,9 +195,9 @@ public static void insertOOFormattedTextAtCurrentLocation(XText text, } if (piv < lText.length()) { - OOUtil.insertTextAtCurrentLocation(text, cursor, lText.substring(piv), formatting); + OOUtil.insertTextAtCurrentLocation(text, cursor3, lText.substring(piv), formatting); } - cursor.collapseToEnd(); + // cursor3.collapseToEnd(); } public static void insertParagraphBreak(XText text, XTextCursor cursor) From ec7dc959ec83170045d274a10ef6386a96465fc6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 18:55:27 +0200 Subject: [PATCH 0607/1068] subscript and superscript did not look right. Adjusted to use numbers taken from LibreOffice defaults. --- .../org/jabref/logic/openoffice/OOUtil.java | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 7e39b2d851f..4d86427a1aa 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -264,21 +264,29 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S com.sun.star.awt.FontPitch.VARIABLE); } */ + /* + * short CharEscapement. + * specifies the percentage by which to raise/lower superscript/subscript characters. + * Negative values denote subscripts and positive values superscripts. + * + * byte CharEscapementHeight + * This is the relative height used for subscript or superscript characters in units of percent. + * The value 100 denotes the original height of the characters. + * + * From LibreOffice: + * SuperScript: 33 and 58 + * SubScript: 10 and 58 + * + */ if (formatting.contains(Formatting.SUBSCRIPT)) { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, - (byte) -101); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, - (byte) 58); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) -10); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, (byte) 58); } else if (formatting.contains(Formatting.SUPERSCRIPT)) { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, - (byte) 101); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, - (byte) 58); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) 33); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, (byte) 58); } else { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, - (byte) 0); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, - (byte) 100); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) 0); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, (byte) 100); } if (formatting.contains(Formatting.UNDERLINE)) { From 296d3e9613efdef163a80186e7811a2f80bb5196 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 19:58:02 +0200 Subject: [PATCH 0608/1068] Most text we emit into the document handled as OOFormattedText --- .../org/jabref/gui/openoffice/OOBibBase.java | 58 ++++++++----------- .../jabref/logic/openoffice/OOBibStyle.java | 6 +- 2 files changed, 29 insertions(+), 35 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index da1ce0d2f28..42043f35057 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1101,12 +1101,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti Objects.requireNonNull(style); if (withText) { - // setString: All styles are removed when applying this method. - // cursor.setString(citationText); - OOUtil.insertOOFormattedTextAtCurrentLocation( - cursor, - citationText); - + OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, citationText); DocumentConnection.setCharLocaleNone(cursor); if (style.getFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); @@ -1858,6 +1853,20 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // this is where we create the paragraph. OOUtil.insertParagraphBreak(documentConnection.xText, cursor); + // format the paragraph + try { + if (parStyle != null) { + DocumentConnection.setParagraphStyle(cursor, + parStyle); + } + } catch ( UndefinedParagraphFormatException ex ) { + // TODO: precheck or remember if we already emitted this message. + String message = + String.format("Could not apply paragraph format '%s' to bibliography entry", + parStyle); + // LOGGER.warn(message, ex); + LOGGER.warn(message); // no stack trace + } // insert marker "[1]" if (style.getIsNumberEntries()) { @@ -1869,11 +1878,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, int number = ck.number.get(); String marker = style.getNumCitationMarkerForBibliography(number); - - OOUtil.insertTextAtCurrentLocation(documentConnection.xText, - cursor, - marker, - Collections.emptyList()); + OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, marker); + cursor.collapseToEnd(); } else { // !style.getIsNumberEntries() : emit no prefix // TODO: We might want [citationKey] prefix for style.getBibTeXKeyCitations(); @@ -1881,10 +1887,9 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, if ( ck.db.isEmpty() ) { // Unresolved entry - OOUtil.insertTextAtCurrentLocation(documentConnection.xText, - cursor, - String.format("Unresolved(%s)", ck.citationKey), - Collections.emptyList()); + String referenceDetails = String.format("Unresolved(%s)", ck.citationKey); + OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, referenceDetails); + cursor.collapseToEnd(); // Try to list citations: if (true) { OOUtil.insertTextAtCurrentLocation( @@ -1932,24 +1937,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, ck.db.get().database, ck.uniqueLetter.orElse(null)); - // format the paragraph - try { - if (parStyle != null) { - DocumentConnection.setParagraphStyle(cursor, - parStyle); - } - } catch ( UndefinedParagraphFormatException ex ) { - // TODO: precheck or remember if we already emitted this message. - String message = - String.format("Could not apply paragraph format '%s' to bibliography entry", - parStyle); - // LOGGER.warn(message, ex); - LOGGER.warn(message); // no stack trace - } // Insert the formatted text: - OOUtil.insertOOFormattedTextAtCurrentLocation(//documentConnection.xText, - cursor, - formattedText); + OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, formattedText); cursor.collapseToEnd(); } } @@ -2044,9 +2033,12 @@ private void populateBibTextSection(DocumentConnection documentConnection, .createTextCursorByRange(section.getAnchor())); // emit header + /* documentConnection.xText.insertString(cursor, - style.getReferenceHeaderText(), + style.getReferenceHeaderText(), true); + */ + OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, style.getReferenceHeaderText()); String parStyle = style.getReferenceHeaderParagraphFormat(); try { if (parStyle != null) { diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 7b9bce0b733..29a88cbd052 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -854,7 +854,9 @@ private String getBracketBeforeInList() { return getStringCitProperty(OOBibStyle.BRACKET_BEFORE_IN_LIST); } - protected String getBracketBeforeInListWithFallBack() { + // Should be protected, but that needs getNumCitationMarkerCommon + // to take over handling Unresolved + public String getBracketBeforeInListWithFallBack() { return Objects.requireNonNullElse(getBracketBeforeInList(), getBracketBefore()); } @@ -864,7 +866,7 @@ private String getBracketAfterInList() { return getStringCitProperty(OOBibStyle.BRACKET_AFTER_IN_LIST); } - protected String getBracketAfterInListWithFallBack() { + public String getBracketAfterInListWithFallBack() { return Objects.requireNonNullElse(getBracketAfterInList(), getBracketAfter()); } From cfc71d0f63959fbb321a713626268bbbc6a2813f Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 19:58:38 +0200 Subject: [PATCH 0609/1068] moved handling of getItalicEtAl from last-minute to getCitationMarker Now fillCitationMarkInCursor does not modify its output, only applies what it receives. --- .../org/jabref/gui/openoffice/OOBibBase.java | 43 ------------------- .../OOBibStyleGetCitationMarker.java | 7 +++ 2 files changed, 7 insertions(+), 43 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 42043f35057..1818e3171dd 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1110,49 +1110,6 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti } else { cursor.setString(""); } - - // Last minute editing: find "et al." (OOBibStyle.ET_AL_STRING) and - // format it as italic. - - // Check if we should italicize the "et al." string in citations: - boolean italicize = style.getItalicEtAl(); - if (italicize) { - String etAlString = style.getEtAlString(); - Objects.requireNonNull(etAlString); - Objects.requireNonNull(citationText); - for (int index = citationText.indexOf(etAlString); - index >= 0; - index = citationText.indexOf(etAlString, index + 1)) { - italicizeRangeFromPosition(cursor, index, index + etAlString.length()); - } - } - } - - /** - * Taking position.getStart() as a reference point, italicize the range (ref+start,ref+end) - * - * @param position : position.getStart() is out reference point. - * @param start : start of range to italicize w.r.t position.getStart(). - * @param end : end of range to italicize w.r.t position.getStart(). - * - * Why this API? This is used after finding "et al." string in a - * citation marker. - */ - private static void italicizeRangeFromPosition(XTextCursor position, - int start, - int end) - throws - UnknownPropertyException, - PropertyVetoException, - IllegalArgumentException, - WrappedTargetException { - - XTextRange range = position.getStart(); - XTextCursor cursor = position.getText().createTextCursorByRange(range); - cursor.goRight((short) start, false); - cursor.goRight((short) (end - start), true); - - DocumentConnection.setCharFormatItalic(cursor); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 82cb38f9e0d..f32b090cd24 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -97,6 +97,13 @@ private static String formatAuthorList(OOBibStyle style, // e.g. " et al." String etAlString = style.getEtAlString(); + // getItalicEtAl is not necessary now, since etAlString could + // itself contain the markup. + // This is for backward compatibility. + if (style.getItalicEtAl()) { + etAlString = "" + etAlString + ""; + } + // The String to add between author names except the last two, // e.g. ", ". String authorSep = style.getAuthorSeparator(); From 2b88e383dfbbe418983b48af014090c4eb1d3d59 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 12 Apr 2021 23:02:11 +0200 Subject: [PATCH 0610/1068] xxxMarkupBefore xxxMarkupAfter *.jstyle now allows insertion of markup before and after a citation group as well as some of its parts implemented CitationGroupMarkupBefore and CitationGroupMarkupAfter AuthorsPartMarkupBefore and AuthorsPartMarkupAfter AuthorNamesListMarkupBefore and AuthorNamesListMarkupAfter AuthorNameMarkupBefore and AuthorNameMarkupAfter --- .../org/jabref/gui/openoffice/OOBibBase.java | 9 +- .../jabref/logic/openoffice/OOBibStyle.java | 114 ++++++++++-------- .../OOBibStyleGetCitationMarker.java | 38 ++++-- .../OOBibStyleGetNumCitationMarker.java | 5 +- .../logic/openoffice/OOBibStyleParser.java | 58 ++++++--- .../logic/openoffice/OOBibStyleTest.java | 6 - .../openoffice/example_style_file.jstyle | 53 +++++--- .../openoffice/multilineLayoutRule.jstyle | 16 --- 8 files changed, 181 insertions(+), 118 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 1818e3171dd..e85256edacc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -888,9 +888,12 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { List cits = cgs.getSortedCitations(cgid); - String citMarker = (cits.stream() - .map(cit -> cit.citationKey) - .collect(Collectors.joining(","))); + String citMarker = + style.getCitationGroupMarkupBefore() + + (cits.stream() + .map(cit -> cit.citationKey) + .collect(Collectors.joining(","))) + + style.getCitationGroupMarkupAfter(); citMarkers.put(cgid, citMarker); } return citMarkers; diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 29a88cbd052..68d27487263 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -90,22 +90,28 @@ public class OOBibStyle implements Comparable { private static final String FORMAT_CITATIONS = "FormatCitations"; private static final String CITATION_CHARACTER_FORMAT = "CitationCharacterFormat"; - // TODO: ITALIC_CITATIONS ItalicCitations is not implemented - // status: - // - jstyles.jabref.org-master : 4 styles mention it, value is false in all of them. - // - getter: getItalicCitations() exists, but only called from tests, to assert it is false. - // - default: citProperties.put(ITALIC_CITATIONS, Boolean.FALSE); + + // These two can do wat ItalicCitations, BoldCitations, + // SuperscriptCitations and SubscriptCitations were supposed to do, + // as well as underline smallcaps and strikeout. + private static final String CITATION_GROUP_MARKUP_BEFORE = "CitationGroupMarkupBefore"; + private static final String CITATION_GROUP_MARKUP_AFTER = "CitationGroupMarkupAfter"; + + // These are replaced by CitationGroupMarkupBefore and CitationGroupMarkupAfter // - private static final String ITALIC_CITATIONS = "ItalicCitations"; + // private static final String ITALIC_CITATIONS = "ItalicCitations"; + // private static final String BOLD_CITATIONS = "BoldCitations"; + // private static final String SUPERSCRIPT_CITATIONS = "SuperscriptCitations"; + // private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations"; - // TODO: BOLD_CITATIONS is not implemented - private static final String BOLD_CITATIONS = "BoldCitations"; + private static final String AUTHORS_PART_MARKUP_BEFORE = "AuthorsPartMarkupBefore"; + private static final String AUTHORS_PART_MARKUP_AFTER = "AuthorsPartMarkupAfter"; - // TODO: SUPERSCRIPT_CITATIONS is not implemented - private static final String SUPERSCRIPT_CITATIONS = "SuperscriptCitations"; + private static final String AUTHOR_NAMES_LIST_MARKUP_BEFORE = "AuthorNamesListMarkupBefore"; + private static final String AUTHOR_NAMES_LIST_MARKUP_AFTER = "AuthorNamesListMarkupAfter"; - // TODO: SUBSCRIPT_CITATIONS is not implemented - private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations"; + private static final String AUTHOR_NAME_MARKUP_BEFORE = "AuthorNameMarkupBefore"; + private static final String AUTHOR_NAME_MARKUP_AFTER = "AuthorNameMarkupAfter"; /* * common (numeric and author-year) @@ -280,10 +286,19 @@ private void setDefaultProperties() { obsCitProperties.put(FORMAT_CITATIONS, Boolean.FALSE); // was "Default", but that is not knowm to LO obsCitProperties.put(CITATION_CHARACTER_FORMAT, "Standard"); - obsCitProperties.put(ITALIC_CITATIONS, Boolean.FALSE); - obsCitProperties.put(BOLD_CITATIONS, Boolean.FALSE); - obsCitProperties.put(SUPERSCRIPT_CITATIONS, Boolean.FALSE); - obsCitProperties.put(SUBSCRIPT_CITATIONS, Boolean.FALSE); + + + obsCitProperties.put(CITATION_GROUP_MARKUP_BEFORE, ""); + obsCitProperties.put(CITATION_GROUP_MARKUP_AFTER, ""); + + obsCitProperties.put(AUTHORS_PART_MARKUP_BEFORE, ""); + obsCitProperties.put(AUTHORS_PART_MARKUP_AFTER, ""); + + obsCitProperties.put(AUTHOR_NAMES_LIST_MARKUP_BEFORE, ""); + obsCitProperties.put(AUTHOR_NAMES_LIST_MARKUP_AFTER, ""); + + obsCitProperties.put(AUTHOR_NAME_MARKUP_BEFORE, ""); + obsCitProperties.put(AUTHOR_NAME_MARKUP_AFTER, ""); obsCitProperties.put(AUTHOR_FIELD, FieldFactory.serializeOrFields(StandardField.AUTHOR, @@ -308,8 +323,10 @@ private void setDefaultProperties() { obsCitProperties.put(MULTI_CITE_CHRONOLOGICAL, Boolean.TRUE); obsCitProperties.put(BIBTEX_KEY_CITATIONS, Boolean.FALSE); //"BibTeXKeyCitations" - obsCitProperties.put(ITALIC_ET_AL, Boolean.FALSE); obsCitProperties.put(OXFORD_COMMA, ""); + + // Obsolete, keep for backward compat. + obsCitProperties.put(ITALIC_ET_AL, Boolean.FALSE); } // public Layout getDefaultBibLayout() { @@ -720,49 +737,41 @@ public String getCitationCharacterFormat() { /** * Should citation markers be italicized? * - * @return true to indicate that citations should be in italics. - * - * TODO: unused getItalicCitations, getBoldCitations, - * getSuperscriptCitations, getSubscriptCitations - * - * May be worth implementing, because only getItalicCitations has - * a corresponding predefined character style in LibreOffice - * (Emphasis), and asking the user to create a style complicates - * usage. - * - * (a) Alternatively, we could have a character style, for example - * JR_citation that we always apply, and modify according to the - * current style. But that might interact with other uses of - * styles: I think a character can only have a single character - * style applied: if we are doing that, then a style applied by the - * user, for example a change in the font-size is going to be - * overwritten. Is it possible to create partial styles, that - * only override some, but not all character properties? Probably not. - * - * (b) Considering ItalicEtAl, we may want to switch to citation - * marks generated as OOFormattedText instead of plain - * text. If we do so, getItalicCitations et al could be - * replaced by BracketBefore="[" BracketAfter="]". - * - * Probably this is the way to go. */ - public boolean getItalicCitations() { - return getBooleanCitProperty(ITALIC_CITATIONS); + public String getCitationGroupMarkupBefore() { + return getStringCitProperty(CITATION_GROUP_MARKUP_BEFORE); } - public boolean getBoldCitations() { - return (Boolean) obsCitProperties.get(BOLD_CITATIONS); + public String getCitationGroupMarkupAfter() { + return getStringCitProperty(CITATION_GROUP_MARKUP_AFTER); } - public boolean getSuperscriptCitations() { - return (Boolean) obsCitProperties.get(SUPERSCRIPT_CITATIONS); + + /** Author list, including " et al." */ + public String getAuthorsPartMarkupBefore() { + return getStringCitProperty(AUTHORS_PART_MARKUP_BEFORE); } - public boolean getSubscriptCitations() { - return (Boolean) obsCitProperties.get(SUBSCRIPT_CITATIONS); + public String getAuthorsPartMarkupAfter() { + return getStringCitProperty(AUTHORS_PART_MARKUP_AFTER); + } + + /** Author list, excluding " et al." */ + public String getAuthorNamesListMarkupBefore() { + return getStringCitProperty(AUTHOR_NAMES_LIST_MARKUP_BEFORE); + } + public String getAuthorNamesListMarkupAfter() { + return getStringCitProperty(AUTHOR_NAMES_LIST_MARKUP_AFTER); + } + + /** Author names. Excludes Author separators */ + public String getAuthorNameMarkupBefore() { + return getStringCitProperty(AUTHOR_NAME_MARKUP_BEFORE); + } + public String getAuthorNameMarkupAfter() { + return getStringCitProperty(AUTHOR_NAME_MARKUP_AFTER); } /* * */ - public boolean getBibTeXKeyCitations() { // "BibTeXKeyCitations" return (Boolean) obsCitProperties.get(BIBTEX_KEY_CITATIONS); @@ -773,6 +782,7 @@ public boolean getMultiCiteChronological() { return this.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL); } + // Probably obsolete, now we can use " et al." instead in EtAlString public boolean getItalicEtAl() { // "ItalicEtAl" return this.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); @@ -780,7 +790,7 @@ public boolean getItalicEtAl() { /** * @return Names of fields containing authors: the first - * non-empty field is will be used. + * non-empty field will be used. */ protected OrFields getAuthorFieldNames() { String authorFieldNamesString = this.getStringCitProperty(OOBibStyle.AUTHOR_FIELD); diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index f32b090cd24..767c70ffd15 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -46,6 +46,12 @@ private static String getAuthorLastName(AuthorList al, return sb.toString(); } + private static String markupAuthorName(OOBibStyle style, String name) { + return (style.getAuthorNameMarkupBefore() + + name + + style.getAuthorNameMarkupAfter()); + } + /** * @param authorList Parsed list of authors. * @@ -133,9 +139,12 @@ private static String formatAuthorList(OOBibStyle style, // number of authors emitted. : Math.min(maxAuthorsBeforeEtAl, nAuthors)); - if (nAuthorsToEmit > 0) { + if (nAuthorsToEmit >= 1) { + sb.append(style.getAuthorsPartMarkupBefore()); + sb.append(style.getAuthorNamesListMarkupBefore()); // The first author - sb.append(getAuthorLastName(authorList, 0)); + String name = getAuthorLastName(authorList, 0); + sb.append(markupAuthorName(style, name)); } if (nAuthors >= 2) { @@ -145,7 +154,8 @@ private static String formatAuthorList(OOBibStyle style, int j = 1; while (j < (nAuthors - 1)) { sb.append(authorSep); - sb.append(getAuthorLastName(authorList, j)); + String name = getAuthorLastName(authorList, j); + sb.append(markupAuthorName(style, name)); j++; } // oxfordComma if at least 3 authors @@ -154,7 +164,8 @@ private static String formatAuthorList(OOBibStyle style, } // Emit " and "+"LastAuthor" sb.append(andString); - sb.append(getAuthorLastName(authorList, nAuthors - 1)); + String name = getAuthorLastName(authorList, nAuthors - 1); + sb.append(markupAuthorName(style, name)); } else { // Emit last names up to nAuthorsToEmit. @@ -166,14 +177,23 @@ private static String formatAuthorList(OOBibStyle style, int j = 1; while (j < nAuthorsToEmit) { sb.append(authorSep); - sb.append(getAuthorLastName(authorList, j)); + String name = getAuthorLastName(authorList, j); + sb.append(markupAuthorName(style, name)); j++; } } - sb.append(etAlString); } } + if (nAuthorsToEmit >= 1) { + sb.append(style.getAuthorNamesListMarkupAfter()); + } + + if (nAuthors >= 2 && !emitAllAuthors ) { + sb.append(etAlString); + } + + sb.append(style.getAuthorsPartMarkupAfter()); return sb.toString(); } @@ -182,7 +202,7 @@ private static String formatAuthorList(OOBibStyle style, * but we also need to know which field matched, because * for some fields (actually: for author names) we need to * reproduce the surrounding braces to inform AuthorList.parse - * not to split up teh content. + * not to split up the content. */ private static class FieldAndContent { Field field; @@ -392,6 +412,7 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, String uniquefierSeparator = style.getUniquefierSeparator(); StringBuilder sb = new StringBuilder(); + sb.append(style.getCitationGroupMarkupBefore()); if (inParenthesis) { sb.append(startBrace); } @@ -478,6 +499,7 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, if (inParenthesis) { sb.append(endBrace); } + sb.append(style.getCitationGroupMarkupAfter()); return sb.toString(); } @@ -496,6 +518,8 @@ private static String nullToEmptyString(String s) { * citations need uniqueLetters. * * For details of what "normalized" means: {@see getAuthorYearParenthesisMarker} + * + * Note: now includes some markup. */ public static String getNormalizedCitationMarker(OOBibStyle style, CitationMarkerEntry ce, diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java index 13f7547ed37..0749a747b78 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java @@ -155,7 +155,9 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, + String.format(" nCitations = %d", nCitations)); } // - StringBuilder sb = new StringBuilder(bracketBefore); + StringBuilder sb = new StringBuilder(); + sb.append(style.getCitationGroupMarkupBefore()); + sb.append(bracketBefore); final int current = numbers.get(0); if (current < 0) { throw new RuntimeException("getNumCitationMarker: found negative value"); @@ -164,6 +166,7 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, ? String.valueOf(current) : OOBibStyle.UNDEFINED_CITATION_MARKER); sb.append(bracketAfter); + sb.append(style.getCitationGroupMarkupAfter()); return sb.toString(); } } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java index 86dafd40751..70fadc6d96b 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -192,10 +192,11 @@ private static Map makeCitationPropertyWarnings() { Map res = new HashMap(); /* ItalicCitations was only recognized, but not used in JabRef5.2. */ - res.put("ItalicCitations", "ItalicCitations is not implemented"); - res.put("BoldCitations", "BoldCitations is not implemented"); - res.put("SuperscriptCitations", "SuperscriptCitations is not implemented"); - res.put("SubscriptCitations", "SubscriptCitations is not implemented"); + res.put("ItalicCitations", "ItalicCitations is not implemented, use CitationGroupMarkupBefore/After"); + res.put("BoldCitations", "BoldCitations is not implemented, use CitationGroupMarkupBefore/After"); + res.put("SuperscriptCitations", "SuperscriptCitations is not implemented, use CitationGroupMarkupBefore/After"); + res.put("SubscriptCitations", "SubscriptCitations is not implemented, use CitationGroupMarkupBefore/After"); + res.put("BibtexKeyCitations", "Found 'BibtexKeyCitations' instead of 'BibTeXKeyCitations'"); return Collections.unmodifiableMap(res); } @@ -203,6 +204,20 @@ private static Map makeCitationPropertyWarnings() { private static Map makeKnownCitationProperties() { Map res = new HashMap(); + res.put("MultiCiteChronological", PropertyType.BOOL); + res.put("BibTeXKeyCitations", PropertyType.BOOL); // BIBTEX_KEY_CITATIONS + + res.put("BracketBefore", PropertyType.STRING); + res.put("BracketAfter", PropertyType.STRING); + res.put("BracketBeforeInList", PropertyType.STRING); + res.put("BracketAfterInList", PropertyType.STRING); + + res.put("CitationSeparator", PropertyType.STRING); + res.put("PageInfoSeparator", PropertyType.STRING); + + res.put("GroupedNumbersSeparator", PropertyType.STRING); + res.put("MinimumGroupingCount", PropertyType.INT); + res.put("AuthorField", PropertyType.STRING); res.put("YearField", PropertyType.STRING); res.put("MaxAuthors", PropertyType.INT); @@ -213,25 +228,30 @@ private static Map makeKnownCitationProperties() { res.put("EtAlString", PropertyType.STRING); res.put("YearSeparator", PropertyType.STRING); res.put("InTextYearSeparator", PropertyType.STRING); - res.put("BracketBefore", PropertyType.STRING); - res.put("BracketAfter", PropertyType.STRING); - res.put("BracketBeforeInList", PropertyType.STRING); - res.put("BracketAfterInList", PropertyType.STRING); - res.put("CitationSeparator", PropertyType.STRING); - res.put("PageInfoSeparator", PropertyType.STRING); - res.put("GroupedNumbersSeparator", PropertyType.STRING); - res.put("MinimumGroupingCount", PropertyType.INT); res.put("FormatCitations", PropertyType.BOOL); res.put("CitationCharacterFormat", PropertyType.STRING); - res.put("ItalicCitations", PropertyType.BOOL); - res.put("BoldCitations", PropertyType.BOOL); - res.put("SuperscriptCitations", PropertyType.BOOL); - res.put("SubscriptCitations", PropertyType.BOOL); - res.put("MultiCiteChronological", PropertyType.BOOL); - res.put("BibTeXKeyCitations", PropertyType.BOOL); // BIBTEX_KEY_CITATIONS - res.put("ItalicEtAl", PropertyType.BOOL); res.put("OxfordComma", PropertyType.STRING); res.put("UniquefierSeparator", PropertyType.STRING); + + res.put("CitationGroupMarkupBefore", PropertyType.STRING); + res.put("CitationGroupMarkupAfter", PropertyType.STRING); + + res.put("AuthorsPartMarkupBefore", PropertyType.STRING); + res.put("AuthorsPartMarkupAfter", PropertyType.STRING); + + res.put("AuthorNamesListMarkupBefore", PropertyType.STRING); + res.put("AuthorNamesListMarkupAfter", PropertyType.STRING); + + res.put("AuthorNameMarkupBefore", PropertyType.STRING); + res.put("AuthorNameMarkupAfter", PropertyType.STRING); + + // + res.put("ItalicCitations", PropertyType.IGNORE); + res.put("BoldCitations", PropertyType.IGNORE); + res.put("SuperscriptCitations", PropertyType.IGNORE); + res.put("SubscriptCitations", PropertyType.IGNORE); + + res.put("ItalicEtAl", PropertyType.BOOL); return Collections.unmodifiableMap(res); } diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 2db21938f8d..8a010b502ed 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -45,9 +45,7 @@ void testAuthorYear() throws IOException { assertTrue(style.isValid()); assertTrue(style.isInternalStyle()); assertFalse(style.getBibTeXKeyCitations()); - assertFalse(style.getBoldCitations()); assertFalse(style.getFormatCitations()); - assertFalse(style.getItalicCitations()); assertFalse(style.getIsNumberEntries()); assertFalse(style.getIsSortByPosition()); } @@ -60,9 +58,7 @@ void testAuthorYearAsFile() throws URISyntaxException, IOException { assertTrue(style.isValid()); assertFalse(style.isInternalStyle()); assertFalse(style.getBibTeXKeyCitations()); - assertFalse(style.getBoldCitations()); assertFalse(style.getFormatCitations()); - assertFalse(style.getItalicCitations()); assertFalse(style.getIsNumberEntries()); assertFalse(style.getIsSortByPosition()); } @@ -73,9 +69,7 @@ void testNumerical() throws IOException { layoutFormatterPreferences); assertTrue(style.isValid()); assertFalse(style.getBibTeXKeyCitations()); - assertFalse(style.getBoldCitations()); assertFalse(style.getFormatCitations()); - assertFalse(style.getItalicCitations()); assertTrue(style.getIsNumberEntries()); assertTrue(style.getIsSortByPosition()); } diff --git a/src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle b/src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle index e00ab23d1dd..f79880b8a44 100644 --- a/src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle +++ b/src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle @@ -72,6 +72,18 @@ # show the corresponding internal name, which otherwise I # do not know how to get. # +# New: the text emitted into the document, may contain some HTML-like +# tags. This was true before for the bibliography entries +# (controlled by the LAYOUT section), not it includes the title +# of the bibliography (Title below), the citations in the text and +# entry labels (for numeric styles). +# +# A sample of the available tags is inserted into the Title below. +# +# This makes ItalicEtAl obsolete, since EtAlString may contain " et al." +# +# Also raises the question how to describe which tags surround what. +# # NAME # The NAME section provides a name for the style. @@ -96,7 +108,7 @@ PROPERTIES ## Title: string, the title of the bibliography. ## default: "Bibliography" -Title = "References" +Title = "References b: bold i: italic (tt: does not work) SmallCaps sup sub u s" ## ReferenceHeaderParagraphFormat : string. ## The paragraph style for the title of the bibliography. @@ -196,21 +208,34 @@ FormatCitations = false ## They are not controlled by FormatCitations. ## -## ItalicCitations : boolean, default: false. -## Not implemented. -# ItalicCitations = false +## CitationGroupMarkupBefore: string, default: "" +## CitationGroupMarkupAfter: string, default: "" +## +## Purpose: what is to be injected before and after a citation group. +## Providing both ends allows for example labeling. +CitationGroupMarkupBefore = "" +CitationGroupMarkupAfter = "" + +## AuthorsPartMarkup : "Au et al." +AuthorsPartMarkupBefore = "" +AuthorsPartMarkupAfter = "" -## BoldCitations : boolean, default: false. -## Not implemented. -# BoldCitations = false +# AuthorNamesListMarkup : excludes " et al.", includes names and separators +AuthorNamesListMarkupBefore = "" +AuthorNamesListMarkupAfter = "" -## SuperscriptCitations : boolean, default: false. -## Not implemented. -# SuperscriptCitations = false +# AuthorNameMarkup : "Au" excludes AuthorSeparator +AuthorNameMarkupBefore = "" +AuthorNameMarkupAfter = "" -## SubscriptCitations : boolean, default: false. -## Not implemented. -# SubscriptCitations = false +## These probably could be done, if there is a need: +# CitationMarkup = "" +# YearMarkup = "" +# UniquefierListMarkup = "" # "a,b" +# UniquefierMarkup = "" # excludes UniquefierSeparator +# NunberRangeMarkup = "" # "1" or "2-3" +# NumberMarkup = "" # excludes GroupedNumbersSeparator +# PageInfoMarkup="" # Does not include PageInfoSeparator ## ## For text fragments below, examples show the location @@ -308,7 +333,7 @@ AuthorSeparator=", " ## AuthorLastSeparator : string default: " & " ## Location: "[Smith, Jones,{ and }Brown 2000]" */ -AuthorLastSeparator=" & " +AuthorLastSeparator=" and " ## AuthorLastSeparatorInText : string, default: not set. ## If not set, AuthorLastSeparator is used instead. diff --git a/src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle b/src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle index 8e6c1f5a552..0f94711436b 100644 --- a/src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle +++ b/src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle @@ -196,22 +196,6 @@ FormatCitations = false ## They are not controlled by FormatCitations. ## -## ItalicCitations : boolean, default: false. -## Not implemented. -# ItalicCitations = false - -## BoldCitations : boolean, default: false. -## Not implemented. -# BoldCitations = false - -## SuperscriptCitations : boolean, default: false. -## Not implemented. -# SuperscriptCitations = false - -## SubscriptCitations : boolean, default: false. -## Not implemented. -# SubscriptCitations = false - ## ## For text fragments below, examples show the location ## by bracketing the relevant part with "{}" From 79601f4ccaa62971b4b10ff66f688ef81797841d Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 17 Apr 2021 20:04:30 +0200 Subject: [PATCH 0611/1068] checkstyle, cleanup, prefer Optional style: reduce ( at eol do not put ");" on its own line less line breaks in function heads --- .../org/jabref/gui/openoffice/Backend52.java | 149 ++-- .../org/jabref/gui/openoffice/Citation.java | 43 +- .../jabref/gui/openoffice/CitationGroup.java | 50 +- .../jabref/gui/openoffice/CitationGroups.java | 173 ++-- .../jabref/gui/openoffice/CitationSort.java | 9 +- .../org/jabref/gui/openoffice/CitedKey.java | 40 +- .../org/jabref/gui/openoffice/CitedKeys.java | 29 - .../org/jabref/gui/openoffice/Codec52.java | 35 +- .../gui/openoffice/DocumentConnection.java | 511 ++++------- .../org/jabref/gui/openoffice/OOBibBase.java | 824 +++++++----------- .../gui/openoffice/OpenOfficePanel.java | 60 +- .../jabref/gui/openoffice/RangeKeyedMap.java | 56 +- .../gui/openoffice/RangeKeyedMapList.java | 43 +- .../org/jabref/gui/openoffice/RangeSort.java | 49 +- .../gui/openoffice/RangeSortVisual.java | 91 +- .../jabref/gui/openoffice/StorageBase.java | 56 +- .../gui/openoffice/StorageBaseRefMark.java | 184 ++-- .../StyleSelectDialogViewModel.java | 13 +- .../logic/openoffice/CitationMarkerEntry.java | 28 +- .../openoffice/CitationMarkerEntryImpl.java | 66 +- .../jabref/logic/openoffice/OOBibStyle.java | 27 +- .../OOBibStyleGetCitationMarker.java | 49 +- .../OOBibStyleGetNumCitationMarker.java | 16 +- .../logic/openoffice/OOBibStyleParser.java | 80 +- .../org/jabref/logic/openoffice/OOUtil.java | 33 +- .../jabref/logic/openoffice/StyleLoader.java | 12 +- 26 files changed, 1028 insertions(+), 1698 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/Backend52.java b/src/main/java/org/jabref/gui/openoffice/Backend52.java index 6f70af0f4f8..0d9d4305cb3 100644 --- a/src/main/java/org/jabref/gui/openoffice/Backend52.java +++ b/src/main/java/org/jabref/gui/openoffice/Backend52.java @@ -1,45 +1,19 @@ package org.jabref.gui.openoffice; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; -import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.PropertyExistException; -import com.sun.star.beans.UnknownPropertyException; - import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XText; -import com.sun.star.text.XTextContent; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextRange; -import com.sun.star.uno.UnoRuntime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; class Backend52 { public final Compat.DataModel dataModel; @@ -92,23 +66,22 @@ private List findUnusedJabrefPropertyNames(DocumentConnection documentCo } /** - * @return null if all is OK, message text otherwise. + * @return Optional.empty if all is OK, message text otherwise. */ - public String healthReport(DocumentConnection documentConnection) + public Optional healthReport(DocumentConnection documentConnection) throws NoDocumentException { List pageInfoThrash = this.findUnusedJabrefPropertyNames(documentConnection, this.getJabRefReferenceMarkNames(documentConnection)); - if ( pageInfoThrash.isEmpty() ){ - return null; //"Backend52: found no unused pageInfo data"; + if (pageInfoThrash.isEmpty()) { + return Optional.empty(); // "Backend52: found no unused pageInfo data"; } - String msg = ( + String msg = "Backend52: found unused pageInfo data, with names listed below.\n" - + "In LibreOffice you may remove these in [File]/[Properties]/[Custom Properties]\n" - ); - msg += "" + String.join( "\n", pageInfoThrash ) + ""; - return msg; + + "In LibreOffice you may remove these in [File]/[Properties]/[Custom Properties]\n"; + msg += "" + String.join("\n", pageInfoThrash) + ""; + return Optional.of(msg); } /** @@ -123,33 +96,27 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc Optional op = Codec52.parseMarkName(refMarkName); if (op.isEmpty()) { - // We have a problem. We want types[i] and bibtexKeys[i] - // to correspond to referenceMarkNames.get(i). - // And do not want null in bibtexKeys (or error code in types) - // on return. throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" + " found unparsable referenceMarkName"); } Codec52.ParsedMarkName ov = op.get(); CitationGroupID id = new CitationGroupID(refMarkName); - List citations = ((ov.citationKeys == null) - ? new ArrayList<>() - : (ov.citationKeys.stream() - .map(Citation::new) - .collect(Collectors.toList()))); + List citations = (ov.citationKeys.stream() + .map(Citation::new) + .collect(Collectors.toList())); Optional pageInfo = documentConnection.getCustomProperty(refMarkName); - StorageBase.NamedRange sr = citationStorageManager.getFromDocumentOrNull(documentConnection, - refMarkName); + Optional sr = (citationStorageManager + .getFromDocument(documentConnection, refMarkName)); - if (sr == null) { - throw new IllegalArgumentException( - "readCitationGroupFromDocumentOrThrow: referenceMarkName is not in the document"); + if (sr.isEmpty()) { + throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" + + " referenceMarkName is not in the document"); } CitationGroup cg = new CitationGroup(id, - sr, + sr.get(), ov.itcType, citations, pageInfo, @@ -206,7 +173,6 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc */ public CitationGroup createCitationGroup(DocumentConnection documentConnection, List citationKeys, - // Optional pageInfo, List pageInfosForCitations, int itcType, XTextCursor position, @@ -220,16 +186,15 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, PropertyExistException, IllegalTypeException { - String xkey = - citationKeys.stream() - .collect(Collectors.joining(",")); + String xkey = (citationKeys.stream() + .collect(Collectors.joining(","))); - Set usedNames = new HashSet<>( this.citationStorageManager - .getUsedNames(documentConnection) ); - String refMarkName = - Codec52.getUniqueMarkName(usedNames, - xkey, - itcType); + Set usedNames = new HashSet<>(this.citationStorageManager + .getUsedNames(documentConnection)); + + String refMarkName = Codec52.getUniqueMarkName(usedNames, + xkey, + itcType); CitationGroupID cgid = new CitationGroupID(refMarkName); @@ -249,12 +214,13 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, insertSpaceAfter, withoutBrackets); - switch (dataModel){ + switch (dataModel) { case JabRef52: - Optional pageInfo = getJabRef52PageInfoFromList( pageInfosForCitations ); - if ( pageInfo.isPresent() && !pageInfo.get().equals("") ) { + Optional pageInfo = getJabRef52PageInfoFromList(pageInfosForCitations); + if (pageInfo.isPresent() && !pageInfo.get().equals("")) { documentConnection.setCustomProperty(refMarkName, pageInfo.get()); } else { + // do not inherit from trash documentConnection.removeCustomProperty(refMarkName); } CitationGroup cg = new CitationGroup(cgid, @@ -269,6 +235,9 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, } } + /** + * Return the last pageInfo from the list, if there is one. + */ Optional getJabRef52PageInfoFromList(List pageInfosForCitations) { if (pageInfosForCitations == null) { return Optional.empty(); @@ -277,25 +246,21 @@ Optional getJabRef52PageInfoFromList(List pageInfosForCitations) if (n == 0) { return Optional.empty(); } - return Optional.ofNullable(pageInfosForCitations.get(n-1)); + return Optional.ofNullable(pageInfosForCitations.get(n - 1)); } /** * @param pageInfo Nullable. + * @return JabRef53 style pageInfo list */ static List fakePageInfosForCitations(String pageInfo, - int nCitations, - boolean mayReturnNull) { - // JabRef53 style pageInfo list, or null - List pageInfosForCitations = null; - if (!mayReturnNull || (pageInfo != null && !pageInfo.equals(""))) { - pageInfosForCitations = new ArrayList<>(nCitations); - for (int i = 0; i < nCitations; i++) { - if (i == nCitations - 1) { - pageInfosForCitations.add(pageInfo); - } else { - pageInfosForCitations.add(null); - } + int nCitations) { + List pageInfosForCitations = new ArrayList<>(nCitations); + for (int i = 0; i < nCitations; i++) { + if (i == nCitations - 1) { + pageInfosForCitations.add(pageInfo); + } else { + pageInfosForCitations.add(null); } } return pageInfosForCitations; @@ -315,20 +280,18 @@ static List fakePageInfosForCitations(String pageInfo, * TODO: we may want class DataModel52, DataModel53 and split this. */ static List getPageInfosForCitations(Compat.DataModel dataModel, CitationGroup cg) { - switch (dataModel){ + switch (dataModel) { case JabRef52: // check conformance to dataModel - for ( int i = 0; i < cg.citations.size(); i++ ) { - if ( cg.citations.get(i).pageInfo.isPresent() ) { + for (int i = 0; i < cg.citations.size(); i++) { + if (cg.citations.get(i).pageInfo.isPresent()) { throw new RuntimeException("getPageInfosForCitations:" + " found Citation.pageInfo under JabRef52 dataModel"); } } // A list of null values, except the last that comes from this.pageInfo return Backend52.fakePageInfosForCitations(cg.pageInfo.orElse(null), - cg.citations.size(), - false /*mayReturnNull*/); - + cg.citations.size()); case JabRef53: // check conformance to dataModel if (cg.pageInfo.isPresent()) { @@ -373,14 +336,12 @@ static List combinePageInfos(Compat.DataModel dataModel, .map(cg -> cg.citations.size()) .mapToInt(Integer::intValue).sum()); - return Backend52.fakePageInfosForCitations(cgPageInfo, - nCitations, - false /*mayReturnNull*/); + return Backend52.fakePageInfosForCitations(cgPageInfo, nCitations); case JabRef53: return (joinableGroup.stream() - .flatMap( cg -> (cg.citations.stream() - .map(cit -> cit.pageInfo.orElse(null)))) + .flatMap(cg -> (cg.citations.stream() + .map(cit -> cit.pageInfo.orElse(null)))) .collect(Collectors.toList())); default: throw new RuntimeException("unhandled dataModel here"); @@ -390,7 +351,7 @@ static List combinePageInfos(Compat.DataModel dataModel, /** * */ - public List combinePageInfos(List joinableGroup ) { + public List combinePageInfos(List joinableGroup) { return combinePageInfos(this.dataModel, joinableGroup); } @@ -420,24 +381,24 @@ public void removeCitationGroup(CitationGroup cg, DocumentConnection documentCon /** * - * @return Null if the reference mark is missing. + * @return Optional.empty if the reference mark is missing. * */ - public XTextRange getMarkRangeOrNull(CitationGroup cg, - DocumentConnection documentConnection) + public Optional getMarkRange(CitationGroup cg, + DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException { - return cg.cgRangeStorage.getMarkRangeOrNull(documentConnection); + return cg.cgRangeStorage.getMarkRange(documentConnection); } /** * Cursor for the reference marks as is, not prepared for filling, * but does not need cleanFillCursorForCitationGroup either. */ - public XTextCursor getRawCursorForCitationGroup(CitationGroup cg, - DocumentConnection documentConnection) + public Optional getRawCursorForCitationGroup(CitationGroup cg, + DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException, diff --git a/src/main/java/org/jabref/gui/openoffice/Citation.java b/src/main/java/org/jabref/gui/openoffice/Citation.java index fdaf51136c9..6d105db7d82 100644 --- a/src/main/java/org/jabref/gui/openoffice/Citation.java +++ b/src/main/java/org/jabref/gui/openoffice/Citation.java @@ -1,43 +1,10 @@ package org.jabref.gui.openoffice; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; -import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XText; -import com.sun.star.text.XTextContent; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextRange; -import com.sun.star.uno.UnoRuntime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -class Citation implements CitationSort.ComparableCitation { +class Citation implements CitationSort.ComparableCitation { /** key in database */ String citationKey; @@ -69,17 +36,17 @@ class Citation implements CitationSort.ComparableCitation { } @Override - public String getCitationKey(){ + public String getCitationKey() { return citationKey; } @Override - public String getPageInfoOrNull(){ - return pageInfo.orElse(null); + public Optional getPageInfo() { + return pageInfo; } @Override - public Optional getBibEntry(){ + public Optional getBibEntry() { return (db.isPresent() ? Optional.of(db.get().entry) : Optional.empty()); diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroup.java b/src/main/java/org/jabref/gui/openoffice/CitationGroup.java index 9ab6033fd11..5e614d78126 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroup.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroup.java @@ -1,43 +1,14 @@ package org.jabref.gui.openoffice; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; -import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; -import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XText; -import com.sun.star.text.XTextContent; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextRange; -import com.sun.star.uno.UnoRuntime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - class CitationGroup { CitationGroupID cgid; StorageBase.NamedRange cgRangeStorage; // knows referenceMarkName @@ -55,13 +26,12 @@ class CitationGroup { */ String referenceMarkName; - CitationGroup( - CitationGroupID cgid, - StorageBase.NamedRange cgRangeStorage, - int itcType, - List citations, - Optional pageInfo, - String referenceMarkName) { + CitationGroup(CitationGroupID cgid, + StorageBase.NamedRange cgRangeStorage, + int itcType, + List citations, + Optional pageInfo, + String referenceMarkName) { this.cgid = cgid; this.cgRangeStorage = cgRangeStorage; this.itcType = itcType; @@ -101,18 +71,18 @@ class CitationAndIndex implements CitationSort.ComparableCitation { } @Override - public String getCitationKey(){ + public String getCitationKey() { return c.getCitationKey(); } @Override - public Optional getBibEntry(){ + public Optional getBibEntry() { return c.getBibEntry(); } @Override - public String getPageInfoOrNull(){ - return c.pageInfo.orElse(null); + public Optional getPageInfo() { + return c.pageInfo; } } diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroups.java b/src/main/java/org/jabref/gui/openoffice/CitationGroups.java index 9adee3623f4..bdeb7571d94 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroups.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationGroups.java @@ -1,23 +1,16 @@ package org.jabref.gui.openoffice; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.Comparator; import java.util.HashMap; -import java.util.HashSet; import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.stream.Collectors; -import java.util.stream.Stream; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; @@ -27,13 +20,8 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.PropertyExistException; -import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XText; -import com.sun.star.text.XTextContent; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextRange; import com.sun.star.uno.UnoRuntime; @@ -51,11 +39,8 @@ class CitationGroups { - private static final Logger LOGGER = - LoggerFactory.getLogger(CitationGroups.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CitationGroups.class); - // public final Compat.DataModel dataModel; - // private StorageBase.NamedRangeManager citationStorageManager; public final Backend52 backend; /** @@ -63,14 +48,19 @@ class CitationGroups { */ private Map citationGroups; - /** + /* * Extra Data */ + /** + * Provides order of appearance for the citation groups. + * + * Background: just getting the reference marks does not provide + * this. Citation groups in footnotes, frames etc make getting + * this order right tricky. {@see class RangeSortVisual} + */ private Optional> globalOrder; - private Optional citedKeysAfterDatabaseLookup; - /** * This is going to be the bibliography */ @@ -92,7 +82,6 @@ public CitationGroups(DocumentConnection documentConnection) // Get the citationGroupNames List citationGroupNames = this.backend.getJabRefReferenceMarkNames(documentConnection); - this.citationGroups = readCitationGroupsFromDocument(this.backend, documentConnection, citationGroupNames); @@ -102,7 +91,6 @@ public CitationGroups(DocumentConnection documentConnection) // But (I guess) those change too easily, so we only ask when actually needed. this.globalOrder = Optional.empty(); - this.citedKeysAfterDatabaseLookup = Optional.empty(); this.bibliography = Optional.empty(); } @@ -110,12 +98,10 @@ public Compat.DataModel getDataModel() { return backend.dataModel; } - public String healthReport(DocumentConnection documentConnection) + public Optional healthReport(DocumentConnection documentConnection) throws NoDocumentException { - String r1 = backend.healthReport(documentConnection); - // add more? - return r1; + return backend.healthReport(documentConnection); } private static Map @@ -156,9 +142,6 @@ public CitedKeys lookupEntriesInDatabases(List databases) { cks.lookupInDatabases(databases); cks.distributeDatabaseLookupResults(cgs); - // record we did a database lookup - // and allow extracting unresolved keys. - this.citedKeysAfterDatabaseLookup = Optional.of(cks); return cks; } @@ -244,39 +227,42 @@ Optional getBibliography() { public void createNumberedBibliographySortedInOrderOfAppearance() { CitationGroups cgs = this; if (!cgs.bibliography.isEmpty()) { - throw new RuntimeException( - "createNumberedBibliographySortedInOrderOfAppearance: already have a bibliography"); + throw new RuntimeException("createNumberedBibliographySortedInOrderOfAppearance:" + + " already have a bibliography"); } - CitedKeys sortedCitedKeys = - cgs.getCitedKeysSortedInOrderOfAppearance(); + CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); sortedCitedKeys.numberCitedKeysInCurrentOrder(); sortedCitedKeys.distributeNumbers(cgs); cgs.bibliography = Optional.of(sortedCitedKeys); } - public void createNumberedBibliographySortedByComparator(Comparator entryComparator) { + /** + * precondition: database lookup already performed (otherwise we just sort citation keys) + */ + public void createPlainBibliographySortedByComparator(Comparator entryComparator) { CitationGroups cgs = this; - if (!cgs.bibliography.isEmpty()) { - throw new RuntimeException( - "createNumberedBibliographySortedByComparator: already have a bibliography"); + if (!this.bibliography.isEmpty()) { + throw new RuntimeException("createPlainBibliographySortedByComparator:" + + " already have a bibliography"); } CitedKeys citedKeys = cgs.getCitedKeys(); - citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup - citedKeys.numberCitedKeysInCurrentOrder(); - citedKeys.distributeNumbers(cgs); + citedKeys.sortByComparator(entryComparator); this.bibliography = Optional.of(citedKeys); } - public void createPlainBibliographySortedByComparator(Comparator entryComparator) { + /** + * precondition: database lookup already performed (otherwise we just sort citation keys) + */ + public void createNumberedBibliographySortedByComparator(Comparator entryComparator) { CitationGroups cgs = this; - if (!this.bibliography.isEmpty()) { - throw new RuntimeException( - "createPlainBibliographySortedByComparator: already have a bibliography"); + if (!cgs.bibliography.isEmpty()) { + throw new RuntimeException("createNumberedBibliographySortedByComparator:" + + " already have a bibliography"); } CitedKeys citedKeys = cgs.getCitedKeys(); - citedKeys.sortByComparator(entryComparator); // TODO: must be after database lookup - // citedKeys.numberCitedKeysInCurrentOrder(); - // citedKeys.distributeNumbers(); + citedKeys.sortByComparator(entryComparator); + citedKeys.numberCitedKeysInCurrentOrder(); + citedKeys.distributeNumbers(cgs); this.bibliography = Optional.of(citedKeys); } @@ -316,15 +302,13 @@ public Set getCitationGroupIDs() { NoDocumentException, WrappedTargetException { - List cgids = - new ArrayList<>(cgs.getCitationGroupIDs()); + List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); List vses = new ArrayList<>(); for (CitationGroupID cgid : cgids) { - XTextRange range = cgs.getMarkRangeOrNull(documentConnection, cgid); - if (range == null) { - throw new RuntimeException("getMarkRangeOrNull returned null"); - } + XTextRange range = (cgs + .getMarkRange(documentConnection, cgid) + .orElseThrow(RuntimeException::new)); vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); } @@ -372,12 +356,10 @@ public Set getCitationGroupIDs() { RangeSort.RangeSortEntry v = avs.get(j); v.indexInPosition = indexInPartition++; if (mapFootnotesToFootnoteMarks) { + Optional fmr = DocumentConnection.getFootnoteMarkRange(v.getRange()); // Adjust range if we are inside a footnote: - if (unoQI(XFootnote.class, v.range.getText()) != null) { - // Find the linking footnote marker: - XFootnote footer = unoQI(XFootnote.class, v.range.getText()); - // The footnote's anchor gives the correct position in the text: - v.range = footer.getAnchor(); + if (fmr.isPresent()) { + v.range = fmr.get(); } } res.add(v); @@ -456,11 +438,10 @@ public List getVisuallySortedCitationGroupIDs(DocumentConnectio // This is like getVisuallySortedCitationGroupIDs, // but we skip the visualSort part. CitationGroups cgs = this; - // boolean mapFootnotesToFootnoteMarks = false; List> vses = CitationGroups.createVisualSortInput(cgs, - documentConnection, - mapFootnotesToFootnoteMarks); + documentConnection, + mapFootnotesToFootnoteMarks); if (vses.size() != cgs.citationGroups.size()) { throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" @@ -484,8 +465,8 @@ public List getSortedCitationGroupIDs() { public void setGlobalOrder(List globalOrder) { Objects.requireNonNull(globalOrder); if (globalOrder.size() != citationGroups.size()) { - throw new RuntimeException( - "setGlobalOrder: globalOrder.size() != citationGroups.size()"); + throw new RuntimeException("setGlobalOrder:" + + " globalOrder.size() != citationGroups.size()"); } this.globalOrder = Optional.of(globalOrder); } @@ -538,7 +519,7 @@ public List getSortedCitations(CitationGroupID cgid) { } /** - * Create a reference mark with the given name, at the + * Create a citation group for the given citation keys, at the * end of position. * * To reduce the difference from the original representation, we @@ -574,19 +555,21 @@ public List getSortedCitations(CitationGroupID cgid) { * On return {@code position} is collapsed, and is after the * inserted space, or at the end of the reference mark. * - * @param documentConnection Connection to document. - * @param position Collapsed to its end. - * @param insertSpaceAfter We insert a space after the mark, that - * carries on format of characters from - * the original position. + * @param documentConnection Connection to document. + * @param citationKeys + * @param pageInfosForCitations + * @param itcType + * @param position Collapsed to its end. + * @param insertSpaceAfter If true, we insert a space after the mark, that + * carries on format of characters from + * the original position. * - * @param withoutBrackets Force empty reference mark (no brackets). - * For use with INVISIBLE_CIT. + * @param withoutBrackets Force empty reference mark (no brackets). + * For use with INVISIBLE_CIT. * */ public CitationGroupID createCitationGroup(DocumentConnection documentConnection, List citationKeys, - //Optional pageInfo, List pageInfosForCitations, int itcType, XTextCursor position, @@ -627,7 +610,7 @@ public void removeCitationGroups(List cgs, DocumentConnection doc IllegalTypeException { for (CitationGroup cg : cgs) { - removeCitationGroup( cg, documentConnection ); + removeCitationGroup(cg, documentConnection); } } @@ -662,9 +645,7 @@ public void removeCitationGroup(CitationGroup cg, // Update what we can. this.globalOrder.map(l -> l.remove(cg.cgid)); - - // Invalidate what we cannot update: CitedKeys - this.citedKeysAfterDatabaseLookup = Optional.empty(); + // Invalidate what we cannot this.bibliography = Optional.empty(); // Could also: reset citation.number, citation.uniqueLetter. } @@ -676,29 +657,32 @@ public void removeCitationGroup(CitationGroup cg, * @return Null if the reference mark is missing. * */ - public XTextRange getMarkRangeOrNull(DocumentConnection documentConnection, - CitationGroupID cgid) + public Optional getMarkRange(DocumentConnection documentConnection, + CitationGroupID cgid) throws NoDocumentException, WrappedTargetException { CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return backend.getMarkRangeOrNull(cg, documentConnection); + return backend.getMarkRange(cg, documentConnection); } /** * Cursor for the reference marks as is, not prepared for filling, * but does not need cleanFillCursorForCitationGroup either. */ - public XTextCursor getRawCursorForCitationGroup(CitationGroupID cgid, - DocumentConnection documentConnection) + public Optional getRawCursorForCitationGroup(CitationGroupID cgid, + DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException, CreationException { - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return backend.getRawCursorForCitationGroup(cg, documentConnection); + Optional cg = this.getCitationGroup(cgid); + if (cg.isEmpty()) { + return Optional.empty(); + } + return backend.getRawCursorForCitationGroup(cg.get(), documentConnection); } public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, @@ -715,9 +699,6 @@ public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConn /** * Remove brackets, but if the result would become empty, leave * them; if the result would be a single characer, leave the left bracket. - * - * @param removeBracketsFromEmpty is intended to force removal if - * we are working on an "Empty citation" (INVISIBLE_CIT). */ public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, CitationGroupID cgid) @@ -727,7 +708,7 @@ public void cleanFillCursorForCitationGroup(DocumentConnection documentConnectio CreationException { CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - backend.cleanFillCursorForCitationGroup(cg,documentConnection); + backend.cleanFillCursorForCitationGroup(cg, documentConnection); } /** @@ -745,7 +726,7 @@ List citationRanges(DocumentConnection documentConnection) List cgids = new ArrayList<>(this.getCitationGroupIDs()); for (CitationGroupID cgid : cgids) { - XTextRange r = this.getMarkRangeOrNull(documentConnection, cgid); + XTextRange r = this.getMarkRange(documentConnection, cgid).orElseThrow(RuntimeException::new); CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); String name = cg.cgRangeStorage.getName(); xs.add(new RangeForOverlapCheck(r, @@ -786,22 +767,20 @@ List footnoteMarkRanges(DocumentConnection documentConnect for (RangeForOverlapCheck base : citRanges) { XTextRange r = base.range; - XTextRange footnoteMarkRange = - DocumentConnection.getFootnoteMarkRangeOrNull(r); + Optional footnoteMarkRange = DocumentConnection.getFootnoteMarkRange(r); - if (footnoteMarkRange == null) { + if (footnoteMarkRange.isEmpty()) { // not in footnote continue; } - boolean seenContains = seen.containsKey(footnoteMarkRange); + boolean seenContains = seen.containsKey(footnoteMarkRange.get()); if (!seenContains) { - seen.put(footnoteMarkRange, true); - xs.add(new RangeForOverlapCheck( - footnoteMarkRange, - base.i, // cgid :: identifies of citation group - RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + base.description)); + seen.put(footnoteMarkRange.get(), true); + xs.add(new RangeForOverlapCheck(footnoteMarkRange.get(), + base.i, // cgid :: identifies of citation group + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + base.description)); } } return xs; diff --git a/src/main/java/org/jabref/gui/openoffice/CitationSort.java b/src/main/java/org/jabref/gui/openoffice/CitationSort.java index b2a7fa154b6..76f406606e3 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationSort.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationSort.java @@ -3,15 +3,17 @@ import java.util.Comparator; import java.util.Optional; -import org.jabref.model.entry.BibEntry; import org.jabref.logic.openoffice.OOBibStyle; +import org.jabref.model.entry.BibEntry; class CitationSort { interface ComparableCitation { public String getCitationKey(); + public Optional getBibEntry(); - public String getPageInfoOrNull(); + + public Optional getPageInfo(); } static class CitationComparator implements Comparator { @@ -49,7 +51,8 @@ public int compare(ComparableCitation a, ComparableCitation b) { bbe.get()); // Also consider pageInfo if (res == 0) { - OOBibStyle.comparePageInfo( a.getPageInfoOrNull(), b.getPageInfoOrNull() ); + OOBibStyle.comparePageInfo(a.getPageInfo().orElse(null), + b.getPageInfo().orElse(null)); } return res; } diff --git a/src/main/java/org/jabref/gui/openoffice/CitedKey.java b/src/main/java/org/jabref/gui/openoffice/CitedKey.java index 96323c95d35..c24b45ea78d 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitedKey.java +++ b/src/main/java/org/jabref/gui/openoffice/CitedKey.java @@ -1,42 +1,12 @@ package org.jabref.gui.openoffice; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; -import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XText; -import com.sun.star.text.XTextContent; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextRange; -import com.sun.star.uno.UnoRuntime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - class CitedKey implements CitationSort.ComparableCitation { String citationKey; LinkedHashSet where; @@ -56,25 +26,25 @@ class CitedKey implements CitationSort.ComparableCitation { } @Override - public String getCitationKey(){ + public String getCitationKey() { return citationKey; } @Override - public Optional getBibEntry(){ + public Optional getBibEntry() { return (db.isPresent() ? Optional.of(db.get().entry) : Optional.empty()); } /** No pageInfo is needed for sorting the bibliography, - * getPageInfoOrNull always returns null. Only exists to implement ComparableCitation. + * getPageInfo always returns Optional.empty. Only exists to implement ComparableCitation. * * @return null */ @Override - public String getPageInfoOrNull(){ - return null; + public Optional getPageInfo() { + return Optional.empty(); } /** diff --git a/src/main/java/org/jabref/gui/openoffice/CitedKeys.java b/src/main/java/org/jabref/gui/openoffice/CitedKeys.java index 014f94b80a1..a865b790bb0 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitedKeys.java +++ b/src/main/java/org/jabref/gui/openoffice/CitedKeys.java @@ -1,43 +1,14 @@ package org.jabref.gui.openoffice; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; -import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XText; -import com.sun.star.text.XTextContent; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextRange; -import com.sun.star.uno.UnoRuntime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - class CitedKeys { /** diff --git a/src/main/java/org/jabref/gui/openoffice/Codec52.java b/src/main/java/org/jabref/gui/openoffice/Codec52.java index b3b65e92d86..71a5b5cd8d9 100644 --- a/src/main/java/org/jabref/gui/openoffice/Codec52.java +++ b/src/main/java/org/jabref/gui/openoffice/Codec52.java @@ -1,40 +1,13 @@ package org.jabref.gui.openoffice; -import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; - -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XText; -import com.sun.star.text.XTextContent; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextRange; -import com.sun.star.uno.UnoRuntime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * How and what is encoded in a mark names. @@ -55,13 +28,15 @@ class Codec52 { */ public static class ParsedMarkName { /** "", "0", "1" ... */ - public String i; + public final String i; /** in-text-citation type */ - public int itcType; + public final int itcType; /** Citation keys embedded in the reference mark. */ - public List citationKeys; + public final List citationKeys; ParsedMarkName(String i, int itcType, List citationKeys) { + Objects.requireNonNull(i); + Objects.requireNonNull(citationKeys); this.i = i; this.itcType = itcType; this.citationKeys = citationKeys; diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java index ac2580ddfc2..67a88ce628d 100644 --- a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java @@ -1,44 +1,13 @@ package org.jabref.gui.openoffice; -// import java.io.IOException; -// import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; -// import java.util.Collections; -// import java.util.Comparator; -// import java.util.HashMap; -// import java.util.HashSet; -// import java.util.LinkedHashMap; import java.util.List; -// import java.util.Map; -// import java.util.Objects; import java.util.Optional; -// import java.util.Set; -// import java.util.SortedMap; -// import java.util.TreeMap; -// import java.util.TreeSet; -// import java.util.regex.Matcher; -// import java.util.regex.Pattern; -// import java.util.stream.Collectors; - -// import org.jabref.architecture.AllowedToUseAwt; -// import org.jabref.gui.DialogService; -// import org.jabref.logic.JabRefException; -// import org.jabref.logic.bibtex.comparator.FieldComparator; -// import org.jabref.logic.bibtex.comparator.FieldComparatorStack; -// import org.jabref.logic.l10n.Localization; -// import org.jabref.logic.layout.Layout; -// import org.jabref.logic.openoffice.CitationEntry; -// import org.jabref.logic.openoffice.OOBibStyle; -// import org.jabref.logic.openoffice.OOPreFormatter; + import org.jabref.logic.openoffice.OOUtil; -// import org.jabref.logic.openoffice.UndefinedBibtexEntry; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; -// import org.jabref.model.database.BibDatabase; -// import org.jabref.model.entry.BibEntry; -// import org.jabref.model.entry.field.StandardField; -// import com.sun.star.awt.Point; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.Property; @@ -48,19 +17,14 @@ import com.sun.star.beans.XPropertyContainer; import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; -// import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; -// import com.sun.star.container.XEnumeration; -// import com.sun.star.container.XEnumerationAccess; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNameContainer; import com.sun.star.container.XNamed; import com.sun.star.document.XDocumentPropertiesSupplier; import com.sun.star.document.XUndoManager; import com.sun.star.document.XUndoManagerSupplier; -// import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XController; -// import com.sun.star.frame.XDesktop; import com.sun.star.frame.XFrame; import com.sun.star.frame.XModel; import com.sun.star.lang.DisposedException; @@ -68,13 +32,12 @@ import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XComponent; -// import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XServiceInfo; import com.sun.star.style.XStyle; import com.sun.star.style.XStyleFamiliesSupplier; -import com.sun.star.text.ReferenceFieldSource; import com.sun.star.text.ReferenceFieldPart; +import com.sun.star.text.ReferenceFieldSource; import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XFootnote; import com.sun.star.text.XParagraphCursor; @@ -92,7 +55,6 @@ import com.sun.star.uno.Any; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; -// import com.sun.star.uno.XComponentContext; import com.sun.star.util.InvalidStateException; import com.sun.star.util.XRefreshable; import com.sun.star.view.XSelectionSupplier; @@ -130,9 +92,7 @@ class DocumentConnection { public XPropertyContainer userProperties; public XPropertySet propertySet; - DocumentConnection( - XTextDocument mxDoc - ) { + DocumentConnection(XTextDocument mxDoc) { this.mxDoc = mxDoc; this.xCurrentComponent = unoQI(XComponent.class, mxDoc); this.mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); @@ -145,109 +105,98 @@ class DocumentConnection { XController co = mo.getCurrentController(); this.xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); - XDocumentPropertiesSupplier supp = - unoQI(XDocumentPropertiesSupplier.class, mxDoc); - this.userProperties = - supp.getDocumentProperties().getUserDefinedProperties(); - + XDocumentPropertiesSupplier supp = unoQI(XDocumentPropertiesSupplier.class, mxDoc); + this.userProperties = supp.getDocumentProperties().getUserDefinedProperties(); this.propertySet = unoQI(XPropertySet.class, userProperties); } - private XStyle getStyleFromFamilyOrNull(String familyName, String styleName) + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if available, + * otherwise null + */ + private static T unoQI(Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + + private Optional getStyleFromFamily(String familyName, String styleName) throws NoSuchElementException, WrappedTargetException { - XStyleFamiliesSupplier xFamiliesSupplier = unoQI(XStyleFamiliesSupplier.class, mxDoc); - XNameAccess xFamilies = (XNameAccess) unoQI(XNameAccess.class, - xFamiliesSupplier.getStyleFamilies()); - - // Access the 'ParagraphStyles' Family - XNameContainer xFamily = (XNameContainer) unoQI(XNameContainer.class, - xFamilies.getByName(familyName)); + XStyleFamiliesSupplier fss = unoQI(XStyleFamiliesSupplier.class, mxDoc); + XNameAccess fs = unoQI(XNameAccess.class, fss.getStyleFamilies()); + XNameContainer xFamily = unoQI(XNameContainer.class, fs.getByName(familyName)); try { Object s = xFamily.getByName(styleName); - XStyle xs = (XStyle) unoQI( XStyle.class, s ); - return xs; + XStyle xs = (XStyle) unoQI(XStyle.class, s); + return Optional.ofNullable(xs); } catch (NoSuchElementException ex) { - return null; + return Optional.empty(); } } - private XStyle getParagraphStyleOrNull(String styleName) + private Optional getParagraphStyle(String styleName) throws NoSuchElementException, WrappedTargetException { - return getStyleFromFamilyOrNull("ParagraphStyles", styleName ); + return getStyleFromFamily("ParagraphStyles", styleName); } - private XStyle getCharacterStyleOrNull(String styleName) + private Optional getCharacterStyle(String styleName) throws NoSuchElementException, WrappedTargetException { - return getStyleFromFamilyOrNull("CharacterStyles", styleName ); + return getStyleFromFamily("CharacterStyles", styleName); } - public String getInternalNameOfParagraphStyleOrNull(String name) + public Optional getInternalNameOfParagraphStyle(String name) throws NoSuchElementException, WrappedTargetException { - - XStyle xs = getParagraphStyleOrNull(name); - if (xs == null) { - return null; - } else { - return xs.getName(); - } + return (getParagraphStyle(name) + .map(e -> e.getName())); } - public String getInternalNameOfCharacterStyleOrNull(String name) + public Optional getInternalNameOfCharacterStyle(String name) throws NoSuchElementException, WrappedTargetException { - - XStyle xs = getCharacterStyleOrNull(name); - if (xs == null) { - return null; - } else { - return xs.getName(); - } + return (getCharacterStyle(name) + .map(e -> e.getName())); } /** - * @param An uno object, hopefully implementing XServiceInfo + * @param o An uno object, hopefully implementing XServiceInfo */ - public static void - printServiceInfo(Object o) { - XServiceInfo xserviceinfo = unoQI(XServiceInfo.class, o ); + public static void printServiceInfo(Object o) { + XServiceInfo xserviceinfo = unoQI(XServiceInfo.class, o); System.out.printf("*** xserviceinfo%n"); - System.out.printf(" object is %s%n", o == null ? "null" : "OK"); + System.out.printf(" object is %s%n", o == null ? "null" : "OK"); System.out.printf(" xserviceinfo is %s%n", xserviceinfo == null ? "null" : "OK"); - if ( xserviceinfo != null ){ + if (xserviceinfo != null) { System.out.printf(" .getImplementationName: \"%s\"%n", xserviceinfo.getImplementationName()); System.out.printf(" .getSupportedServiceNames:%n"); - for ( String s : xserviceinfo.getSupportedServiceNames() ) { + for (String s : xserviceinfo.getSupportedServiceNames()) { System.out.printf(" \"%s\"%n", s); } } } - public XModel - getModel() { + public XModel getModel() { return unoQI(XModel.class, this.xCurrentComponent); } - public XController - getCurrentController() { + public XController getCurrentController() { return this.getModel().getCurrentController(); } - public XSelectionSupplier - getSelectionSupplier() { - return unoQI(XSelectionSupplier.class, - this.getCurrentController()); + public XSelectionSupplier getSelectionSupplier() { + return unoQI(XSelectionSupplier.class, this.getCurrentController()); } /** @@ -288,34 +237,32 @@ public String getInternalNameOfCharacterStyleOrNull(String name) * "com.sun.star.text.TextGraphicObject" * */ - public Object - getSelectionAsObject() { + private Object getSelectionAsObject() { XSelectionSupplier xss = this.getSelectionSupplier(); return xss.getSelection(); } /** - * So far it seems teh first thing we have to do + * So far it seems the first thing we have to do * with a selection is to decide what do we have. * * One way to do that is accessing its XServiceInfo interface. * * Note: may return null. */ - public XServiceInfo - getSelectionAsServiceInfo() { + public Optional getSelectionAsServiceInfo() { Object o = getSelectionAsObject(); if (o == null) { - return null; + return Optional.empty(); } - XServiceInfo xserviceinfo = unoQI(XServiceInfo.class, o ); + XServiceInfo xserviceinfo = unoQI(XServiceInfo.class, o); if (xserviceinfo == null) { // I do not know if this is possible: make a note // if it is. LOGGER.warn("DocumentConnection.getSelectionAsObject:" + " XServiceInfo is null when Object is not"); } - return xserviceinfo; + return Optional.ofNullable(xserviceinfo); } /** @@ -329,41 +276,26 @@ public String getInternalNameOfCharacterStyleOrNull(String name) * @return Apparently always returns true. * */ - public boolean - select(Object newSelection) { + public boolean select(Object newSelection) { XSelectionSupplier xss = this.getSelectionSupplier(); return xss.select(newSelection); } - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if available, - * otherwise null - */ - private static T - unoQI( - Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - /** * 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 void - enterUndoContext(String title) { + public void enterUndoContext(String title) { XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); XUndoManager um = mxUndoManagerSupplier.getUndoManager(); // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html um.enterUndoContext(title); } - public void - leaveUndoContext() - throws InvalidStateException { + public void leaveUndoContext() + throws + InvalidStateException { XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); XUndoManager um = mxUndoManagerSupplier.getUndoManager(); // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html @@ -380,20 +312,17 @@ public String getInternalNameOfCharacterStyleOrNull(String name) * While there is at least one lock remaining, some * notifications for display updates are not broadcasted. */ - public void - lockControllers() { + public void lockControllers() { XModel mo = unoQI(XModel.class, this.xCurrentComponent); mo.lockControllers(); } - public void - unlockControllers() { + public void unlockControllers() { XModel mo = unoQI(XModel.class, this.xCurrentComponent); mo.unlockControllers(); } - public boolean - hasControllersLocked() { + public boolean hasControllersLocked() { XModel mo = unoQI(XModel.class, this.xCurrentComponent); return mo.hasControllersLocked(); } @@ -401,8 +330,7 @@ public String getInternalNameOfCharacterStyleOrNull(String name) /** * @return True if we cannot reach the current document. */ - public boolean - documentConnectionMissing() { + public boolean documentConnectionMissing() { boolean missing = false; // These are set by DocumentConnection constructor. @@ -442,8 +370,7 @@ public String getInternalNameOfCharacterStyleOrNull(String name) * @param doc The XTextDocument we want the title for. Null allowed. * @return The title or Optional.empty() */ - public static Optional - getDocumentTitle(XTextDocument doc) { + public static Optional getDocumentTitle(XTextDocument doc) { if (doc == null) { return Optional.empty(); @@ -463,17 +390,14 @@ public String getInternalNameOfCharacterStyleOrNull(String name) /** * Get the title of the connected document. */ - public Optional - getDocumentTitle() { + public Optional getDocumentTitle() { return DocumentConnection.getDocumentTitle(this.mxDoc); } - public List - getCustomPropertyNames() { + public List getCustomPropertyNames() { assert (this.propertySet != null); - XPropertySetInfo psi = (this.propertySet - .getPropertySetInfo()); + XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); List names = new ArrayList<>(); for (Property p : psi.getProperties()) { @@ -492,16 +416,13 @@ public String getInternalNameOfCharacterStyleOrNull(String name) * individual citation. In particular, the `pageInfo` part. * */ - public Optional - getCustomProperty(String property) + public Optional getCustomProperty(String property) throws - // UnknownPropertyException, WrappedTargetException { assert (this.propertySet != null); - XPropertySetInfo psi = (this.propertySet - .getPropertySetInfo()); + XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); if (psi.hasPropertyByName(property)) { try { @@ -511,9 +432,7 @@ public String getInternalNameOfCharacterStyleOrNull(String name) .toString(); return Optional.ofNullable(v); } catch (UnknownPropertyException ex) { - // LOGGER.warn("getCustomProperty: cought UnknownPropertyException: ", ex); - // return Optional.empty(); - throw new RuntimeException("getCustomProperty: cought UnknownPropertyException"); + throw new RuntimeException("getCustomProperty: caught UnknownPropertyException"); } } return Optional.empty(); @@ -525,10 +444,8 @@ public String getInternalNameOfCharacterStyleOrNull(String name) * * @param value The value to be stored. */ - public void - setCustomProperty(String property, String value) + public void setCustomProperty(String property, String value) throws - // UnknownPropertyException, NotRemoveableException, PropertyExistException, IllegalTypeException, @@ -542,10 +459,9 @@ public String getInternalNameOfCharacterStyleOrNull(String name) if (value != null) { this.userProperties - .addProperty( - property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value)); + .addProperty(property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value)); } } @@ -555,7 +471,6 @@ public String getInternalNameOfCharacterStyleOrNull(String name) */ public void removeCustomProperty(String property) throws - // UnknownPropertyException, NotRemoveableException, PropertyExistException, IllegalTypeException, @@ -580,15 +495,12 @@ public void removeCustomProperty(String property) * we have a working connection. * */ - public XNameAccess - getReferenceMarks() - throws NoDocumentException { + public XNameAccess getReferenceMarks() + throws + NoDocumentException { - XReferenceMarksSupplier supplier = - unoQI( - XReferenceMarksSupplier.class, - this.xCurrentComponent - ); + XReferenceMarksSupplier supplier = unoQI(XReferenceMarksSupplier.class, + this.xCurrentComponent); try { return supplier.getReferenceMarks(); } catch (DisposedException ex) { @@ -599,30 +511,20 @@ public void removeCustomProperty(String property) /** * Provides access to bookmarks by name. */ - public XNameAccess - getBookmarks() { - - XBookmarksSupplier supplier = - unoQI( - XBookmarksSupplier.class, - this.xCurrentComponent - ); + public XNameAccess getBookmarks() { + + XBookmarksSupplier supplier = unoQI(XBookmarksSupplier.class, + this.xCurrentComponent); return supplier.getBookmarks(); } /** * @return An XNameAccess to find sections by name. */ - public XNameAccess - getTextSections() - throws - IllegalArgumentException { + public XNameAccess getTextSections() { - XTextSectionsSupplier supplier = - unoQI( - XTextSectionsSupplier.class, - this.mxDoc - ); + XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, + this.mxDoc); return supplier.getTextSections(); } @@ -631,8 +533,7 @@ public void removeCustomProperty(String property) * * Empty list for nothing. */ - public List - getReferenceMarkNames() + public List getReferenceMarkNames() throws NoDocumentException { XNameAccess nameAccess = getReferenceMarks(); @@ -648,8 +549,7 @@ public void removeCustomProperty(String property) * * @return null for null and for no-such-interface */ - public static XTextContent - asTextContent(Object mark) { + public static XTextContent asTextContent(Object mark) { if (mark == null) { return null; } @@ -660,21 +560,24 @@ public void removeCustomProperty(String property) * @return null if name not found, or if the result does not * support the XTextContent interface. */ - public static XTextContent - nameAccessGetTextContentByNameOrNull(XNameAccess nameAccess, String name) - throws WrappedTargetException { + public static Optional nameAccessGetTextContentByName(XNameAccess nameAccess, + String name) + throws + WrappedTargetException { if (!nameAccess.hasByName(name)) { - return null; + return Optional.empty(); } + try { Object referenceMark = nameAccess.getByName(name); - return asTextContent(referenceMark); + return Optional.ofNullable(asTextContent(referenceMark)); } catch (NoSuchElementException ex) { - LOGGER.warn(String.format( - "nameAccessGetTextContentByNameOrNull got NoSuchElementException" - + " for '%s'", name)); - return null; + String msg = String.format("nameAccessGetTextContentByName got NoSuchElementException" + + " for '%s'", + name); + LOGGER.warn(msg); + return Optional.empty(); } } @@ -684,15 +587,13 @@ public void removeCustomProperty(String property) * @return null if mark is null, otherwise cursor. * */ - public static XTextCursor - getTextCursorOfTextContent(XTextContent mark) { + public static XTextCursor getTextCursorOfTextContent(XTextContent mark) { if (mark == null) { return null; } XTextRange markAnchor = mark.getAnchor(); - return - markAnchor.getText() - .createTextCursorByRange(markAnchor); + return (markAnchor.getText() + .createTextCursorByRange(markAnchor)); } /** @@ -700,8 +601,7 @@ public void removeCustomProperty(String property) * * Removes both the text and the mark itself. */ - public void - removeReferenceMark(String name) + public void removeReferenceMark(String name) throws WrappedTargetException, NoDocumentException, @@ -710,12 +610,11 @@ public void removeCustomProperty(String property) XNameAccess xReferenceMarks = this.getReferenceMarks(); if (xReferenceMarks.hasByName(name)) { - XTextContent mark = - nameAccessGetTextContentByNameOrNull(xReferenceMarks, name); - if (mark == null) { + Optional mark = nameAccessGetTextContentByName(xReferenceMarks, name); + if (mark.isEmpty()) { return; } - this.xText.removeTextContent(mark); + this.xText.removeTextContent(mark.get()); } } @@ -723,8 +622,7 @@ public void removeCustomProperty(String property) * Get the cursor positioned by the user. * */ - public XTextViewCursor - getViewCursor() { + public XTextViewCursor getViewCursor() { return this.xViewCursorSupplier.getViewCursor(); } @@ -734,48 +632,37 @@ public void removeCustomProperty(String property) * @param name The name of the bookmark to find. * @return The XTextRange for the bookmark, or null. */ - public XTextRange - getBookmarkRangeOrNull(String name) + public Optional getBookmarkRange(String name) throws WrappedTargetException { XNameAccess nameAccess = this.getBookmarks(); - XTextContent textContent = - nameAccessGetTextContentByNameOrNull(nameAccess, name); - if (textContent == null) { - return null; - } - return textContent.getAnchor(); + return (nameAccessGetTextContentByName(nameAccess, name) + .map(e -> e.getAnchor())); } /** - * @return reference mark as XTextContent, null if not found. + * @return reference mark as XTextContent, Optional.empty if not found. */ - public XTextContent - getReferenceMarkAsTextContentOrNull(String name) + public Optional getReferenceMarkAsTextContent(String name) throws NoDocumentException, WrappedTargetException { XNameAccess nameAccess = this.getReferenceMarks(); - return nameAccessGetTextContentByNameOrNull(nameAccess, name); + return nameAccessGetTextContentByName(nameAccess, name); } /** - * XTextRange for the named reference mark, null if not found. + * XTextRange for the named reference mark, Optional.empty if not found. */ - public XTextRange - getReferenceMarkRangeOrNull(String name) + public Optional getReferenceMarkRange(String name) throws NoDocumentException, WrappedTargetException { - XTextContent textContent = - getReferenceMarkAsTextContentOrNull(name); - if (textContent == null) { - return null; - } - return textContent.getAnchor(); + return (getReferenceMarkAsTextContent(name) + .map(e -> e.getAnchor())); } /** @@ -807,21 +694,16 @@ public void removeCustomProperty(String property) * @return The XNamed interface, in case we need to check the actual name. * */ - private XNamed - insertNamedTextContent( - String service, - String name, - XTextRange range, - boolean absorb - ) + private XNamed insertNamedTextContent(String service, + String name, + XTextRange range, + boolean absorb) throws CreationException { Object xObject; try { - xObject = - this.mxDocFactory - .createInstance(service); + xObject = this.mxDocFactory.createInstance(service); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -859,13 +741,10 @@ public XNamed insertReferenceMark(String name, throws CreationException { - return - insertNamedTextContent( - "com.sun.star.text.ReferenceMark", - name, - range, - absorb // was true - ); + return insertNamedTextContent("com.sun.star.text.ReferenceMark", + name, + range, + absorb); } /** @@ -885,22 +764,17 @@ public XNamed insertReferenceMark(String name, * caller, because its name may differ from the one * requested. */ - public XNamed - insertBookmark( - String name, - XTextRange range, - boolean absorb) + public XNamed insertBookmark(String name, + XTextRange range, + boolean absorb) throws IllegalArgumentException, CreationException { - return - insertNamedTextContent( - "com.sun.star.text.Bookmark", - name, - range, - absorb // was true - ); + return insertNamedTextContent("com.sun.star.text.Bookmark", + name, + range, + absorb); } /** @@ -910,11 +784,8 @@ public XNamed insertReferenceMark(String name, * May need a documentConnection.refresh() after, to update * the text shown. */ - public void - insertGetreferenceToPageNumberOfReferenceMark( - String referenceMarkName, - XTextRange cursor - ) + public void insertGetreferenceToPageNumberOfReferenceMark(String referenceMarkName, + XTextRange cursor) throws CreationException, UnknownPropertyException, @@ -928,10 +799,9 @@ public XNamed insertReferenceMark(String name, // and get it's XPropertySet interface XPropertySet xFieldProps; try { - xFieldProps = - (XPropertySet) unoQI(XPropertySet.class, - this.mxDocFactory.createInstance( - "com.sun.star.text.textfield.GetReference")); + String name = "com.sun.star.text.textfield.GetReference"; + xFieldProps = (XPropertySet) unoQI(XPropertySet.class, + this.mxDocFactory.createInstance(name)); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -941,12 +811,12 @@ public XNamed insertReferenceMark(String name, // specify that the source is a reference mark (could also be a footnote, // bookmark or sequence field) - xFieldProps.setPropertyValue ("ReferenceFieldSource", - new Short(ReferenceFieldSource.REFERENCE_MARK)); + xFieldProps.setPropertyValue("ReferenceFieldSource", + new Short(ReferenceFieldSource.REFERENCE_MARK)); // We want the reference displayed as page number xFieldProps.setPropertyValue("ReferenceFieldPart", - new Short (ReferenceFieldPart.PAGE)); + new Short(ReferenceFieldPart.PAGE)); // Get the XTextContent interface of the GetReference text field XTextContent xRefContent = (XTextContent) unoQI(XTextContent.class, xFieldProps); @@ -963,12 +833,9 @@ public XNamed insertReferenceMark(String name, /** * Update TextFields, etc. */ - public void - refresh() { + public void refresh() { // Refresh the document - XRefreshable xRefresh = - (XRefreshable) unoQI(XRefreshable.class, - this.mxDoc); + XRefreshable xRefresh = unoQI(XRefreshable.class, this.mxDoc); xRefresh.refresh(); } @@ -983,58 +850,50 @@ public XNamed insertReferenceMark(String name, * LibreOffice (6.4.6.2) creates a section with a name different from * what we requested, in "Section {number}" format. */ - public XNamed - insertTextSection( - String name, - XTextRange range, - boolean absorb) + public XNamed insertTextSection(String name, + XTextRange range, + boolean absorb) throws IllegalArgumentException, CreationException { - return - insertNamedTextContent( - "com.sun.star.text.TextSection", - name, - range, - absorb // was false - ); + return insertNamedTextContent("com.sun.star.text.TextSection", + name, + range, + absorb); } /** * Get an XTextSection by name. */ - public XTextSection - getTextSectionByName(String name) + public Optional getTextSectionByName(String name) throws NoSuchElementException, WrappedTargetException { - XTextSectionsSupplier supplier = - unoQI(XTextSectionsSupplier.class, - this.mxDoc); + XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, + this.mxDoc); - return ((XTextSection) - ((Any) supplier.getTextSections().getByName(name)) - .getObject()); + return Optional.ofNullable((XTextSection) + ((Any) supplier.getTextSections().getByName(name)) + .getObject()); } /** * If original is in a footnote, return a range containing * the corresponding footnote marker. * - * Returns null if not in a footnote. + * Returns Optional.empty if not in a footnote. */ - public static XTextRange - getFootnoteMarkRangeOrNull(XTextRange original) { - // If we are inside a footnote: - if (unoQI(XFootnote.class, original.getText()) != null) { - // Find the linking footnote marker: - XFootnote footer = unoQI(XFootnote.class, original.getText()); + public static Optional getFootnoteMarkRange(XTextRange original) { + XFootnote footer = unoQI(XFootnote.class, original.getText()); + if (footer != null) { + // If we are inside a footnote, + // find the linking footnote marker: // The footnote's anchor gives the correct position in the text: - return footer.getAnchor(); + return Optional.ofNullable(footer.getAnchor()); } - return null; + return Optional.empty(); } /** @@ -1044,9 +903,8 @@ public XNamed insertReferenceMark(String name, * @param position The range to apply to. * @param charStyle Name of the character style as known by Openoffice. */ - public static void - setCharStyle(XTextCursor position, // TODO: maybe an XTextRange is sufficient here - String charStyle) + public static void setCharStyle(XTextCursor position, + String charStyle) throws UndefinedCharacterFormatException { @@ -1058,14 +916,14 @@ public XNamed insertReferenceMark(String name, | PropertyVetoException | IllegalArgumentException | WrappedTargetException ex) { - throw new UndefinedCharacterFormatException(charStyle); // Setting the character format failed, so we throw an exception that // will result in an error message for the user: + throw new UndefinedCharacterFormatException(charStyle); } } public static void setParagraphStyle(XTextCursor cursor, - String parStyle) + String parStyle) throws UndefinedParagraphFormatException { XParagraphCursor parCursor = unoQI(XParagraphCursor.class, cursor); @@ -1088,8 +946,7 @@ public static void setParagraphStyle(XTextCursor cursor, * * Ref: https://www.openoffice.org/api/docs/common/ref/com/sun/star/style/CharacterProperties.html */ - public static void - setCharFormatItalic(XTextRange textRange) + public static void setCharFormatItalic(XTextRange textRange) throws UnknownPropertyException, PropertyVetoException, @@ -1101,8 +958,7 @@ public static void setParagraphStyle(XTextCursor cursor, /** * Apply direct character format "Bold" to a range of text. */ - public static void - setCharFormatBold(XTextRange textRange) + public static void setCharFormatBold(XTextRange textRange) throws UnknownPropertyException, PropertyVetoException, @@ -1117,8 +973,7 @@ public static void setParagraphStyle(XTextCursor cursor, * Note: "zxx" is an https://en.wikipedia.org/wiki/ISO_639 code for * "No linguistic information at all" */ - public static void - setCharLocaleNone(XTextRange textRange) + public static void setCharLocaleNone(XTextRange textRange) throws UnknownPropertyException, PropertyVetoException, @@ -1131,23 +986,17 @@ public static void setParagraphStyle(XTextCursor cursor, * Test if two XTextRange values are comparable (i.e. they share * the same getText()). */ - public static boolean - comparableRanges( - XTextRange a, - XTextRange b - ) { + public static boolean comparableRanges(XTextRange a, + XTextRange b) { return a.getText() == b.getText(); } /** * Test if two XTextRange values are equal. */ - public static boolean - equalRanges( - XTextRange a, - XTextRange b - ) { - if (!comparableRanges(a,b)) { + public static boolean equalRanges(XTextRange a, + XTextRange b) { + if (!comparableRanges(a, b)) { return false; } final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, @@ -1165,8 +1014,8 @@ public static void setParagraphStyle(XTextCursor cursor, * @return follows OO conventions, the opposite of java conventions: * 1 if (a < b), 0 if same start, (-1) if (b < a) */ - private static int - ooCompareRegionStarts(XTextRange a, XTextRange b) { + private static int ooCompareRegionStarts(XTextRange a, + XTextRange b) { if (!comparableRanges(a, b)) { throw new RuntimeException("ooCompareRegionStarts: got incomparable regions"); } @@ -1179,8 +1028,8 @@ public static void setParagraphStyle(XTextCursor cursor, * @return follows OO conventions, the opposite of java conventions: * 1 if (a < b), 0 if same start, (-1) if (b < a) */ - private static int - ooCompareRegionEnds(XTextRange a, XTextRange b) { + private static int ooCompareRegionEnds(XTextRange a, + XTextRange b) { if (!comparableRanges(a, b)) { throw new RuntimeException("ooCompareRegionEnds: got incomparable regions"); } @@ -1194,8 +1043,8 @@ public static void setParagraphStyle(XTextCursor cursor, * * 1 if (a > b); (-1) if (a < b) */ - public static int - javaCompareRegionStarts(XTextRange a, XTextRange b) { + public static int javaCompareRegionStarts(XTextRange a, + XTextRange b) { return (-1) * ooCompareRegionStarts(a, b); } @@ -1204,8 +1053,8 @@ public static void setParagraphStyle(XTextCursor cursor, * * 1 if (a > b); (-1) if (a < b) */ - public static int - javaCompareRegionEnds(XTextRange a, XTextRange b) { + public static int javaCompareRegionEnds(XTextRange a, + XTextRange b) { return (-1) * ooCompareRegionEnds(a, b); } } // end DocumentConnection diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e85256edacc..37100a2f93c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3,12 +3,10 @@ import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -16,17 +14,10 @@ import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.stream.Collectors; -import java.util.stream.Stream; -import java.util.function.Function; -import java.util.function.Predicate; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.gui.DialogService; -import org.jabref.gui.openoffice.RangeSortVisual; import org.jabref.logic.JabRefException; import org.jabref.logic.bibtex.comparator.FieldComparator; import org.jabref.logic.bibtex.comparator.FieldComparatorStack; @@ -38,68 +29,35 @@ import org.jabref.logic.openoffice.OOBibStyle; import org.jabref.logic.openoffice.OOPreFormatter; import org.jabref.logic.openoffice.OOUtil; -import org.jabref.logic.openoffice.UndefinedBibtexEntry; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; -import com.sun.star.awt.Point; -import com.sun.star.awt.Selection; -import com.sun.star.awt.XTextComponent; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.Property; 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.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XEnumeration; import com.sun.star.container.XEnumerationAccess; import com.sun.star.container.XNameAccess; -import com.sun.star.container.XNamed; -import com.sun.star.document.XDocumentPropertiesSupplier; -import com.sun.star.document.XUndoManager; -import com.sun.star.document.XUndoManagerSupplier; import com.sun.star.frame.XComponentLoader; -import com.sun.star.frame.XController; import com.sun.star.frame.XDesktop; -import com.sun.star.frame.XFrame; -import com.sun.star.frame.XModel; import com.sun.star.lang.DisposedException; -import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.lang.XMultiServiceFactory; -import com.sun.star.lang.XServiceInfo; -import com.sun.star.text.ReferenceFieldSource; -import com.sun.star.text.ReferenceFieldPart; -import com.sun.star.text.XBookmarksSupplier; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XReferenceMarksSupplier; -import com.sun.star.text.XText; -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.XTextRangeCompare; import com.sun.star.text.XTextSection; -import com.sun.star.text.XTextSectionsSupplier; -import com.sun.star.text.XTextViewCursor; -import com.sun.star.text.XTextViewCursorSupplier; import com.sun.star.uno.Any; -import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; -import com.sun.star.uno.XInterface; import com.sun.star.util.InvalidStateException; -import com.sun.star.util.XRefreshable; -import com.sun.star.view.XSelectionSupplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -122,8 +80,10 @@ class OOBibBase { private static final int AUTHORYEAR_INTEXT = 2; private static final int INVISIBLE_CIT = 3; - private static final Comparator entryComparator = makeEntryComparator(); - private static final Comparator yearAuthorTitleComparator = makeYearAuthorTitleComparator(); + private static final Comparator AUTHOR_YEAR_TITLE_COMPARATOR = + makeAuthorYearTitleComparator(); + private static final Comparator YEAR_AUTHOR_TITLE_COMPARATOR = + makeYearAuthorTitleComparator(); private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); @@ -132,8 +92,27 @@ class OOBibBase { private final DialogService dialogService; private final XDesktop xDesktop; - static Comparator - makeEntryComparator() { + /** + * Created when connected to a document. + * + * Cleared (to null) when we discover we lost the connection. + */ + private DocumentConnection xDocumentConnection; + + /* + * Constructor + */ + public OOBibBase(Path loPath, + DialogService dialogService) + throws + BootstrapException, + CreationException { + + this.dialogService = dialogService; + this.xDesktop = simpleBootstrap(loPath); + } + + private static Comparator makeAuthorYearTitleComparator() { FieldComparator a = new FieldComparator(StandardField.AUTHOR); FieldComparator y = new FieldComparator(StandardField.YEAR); FieldComparator t = new FieldComparator(StandardField.TITLE); @@ -145,8 +124,7 @@ class OOBibBase { return new FieldComparatorStack<>(ayt); } - static Comparator - makeYearAuthorTitleComparator() { + private static Comparator makeYearAuthorTitleComparator() { FieldComparator y = new FieldComparator(StandardField.YEAR); FieldComparator a = new FieldComparator(StandardField.AUTHOR); FieldComparator t = new FieldComparator(StandardField.TITLE); @@ -158,36 +136,13 @@ class OOBibBase { return new FieldComparatorStack<>(yat); } - /** - * Created when connected to a document. - * - * Cleared (to null) when we discover we lost the connection. - */ - private DocumentConnection xDocumentConnection; - - - /* - * Constructor - */ - public - OOBibBase(Path loPath, - DialogService dialogService) - throws - BootstrapException, - CreationException { - - this.dialogService = dialogService; - this.xDesktop = simpleBootstrap(loPath); - } - /* ***************************** * * Establish connection * * *****************************/ - private XDesktop - simpleBootstrap(Path loPath) + private XDesktop simpleBootstrap(Path loPath) throws CreationException, BootstrapException { @@ -211,8 +166,7 @@ class OOBibBase { return result; } - private static List - getTextDocuments(XDesktop desktop) + private static List getTextDocuments(XDesktop desktop) throws NoSuchElementException, WrappedTargetException { @@ -272,11 +226,10 @@ public String toString() { // thread Optional selectedDocument = (dialogService - .showChoiceDialogAndWait( - Localization.lang("Select document"), - Localization.lang("Found documents:"), - Localization.lang("Use selected document"), - viewModel)); + .showChoiceDialogAndWait(Localization.lang("Select document"), + Localization.lang("Found documents:"), + Localization.lang("Use selected document"), + viewModel)); return (selectedDocument .map(DocumentTitleViewModel::getXtextDocument) @@ -465,13 +418,13 @@ public void checkRangeOverlaps(CitationGroups cgs, RangeKeyedMapList xall = new RangeKeyedMapList<>(); for (RangeForOverlapCheck x : xs) { XTextRange key = x.range; - xall.add(key,x); + xall.add(key, x); } List.RangeOverlap> ovs = xall.findOverlappingRanges(reportAtMost, requireSeparation); - //checkSortedPartitionForOverlap(requireSeparation, oxs); + // checkSortedPartitionForOverlap(requireSeparation, oxs); if (ovs.size() > 0) { String msg = ""; for (RangeKeyedMapList.RangeOverlap e : ovs) { @@ -482,9 +435,12 @@ public void checkRangeOverlaps(CitationGroups cgs, + "\n"); switch (e.kind) { - case EQUAL_RANGE: msg = msg + Localization.lang("Found identical ranges") + l; break; - case OVERLAP: msg = msg + Localization.lang("Found overlapping ranges") + l; break; - case TOUCH: msg = msg + Localization.lang("Found touching ranges") + l; break; + case EQUAL_RANGE: msg = msg + Localization.lang("Found identical ranges") + l; + break; + case OVERLAP: msg = msg + Localization.lang("Found overlapping ranges") + l; + break; + case TOUCH: msg = msg + Localization.lang("Found touching ranges") + l; + break; } } throw new JabRefException("Found overlapping or touching ranges", msg); @@ -539,11 +495,10 @@ public List getCitationEntries() List citations = new ArrayList<>(n); for (CitationGroupID cgid : cgs.getCitationGroupIDs()) { String name = cgid.asString(); - CitationEntry entry = - new CitationEntry( - name, - this.getCitationContext(cgs, cgid, documentConnection, 30, 30, true), - cgs.getPageInfo(cgid)); + String context = this.getCitationContext(cgs, cgid, documentConnection, 30, 30, true); + CitationEntry entry = new CitationEntry(name, + context, + cgs.getPageInfo(cgid)); citations.add(entry); } return citations; @@ -555,11 +510,13 @@ public List getCitationEntries() * * The actual context may be smaller than requested. * - * @param refMarkName Name of a reference mark. + * @param cgs + * @param cgid + * @param documentConnection * @param charBefore Number of characters requested. * @param charAfter Number of characters requested. * @param htmlMarkup If true, the text belonging to the - * reference mark is surrounded by bold html tag. + * reference mark is surrounded by bold html tag. */ private String getCitationContext(CitationGroups cgs, CitationGroupID cgid, @@ -572,7 +529,9 @@ private String getCitationContext(CitationGroups cgs, NoDocumentException, CreationException { - XTextCursor cursor = cgs.getRawCursorForCitationGroup(cgid, documentConnection); + XTextCursor cursor = (cgs + .getRawCursorForCitationGroup(cgid, documentConnection) + .orElseThrow(RuntimeException::new)); String citPart = cursor.getString(); @@ -612,10 +571,9 @@ private String getCitationContext(CitationGroups cgs, String result = cursor.getString(); if (htmlMarkup) { - result = - result.substring(0, addedBefore) - + "" + citPart + "" - + result.substring(lengthWithBefore); + result = (result.substring(0, addedBefore) + + "" + citPart + "" + + result.substring(lengthWithBefore)); } return result.trim(); } @@ -645,8 +603,7 @@ private String getCitationContext(CitationGroups cgs, * citation from the text). * */ - public void applyCitationEntries( - List citationEntries) + public void applyCitationEntries(List citationEntries) throws UnknownPropertyException, NotRemoveableException, @@ -666,13 +623,6 @@ public void applyCitationEntries( } } - /* ************************************* - * - * Look up in databases - * - * *************************************/ - - /* *************************************** * * Local order: Presentation order within citation groups @@ -688,29 +638,14 @@ public void applyCitationEntries( * * Yes, they are always sorted one way or another. */ - private Comparator - comparatorForMulticite(OOBibStyle style) { + private Comparator comparatorForMulticite(OOBibStyle style) { if (style.getMultiCiteChronological()) { - return this.yearAuthorTitleComparator; + return OOBibBase.YEAR_AUTHOR_TITLE_COMPARATOR; } else { - return this.entryComparator; + return OOBibBase.AUTHOR_YEAR_TITLE_COMPARATOR; } } - /** - * Sort entries within a group of merged citations. - * - * Note: the sort is in-place, modifies the argument. - */ - // private void - // sortBibEntryListForMulticite(List entries, - // OOBibStyle style) { - // if (entries.size() <= 1) { - // return; - // } - // entries.sort(comparatorForMulticite(style)); - // } - /* *************************************** * * Global order: by first appearance or by bibliography order @@ -724,21 +659,17 @@ public void applyCitationEntries( * * For sorting the bibliography. */ - SortedMap - sortEntriesByComparator( - Map entries, - Comparator entryComparator - ) { + SortedMap sortEntriesByComparator(Map entries, + Comparator entryComparator) { + SortedMap newMap = new TreeMap<>(entryComparator); for (Map.Entry kv : entries.entrySet()) { - newMap.put( - kv.getKey(), - kv.getValue()); + newMap.put(kv.getKey(), + kv.getValue()); } return newMap; } - /* *************************************** * * Make them unique: uniqueLetters or numbers @@ -747,17 +678,17 @@ public void applyCitationEntries( private String normalizedCitationMarkerForNormalStyle(CitedKey ck, OOBibStyle style) { - if (ck.db.isEmpty()){ + if (ck.db.isEmpty()) { return String.format("(Unresolved(%s))", ck.citationKey); } // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: // createNormalizedCitationMarker CitationMarkerEntry ce = new CitationMarkerEntryImpl(ck.citationKey, - ck.db.get().entry, - ck.db.get().database, - null, // uniqueLetter - null, // pageInfo + ck.db.map(e -> e.entry), + ck.db.map(e -> e.database), + Optional.empty(), // uniqueLetter + Optional.empty(), // pageInfo false /* isFirstAppearanceOfSource */); return style.getNormalizedCitationMarker(ce); } @@ -775,19 +706,17 @@ private String normalizedCitationMarkerForNormalStyle(CitedKey ck, } /** - * Given bibtexKeys for each reference mark and the corresponding - * normalized citation markers for each, fills uniqueLetters. - * - * We expect to see data for all JabRef reference marks here, and - * clear uniqueLetters before filling. + * For each cited source make the citation keys unique by setting + * the uniqueLetter fields to letters ("a", "b") or Optional.empty() * - * On return: uniqueLetters.get(bibtexkey) provides letter to be - * added after the year (null for none). + * precondition: sortedCitedKeys already has normalized citation markers. + * precondition: sortedCitedKeys is sorted (according to the order we want the letters to be assigned) * - * Note: bibtexKeys[i][j] may be null (from UndefinedBibtexEntry) + * Expects to see data for all cited sources here. + * Clears uniqueLetters before filling. * - * Map citation keys to letters ("a", "b") that - * make the citation markers unique. + * On return: Each citedKey in sortedCitedKeys has uniqueLetter set as needed. + * The same values are copied to the corresponding citations in cgs. * * Depends on: style, citations and their order. */ @@ -821,8 +750,7 @@ void createUniqueLetters(CitedKeys sortedCitedKeys, } } - // Map uniqueLetters = new HashMap<>(); - // uniqueLetters.clear(); + // Clear old uniqueLetter values. for (CitedKey ck : sortedCitedKeys.data.values()) { ck.uniqueLetter = Optional.empty(); } @@ -845,7 +773,6 @@ void createUniqueLetters(CitedKeys sortedCitedKeys, sortedCitedKeys.distributeUniqueLetters(cgs); } - /* *************************************** * * Calculate presentation of citation groups @@ -874,7 +801,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * Produce citation markers for the case when the citation * markers are the citation keys themselves, separated by commas. */ - private static Map + private static Map produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroups cgs, OOBibStyle style) throws @@ -882,9 +809,9 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes assert style.getBibTeXKeyCitations(); - cgs.createPlainBibliographySortedByComparator(OOBibBase.entryComparator); + cgs.createPlainBibliographySortedByComparator(OOBibBase.AUTHOR_YEAR_TITLE_COMPARATOR); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { List cits = cgs.getSortedCitations(cgid); @@ -903,21 +830,15 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * Produce citation markers for the case of numbered citations * with bibliography sorted by first appearance in the text. * - * @param referenceMarkNames Names of reference marks. - * - * @param bibtexKeys Expects bibtexKeys[i] to correspond to - * referenceMarkNames.get(i) + * @param cgs + * @param style * - * @param citeKeyToBibEntry Look up BibEntry by bibtexKey. - * Must contain all bibtexKeys, - * but may map to UndefinedBibtexEntry. - * - * @return Numbered citation markers for bibtexKeys. - * Numbering is according to first encounter - * in bibtexKeys[i][j] + * @return Numbered citation markers for each CitationGroupID. + * Numbering is according to first appearance. + * Assumes global order and local order ae already applied. * */ - private static Map + private static Map produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, OOBibStyle style) throws @@ -930,7 +851,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes final int minGroupingCount = style.getMinimumGroupingCount(); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); @@ -949,17 +870,17 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * Produce citation markers for the case of numbered citations * when the bibliography is not sorted by position. */ - private Map + private Map produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, OOBibStyle style) { assert style.getIsNumberEntries(); assert !style.getIsSortByPosition(); - cgs.createNumberedBibliographySortedByComparator( entryComparator ); + cgs.createNumberedBibliographySortedByComparator(OOBibBase.AUTHOR_YEAR_TITLE_COMPARATOR); final int minGroupingCount = style.getMinimumGroupingCount(); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); @@ -977,16 +898,11 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * Produce citMarkers for normal * (!getBibTeXKeyCitations && !getIsNumberEntries) styles. * - * @param referenceMarkNames Names of reference marks. - * @param bibtexKeysIn Bibtex citation keys. - * @param citeKeyToBibEntry Maps citation keys to BibEntry. - * @param itcTypes Citation types. - * @param entries Map BibEntry to BibDatabase. + * @param cgs * @param style Bibliography style. */ - private Map - produceCitationMarkersForNormalStyle(CitationGroups cgs, - OOBibStyle style) + private Map produceCitationMarkersForNormalStyle(CitationGroups cgs, + OOBibStyle style) throws BibEntryNotFoundException { @@ -998,7 +914,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes createNormalizedCitationMarkersForNormalStyle(sortedCitedKeys, style); createUniqueLetters(sortedCitedKeys, cgs); // calls distributeUniqueLetters(cgs) - cgs.createPlainBibliographySortedByComparator(entryComparator); + cgs.createPlainBibliographySortedByComparator(OOBibBase.AUTHOR_YEAR_TITLE_COMPARATOR); // Finally, go through all citation markers, and update // those referring to entries in our current list: @@ -1006,7 +922,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes Set seenBefore = new HashSet<>(); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); @@ -1019,28 +935,25 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes boolean hasUnresolved = false; for (int j = 0; j < nCitedEntries; j++) { Citation cit = cits.get(j); - String currentKey = cit.citationKey; // nullable + String currentKey = cit.citationKey; boolean isFirst = false; if (!seenBefore.contains(currentKey)) { isFirst = true; seenBefore.add(currentKey); } - String uniqueLetterForKey = cit.uniqueLetter.orElse(null); - BibDatabase database = null; - BibEntry bibEntry = null; + Optional uniqueLetterForKey = cit.uniqueLetter; if (cit.db.isEmpty()) { hasUnresolved = true; - } else { - database = cit.db.get().database; - bibEntry = cit.db.get().entry; } + Optional database = cit.db.map(e -> e.database); + Optional bibEntry = cit.db.map(e -> e.entry); CitationMarkerEntry cm = new CitationMarkerEntryImpl(currentKey, bibEntry, database, uniqueLetterForKey, - pageInfosForCitations.get(j), + Optional.ofNullable(pageInfosForCitations.get(j)), isFirst); citationMarkerEntries.add(cm); } @@ -1050,7 +963,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes // maybe the fall back to ungrouped citations here is // not needed anymore. - if ( hasUnresolved ) { + if (hasUnresolved) { /* * Some entries are unresolved. */ @@ -1058,9 +971,9 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes for (int j = 0; j < nCitedEntries; j++) { CitationMarkerEntry cm = citationMarkerEntries.get(j); - if (cm.getBibEntryOrNull() == null) { + if (cm.getBibEntry().isPresent()) { s = (s - + style.getCitationMarker(citationMarkerEntries.subList(j,j+1), + + style.getCitationMarker(citationMarkerEntries.subList(j, j + 1), cg.itcType == OOBibBase.AUTHORYEAR_PAR, OOBibStyle.NonUniqueCitationMarker.THROWS)); } else { @@ -1116,27 +1029,35 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti } /** - * Insert a reference mark: creates and fills it. + * Inserts a citation group in the document: creates and fills it. * + * @param cgs * @param documentConnection Connection to a document. - * - * @param name Name of the reference mark to be created and also - * the name of the custom property holding the pageInfo part. - * - * @param position OUT: left collapsed, just after the space inserted, - * or after the reference mark inserted. + * @param citationKeys BibTeX keys of + * @param pageInfosForCitations + * @param itcType + * + * @param citationText Text for the citation. A citation mark or + * placeholder if not yet available. + * + * @param position Location to insert at. + * @param withText If false, citationText is not shown. + * @param style + * @param insertSpaceAfter A space inserted after the reference + * mark makes it easier to separate from the text + * coming after. But is not wanted when we recreate a + * reference mark. */ - private void insertReferenceMark(CitationGroups cgs, - DocumentConnection documentConnection, - List citationKeys, - // Optional pageInfo, - List pageInfosForCitations, - int itcType, - String citationText, - XTextCursor position, - boolean withText, - OOBibStyle style, - boolean insertSpaceAfter) + private void createAndFillCitationGroup(CitationGroups cgs, + DocumentConnection documentConnection, + List citationKeys, + List pageInfosForCitations, + int itcType, + String citationText, + XTextCursor position, + boolean withText, + OOBibStyle style, + boolean insertSpaceAfter) throws UnknownPropertyException, NotRemoveableException, @@ -1188,18 +1109,15 @@ private void insertReferenceMark(CitationGroups cgs, * @param cursor Provides location where we insert, format and * remove a character. */ - void assertCitationCharacterFormatIsOK( - XTextCursor cursor, - OOBibStyle style - ) + void assertCitationCharacterFormatIsOK(XTextCursor cursor, + OOBibStyle style) throws UndefinedCharacterFormatException { if (!style.getFormatCitations()) { return; } /* We do not want to change the cursor passed in, so using a copy. */ - XTextCursor c2 = - cursor.getText().createTextCursorByRange(cursor.getEnd()); + XTextCursor c2 = cursor.getText().createTextCursorByRange(cursor.getEnd()); /* * Inserting, formatting and removing a single character @@ -1239,9 +1157,8 @@ void assertCitationCharacterFormatIsOK( private static String insertCitationGetCitationKey(BibEntry entry) { Optional key = entry.getCitationKey(); if (key.isEmpty()) { - throw new RuntimeException( - "insertCitationGetCitationKey:" - + " cannot cite entries without citation key"); + throw new RuntimeException("insertCitationGetCitationKey:" + + " cannot cite entries without citation key"); } return key.get(); } @@ -1331,13 +1248,11 @@ public void insertCitation(List entries, styleIsRequired(style); if (entries == null || entries.size() == 0) { - throw new JabRefException( - "No bibliography entries selected", - Localization.lang( - "No bibliography entries are selected for citation.") - + "\n" - + Localization.lang("Select some before citing.") - ); + String title = "No bibliography entries selected"; + String msg = (Localization.lang("No bibliography entries are selected for citation.") + + "\n" + + Localization.lang("Select some before citing.")); + throw new JabRefException(title, msg); } final int nEntries = entries.size(); @@ -1357,11 +1272,8 @@ public void insertCitation(List entries, cursor = documentConnection.getViewCursor(); } catch (RuntimeException ex) { // com.sun.star.uno.RuntimeException - throw new JabRefException( - "Could not get the cursor", - Localization.lang( - "Could not get the cursor.") - ); + throw new JabRefException("Could not get the cursor", + Localization.lang("Could not get the cursor.")); } // Check for crippled XTextViewCursor @@ -1369,57 +1281,25 @@ public void insertCitation(List entries, try { cursor.getStart(); } catch (com.sun.star.uno.RuntimeException ex) { - throw new JabRefException( - Localization.lang("Please move the cursor to the location for the new citation.") + String msg = + Localization.lang("Please move the cursor" + + " to the location for the new citation.") + "\n" - + Localization.lang("I cannot insert to the cursors current location."), - ex); + + Localization.lang("I cannot insert to the cursors current location."); + throw new JabRefException(msg, ex); } - // sortBibEntryListForMulticite(entries, style); - List citationKeys = entries.stream() .map(OOBibBase::insertCitationGetCitationKey) .collect(Collectors.toList()); - // Generate unique mark-name int itcType = citationTypeFromOptions(withText, inParenthesis); - // If we should store metadata for page info, do that now: - // - // Note: the (single) pageInfo here gets associated with - // the citation group. At presentation it is injected - // to before the final parenthesis, appearing to - // belong to the last entry added here. - // - // But: (1) the last entry depends on the above - // sortBibEntryListForMulticite call; (2) On - // "Separate" it belongs to nobody. - // - /* - if (pageInfo != null) { - LOGGER.info("Storing page info: " + pageInfo); - documentConnection.setCustomProperty(newName, pageInfo); - } - */ - // else: branch ??? - // Note: if (pageInfo is null), we might inadvertently - // pick up a pageInfo from an earlier citation. The user - // may have removed the citation, thus the reference mark, - // but pageInfo stored separately stays there. - assertCitationCharacterFormatIsOK(cursor, style); - // Insert reference mark and text - - // JabRef53 style pageInfo list, or null - List pageInfosForCitations = - Backend52.fakePageInfosForCitations(pageInfo, - nEntries, - false /* mayReturnNull */); - // Make it non-null, with a (possibly null) entry for each - // pageInfosForCitations = OOBibStyle.regularizePageInfosForCitations(pageInfosForCitations); + // JabRef53 style pageInfo list + List pageInfosForCitations = Backend52.fakePageInfosForCitations(pageInfo, nEntries); List citationMarkerEntries = new ArrayList<>(entries.size()); for (int i = 0; i < nEntries; i++) { @@ -1427,10 +1307,10 @@ public void insertCitation(List entries, // Probably the GUI limits selection to a single database. CitationMarkerEntry cm = new CitationMarkerEntryImpl(citationKeys.get(i), - entries.get(i), - database, - null, // uniqueLetter - pageInfosForCitations.get(i), + Optional.ofNullable(entries.get(i)), + Optional.ofNullable(database), + Optional.empty(), // uniqueLetter + Optional.ofNullable(pageInfosForCitations.get(i)), false /* isFirstAppearanceOfSource */); citationMarkerEntries.add(cm); } @@ -1446,16 +1326,16 @@ public void insertCitation(List entries, citeText = "[?]"; } - insertReferenceMark(cgs, - documentConnection, - citationKeys, - pageInfosForCitations, - itcType, - citeText, - cursor, - withText, - style, - true /* insertSpaceAfter */); + createAndFillCitationGroup(cgs, + documentConnection, + citationKeys, + pageInfosForCitations, + itcType, + citeText, + cursor, + withText, + style, + true /* insertSpaceAfter */); // Remember this position: we will come back here in the // end. @@ -1511,7 +1391,6 @@ public void insertCitation(List entries, * * **************************************************/ - /** * Visit each reference mark in referenceMarkNames, overwrite its * text content. @@ -1519,19 +1398,18 @@ public void insertCitation(List entries, * After each fillCitationMarkInCursor call check if we lost the * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. * - * @param referenceMarkNames Reference mark names + * @param documentConnection + * @param cgs * * @param citMarkers Corresponding text for each reference mark, * that replaces the old text. * - * @param types itcType codes for each reference mark. - * * @param style Bibliography style to use. * */ private void applyNewCitationMarkers(DocumentConnection documentConnection, CitationGroups cgs, - Map citMarkers, + Map citMarkers, OOBibStyle style) throws NoDocumentException, @@ -1541,8 +1419,9 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, WrappedTargetException, PropertyVetoException { - final boolean hadBibSection = - (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) != null); + final boolean hadBibSection = (documentConnection + .getBookmarkRange(OOBibBase.BIB_SECTION_NAME) + .isPresent()); // If we are supposed to set character format for citations, // must run a test before we delete old citation @@ -1552,7 +1431,7 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, // catastrophic consequences for the user. boolean mustTestCharFormat = style.getFormatCitations(); - for (Map.Entry kv : citMarkers.entrySet() ) { + for (Map.Entry kv : citMarkers.entrySet()) { CitationGroupID cgid = kv.getKey(); Objects.requireNonNull(cgid); @@ -1566,10 +1445,8 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, if (withText) { - XTextCursor cursor = - cgs.getFillCursorForCitationGroup( - documentConnection, - cgid /* Identifies group */); + XTextCursor cursor = cgs.getFillCursorForCitationGroup(documentConnection, + cgid); if (mustTestCharFormat) { assertCitationCharacterFormatIsOK(cursor, style); @@ -1588,7 +1465,9 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, } if (hadBibSection - && (documentConnection.getBookmarkRangeOrNull(OOBibBase.BIB_SECTION_NAME) == null)) { + && (documentConnection + .getBookmarkRange(OOBibBase.BIB_SECTION_NAME) + .isEmpty())) { // Overwriting text already there is too harsh. // I am making it an error, to see if we ever get here. throw new RuntimeException("OOBibBase.applyNewCitationMarkers:" @@ -1605,21 +1484,20 @@ static class ProduceCitationMarkersResult { CitationGroups cgs; /** citation markers */ - Map citMarkers; + Map citMarkers; ProduceCitationMarkersResult(CitationGroups cgs, - Map citMarkers) { + Map citMarkers) { this.cgs = cgs; this.citMarkers = citMarkers; - if ( cgs.getBibliography().isEmpty() ) { + if (cgs.getBibliography().isEmpty()) { throw new RuntimeException("ProduceCitationMarkersResult.constructor:" + " cgs does not have a bibliography"); } } - public CitedKeys - getBibliography() { - if ( cgs.getBibliography().isEmpty() ) { + public CitedKeys getBibliography() { + if (cgs.getBibliography().isEmpty()) { throw new RuntimeException("ProduceCitationMarkersResult.getBibliography:" + " cgs does not have a bibliography"); } @@ -1652,10 +1530,10 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d CitationGroups cgs = new CitationGroups(documentConnection); - cgs.lookupEntriesInDatabases( databases ); + cgs.lookupEntriesInDatabases(databases); // requires cgs.lookupEntryInDatabases: needs BibEntry data - cgs.imposeLocalOrderByComparator( comparatorForMulticite(style) ); + cgs.imposeLocalOrderByComparator(comparatorForMulticite(style)); // Normally we sort the reference marks according to their // order of appearance. @@ -1672,16 +1550,14 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d // style.getIsNumberEntries() && !style.getIsSortByPosition() : ??? // produceCitationMarkersForNormalStyle : needs order-of-appearance for uniqueLetters // - { - boolean mapFootnotesToFootnoteMarks = true; - List sortedCitationGroupIDs = - cgs.getVisuallySortedCitationGroupIDs(documentConnection, - mapFootnotesToFootnoteMarks); - cgs.setGlobalOrder(sortedCitationGroupIDs); - } + boolean mapFootnotesToFootnoteMarks = true; + List sortedCitationGroupIDs = + cgs.getVisuallySortedCitationGroupIDs(documentConnection, + mapFootnotesToFootnoteMarks); + cgs.setGlobalOrder(sortedCitationGroupIDs); // localOrder and globalOrder together gives us order-of-appearance of citations - Map citMarkers; + Map citMarkers; // fill citMarkers Map uniqueLetters = new HashMap<>(); @@ -1709,39 +1585,6 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d * * **************************************************/ - /** - * Return bibliography entries sorted according to the order of - * first appearance in referenceMarkNames. - * - * @param referenceMarkNames Names of reference marks. - * @param citeKeyToBibEntry Helps to find the entries - * @return LinkedHashMap from BibEntry to BibDatabase with - * iteration order as first appearance in referenceMarkNames. - * - * Note: Within citation group (a reference mark) the order is - * as appears there. - * - * Used by rebuildBibTextSection - */ - private List - sortEntriesByRefMarkNames(CitationGroups cgs) { - Set seen = new HashSet<>(); - List res = new ArrayList<>(); - for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - List cits = cgs.getSortedCitations(cgid); - - // no need to look in the database again - for (Citation cit : cgs.getSortedCitations(cgid)) { - String key = cit.citationKey; - if (!seen.contains(key)) { - res.add(cit); - seen.add(key); - } - } - } - return res; - } - /** * Rebuilds the bibliography. * @@ -1774,9 +1617,9 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, * * @param documentConnection Connection. * @param cursor Where to - * @param entries Its iteration order defines order in bibliography. + * @param cgs + * @param bibliography * @param style Style. - * @param uniqueLetters * * Only called from populateBibTextSection (and that from rebuildBibTextSection) */ @@ -1805,10 +1648,10 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, if (debugThisFun) { System.out.printf("Ref cit %-20s ck.number %7s%n", - String.format("'%s'",ck.citationKey), + String.format("'%s'", ck.citationKey), (ck.number.isEmpty() ? "(empty)" - : String.format("%02d",ck.number.get()))); + : String.format("%02d", ck.number.get()))); } // this is where we create the paragraph. @@ -1819,21 +1662,20 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, DocumentConnection.setParagraphStyle(cursor, parStyle); } - } catch ( UndefinedParagraphFormatException ex ) { + } catch (UndefinedParagraphFormatException ex) { // TODO: precheck or remember if we already emitted this message. String message = String.format("Could not apply paragraph format '%s' to bibliography entry", parStyle); - // LOGGER.warn(message, ex); LOGGER.warn(message); // no stack trace } // insert marker "[1]" if (style.getIsNumberEntries()) { - if ( ck.number.isEmpty() ) { - throw new RuntimeException( - "insertFullReferenceAtCursor: numbered style, but found unnumbered entry"); + if (ck.number.isEmpty()) { + throw new RuntimeException("insertFullReferenceAtCursor:" + + " numbered style, but found unnumbered entry"); } int number = ck.number.get(); @@ -1845,21 +1687,22 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // TODO: We might want [citationKey] prefix for style.getBibTeXKeyCitations(); } - if ( ck.db.isEmpty() ) { + if (ck.db.isEmpty()) { // Unresolved entry String referenceDetails = String.format("Unresolved(%s)", ck.citationKey); OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, referenceDetails); cursor.collapseToEnd(); // Try to list citations: if (true) { - OOUtil.insertTextAtCurrentLocation( - documentConnection.xText, - cursor, - String.format(" (%s: ", Localization.lang("Cited on pages")), - Collections.emptyList()); + String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); + String suffix = ")"; + OOUtil.insertTextAtCurrentLocation(documentConnection.xText, + cursor, + prefix, + Collections.emptyList()); int last = ck.where.size(); - int i=0; + int i = 0; for (CitationPath p : ck.where) { CitationGroupID cgid = p.group; CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); @@ -1872,16 +1715,15 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, Collections.emptyList()); } documentConnection - .insertGetreferenceToPageNumberOfReferenceMark(refMarkName,cursor); + .insertGetreferenceToPageNumberOfReferenceMark(refMarkName, cursor); i++; } documentConnection.refresh(); - OOUtil.insertTextAtCurrentLocation( - documentConnection.xText, - cursor, - ")", - Collections.emptyList()); + OOUtil.insertTextAtCurrentLocation(documentConnection.xText, + cursor, + suffix, + Collections.emptyList()); } } else { @@ -1986,29 +1828,24 @@ private void populateBibTextSection(DocumentConnection documentConnection, IllegalArgumentException, CreationException { - XTextSection section = - documentConnection.getTextSectionByName(OOBibBase.BIB_SECTION_NAME); + XTextSection section = (documentConnection + .getTextSectionByName(OOBibBase.BIB_SECTION_NAME) + .orElseThrow(RuntimeException::new)); XTextCursor cursor = (documentConnection.xText .createTextCursorByRange(section.getAnchor())); - // emit header - /* - documentConnection.xText.insertString(cursor, - style.getReferenceHeaderText(), - true); - */ + // emit the title of the bibliography OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, style.getReferenceHeaderText()); String parStyle = style.getReferenceHeaderParagraphFormat(); try { if (parStyle != null) { DocumentConnection.setParagraphStyle(cursor, parStyle); } - } catch ( UndefinedParagraphFormatException ex ) { + } catch (UndefinedParagraphFormatException ex) { String message = String.format("Could not apply paragraph format '%s' to bibliography header", parStyle); - // LOGGER.warn(message, ex); LOGGER.warn(message); // No stack trace. } cursor.collapseToEnd(); @@ -2111,8 +1948,9 @@ public void combineCiteMarkers(List databases, for (CitationGroupID cgid : referenceMarkNames) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - XTextRange currentRange = cgs.getMarkRangeOrNull(documentConnection, cgid); - Objects.requireNonNull(currentRange); + XTextRange currentRange = (cgs + .getMarkRange(documentConnection, cgid) + .orElseThrow(RuntimeException::new)); boolean addToGroup = true; /* @@ -2142,19 +1980,20 @@ public void combineCiteMarkers(List databases, addToGroup = false; } else { - int textOrder = - DocumentConnection.javaCompareRegionStarts(prevRange, - currentRange); + int textOrder = DocumentConnection.javaCompareRegionStarts(prevRange, + currentRange); if (textOrder != (-1)) { - String msg = String.format( - "combineCiteMarkers:" - + " \"%s\" supposed to be followed by \"%s\", but %s", - prevRange.getString(), - currentRange.getString(), - ((textOrder == 0) - ? "they start at the same position" - : "the start of the latter precedes the start of the first")); + String msg = + String.format("combineCiteMarkers:" + + " \"%s\" supposed to be followed by \"%s\"," + + " but %s", + prevRange.getString(), + currentRange.getString(), + ((textOrder == 0) + ? "they start at the same position" + : ("the start of the latter precedes" + + " the start of the first"))); LOGGER.warn(msg); addToGroup = false; } @@ -2166,9 +2005,9 @@ public void combineCiteMarkers(List databases, // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() if (DocumentConnection .javaCompareRegionEnds(cursorBetween, currentGroupCursor) != 0) { - throw new RuntimeException( - "combineCiteMarkers:" - + " cursorBetween.end != currentGroupCursor.end"); + String msg = ("combineCiteMarkers:" + + " cursorBetween.end != currentGroupCursor.end"); + throw new RuntimeException(msg); } XTextRange rangeStart = currentRange.getStart(); @@ -2193,12 +2032,12 @@ public void combineCiteMarkers(List databases, || !thisChar.trim().isEmpty()) { couldExpand = false; } - if (DocumentConnection.javaCompareRegionEnds( - cursorBetween, currentGroupCursor) != 0) { - throw new RuntimeException( - "combineCiteMarkers:" - + " cursorBetween.end != currentGroupCursor.end" - + " (during expand)"); + if (DocumentConnection + .javaCompareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + String msg = ("combineCiteMarkers:" + + " cursorBetween.end != currentGroupCursor.end" + + " (during expand)"); + throw new RuntimeException(msg); } } // while @@ -2262,7 +2101,7 @@ public void combineCiteMarkers(List databases, * is now BEFORE currentGroupCursor (on * 2nd page). */ - throw new RuntimeException( + String msg = "combineCiteMarkers: " + "cursorBetween.end != currentGroupCursor.end" + String.format(" (after %s)", @@ -2278,7 +2117,8 @@ public void combineCiteMarkers(List databases, cursorBetween.getString(), currentRange.getString(), currentGroupCursor.getString()) - : "")); + : ""); + throw new RuntimeException(msg); } prev = cg; prevRange = currentRange; @@ -2327,7 +2167,7 @@ public void combineCiteMarkers(List databases, // Remove the old citation groups from the document. for (int gj = 0; gj < joinableGroup.size(); gj++) { - cgs.removeCitationGroups( joinableGroup, documentConnection ); + cgs.removeCitationGroups(joinableGroup, documentConnection); } XTextCursor textCursor = joinableGroupsCursors.get(gi); @@ -2344,16 +2184,16 @@ public void combineCiteMarkers(List databases, * be) */ boolean insertSpaceAfter = false; - insertReferenceMark(cgs, - documentConnection, - citationKeys, - pageInfosForCitations, - itcType, // OOBibBase.AUTHORYEAR_PAR - "tmp", - textCursor, - true, // withText - style, - insertSpaceAfter); + createAndFillCitationGroup(cgs, + documentConnection, + citationKeys, + pageInfosForCitations, + itcType, // OOBibBase.AUTHORYEAR_PAR + "tmp", + textCursor, + true, // withText + style, + insertSpaceAfter); } // for gi madeModifications = (joinableGroups.size() > 0); @@ -2438,7 +2278,9 @@ public void unCombineCiteMarkers(List databases, while (pivot < (names.size())) { CitationGroupID cgid = names.get(pivot); CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - XTextRange range1 = cgs.getMarkRangeOrNull(documentConnection,cgid); + XTextRange range1 = (cgs + .getMarkRange(documentConnection, cgid) + .orElseThrow(RuntimeException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); // If we are supposed to set character format for @@ -2454,8 +2296,8 @@ public void unCombineCiteMarkers(List databases, // Note: JabRef52 returns cg.pageInfo for the last citation. List pageInfosForCitations = cgs.backend.getPageInfosForCitations(cg); - List cits=cg.citations; - if ( cits.size() <= 1 ) { + List cits = cg.citations; + if (cits.size() <= 1) { pivot++; continue; } @@ -2463,30 +2305,30 @@ public void unCombineCiteMarkers(List databases, List keys = cits.stream().map(cit -> cit.citationKey).collect(Collectors.toList()); - cgs.removeCitationGroup( cg, documentConnection ); + cgs.removeCitationGroup(cg, documentConnection); // Now we own the content of cits // Insert mark for each key final int last = keys.size() - 1; for (int i = 0; i < keys.size(); i++) { - // Note: by using insertReferenceMark (and not something + // Note: by using createAndFillCitationGroup (and not something // that accepts List, we lose the extra // info stored in the citations. // We just reread below. boolean insertSpaceAfter = (i != last); - insertReferenceMark(cgs, - documentConnection, - keys.subList(i,i+1), //citationKeys, - pageInfosForCitations.subList(i,i+1), //pageInfos, - OOBibBase.AUTHORYEAR_PAR, // itcType, - "tmp", - textCursor, - true, /* withText. - * Should be itcType != OOBibBase.INVISIBLE_CIT */ - style, - insertSpaceAfter); + createAndFillCitationGroup(cgs, + documentConnection, + keys.subList(i, i + 1), // citationKeys, + pageInfosForCitations.subList(i, i + 1), // pageInfos, + OOBibBase.AUTHORYEAR_PAR, // itcType, + "tmp", + textCursor, + true, /* withText. + * Should be itcType != OOBibBase.INVISIBLE_CIT */ + style, + insertSpaceAfter); textCursor.collapseToEnd(); } @@ -2518,17 +2360,14 @@ public void unCombineCiteMarkers(List databases, } } - static class ExportCitedHelperResult { /** * null: not done; isempty: no unresolved */ List unresolvedKeys; BibDatabase newDatabase; - ExportCitedHelperResult( - List unresolvedKeys, - BibDatabase newDatabase - ) { + ExportCitedHelperResult(List unresolvedKeys, + BibDatabase newDatabase) { this.unresolvedKeys = unresolvedKeys; this.newDatabase = newDatabase; } @@ -2569,16 +2408,17 @@ public ExportCitedHelperResult exportCitedHelper(List databases, * Used from GUI: "Export cited" * * @param databases The databases to look up the citation keys in the document from. + * @param documentConnection * @return A new database, with cloned entries. * - * If a key is not found, it is silently ignored. + * If a key is not found, it is added to result.unresolvedKeys * * Cross references (in StandardField.CROSSREF) are followed (not recursively): * if the referenced entry is found, it is included in the result. * If it is not found, it is silently ignored. */ - private ExportCitedHelperResult // BibDatabase - generateDatabase(List databases, DocumentConnection documentConnection) + private ExportCitedHelperResult generateDatabase(List databases, + DocumentConnection documentConnection) throws NoSuchElementException, WrappedTargetException, @@ -2587,8 +2427,7 @@ public ExportCitedHelperResult exportCitedHelper(List databases, CitationGroups cgs = new CitationGroups(documentConnection); CitedKeys cks = cgs.getCitedKeys(); - cks.lookupInDatabases( databases ); - + cks.lookupInDatabases(databases); List unresolvedKeys = new ArrayList<>(); BibDatabase resultDatabase = new BibDatabase(); @@ -2597,7 +2436,7 @@ public ExportCitedHelperResult exportCitedHelper(List databases, Set seen = new HashSet<>(); // Only add crossReference once. for (CitedKey ck : cks.values()) { - if ( ck.db.isEmpty() ) { + if (ck.db.isEmpty()) { unresolvedKeys.add(ck.citationKey); continue; } else { @@ -2614,7 +2453,7 @@ public ExportCitedHelperResult exportCitedHelper(List databases, clonedEntry .getField(StandardField.CROSSREF) .ifPresent(crossReference -> { - boolean isNew = !seen.contains( crossReference ); + boolean isNew = !seen.contains(crossReference); if (isNew) { // Add it if it is in the current library loopDatabase @@ -2627,11 +2466,12 @@ public ExportCitedHelperResult exportCitedHelper(List databases, } resultDatabase.insertEntries(entriesToInsert); - return new ExportCitedHelperResult( unresolvedKeys, resultDatabase ); + return new ExportCitedHelperResult(unresolvedKeys, resultDatabase); } void styleIsRequired(OOBibStyle style) - throws JabRefException { + throws + JabRefException { if (style == null) { throw new JabRefException("This operation requires a style", Localization.lang("This operation requires a style.") @@ -2649,30 +2489,34 @@ public void checkParagraphStyleExistsInTheDocument(String styleName, NoSuchElementException, WrappedTargetException { - String internalName = documentConnection.getInternalNameOfParagraphStyleOrNull(styleName); - if (internalName == null) { - throw new JabRefException(Localization.lang( - "The %0 paragraph style '%1'" - + " is missing from the document", - labelInJstyleFile, - styleName) - + "\n" - + Localization.lang( - "Please create it in the document or change in the file:") - + "\n" + pathToStyleFile); + Optional internalName = documentConnection.getInternalNameOfParagraphStyle(styleName); + + if (internalName.isEmpty()) { + String msg = + Localization.lang("The %0 paragraph style '%1'" + + " is missing from the document", + labelInJstyleFile, + styleName) + + "\n" + + Localization.lang("Please create it in the document or change in the file:") + + "\n" + + pathToStyleFile; + throw new JabRefException(msg); } - if (!internalName.equals(styleName)) { - throw new JabRefException(Localization.lang( - "The %0 paragraph style '%1'" - + " is a display name for '%2'.", - labelInJstyleFile, - styleName, - internalName) - + "\n" - + Localization.lang( - "Please use the latter in the style file below" - + " to avoid localization problems.") - + "\n" + pathToStyleFile); + + if (!internalName.get().equals(styleName)) { + String msg = + Localization.lang("The %0 paragraph style '%1'" + + " is a display name for '%2'.", + labelInJstyleFile, + styleName, + internalName.get()) + + "\n" + + Localization.lang("Please use the latter in the style file below" + + " to avoid localization problems.") + + "\n" + + pathToStyleFile; + throw new JabRefException(msg); } } @@ -2685,34 +2529,38 @@ public void checkCharacterStyleExistsInTheDocument(String styleName, NoSuchElementException, WrappedTargetException { - String internalName = documentConnection.getInternalNameOfCharacterStyleOrNull(styleName); - if (internalName == null) { - throw new JabRefException(Localization.lang( - "The %0 character style '%1'" - + " is missing from the document", - labelInJstyleFile, - styleName) - + "\n" - + Localization.lang( - "Please create it in the document or change in the file:") - + "\n" + pathToStyleFile); + Optional internalName = (documentConnection + .getInternalNameOfCharacterStyle(styleName)); + + if (internalName.isEmpty()) { + String msg = + Localization.lang("The %0 character style '%1'" + + " is missing from the document", + labelInJstyleFile, + styleName) + + "\n" + + Localization.lang("Please create it in the document or change in the file:") + + "\n" + pathToStyleFile; + throw new JabRefException(msg); } - if (!internalName.equals(styleName)) { - throw new JabRefException(Localization.lang( - "The %0 character style '%1'" - + " is a display name for '%2'.", - labelInJstyleFile, - styleName, - internalName) - + "\n" - + Localization.lang( - "Please use the latter in the style file below" - + " to avoid localization problems.") - + "\n" + pathToStyleFile); + + if (!internalName.get().equals(styleName)) { + String msg = + Localization.lang("The %0 character style '%1'" + + " is a display name for '%2'.", + labelInJstyleFile, + styleName, + internalName.get()) + + "\n" + + Localization.lang("Please use the latter in the style file below" + + " to avoid localization problems.") + + "\n" + + pathToStyleFile; + throw new JabRefException(msg); } } - public void checkStylesExistInTheDocument( OOBibStyle style, DocumentConnection documentConnection ) + public void checkStylesExistInTheDocument(OOBibStyle style, DocumentConnection documentConnection) throws JabRefException, NoSuchElementException, diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index d4d716a5b7a..2bf60e5ce9d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -222,8 +222,7 @@ private void initPanel() { } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( Localization.lang("JabRefException"), - ex.getLocalizedMessage() - ); + ex.getLocalizedMessage()); } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); } catch (UndefinedParagraphFormatException ex) { @@ -269,8 +268,7 @@ private void initPanel() { } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( Localization.lang("JabRefException"), - ex.getLocalizedMessage() - ); + ex.getLocalizedMessage()); } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); } catch (NoDocumentException ex) { @@ -299,8 +297,7 @@ private void initPanel() { } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( Localization.lang("JabRefException"), - ex.getLocalizedMessage() - ); + ex.getLocalizedMessage()); } catch (NoDocumentException ex) { showNoDocumentErrorMessage(); } catch (UndefinedCharacterFormatException ex) { @@ -327,7 +324,7 @@ private void initPanel() { settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { - if ( ooBase.documentConnectionMissing() ){ + if (ooBase.documentConnectionMissing()) { showNoDocumentErrorMessage(); } else { dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); @@ -373,21 +370,19 @@ private void exportEntries() { style.ensureUpToDate(); } - List databases = getBaseList(); - if ( databases.isEmpty() ){ + if (databases.isEmpty()) { dialogService.showErrorDialogAndWait( Localization.lang("No database is open"), - Localization.lang("We need a database to export from. Open one.") - ); + Localization.lang("We need a database to export from. Open one.")); return; } - OOBibBase.ExportCitedHelperResult r = ooBase.exportCitedHelper( databases, style ); - if ( r.unresolvedKeys == null ){ + OOBibBase.ExportCitedHelperResult r = ooBase.exportCitedHelper(databases, style); + if (r.unresolvedKeys == null) { throw new RuntimeException("OpenOfficePanel.exportEntries: r.unresolvedKeys is null"); } - if ( r.newDatabase == null ){ + if (r.newDatabase == null) { throw new RuntimeException("OpenOfficePanel.exportEntries: r.newDatabase is null"); } if (!r.unresolvedKeys.isEmpty()) { @@ -587,20 +582,18 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP Localization.lang( "No bibliography database is open for citation.") + "\n" - + Localization.lang("Open one before citing.") - ); + + Localization.lang("Open one before citing.")); return; } List entries = libraryTab.getSelectedEntries(); - if (entries.isEmpty()){ + if (entries.isEmpty()) { dialogService.showErrorDialogAndWait( Localization.lang("No entries selected for citation"), Localization.lang( "No bibliography entries are selected for citation.") + "\n" - + Localization.lang("Select some before citing.") - ); + + Localization.lang("Select some before citing.")); return; } @@ -612,9 +605,7 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP Localization.lang( "No bibliography style is selected for citation.") + "\n" - + Localization.lang( - "Select one before citing.") - ); + + Localization.lang("Select one before citing.")); return; } } @@ -636,16 +627,14 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { try { - ooBase.insertCitation( - entries, - database, - getBaseList(), - style, - inParenthesis, - withText, - pageInfo, - ooPrefs.getSyncWhenCiting() - ); + ooBase.insertCitation(entries, + database, + getBaseList(), + style, + inParenthesis, + withText, + pageInfo, + ooPrefs.getSyncWhenCiting()); } catch (FileNotFoundException ex) { dialogService.showErrorDialogAndWait( @@ -664,8 +653,7 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( Localization.lang("JabRefException"), - ex.getLocalizedMessage() - ); + ex.getLocalizedMessage()); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | BibEntryNotFoundException | IllegalTypeException | PropertyExistException | @@ -750,9 +738,7 @@ private void reportUndefinedCharacterFormat(UndefinedCharacterFormatException ex dialogService.showErrorDialogAndWait(Localization.lang("Undefined character format"), Localization.lang("Your style file specifies the character format '%0', " + "which is undefined in your current OpenOffice/LibreOffice document.", - ex.getFormatName()) + "\n" + Localization.lang("The character format is controlled by the citation property 'CitationCharacterFormat' in the style file.") - - ); + ex.getFormatName()) + "\n" + Localization.lang("The character format is controlled by the citation property 'CitationCharacterFormat' in the style file.")); } private ContextMenu createSettingsPopup() { diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java index 0898ed223b4..09fa2d344a6 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java @@ -1,18 +1,19 @@ package org.jabref.gui.openoffice; import java.util.ArrayList; -//import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; - import java.util.TreeMap; + import com.sun.star.text.XText; import com.sun.star.text.XTextRange; /** - * Map XTextRange values to some value of type V. + * Purpose: in order to check overlaps of XTextRange values, sort + * them, and allow recovering some corresponding information + * (of type V) * * Since XTextRange values are only comparable if they share the same * r.getText(), we group them by these. @@ -21,61 +22,56 @@ * based on (r.getStart(),r.getEnd()), thus equality means identical * ranges. * - * For finding overlapping ranges we use RangeKeyedMapList, that - * allows a list of values to be associated with a single XTextRange. + * For finding overlapping ranges this class proved insufficient, + * beacause it does not allow multiple values to be associated with a + * single XTextRange. The class RangeKeyedMapList solves this. * */ class RangeKeyedMap { - Map> xxs; + private final Map> xxs; - public - RangeKeyedMap() { + public RangeKeyedMap() { this.xxs = new HashMap<>(); } - public boolean - containsKey(XTextRange r) { + public boolean containsKey(XTextRange r) { Objects.requireNonNull(r); XText partitionKey = r.getText(); - if ( !xxs.containsKey(partitionKey)) { + if (!xxs.containsKey(partitionKey)) { return false; } return xxs.get(partitionKey).containsKey(r); } - public V - get(XTextRange r) { - TreeMap xs = xxs.get(r.getText()); - if ( xs == null ){ + public V get(XTextRange r) { + TreeMap xs = xxs.get(r.getText()); + if (xs == null) { return null; } - return( xs.get(r) ); + return xs.get(r); } - private static int - comparator( XTextRange a, XTextRange b ) { - int startOrder = DocumentConnection.javaCompareRegionStarts( a, b ); - if ( startOrder != 0 ){ + private static int comparator(XTextRange a, XTextRange b) { + int startOrder = DocumentConnection.javaCompareRegionStarts(a, b); + if (startOrder != 0) { return startOrder; } - return DocumentConnection.javaCompareRegionEnds( a, b ); + return DocumentConnection.javaCompareRegionEnds(a, b); } - public V - put(XTextRange r, V value) { - TreeMap xs = xxs.get(r.getText()); - if ( xs == null ){ - xs = new TreeMap<>( RangeKeyedMap::comparator ); - xxs.put( r.getText(), xs ); + public V put(XTextRange r, V value) { + TreeMap xs = xxs.get(r.getText()); + if (xs == null) { + xs = new TreeMap<>(RangeKeyedMap::comparator); + xxs.put(r.getText(), xs); } - return xs.put( r, value ); + return xs.put(r, value); } /** * @return A list of the partitions. */ - public List> - partitionValues() { + public List> partitionValues() { return new ArrayList(xxs.values()); } } diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java index c0cb7aebf3d..ada90642611 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java @@ -1,11 +1,9 @@ package org.jabref.gui.openoffice; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.TreeMap; -import com.sun.star.text.XText; + import com.sun.star.text.XTextRange; class RangeKeyedMapList { @@ -25,10 +23,10 @@ public List get(XTextRange r) { public void add(XTextRange r, V value) { List vs = xxs.get(r); - if (vs == null){ + if (vs == null) { vs = new ArrayList<>(); vs.add(value); - xxs.put(r,vs); + xxs.put(r, vs); } else { vs.add(value); } @@ -37,7 +35,7 @@ public void add(XTextRange r, V value) { /** * @return A list of the partitions. */ - public List>> partitionValues() { + public List>> partitionValues() { return this.xxs.partitionValues(); } @@ -48,8 +46,8 @@ public List>> partitionValues() { */ public List flatListOfValues() { List result = new ArrayList<>(); - for (TreeMap> partition : partitionValues() ) { - for (List valuesUnderARange : partition.values() ) { + for (TreeMap> partition : partitionValues()) { + for (List valuesUnderARange : partition.values()) { result.addAll(valuesUnderARange); } } @@ -72,11 +70,11 @@ class RangeOverlap { OverlapKind kind; List vs; - public RangeOverlap( OverlapKind kind, List vs ) { + public RangeOverlap(OverlapKind kind, List vs) { this.kind = kind; this.vs = vs; } - }; + } /** * Report identical, overlapping or touching ranges. @@ -89,19 +87,14 @@ public RangeOverlap( OverlapKind kind, List vs ) { */ List findOverlappingRanges(int atMost, boolean includeTouching) { List res = new ArrayList<>(); - for (TreeMap> xs : xxs.partitionValues()) { + for (TreeMap> xs : xxs.partitionValues()) { List oxs = new ArrayList<>(xs.keySet()); for (int i = 0; i < oxs.size(); i++) { XTextRange a = oxs.get(i); List avs = xs.get(a); if (avs.size() > 1) { - res.add( - new RangeOverlap( - OverlapKind.EQUAL_RANGE, - avs - ) - ); - if ( atMost > 0 && res.size() >= atMost ) { + res.add(new RangeOverlap(OverlapKind.EQUAL_RANGE, avs)); + if (atMost > 0 && res.size() >= atMost) { return res; } } @@ -112,16 +105,12 @@ List findOverlappingRanges(int atMost, boolean includeTouching) { // found overlap or touch List bvs = xs.get(b); List vs = new ArrayList<>(); - vs.add( avs.get(0) ); - vs.add( bvs.get(0) ); - res.add( - new RangeOverlap( - (cmp == 0) ? OverlapKind.TOUCH : OverlapKind.OVERLAP, - vs - ) - ); + vs.add(avs.get(0)); + vs.add(bvs.get(0)); + res.add(new RangeOverlap((cmp == 0) ? OverlapKind.TOUCH : OverlapKind.OVERLAP, + vs)); } - if ( atMost > 0 && res.size() >= atMost ) { + if (atMost > 0 && res.size() >= atMost) { return res; } } diff --git a/src/main/java/org/jabref/gui/openoffice/RangeSort.java b/src/main/java/org/jabref/gui/openoffice/RangeSort.java index 29b91097d27..1821cd3ac44 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeSort.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeSort.java @@ -1,45 +1,6 @@ package org.jabref.gui.openoffice; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Collections; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import com.sun.star.awt.Point; -import com.sun.star.awt.Selection; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.lang.XServiceInfo; -import com.sun.star.text.XText; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextContent; import com.sun.star.text.XTextRange; -import com.sun.star.text.XTextRangeCompare; -import com.sun.star.text.XTextViewCursor; -import com.sun.star.text.XTextViewCursorSupplier; -import com.sun.star.util.InvalidStateException; - -// import org.jabref.logic.JabRefException; -// import org.jabref.model.database.BibDatabase; -// import org.jabref.model.entry.BibEntry; -// import org.slf4j.Logger; -// import org.slf4j.LoggerFactory; class RangeSort { @@ -52,7 +13,9 @@ class RangeSort { */ public interface RangeSortable { public XTextRange getRange(); + public int getIndexInPosition(); + public T getContent(); } @@ -64,11 +27,9 @@ public static class RangeSortEntry implements RangeSortable { public int indexInPosition; public T content; - RangeSortEntry( - XTextRange range, - int indexInPosition, - T content - ) { + RangeSortEntry(XTextRange range, + int indexInPosition, + T content) { this.range = range; this.indexInPosition = indexInPosition; this.content = content; diff --git a/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java index a3c6867bc62..f14fc69684d 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java @@ -2,43 +2,18 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Collections; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Objects; -import java.util.Optional; import java.util.Set; import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; + +import org.jabref.logic.JabRefException; import com.sun.star.awt.Point; -import com.sun.star.awt.Selection; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XServiceInfo; -import com.sun.star.text.XText; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextContent; import com.sun.star.text.XTextRange; -import com.sun.star.text.XTextRangeCompare; import com.sun.star.text.XTextViewCursor; -import com.sun.star.text.XTextViewCursorSupplier; -import com.sun.star.util.InvalidStateException; - -import org.jabref.logic.JabRefException; -import org.jabref.gui.openoffice.RangeSort; -// import org.jabref.model.database.BibDatabase; -// import org.jabref.model.entry.BibEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -56,8 +31,7 @@ */ class RangeSortVisual { - private static final Logger LOGGER = - LoggerFactory.getLogger(RangeSortVisual.class); + private static final Logger LOGGER = LoggerFactory.getLogger(RangeSortVisual.class); /* first appearance order, based on visual order */ @@ -81,8 +55,7 @@ class RangeSortVisual { * @param cursor To get the position, we need az XTextViewCursor. * It will be moved to the range. */ - private static Point - findPositionOfTextRange(XTextRange range, XTextViewCursor cursor) { + private static Point findPositionOfTextRange(XTextRange range, XTextViewCursor cursor) { cursor.gotoRange(range, false); return cursor.getPosition(); } @@ -133,8 +106,7 @@ public boolean equals(Object o) { return ((this.position.X == other.position.X) && (this.position.Y == other.position.Y) && (this.indexInPosition == other.indexInPosition) - && Objects.equals(this.content, other.content) - ); + && Objects.equals(this.content, other.content)); } return false; } @@ -149,7 +121,6 @@ public int hashCode() { } } - /** * Sort its input {@code vses} visually. * @@ -176,21 +147,10 @@ public int hashCode() { final int inputSize = vses.size(); - // if ( messageOnFailureToObtainAFunctionalXTextViewCursor == null ) { - // messageOnFailureToObtainAFunctionalXTextViewCursor = - // Localization.lang("Please move the cursor into the document text.") - // + "\n" - // + Localization.lang("To get the visual positions of your citations" - // + " I need to move the cursor around," - // + " but could not get it."); - // } - if (documentConnection.hasControllersLocked()) { - LOGGER.warn( - "visualSort:" - + " with ControllersLocked, viewCursor.gotoRange" - + " is probably useless" - ); + LOGGER.warn("visualSort:" + + " with ControllersLocked, viewCursor.gotoRange" + + " is probably useless"); } /* @@ -222,7 +182,7 @@ public int hashCode() { */ final boolean debugThisFun = false; - XServiceInfo initialSelection = documentConnection.getSelectionAsServiceInfo(); + XServiceInfo initialSelection = documentConnection.getSelectionAsServiceInfo().orElse(null); if (initialSelection != null) { if (Arrays.stream(initialSelection.getSupportedServiceNames()) @@ -237,33 +197,20 @@ public int hashCode() { + " We need to change the viewCursor."); } XTextRange newSelection = documentConnection.xText.getStart(); - documentConnection.select( newSelection ); + documentConnection.select(newSelection); } } else { if (debugThisFun) { LOGGER.info("visualSort: initialSelection is null: no idea what to do."); } - /* - * XTextRange newSelection = documentConnection.xText.getStart(); - * boolean res = documentConnection.select( newSelection ); - * XServiceInfo sel2 = documentConnection.getSelectionAsServiceInfo(); - * LOGGER.info( - * String.format("visualSort: initialSelection is null: result of select: %s, isNull: %s%n", - * res, - * sel2 == null)); - * // ^^^ prints true, true - */ } - XTextViewCursor viewCursor = documentConnection.getViewCursor(); Objects.requireNonNull(viewCursor); try { viewCursor.getStart(); } catch (com.sun.star.uno.RuntimeException ex) { - throw new JabRefException( - messageOnFailureToObtainAFunctionalXTextViewCursor, - ex); + throw new JabRefException(messageOnFailureToObtainAFunctionalXTextViewCursor, ex); } // find coordinates @@ -281,23 +228,19 @@ public int hashCode() { documentConnection.select(initialSelection); } - if ( positions.size() != inputSize ) { + if (positions.size() != inputSize) { throw new RuntimeException("visualSort: positions.size() != inputSize"); } // order by position Set>> set = new TreeSet<>(); for (int i = 0; i < vses.size(); i++) { - set.add( - new ComparableMark<>( - positions.get(i), - vses.get(i).getIndexInPosition(), - vses.get(i) - ) - ); + set.add(new ComparableMark<>(positions.get(i), + vses.get(i).getIndexInPosition(), + vses.get(i))); } - if ( set.size() != inputSize ) { + if (set.size() != inputSize) { throw new RuntimeException("visualSort: set.size() != inputSize"); } @@ -307,7 +250,7 @@ public int hashCode() { result.add(mark.getContent()); } - if ( result.size() != inputSize ) { + if (result.size() != inputSize) { throw new RuntimeException("visualSort: result.size() != inputSize"); } diff --git a/src/main/java/org/jabref/gui/openoffice/StorageBase.java b/src/main/java/org/jabref/gui/openoffice/StorageBase.java index 4a97c0e846b..cdb4ae31a87 100644 --- a/src/main/java/org/jabref/gui/openoffice/StorageBase.java +++ b/src/main/java/org/jabref/gui/openoffice/StorageBase.java @@ -1,42 +1,12 @@ package org.jabref.gui.openoffice; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; -import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; -//import org.jabref.gui.openoffice.CitationSort; -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; - -import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XText; -import com.sun.star.text.XTextContent; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextRange; -import com.sun.star.uno.UnoRuntime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - class StorageBase { @@ -47,9 +17,9 @@ interface HasName { interface HasTextRange { /** - * @return Null if the mark is missing from the document. + * @return Optional.empty if the mark is missing from the document. */ - public XTextRange getMarkRangeOrNull(DocumentConnection documentConnection) + public Optional getMarkRange(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException; @@ -58,7 +28,7 @@ public XTextRange getMarkRangeOrNull(DocumentConnection documentConnection) * Cursor for the reference marks as is, not prepared for filling, * but does not need cleanFillCursorForCitationGroup either. */ - public XTextCursor getRawCursor(DocumentConnection documentConnection) + public Optional getRawCursor(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException, @@ -79,14 +49,12 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) * Remove brackets, but if the result would become empty, leave * them; if the result would be a single characer, leave the left bracket. * - * @param removeBracketsFromEmpty is intended to force removal if - * we are working on an "Empty citation" (INVISIBLE_CIT). */ public void cleanFillCursor(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException, - CreationException ; + CreationException; /** * Note: create is in NamedRangeManager @@ -103,11 +71,11 @@ interface NamedRange extends HasName, HasTextRange { } interface NamedRangeManager { - public NamedRange create( DocumentConnection documentConnection, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets ) + public NamedRange create(DocumentConnection documentConnection, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException; @@ -115,10 +83,10 @@ public List getUsedNames(DocumentConnection documentConnection) throws NoDocumentException; - public NamedRange getFromDocumentOrNull(DocumentConnection documentConnection, - String refMarkName) + public Optional getFromDocument(DocumentConnection documentConnection, + String refMarkName) throws NoDocumentException, - WrappedTargetException ; + WrappedTargetException; } } diff --git a/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java index 254fc367bea..c069a47abf0 100644 --- a/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java @@ -1,43 +1,17 @@ package org.jabref.gui.openoffice; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; -import java.util.Map; -import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -//import org.jabref.gui.openoffice.CitationSort; -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; - -import com.sun.star.beans.UnknownPropertyException; + import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XFootnote; import com.sun.star.text.XText; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextRange; -import com.sun.star.uno.UnoRuntime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - class StorageBaseRefMark implements StorageBase.NamedRange { private static final String ZERO_WIDTH_SPACE = "\u200b"; @@ -52,16 +26,17 @@ class StorageBaseRefMark implements StorageBase.NamedRange { public static final String REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; - private static final Logger LOGGER = - LoggerFactory.getLogger(StorageBaseRefMark.class); + private static final Logger LOGGER = LoggerFactory.getLogger(StorageBaseRefMark.class); private String id; /* reference mark name */ - private StorageBaseRefMark( String id ) { + private StorageBaseRefMark(String id) { this.id = id; } - String getId(){ return id; } + String getId() { + return id; + } /** * Insert {@code n} spaces in a way that reference @@ -126,10 +101,9 @@ private static void createReprInDocument(DocumentConnection documentConnection, ? "" : left + right); - cursor.getText().insertString( - cursor, - bracketedContent, - true); + cursor.getText().insertString(cursor, + bracketedContent, + true); documentConnection.insertReferenceMark(refMarkName, cursor, @@ -155,20 +129,19 @@ private static StorageBaseRefMark create(DocumentConnection documentConnection, position, insertSpaceAfter, withoutBrackets); - return new StorageBaseRefMark( refMarkName ); + return new StorageBaseRefMark(refMarkName); } - private static StorageBaseRefMark getFromDocumentOrNull(DocumentConnection documentConnection, - String refMarkName) + /** + * @return Optional.empty if there is no corresponding range. + */ + private static Optional getFromDocument(DocumentConnection documentConnection, + String refMarkName) throws NoDocumentException, WrappedTargetException { - XTextRange r = documentConnection.getReferenceMarkRangeOrNull(refMarkName); - if (r == null) { - return null; - } else { - return new StorageBaseRefMark( refMarkName ); - } + return (documentConnection.getReferenceMarkRange(refMarkName) + .map(e -> new StorageBaseRefMark(refMarkName))); } /* @@ -185,24 +158,25 @@ public void removeFromDocument(DocumentConnection documentConnection) documentConnection.removeReferenceMark(this.getName()); } - @Override - public String getName(){ return id; } + public String getName() { + return id; + } /* * ranges controlled by citation groups should not overlap with each other. * - * @return Null if the reference mark is missing. + * @return Optional.empty if the reference mark is missing. * - * See: getReferenceMarkRangeOrNull + * See: getReferenceMarkRange */ @Override - public XTextRange getMarkRangeOrNull(DocumentConnection documentConnection) + public Optional getMarkRange(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException { String name = this.getName(); - return documentConnection.getReferenceMarkRangeOrNull(name); + return documentConnection.getReferenceMarkRange(name); } /** @@ -210,12 +184,12 @@ public XTextRange getMarkRangeOrNull(DocumentConnection documentConnection) * but does not need cleanFillCursorForCitationGroup either. * * @return null if reference mark is missing from the document, - * otherwise an XTextCursor for getMarkRangeOrNull + * otherwise an XTextCursor for getMarkRange * * See: getRawCursorForCitationGroup */ @Override - public XTextCursor getRawCursor(DocumentConnection documentConnection) + public Optional getRawCursor(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException, @@ -224,21 +198,21 @@ public XTextCursor getRawCursor(DocumentConnection documentConnection) String name = this.getName(); XTextCursor full = null; - XTextContent markAsTextContent = - documentConnection.getReferenceMarkAsTextContentOrNull(name); + Optional markAsTextContent = (documentConnection + .getReferenceMarkAsTextContent(name)); - if (markAsTextContent == null) { - throw new RuntimeException( - String.format( - "getRawCursor: markAsTextContent(%s) == null", - name)); + if (markAsTextContent.isEmpty()) { + String msg = String.format("getRawCursor: markAsTextContent(%s).isEmpty()", name); + LOGGER.warn(msg); } - full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); + full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent.get()); if (full == null) { - throw new RuntimeException("getRawCursor: full == null"); + String msg = "getRawCursor: full == null"; + LOGGER.warn(msg); + return Optional.empty(); } - return full; + return Optional.ofNullable(full); } /** @@ -263,20 +237,20 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) String fullText = null; for (int i = 1; i <= 2; i++) { XTextContent markAsTextContent = - documentConnection.getReferenceMarkAsTextContentOrNull(name); + documentConnection.getReferenceMarkAsTextContent(name).orElse(null); if (markAsTextContent == null) { - throw new RuntimeException( - String.format("getFillCursor:" - + " markAsTextContent(%s) == null (attempt %d)", - name, - i)); + String msg = String.format("getFillCursor:" + + " markAsTextContent(%s) == null (attempt %d)", + name, + i); + throw new RuntimeException(msg); } full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); if (full == null) { - throw new RuntimeException( - String.format("getFillCursor: full == null (attempt %d)", i)); + String msg = String.format("getFillCursor: full == null (attempt %d)", i); + throw new RuntimeException(msg); } fullText = full.getString(); @@ -290,10 +264,10 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) } else { // (fullText.length() < 2) if (i == 2) { - throw new RuntimeException( - String.format("getFillCursor:" - + " (fullText.length() < 2) (attempt %d)", - i)); + String msg = String.format("getFillCursor:" + + " (fullText.length() < 2) (attempt %d)", + i); + throw new RuntimeException(msg); } // too short, recreate if (debugThisFun) { @@ -303,17 +277,16 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) try { documentConnection.removeReferenceMark(name); } catch (NoSuchElementException ex) { - LOGGER.warn( - String.format("getFillCursor got NoSuchElementException" - + " for '%s'", - name)); + String msg = String.format("getFillCursor got NoSuchElementException" + + " for '%s'", + name); + LOGGER.warn(msg); } - createReprInDocument( - documentConnection, - name, - full, - false, /* insertSpaceAfter */ - false /* withoutBrackets */); + createReprInDocument(documentConnection, + name, + full, + false, /* insertSpaceAfter */ + false /* withoutBrackets */); } } @@ -372,11 +345,9 @@ public void cleanFillCursor(DocumentConnection documentConnection) final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); - // CitationGroupsV001 cgs = this; - // String name = cgs.getReferenceMarkName(cgid).orElseThrow(RuntimeException::new); String name = this.getName(); - XTextCursor full = this.getRawCursor(documentConnection); + XTextCursor full = this.getRawCursor(documentConnection).orElseThrow(RuntimeException::new); final String fullText = full.getString(); final int fullTextLength = fullText.length(); @@ -391,24 +362,23 @@ public void cleanFillCursor(DocumentConnection documentConnection) omega.collapseToEnd(); if (!fullText.startsWith(left)) { - throw new RuntimeException( - String.format("cleanFillCursor:" - + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", - name)); + String msg = String.format("cleanFillCursor:" + + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", + name); + throw new RuntimeException(msg); } if (!fullText.endsWith(right)) { - throw new RuntimeException( - String.format("cleanFillCursor:" - + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", - name)); + String msg = String.format("cleanFillCursor:" + + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", + name); + throw new RuntimeException(msg); } final int contentLength = (fullTextLength - (leftLength + rightLength)); if (contentLength < 0) { - throw new RuntimeException( - String.format("cleanFillCursor: length(%s) < 0", - name)); + String msg = String.format("cleanFillCursor: length(%s) < 0", name); + throw new RuntimeException(msg); } boolean removeRight = ((contentLength >= 1) @@ -438,11 +408,11 @@ private static List getUsedNames(DocumentConnection documentConnection) public static class Manager implements StorageBase.NamedRangeManager { @Override - public StorageBase.NamedRange create( DocumentConnection documentConnection, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets ) + public StorageBase.NamedRange create(DocumentConnection documentConnection, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException { return StorageBaseRefMark.create(documentConnection, @@ -460,12 +430,14 @@ public List getUsedNames(DocumentConnection documentConnection) } @Override - public StorageBase.NamedRange getFromDocumentOrNull(DocumentConnection documentConnection, - String refMarkName) + public Optional getFromDocument(DocumentConnection documentConnection, + String refMarkName) throws NoDocumentException, WrappedTargetException { - return StorageBaseRefMark.getFromDocumentOrNull(documentConnection, refMarkName); + return (StorageBaseRefMark + .getFromDocument(documentConnection, refMarkName) + .map(x -> x)); } } } diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java index 45fc2630879..a8f9d3a639b 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java @@ -68,7 +68,7 @@ public void addStyleFile() { Optional path = dialogService.showFileOpenDialog(fileDialogConfiguration); path.map(Path::toAbsolutePath).map(Path::toString).ifPresent(stylePath -> { OOBibStyleParser.ParseLog parseLog = loader.addStyleIfValid(stylePath); - if ( !parseLog.hasError() ) { + if (!parseLog.hasError()) { preferences.setCurrentStyle(stylePath); styles.setAll(loadStyles()); selectedItem.setValue(getStyleOrDefault(stylePath)); @@ -77,12 +77,11 @@ public void addStyleFile() { parseLog.formatShort()); } } else { - dialogService.showErrorDialogAndWait( - Localization.lang("Invalid style selected"), - Localization.lang("You must select a valid style file.") - + "\n" - + parseLog.formatShort() - ); + String title = Localization.lang("Invalid style selected"); + String msg = (Localization.lang("You must select a valid style file.") + + "\n" + + parseLog.formatShort()); + dialogService.showErrorDialogAndWait(title, msg); } }); } diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java index 3d5e8f14ab6..f6b6ce64475 100644 --- a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java @@ -1,5 +1,7 @@ package org.jabref.logic.openoffice; +import java.util.Optional; + import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; @@ -7,12 +9,6 @@ * This is what we need for getCitationMarker to produce author-year * citation markers. * - * Details of BibEntry are accessed via getBibEntryOrNull() - * - * org/jabref/gui/openoffice.Citation and org/jabref/gui/openoffice.CitedKey - * - * are used as actual sources. - * * Citation misses two things * - isFirstAppearanceOfSource : could be extended to provide this. * - pageInfo under DataModel JabRef52 needs CitationGroup @@ -25,8 +21,8 @@ public interface CitationMarkerEntry { /** Citation key. This is what we usually get from the document. * - * Used if getBibEntryOrNull() and/or getDatabaseOrNull() returns - * null, which indicates failure to lookup in the databases. + * Used if getBibEntry() and/or getDatabase() returns + * empty, which indicates failure to lookup in the databases. * The marker created is "Unresolved({citationKey})". * */ @@ -34,27 +30,27 @@ public interface CitationMarkerEntry { /** Bibliography entry looked up from databases. * - * May be null if not found. In this case getDatabaseOrNull() - * should also return null. + * May be empty if not found. In this case getDatabase() + * should also return empty. */ - BibEntry getBibEntryOrNull(); + Optional getBibEntry(); /** * The database where BibEntry was found. - * May be null, if not found (otherwise not). + * May be empty, if not found (otherwise not). */ - BibDatabase getDatabaseOrNull(); + Optional getDatabase(); /** * uniqueLetter or null if not needed. */ - String getUniqueLetterOrNull(); + Optional getUniqueLetter(); /** * pageInfo for this citation, provided by the user. - * May be null, for none. + * May be empty, for none. */ - String getPageInfoOrNull(); + Optional getPageInfo(); /** * @return true if this citation is the first appearance of the diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java index 986880760cc..e172d8f5614 100644 --- a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java +++ b/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java @@ -1,5 +1,8 @@ package org.jabref.logic.openoffice; +import java.util.Objects; +import java.util.Optional; + import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; @@ -11,27 +14,58 @@ */ public class CitationMarkerEntryImpl implements CitationMarkerEntry { final String citationKey; - final BibEntry bibEntry; - final BibDatabase database; - final String uniqueLetter; - final String pageInfo; + final Optional bibEntry; + final Optional database; + final Optional uniqueLetter; + final Optional pageInfo; final boolean isFirstAppearanceOfSource; public CitationMarkerEntryImpl(String citationKey, - BibEntry bibEntry, - BibDatabase database, - String uniqueLetter, - String pageInfo, + Optional bibEntry, + Optional database, + Optional uniqueLetter, + Optional pageInfo, + boolean isFirstAppearanceOfSource) { + Objects.requireNonNull(citationKey); + this.citationKey = citationKey; + + if (bibEntry.isEmpty() && database.isPresent()) { + throw new RuntimeException("CitationMarkerEntryImpl:" + + " bibEntry is present, but database is not"); + } + + if (bibEntry.isPresent() && database.isEmpty()) { + throw new RuntimeException("CitationMarkerEntryImpl:" + + " bibEntry missing, but database is present"); + } + + this.bibEntry = bibEntry; + this.database = database; + this.uniqueLetter = uniqueLetter; + this.pageInfo = pageInfo; + this.isFirstAppearanceOfSource = isFirstAppearanceOfSource; + } + + public CitationMarkerEntryImpl(String citationKey, + BibEntry bibEntryQ, + BibDatabase databaseQ, + String uniqueLetterQ, + String pageInfoQ, boolean isFirstAppearanceOfSource) { + Objects.requireNonNull(citationKey); this.citationKey = citationKey; + Optional bibEntry = Optional.ofNullable(bibEntryQ); + Optional database = Optional.ofNullable(databaseQ); + Optional uniqueLetter = Optional.ofNullable(uniqueLetterQ); + Optional pageInfo = Optional.ofNullable(pageInfoQ); - if (bibEntry == null && database != null) { + if (bibEntry.isEmpty() && database.isPresent()) { throw new RuntimeException("CitationMarkerEntryImpl:" - + " bibEntry == null, but database != null"); + + " bibEntry is present, but database is not"); } - if (bibEntry != null && database == null) { + if (bibEntry.isPresent() && database.isEmpty()) { throw new RuntimeException("CitationMarkerEntryImpl:" - + " bibEntry != null, but database == null"); + + " bibEntry missing, but database is present"); } this.bibEntry = bibEntry; @@ -47,22 +81,22 @@ public String getCitationKey() { } @Override - public BibEntry getBibEntryOrNull() { + public Optional getBibEntry() { return bibEntry; } @Override - public BibDatabase getDatabaseOrNull() { + public Optional getDatabase() { return database; } @Override - public String getUniqueLetterOrNull() { + public Optional getUniqueLetter() { return uniqueLetter; } @Override - public String getPageInfoOrNull() { + public Optional getPageInfo() { return pageInfo; } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 68d27487263..7d799e95cb4 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -108,10 +108,10 @@ public class OOBibStyle implements Comparable { private static final String AUTHORS_PART_MARKUP_AFTER = "AuthorsPartMarkupAfter"; private static final String AUTHOR_NAMES_LIST_MARKUP_BEFORE = "AuthorNamesListMarkupBefore"; - private static final String AUTHOR_NAMES_LIST_MARKUP_AFTER = "AuthorNamesListMarkupAfter"; + private static final String AUTHOR_NAMES_LIST_MARKUP_AFTER = "AuthorNamesListMarkupAfter"; private static final String AUTHOR_NAME_MARKUP_BEFORE = "AuthorNameMarkupBefore"; - private static final String AUTHOR_NAME_MARKUP_AFTER = "AuthorNameMarkupAfter"; + private static final String AUTHOR_NAME_MARKUP_AFTER = "AuthorNameMarkupAfter"; /* * common (numeric and author-year) @@ -277,7 +277,6 @@ private void setDefaultProperties() { obsProperties.put(IS_NUMBER_ENTRIES, Boolean.FALSE); obsProperties.put(IS_SORT_BY_POSITION, Boolean.FALSE); - // Set default obsCitProperties for the citation marker: /* @@ -287,7 +286,6 @@ private void setDefaultProperties() { // was "Default", but that is not knowm to LO obsCitProperties.put(CITATION_CHARACTER_FORMAT, "Standard"); - obsCitProperties.put(CITATION_GROUP_MARKUP_BEFORE, ""); obsCitProperties.put(CITATION_GROUP_MARKUP_AFTER, ""); @@ -322,7 +320,7 @@ private void setDefaultProperties() { obsCitProperties.put(MINIMUM_GROUPING_COUNT, 3); obsCitProperties.put(MULTI_CITE_CHRONOLOGICAL, Boolean.TRUE); - obsCitProperties.put(BIBTEX_KEY_CITATIONS, Boolean.FALSE); //"BibTeXKeyCitations" + obsCitProperties.put(BIBTEX_KEY_CITATIONS, Boolean.FALSE); // "BibTeXKeyCitations" obsCitProperties.put(OXFORD_COMMA, ""); // Obsolete, keep for backward compat. @@ -357,7 +355,6 @@ public Set getJournals() { private void initialize(InputStream stream, String filename) throws IOException { Objects.requireNonNull(stream); - // remove data from a previous parse localCopy = null; obsName = ""; @@ -556,8 +553,8 @@ public enum NonUniqueCitationMarker { * Format the marker for an the in-text citation according to * this style. * - * Uniquefier letters are added as provided by the - * CitationMarkerEntry.getUniqueLetterOrNull(). + * Uniquefier letters are added as provided by + * CitationMarkerEntry.getUniqueLetter(). * * If successive entries within the citation are uniquefied from * each other, this method will perform a grouping of these @@ -608,8 +605,9 @@ public int compareTo(OOBibStyle other) { } private String nullToEmpty(String s) { - return ( s == null ? "" : s ); + return (s == null ? "" : s); } + @Override public boolean equals(Object o) { if (this == o) { @@ -741,6 +739,7 @@ public String getCitationCharacterFormat() { public String getCitationGroupMarkupBefore() { return getStringCitProperty(CITATION_GROUP_MARKUP_BEFORE); } + public String getCitationGroupMarkupAfter() { return getStringCitProperty(CITATION_GROUP_MARKUP_AFTER); } @@ -749,6 +748,7 @@ public String getCitationGroupMarkupAfter() { public String getAuthorsPartMarkupBefore() { return getStringCitProperty(AUTHORS_PART_MARKUP_BEFORE); } + public String getAuthorsPartMarkupAfter() { return getStringCitProperty(AUTHORS_PART_MARKUP_AFTER); } @@ -757,6 +757,7 @@ public String getAuthorsPartMarkupAfter() { public String getAuthorNamesListMarkupBefore() { return getStringCitProperty(AUTHOR_NAMES_LIST_MARKUP_BEFORE); } + public String getAuthorNamesListMarkupAfter() { return getStringCitProperty(AUTHOR_NAMES_LIST_MARKUP_AFTER); } @@ -765,6 +766,7 @@ public String getAuthorNamesListMarkupAfter() { public String getAuthorNameMarkupBefore() { return getStringCitProperty(AUTHOR_NAME_MARKUP_BEFORE); } + public String getAuthorNameMarkupAfter() { return getStringCitProperty(AUTHOR_NAME_MARKUP_AFTER); } @@ -812,10 +814,9 @@ protected String getAuthorLastSeparator() { /* As getAuthorLastSeparator, for in-text citation. */ protected String getAuthorLastSeparatorInTextWithFallBack() { - return Objects.requireNonNullElse( - getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT), - // Use the default one if no explicit separator for text is defined - getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR)); + String a = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT); + String b = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); + return Objects.requireNonNullElse(a, b); } protected String getPageInfoSeparator() { diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index 767c70ffd15..c54c5f423ac 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -189,7 +189,7 @@ private static String formatAuthorList(OOBibStyle style, sb.append(style.getAuthorNamesListMarkupAfter()); } - if (nAuthors >= 2 && !emitAllAuthors ) { + if (nAuthors >= 2 && !emitAllAuthors) { sb.append(etAlString); } @@ -323,8 +323,8 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, ? style.getMaxAuthorsFirst() : style.getMaxAuthors()); - BibEntry bibEntry = ce.getBibEntryOrNull(); - BibDatabase database = ce.getDatabaseOrNull(); + BibEntry bibEntry = ce.getBibEntry().orElse(null); + BibDatabase database = ce.getDatabase().orElse(null); boolean isUnresolved = (bibEntry == null) || (database == null); if (isUnresolved) { return 0; @@ -358,8 +358,8 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, * omitting them from the list. * * Unresolved citations recognized by - * ce.getBibEntryOrNull() and/or - * ce.getDatabaseOrNull() returning null, and + * ce.getBibEntry() and/or + * ce.getDatabase() returning empty, and * emitted as "Unresolved${citationKey}". * * Neither uniqueLetter nor pageInfo are emitted @@ -424,7 +424,7 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, if (!startingNewGroup) { // Just add our uniqueLetter - String uniqueLetter = ce.getUniqueLetterOrNull(); + String uniqueLetter = ce.getUniqueLetter().orElse(null); if (uniqueLetter != null) { sb.append(uniquefierSeparator); sb.append(uniqueLetter); @@ -441,8 +441,8 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, sb.append(citationSeparator); } - BibDatabase currentDatabase = ce.getDatabaseOrNull(); - BibEntry currentEntry = ce.getBibEntryOrNull(); + BibDatabase currentDatabase = ce.getDatabase().orElse(null); + BibEntry currentEntry = ce.getBibEntry().orElse(null); boolean isUnresolved = (currentEntry == null) || (currentDatabase == null); @@ -478,12 +478,12 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, } if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { - String uniqueLetter = ce.getUniqueLetterOrNull(); + String uniqueLetter = ce.getUniqueLetter().orElse(null); if (uniqueLetter != null) { sb.append(uniqueLetter); } - String pageInfo = OOBibStyle.regularizePageInfo(ce.getPageInfoOrNull()); + String pageInfo = OOBibStyle.regularizePageInfo(ce.getPageInfo().orElse(null)); if (pageInfo != null) { sb.append(pageInfoSeparator); sb.append(pageInfo); @@ -619,11 +619,11 @@ public static String getNormalizedCitationMarker(OOBibStyle style, String nm1 = normalizedMarkers.get(i - 1); String nm2 = normalizedMarkers.get(i); - BibEntry bibEntry1 = ce1.getBibEntryOrNull(); - BibEntry bibEntry2 = ce2.getBibEntryOrNull(); + BibEntry bibEntry1 = ce1.getBibEntry().orElse(null); + BibEntry bibEntry2 = ce2.getBibEntry().orElse(null); - BibDatabase database1 = ce1.getDatabaseOrNull(); - BibDatabase database2 = ce2.getDatabaseOrNull(); + BibDatabase database1 = ce1.getDatabase().orElse(null); + BibDatabase database2 = ce2.getDatabase().orElse(null); boolean isUnresolved1 = (bibEntry1 == null) || (database1 == null); boolean isUnresolved2 = (bibEntry2 == null) || (database2 == null); @@ -674,11 +674,13 @@ public static String getNormalizedCitationMarker(OOBibStyle style, } } - String pi2 = nullToEmptyString(OOBibStyle.regularizePageInfo(ce2.getPageInfoOrNull())); - String pi1 = nullToEmptyString(OOBibStyle.regularizePageInfo(ce1.getPageInfoOrNull())); + String pi2 = + nullToEmptyString(OOBibStyle.regularizePageInfo(ce2.getPageInfo().orElse(null))); + String pi1 = + nullToEmptyString(OOBibStyle.regularizePageInfo(ce1.getPageInfo().orElse(null))); - String ul2 = ce2.getUniqueLetterOrNull(); - String ul1 = ce1.getUniqueLetterOrNull(); + String ul2 = ce2.getUniqueLetter().orElse(null); + String ul1 = ce1.getUniqueLetter().orElse(null); boolean uniqueLetterPresenceChanged = (ul2 == null) != (ul1 == null); @@ -706,12 +708,11 @@ public static String getNormalizedCitationMarker(OOBibStyle style, } boolean normalizedMarkerChanged = !nm2.equals(nm1); - startingNewGroup = ( - normalizedMarkerChanged - || firstAppearanceInhibitsJoin - || pageInfoInhibitsJoin - || uniqueLetterPresenceChanged - || uniqueLetterDoesNotMakeUnique); + startingNewGroup = (normalizedMarkerChanged + || firstAppearanceInhibitsJoin + || pageInfoInhibitsJoin + || uniqueLetterPresenceChanged + || uniqueLetterDoesNotMakeUnique); if (!startingNewGroup) { // inherit from first of group. Used at next i. diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java index 0749a747b78..e23d0c569b7 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java @@ -149,10 +149,9 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, // If (purpose==BIBLIOGRAPHY), then // we expect exactly one number here, and can handle quickly if (nCitations != 1) { - throw new RuntimeException( - "getNumCitationMarker:" - + "nCitations != 1 for purpose==BIBLIOGRAPHY." - + String.format(" nCitations = %d", nCitations)); + throw new RuntimeException("getNumCitationMarker:" + + "nCitations != 1 for purpose==BIBLIOGRAPHY." + + String.format(" nCitations = %d", nCitations)); } // StringBuilder sb = new StringBuilder(); @@ -181,11 +180,10 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, * pageInfos with null values. */ List pageInfos = - OOBibStyle.regularizePageInfosForCitations( - (purpose == CitationMarkerPurpose.BIBLIOGRAPHY - ? null - : pageInfosForCitations), - numbers.size()); + OOBibStyle.regularizePageInfosForCitations((purpose == CitationMarkerPurpose.BIBLIOGRAPHY + ? null + : pageInfosForCitations), + numbers.size()); // Sort the numbers, together with the corresponding pageInfo values List nps = new ArrayList<>(); diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java index 70fadc6d96b..6195fe4d814 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -9,7 +9,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.SortedSet; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -52,19 +51,20 @@ public class OOBibStyleParser { /* * Keys in the PROPERTIES section that we warn about. */ - private static final Map PROPERTY_WARNINGS = Map.of( - // Appeared in setDefaultProperties, otherwise unknown. - "SortAlgorithm", "SortAlgorithm is not used" - ); + private static final Map PROPERTY_WARNINGS = + Map.of(// Appeared in setDefaultProperties, otherwise unknown. + "SortAlgorithm", "SortAlgorithm is not used"); /* * Keys in the CITATION section we warn about. */ private static final Map CITATION_PROPERTY_WARNINGS = makeCitationPropertyWarnings(); - private static final Map KNOWN_PROPERTIES = makeKnownProperties(); - private static final Map KNOWN_CITATION_PROPERTIES = + private static final Map KNOWN_PROPERTIES = makeKnownProperties(); + private static final Map KNOWN_CITATION_PROPERTIES = makeKnownCitationProperties(); + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyleParser.class); + enum PropertyType { BOOL, INT, @@ -77,8 +77,8 @@ private static boolean hasQuotes(String s) { } private static String dropQuotes(String s) { - if (hasQuotes(s)){ - return s.substring(1, s.length()-1); + if (hasQuotes(s)) { + return s.substring(1, s.length() - 1); } return s; } @@ -100,7 +100,7 @@ private static ParseLogLevel addProperty(String propertyName, int lineNumber, ParseLog logger, String whatIsIt) { - final String quotedTrue = "\"true\""; + final String quotedTrue = "\"true\""; final String quotedFalse = "\"false\""; switch (type) { @@ -109,10 +109,10 @@ private static ParseLogLevel addProperty(String propertyName, case BOOL: switch (value) { case "true": - destProperties.put(propertyName, Boolean.TRUE ); + destProperties.put(propertyName, Boolean.TRUE); return ParseLogLevel.OK; case "false": - destProperties.put(propertyName, Boolean.FALSE ); + destProperties.put(propertyName, Boolean.FALSE); return ParseLogLevel.OK; default: String msg = String.format("Boolean %s '%s'" @@ -120,13 +120,13 @@ private static ParseLogLevel addProperty(String propertyName, whatIsIt, propertyName, value); if (patient) { - if (value.equals(quotedTrue)){ - destProperties.put(propertyName, Boolean.TRUE ); + if (value.equals(quotedTrue)) { + destProperties.put(propertyName, Boolean.TRUE); logger.warn(fileName, lineNumber, msg); return ParseLogLevel.WARN; } - if (value.equals(quotedFalse)){ - destProperties.put(propertyName, Boolean.FALSE ); + if (value.equals(quotedFalse)) { + destProperties.put(propertyName, Boolean.FALSE); logger.warn(fileName, lineNumber, msg); return ParseLogLevel.WARN; } @@ -192,10 +192,14 @@ private static Map makeCitationPropertyWarnings() { Map res = new HashMap(); /* ItalicCitations was only recognized, but not used in JabRef5.2. */ - res.put("ItalicCitations", "ItalicCitations is not implemented, use CitationGroupMarkupBefore/After"); - res.put("BoldCitations", "BoldCitations is not implemented, use CitationGroupMarkupBefore/After"); - res.put("SuperscriptCitations", "SuperscriptCitations is not implemented, use CitationGroupMarkupBefore/After"); - res.put("SubscriptCitations", "SubscriptCitations is not implemented, use CitationGroupMarkupBefore/After"); + res.put("ItalicCitations", + "ItalicCitations is not implemented, use CitationGroupMarkupBefore/After"); + res.put("BoldCitations", + "BoldCitations is not implemented, use CitationGroupMarkupBefore/After"); + res.put("SuperscriptCitations", + "SuperscriptCitations is not implemented, use CitationGroupMarkupBefore/After"); + res.put("SubscriptCitations", + "SubscriptCitations is not implemented, use CitationGroupMarkupBefore/After"); res.put("BibtexKeyCitations", "Found 'BibtexKeyCitations' instead of 'BibTeXKeyCitations'"); return Collections.unmodifiableMap(res); @@ -255,9 +259,7 @@ private static Map makeKnownCitationProperties() { return Collections.unmodifiableMap(res); } - private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyleParser.class); - - private static boolean endsWithCharacter(String s, char c){ + private static boolean endsWithCharacter(String s, char c) { return !s.isEmpty() && (s.charAt(s.length() - 1) == c); } @@ -276,7 +278,6 @@ private static enum BibStyleMode { IN_LAYOUT_SECTION_MULTILINE } - /** Also used as return code */ static enum ParseLogLevel { ERROR, @@ -290,12 +291,14 @@ static class ParseLogEntry { public final String fileName; public final int lineNumber; public final String message; + ParseLogEntry(ParseLogLevel level, String fileName, int lineNumber, String message) { this.level = level; this.fileName = fileName; this.lineNumber = lineNumber; this.message = message; } + public String format() { StringBuilder sb = new StringBuilder(); ParseLogEntry e = this; @@ -351,18 +354,23 @@ public String formatShort() { public static class ParseLog { List entries; + ParseLog() { this.entries = new ArrayList<>(); } - void log( ParseLogLevel level, String fileName, int lineNumber, String message) { + + void log(ParseLogLevel level, String fileName, int lineNumber, String message) { this.entries.add(new ParseLogEntry(level, fileName, lineNumber, message)); } + void error(String fileName, int lineNumber, String message) { this.entries.add(new ParseLogEntry(ParseLogLevel.ERROR, fileName, lineNumber, message)); } + void warn(String fileName, int lineNumber, String message) { this.entries.add(new ParseLogEntry(ParseLogLevel.WARN, fileName, lineNumber, message)); } + void info(String fileName, int lineNumber, String message) { this.entries.add(new ParseLogEntry(ParseLogLevel.INFO, fileName, lineNumber, message)); } @@ -375,7 +383,7 @@ public boolean isEmpty() { return entries.isEmpty(); } - public String format(){ + public String format() { StringBuilder sb = new StringBuilder(); for (ParseLogEntry e : entries) { sb.append(e.format()); @@ -384,7 +392,7 @@ public String format(){ } // omits file path - public String formatShort(){ + public String formatShort() { StringBuilder sb = new StringBuilder(); for (ParseLogEntry e : entries) { sb.append(e.formatShort()); @@ -469,7 +477,7 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa final String trimmedLine = line.trim(); // Skip empty lines, unless we are in IN_LAYOUT_SECTION_MULTILINE - if (trimmedLine.isEmpty() && (mode != BibStyleMode.IN_LAYOUT_SECTION_MULTILINE) ) { + if (trimmedLine.isEmpty() && (mode != BibStyleMode.IN_LAYOUT_SECTION_MULTILINE)) { continue; } @@ -494,9 +502,9 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa case IN_NAME_SECTION: if (SECTION_NAMES.contains(trimmedLine)) { - logger.error( fileName, lineNumber, - "Expected name of style, found section name" - + String.format("'%s'", trimmedLine )); + logger.error(fileName, lineNumber, + "Expected name of style, found section name" + + String.format("'%s'", trimmedLine)); return logger; } else { // ok @@ -537,7 +545,7 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa return logger; } } else { - style.journals.add( trimmedLine ); + style.journals.add(trimmedLine); continue; } @@ -627,7 +635,7 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa style, fileName, layoutLineCollectorStartLine, - logger ); + logger); layoutLineCollectorName = "***"; layoutLineCollectorValue = new ArrayList<>(); @@ -674,7 +682,7 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa /** * Parse a line providing a property name and value. * - * @param line The line containing the formatter names. + * @param trimmedLine A line containing a propery setting. * * Format: "{propertyName}={value}" */ @@ -700,7 +708,7 @@ private static ParseLogLevel handlePropertiesLine(String trimmedLine, String propertyName = trimmedLine.substring(0, index).trim(); String value = trimmedLine.substring(index + 1).trim(); - if ("".equals(propertyName)){ + if ("".equals(propertyName)) { logger.log(softError, fileName, lineNumber, String.format("Empty %s name", whatIsIt)); return softError; @@ -795,7 +803,7 @@ private static ParseLogLevel handleLayoutLine(String line, style, fileName, lineNumber, - logger ); + logger); } private static ParseLogLevel handleLayoutLineParts(String name, diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 4d86427a1aa..814abb17153 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -18,7 +18,6 @@ import com.sun.star.beans.XPropertySet; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.ControlCharacter; -import com.sun.star.text.XParagraphCursor; import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.uno.UnoRuntime; @@ -110,29 +109,19 @@ public static String formatFullReference(Layout layout, /** * Insert a text in OOFormattedText * (where character formatting is indicated by HTML-like tags), into - * an {@code XText} at the position given by an {@code XTextCursor}. + * at the position given by an {@code XTextCursor}. * * Process {@code ltext} in chunks between HTML-tags, while * updating current formatting state at HTML-tags. * - * // removed: Finally: {@code cursor.collapseToEnd()} - * Works with a copy of the cursor passed in. - * - * Note: Leaves setting the paragraph style to the caller. - * - * param text The text to insert into. (taken from the cursor) - * - * @param cursor The cursor giving the insert location. + * @param cursor The cursor giving the insert location. Not modified. * @param lText The marked-up text to insert. - * //param keepTheCursor If true, use a copy of the cursor, do not modify. - * // If false the cursor is collapsed at the end. * @throws WrappedTargetException * @throws PropertyVetoException * @throws UnknownPropertyException * @throws IllegalArgumentException */ - public static void insertOOFormattedTextAtCurrentLocation(//XText text, - XTextCursor cursor, + public static void insertOOFormattedTextAtCurrentLocation(XTextCursor cursor, String lText) throws UnknownPropertyException, @@ -140,11 +129,9 @@ public static void insertOOFormattedTextAtCurrentLocation(//XText text, WrappedTargetException, IllegalArgumentException { - // boolean keepTheCursor = true; - XText text = cursor.getText(); + XText text = cursor.getText(); // copy the cursor - XTextCursor cursor3 = cursor.getText().createTextCursorByRange(cursor); - // XTextCursor cursor3 = keepTheCursor ? cursor2 : cursor ; + XTextCursor myCursor = cursor.getText().createTextCursorByRange(cursor); List formatting = new ArrayList<>(); // We need to extract formatting. Use a simple regexp search iteration: @@ -153,7 +140,7 @@ public static void insertOOFormattedTextAtCurrentLocation(//XText text, while (m.find()) { String currentSubstring = lText.substring(piv, m.start()); if (!currentSubstring.isEmpty()) { - OOUtil.insertTextAtCurrentLocation(text, cursor3, currentSubstring, formatting); + OOUtil.insertTextAtCurrentLocation(text, myCursor, currentSubstring, formatting); } String tag = m.group(); // Handle tags: @@ -195,9 +182,8 @@ public static void insertOOFormattedTextAtCurrentLocation(//XText text, } if (piv < lText.length()) { - OOUtil.insertTextAtCurrentLocation(text, cursor3, lText.substring(piv), formatting); + OOUtil.insertTextAtCurrentLocation(text, myCursor, lText.substring(piv), formatting); } - // cursor3.collapseToEnd(); } public static void insertParagraphBreak(XText text, XTextCursor cursor) @@ -282,7 +268,7 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) -10); xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, (byte) 58); } else if (formatting.contains(Formatting.SUPERSCRIPT)) { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) 33); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) 33); xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, (byte) 58); } else { xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) 0); @@ -305,8 +291,7 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S public static Object getProperty(Object o, String property) throws UnknownPropertyException, WrappedTargetException { - XPropertySet props = UnoRuntime.queryInterface( - XPropertySet.class, o); + XPropertySet props = UnoRuntime.queryInterface(XPropertySet.class, o); return props.getPropertyValue(property); } } diff --git a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java b/src/main/java/org/jabref/logic/openoffice/StyleLoader.java index da7842f90f0..2ba8c84ab6b 100644 --- a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java +++ b/src/main/java/org/jabref/logic/openoffice/StyleLoader.java @@ -64,7 +64,7 @@ public OOBibStyleParser.ParseLog addStyleIfValid(String filename) { encoding); OOBibStyleParser.ParseLog parseLog = newStyle.getParseLog(); - if ( parseLog == null ) { + if (parseLog == null) { parseLog = new OOBibStyleParser.ParseLog(); parseLog.error(filename, 0, "OOBibStyle constructor returned with no parseLog"); @@ -75,7 +75,7 @@ public OOBibStyleParser.ParseLog addStyleIfValid(String filename) { parseLog.error(filename, 0, "An external style file with the same content," + " including its path" - + " is already known (not adding)" ); + + " is already known (not adding)"); return parseLog; } else if (newStyle.isValid() && !parseLog.hasError()) { externalStyles.add(newStyle); @@ -91,14 +91,14 @@ public OOBibStyleParser.ParseLog addStyleIfValid(String filename) { // The file couldn't be found... should we tell anyone? String msg = "Cannot find external style file " + filename; LOGGER.info(msg, e); - OOBibStyleParser.ParseLog parseLog = new OOBibStyleParser.ParseLog(); - parseLog.error( filename, 0, msg ); + OOBibStyleParser.ParseLog parseLog = new OOBibStyleParser.ParseLog(); + parseLog.error(filename, 0, msg); return parseLog; } catch (IOException e) { LOGGER.info("Problem reading external style file " + filename, e); - OOBibStyleParser.ParseLog parseLog = new OOBibStyleParser.ParseLog(); + OOBibStyleParser.ParseLog parseLog = new OOBibStyleParser.ParseLog(); String msg = "Problem (IOException) reading external style file " + filename; - parseLog.error( filename, 0, msg ); + parseLog.error(filename, 0, msg); return parseLog; } } From ccc7a69ef4f69cb48dc7ff7cddef3416b349726f Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 13:47:29 +0200 Subject: [PATCH 0612/1068] restore ConnectionLostException.java --- .../org/jabref/gui/openoffice/ConnectionLostException.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java b/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java index 9101ee4cd0a..36fc16e5e3f 100644 --- a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java +++ b/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java @@ -1,11 +1,7 @@ package org.jabref.gui.openoffice; /** - * This exception is used to indicate that connection to OpenOffice - * has been lost. - * - * Note: related, but different: NoDocumentException - * + * This exception is used to indicate that connection to OpenOffice has been lost. */ class ConnectionLostException extends RuntimeException { From 8d659fd999234564a0f3753994e20565e12d3ef1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 14:16:42 +0200 Subject: [PATCH 0613/1068] restore presence of CitationEntryViewModel.java --- ...EntryViewModel.java => CitationEntryViewModel.java} | 6 +++--- .../gui/openoffice/ManageCitationsDialogView.java | 10 +++++----- .../gui/openoffice/ManageCitationsDialogViewModel.java | 8 ++++---- 3 files changed, 12 insertions(+), 12 deletions(-) rename src/main/java/org/jabref/gui/openoffice/{ManageCitationsEntryViewModel.java => CitationEntryViewModel.java} (83%) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsEntryViewModel.java b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java similarity index 83% rename from src/main/java/org/jabref/gui/openoffice/ManageCitationsEntryViewModel.java rename to src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java index 24fde5e076c..028990a6bc8 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsEntryViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java @@ -5,19 +5,19 @@ import org.jabref.logic.openoffice.CitationEntry; -public class ManageCitationsEntryViewModel { +public class CitationEntryViewModel { private final StringProperty citation = new SimpleStringProperty(""); private final StringProperty extraInformation = new SimpleStringProperty(""); private final String refMarkName; - public ManageCitationsEntryViewModel(String refMarkName, String citation, String extraInfo) { + public CitationEntryViewModel(String refMarkName, String citation, String extraInfo) { this.refMarkName = refMarkName; this.citation.setValue(citation); this.extraInformation.setValue(extraInfo); } - public ManageCitationsEntryViewModel(CitationEntry citationEntry) { + public CitationEntryViewModel(CitationEntry citationEntry) { this(citationEntry.getRefMarkName(), citationEntry.getContext(), citationEntry.getPageInfo().orElse("")); } diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index 79b5e5ee50f..5eb9f8bcd0e 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -30,9 +30,9 @@ public class ManageCitationsDialogView extends BaseDialog { private final OOBibBase ooBase; - @FXML private TableView citationsTableView; - @FXML private TableColumn citation; - @FXML private TableColumn extraInfo; + @FXML private TableView citationsTableView; + @FXML private TableColumn citation; + @FXML private TableColumn extraInfo; @Inject private DialogService dialogService; @@ -68,7 +68,7 @@ private void initialize() cellData.getValue() .citationProperty()); - new ValueTableCellFactory() + new ValueTableCellFactory() .withGraphic(this::getText) .install(citation); @@ -81,7 +81,7 @@ private void initialize() citationsTableView.itemsProperty().bindBidirectional(viewModel.citationsProperty()); - extraInfo.setOnEditCommit((CellEditEvent cell) -> { + extraInfo.setOnEditCommit((CellEditEvent cell) -> { cell.getRowValue().setExtraInfo(cell.getNewValue()); }); extraInfo.setCellFactory(TextFieldTableCell.forTableColumn()); diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index c0869cb5380..a4e33250c9a 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -25,7 +25,7 @@ public class ManageCitationsDialogViewModel { private static final Logger LOGGER = LoggerFactory.getLogger(ManageCitationsDialogViewModel.class); - private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList()); private final OOBibBase ooBase; private final DialogService dialogService; @@ -41,7 +41,7 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, try { List cts = ooBase.getCitationEntries(); for (CitationEntry entry : cts) { - ManageCitationsEntryViewModel itemViewModelEntry = new ManageCitationsEntryViewModel(entry); + CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); } } catch (UnknownPropertyException @@ -57,7 +57,7 @@ public void storeSettings() { List citationEntries = citations.stream() - .map(ManageCitationsEntryViewModel::toCitationEntry) + .map(CitationEntryViewModel::toCitationEntry) .collect(Collectors.toList()); try { @@ -74,7 +74,7 @@ public void storeSettings() { } } - public ListProperty citationsProperty() { + public ListProperty citationsProperty() { return citations; } } From 6cb380780b8e5cf820e606e88b410937b72e0678 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 14:34:41 +0200 Subject: [PATCH 0614/1068] restore ManageCitationsDialogView.java --- .../openoffice/ManageCitationsDialogView.java | 19 +++--------- .../ManageCitationsDialogViewModel.java | 29 +++++-------------- 2 files changed, 11 insertions(+), 37 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index 5eb9f8bcd0e..2ad6effb287 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -56,25 +56,14 @@ public ManageCitationsDialogView(OOBibBase ooBase) { } @FXML - private void initialize() - throws NoSuchElementException, - WrappedTargetException, - UnknownPropertyException, - NoDocumentException { + private void initialize() throws NoSuchElementException, WrappedTargetException, UnknownPropertyException { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); - citation.setCellValueFactory(cellData -> - cellData.getValue() - .citationProperty()); + citation.setCellValueFactory(cellData -> cellData.getValue().citationProperty()); + new ValueTableCellFactory().withGraphic(this::getText).install(citation); - new ValueTableCellFactory() - .withGraphic(this::getText) - .install(citation); - - extraInfo.setCellValueFactory(cellData -> - cellData.getValue() - .extraInformationProperty()); + extraInfo.setCellValueFactory(cellData -> cellData.getValue().extraInformationProperty()); extraInfo.setEditable(true); citationsTableView.setEditable(true); diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index a4e33250c9a..ef35b9173d5 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -29,12 +29,7 @@ public class ManageCitationsDialogViewModel { private final OOBibBase ooBase; private final DialogService dialogService; - public ManageCitationsDialogViewModel(OOBibBase ooBase, - DialogService dialogService) - throws NoSuchElementException, - WrappedTargetException, - UnknownPropertyException, - NoDocumentException { + public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) throws NoSuchElementException, WrappedTargetException, UnknownPropertyException { this.ooBase = ooBase; this.dialogService = dialogService; @@ -54,24 +49,14 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, } public void storeSettings() { - - List citationEntries = - citations.stream() - .map(CitationEntryViewModel::toCitationEntry) - .collect(Collectors.toList()); - + List ciationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); try { ooBase.applyCitationEntries(citationEntries); - } catch (UnknownPropertyException - | NotRemoveableException - | PropertyExistException - | IllegalTypeException - | IllegalArgumentException - | NoDocumentException ex - ) { - LOGGER.warn("Problem modifying citation", ex); - dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex); - } + } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException | NoDocumentException | + IllegalArgumentException ex) { + LOGGER.warn("Problem modifying citation", ex); + dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex); + } } public ListProperty citationsProperty() { From 9136d743561c5a36ea31167bf293a691cea81695 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 14:53:56 +0200 Subject: [PATCH 0615/1068] restore ManageCitationsDialogView.java --- .../jabref/gui/openoffice/ManageCitationsDialogView.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index 2ad6effb287..a312a4ef375 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -78,12 +78,9 @@ private void initialize() throws NoSuchElementException, WrappedTargetException, private Node getText(String citationContext) { - String inBetween = StringUtil.substringBetween(citationContext, - HTML_BOLD_START_TAG, - HTML_BOLD_END_TAG); + String inBetween = StringUtil.substringBetween(citationContext, HTML_BOLD_START_TAG, HTML_BOLD_END_TAG); String start = citationContext.substring(0, citationContext.indexOf(HTML_BOLD_START_TAG)); - String end = citationContext.substring(citationContext.lastIndexOf(HTML_BOLD_END_TAG) - + HTML_BOLD_END_TAG.length()); + String end = citationContext.substring(citationContext.lastIndexOf(HTML_BOLD_END_TAG) + HTML_BOLD_END_TAG.length()); Text startText = new Text(start); Text inBetweenText = new Text(inBetween); From 098deb13df77aaf13f732463b4464df788d5df96 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 14:59:58 +0200 Subject: [PATCH 0616/1068] restore NoDocumentException.java --- .../gui/openoffice/NoDocumentException.java | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java b/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java index b952b2adab3..05d5f6d06ac 100644 --- a/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java +++ b/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java @@ -1,19 +1,8 @@ package org.jabref.gui.openoffice; /** - * Exception used to indicate that we cannot manipulate the current - * document. - * - * OOBibBase.selectDocument : NoDocumentException("No Writer documents found"); - * OOBibBase.getReferenceMarks : NoDocumentException("getReferenceMarks failed"); - * - * Note: similar to ConnectionLostException, but here connection to - * OpenOffice may be intact, e.g. if the document is closed, but - * OpenOffice is not. - * - * On the other hand: it is not clear what this distinction buys - * us, since we do not connect to multiple documents. - * + * Exception used to indicate that the plugin attempted to set a character format that is + * not defined in the current OpenOffice document. */ class NoDocumentException extends Exception { From 24d2cc8f81a90ba12b09407b2db9100703b56094 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 15:05:31 +0200 Subject: [PATCH 0617/1068] restore OpenOfficePanel.java --- .../gui/openoffice/OpenOfficePanel.java | 258 +++++++----------- 1 file changed, 100 insertions(+), 158 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 2bf60e5ce9d..2bee70f393e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -163,31 +163,24 @@ private void initPanel() { setStyleFile.setMaxWidth(Double.MAX_VALUE); setStyleFile.setOnAction(event -> { - dialogService.showCustomDialogAndWait(new StyleSelectDialogView(loader)) - .ifPresent(selectedStyle -> { - style = selectedStyle; - try { - style.ensureUpToDate(); - } catch (IOException e) { - LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", e); - } - dialogService.notify(Localization.lang("Current style is '%0'", - style.getName())); - }); - }); - pushEntries.setTooltip( - new Tooltip(Localization.lang("Cite selected entries between parenthesis"))); + dialogService.showCustomDialogAndWait(new StyleSelectDialogView(loader)).ifPresent(selectedStyle -> { + style = selectedStyle; + try { + style.ensureUpToDate(); + } catch (IOException e) { + LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", e); + } + dialogService.notify(Localization.lang("Current style is '%0'", style.getName())); + }); + }); + pushEntries.setTooltip(new Tooltip(Localization.lang("Cite selected entries between parenthesis"))); pushEntries.setOnAction(e -> pushEntries(true, true, false)); pushEntries.setMaxWidth(Double.MAX_VALUE); - - pushEntriesInt.setTooltip( - new Tooltip(Localization.lang("Cite selected entries with in-text citation"))); - + pushEntriesInt.setTooltip(new Tooltip(Localization.lang("Cite selected entries with in-text citation"))); pushEntriesInt.setOnAction(e -> pushEntries(false, true, false)); pushEntriesInt.setMaxWidth(Double.MAX_VALUE); - pushEntriesEmpty.setTooltip(new Tooltip(Localization.lang("Insert a citation without text (the entry will appear in the reference list)"))); pushEntriesEmpty.setOnAction(e -> pushEntries(false, false, false)); pushEntriesEmpty.setMaxWidth(Double.MAX_VALUE); @@ -209,15 +202,9 @@ private void initPanel() { List unresolvedKeys = ooBase.updateDocumentActionHelper(databases, style); if (!unresolvedKeys.isEmpty()) { - dialogService - .showErrorDialogAndWait( - Localization.lang("Unable to synchronize bibliography"), - Localization.lang( - "Your OpenOffice/LibreOffice document references" - + " citation keys which could not be found" - + " in your current library.") - + "\n" - + String.join(" ", unresolvedKeys)); + dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), + Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", + unresolvedKeys.get(0))); } } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( @@ -233,35 +220,22 @@ private void initPanel() { showNoDocumentErrorMessage(); } catch (IOException ex) { LOGGER.warn("Problem with style file", ex); - dialogService.showErrorDialogAndWait( - Localization.lang("No valid style file defined"), - Localization.lang("You must select either a valid style file," - + " or use one of the default styles.")); + dialogService.showErrorDialogAndWait(Localization.lang("No valid style file defined"), + Localization.lang("You must select either a valid style file, or use one of the default styles.")); } catch (BibEntryNotFoundException ex) { LOGGER.debug("BibEntry not found", ex); - dialogService.showErrorDialogAndWait( - Localization.lang("Unable to synchronize bibliography"), - Localization.lang("Your OpenOffice/LibreOffice document" - + " references the citation key '%0'," - + " which could not be found in your current library.", - ex.getCitationKey())); - } catch (com.sun.star.lang.IllegalArgumentException - | PropertyVetoException - | UnknownPropertyException - | WrappedTargetException - | NoSuchElementException - | InvalidStateException - | CreationException ex) { + dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), Localization.lang( + "Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", + ex.getCitationKey())); + } catch (com.sun.star.lang.IllegalArgumentException | PropertyVetoException | UnknownPropertyException | WrappedTargetException | NoSuchElementException | + InvalidStateException | + CreationException ex) { LOGGER.warn("Could not update bibliography", ex); } }); merge.setMaxWidth(Double.MAX_VALUE); - merge.setTooltip( - new Tooltip( - Localization.lang( - "Combine pairs of citations" - + " that are separated by spaces only"))); + merge.setTooltip(new Tooltip(Localization.lang("Combine pairs of citations that are separated by spaces only"))); merge.setOnAction(e -> { try { ooBase.combineCiteMarkers(getBaseList(), style); @@ -273,18 +247,10 @@ private void initPanel() { reportUndefinedCharacterFormat(ex); } catch (NoDocumentException ex) { showNoDocumentErrorMessage(); - } catch (com.sun.star.lang.IllegalArgumentException - | UnknownPropertyException - | PropertyVetoException - | PropertyExistException - | CreationException - | NoSuchElementException - | NotRemoveableException - | IllegalTypeException - | WrappedTargetException - | IOException - | InvalidStateException - | BibEntryNotFoundException ex) { + } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | + CreationException | NoSuchElementException | WrappedTargetException | IOException | + NotRemoveableException | IllegalTypeException | InvalidStateException | + BibEntryNotFoundException ex) { LOGGER.warn("Problem combining cite markers", ex); } }); @@ -302,18 +268,10 @@ private void initPanel() { showNoDocumentErrorMessage(); } catch (UndefinedCharacterFormatException ex) { reportUndefinedCharacterFormat(ex); - } catch (com.sun.star.lang.IllegalArgumentException - | UnknownPropertyException - | PropertyVetoException - | PropertyExistException - | IllegalTypeException - | NotRemoveableException - | CreationException - | NoSuchElementException - | WrappedTargetException - | IOException - | InvalidStateException - | BibEntryNotFoundException ex) { + } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | + CreationException | NoSuchElementException | WrappedTargetException | IOException | + PropertyExistException | IllegalTypeException | NotRemoveableException | InvalidStateException | + BibEntryNotFoundException ex) { LOGGER.warn("Problem uncombining cite markers", ex); } }); @@ -324,11 +282,11 @@ private void initPanel() { settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { - if (ooBase.documentConnectionMissing()) { - showNoDocumentErrorMessage(); - } else { - dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); - } + if (ooBase.documentConnectionMissing()) { + showNoDocumentErrorMessage(); + return; + } + dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); }); exportCitations.setMaxWidth(Double.MAX_VALUE); @@ -379,41 +337,28 @@ private void exportEntries() { } OOBibBase.ExportCitedHelperResult r = ooBase.exportCitedHelper(databases, style); - if (r.unresolvedKeys == null) { - throw new RuntimeException("OpenOfficePanel.exportEntries: r.unresolvedKeys is null"); - } - if (r.newDatabase == null) { - throw new RuntimeException("OpenOfficePanel.exportEntries: r.newDatabase is null"); - } - if (!r.unresolvedKeys.isEmpty()) { + List unresolvedKeys = r.unresolvedKeys; + BibDatabase newDatabase = r.newDatabase; + if (!unresolvedKeys.isEmpty()) { dialogService.showErrorDialogAndWait(Localization.lang("Unable to generate new library"), Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - r.unresolvedKeys.get(0))); + unresolvedKeys.get(0))); } - BibDatabaseContext databaseContext = new BibDatabaseContext(r.newDatabase); + BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase); this.frame.addTab(databaseContext, true); - } catch (NoDocumentException ex) { + } catch (NoDocumentException ex) { showNoDocumentErrorMessage(); } catch (BibEntryNotFoundException ex) { LOGGER.debug("BibEntry not found", ex); - dialogService.showErrorDialogAndWait( - Localization.lang("Unable to synchronize bibliography"), - Localization.lang( - "Your OpenOffice/LibreOffice document references the citation key '%0'," - + " which could not be found in your current library.", - ex.getCitationKey())); - } catch (com.sun.star.lang.IllegalArgumentException - | UnknownPropertyException - | PropertyVetoException - | UndefinedCharacterFormatException - | NoSuchElementException - | WrappedTargetException - | IOException - | InvalidStateException - | CreationException e - ) { + dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), + Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", + ex.getCitationKey())); + } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | + UndefinedCharacterFormatException | NoSuchElementException | WrappedTargetException | IOException | + InvalidStateException | + CreationException e) { LOGGER.warn("Problem generating new database.", e); } } @@ -569,47 +514,6 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP } Boolean inParenthesis = inParenthesisIn; - - LibraryTab libraryTab = frame.getCurrentLibraryTab(); - final BibDatabase database = - (libraryTab == null - ? null - : libraryTab.getDatabase()); - - if (database == null) { - dialogService.showErrorDialogAndWait( - Localization.lang("No database"), - Localization.lang( - "No bibliography database is open for citation.") - + "\n" - + Localization.lang("Open one before citing.")); - return; - } - - List entries = libraryTab.getSelectedEntries(); - if (entries.isEmpty()) { - dialogService.showErrorDialogAndWait( - Localization.lang("No entries selected for citation"), - Localization.lang( - "No bibliography entries are selected for citation.") - + "\n" - + Localization.lang("Select some before citing.")); - return; - } - - if (style == null) { - style = loader.getUsedStyle(); - if (style == null) { - dialogService.showErrorDialogAndWait( - Localization.lang("No style for citation"), - Localization.lang( - "No bibliography style is selected for citation.") - + "\n" - + Localization.lang("Select one before citing.")); - return; - } - } - String pageInfo = null; if (addPageInfo) { @@ -624,17 +528,45 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP } } - if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { + LibraryTab libraryTab = frame.getCurrentLibraryTab(); + if (libraryTab != null) { + final BibDatabase database = libraryTab.getDatabase(); + if (database == null) { + dialogService.showErrorDialogAndWait( + Localization.lang("No database"), + Localization.lang( + "No bibliography database is open for citation.") + + "\n" + + Localization.lang("Open one before citing.")); + return; + } + List entries = libraryTab.getSelectedEntries(); + if (entries.isEmpty()) { + dialogService.showErrorDialogAndWait( + Localization.lang("No entries selected for citation"), + Localization.lang( + "No bibliography entries are selected for citation.") + + "\n" + + Localization.lang("Select some before citing.")); + return; + } + if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { try { - ooBase.insertCitation(entries, - database, - getBaseList(), - style, - inParenthesis, - withText, - pageInfo, - ooPrefs.getSyncWhenCiting()); + if (style == null) { + style = loader.getUsedStyle(); + if (style == null) { + dialogService.showErrorDialogAndWait( + Localization.lang("No style for citation"), + Localization.lang( + "No bibliography style is selected for citation.") + + "\n" + + Localization.lang("Select one before citing.")); + return; + } + } + ooBase.insertEntry(entries, database, getBaseList(), style, inParenthesis, withText, pageInfo, + ooPrefs.getSyncWhenCiting()); } catch (FileNotFoundException ex) { dialogService.showErrorDialogAndWait( @@ -662,6 +594,15 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP LOGGER.warn("Could not insert entry", ex); } } + } else { // libraryTab == null + dialogService.showErrorDialogAndWait( + Localization.lang("No database"), + Localization.lang( + "No bibliography database is open for citation.") + + "\n" + + Localization.lang("Open one before citing.")); + return; + } } /** @@ -718,8 +659,7 @@ private boolean checkThatEntriesHaveKeys(List entries) { private void showConnectionLostErrorMessage() { dialogService.showErrorDialogAndWait(Localization.lang("Connection lost"), - Localization.lang("Connection to OpenOffice/LibreOffice has been lost. " - + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); + Localization.lang("Connection to OpenOffice/LibreOffice has been lost. " + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); } private void showNoDocumentErrorMessage() { @@ -738,7 +678,9 @@ private void reportUndefinedCharacterFormat(UndefinedCharacterFormatException ex dialogService.showErrorDialogAndWait(Localization.lang("Undefined character format"), Localization.lang("Your style file specifies the character format '%0', " + "which is undefined in your current OpenOffice/LibreOffice document.", - ex.getFormatName()) + "\n" + Localization.lang("The character format is controlled by the citation property 'CitationCharacterFormat' in the style file.")); + ex.getFormatName()) + "\n" + Localization.lang("The character format is controlled by the citation property 'CitationCharacterFormat' in the style file.") + + ); } private ContextMenu createSettingsPopup() { From b451c1d85ee0735381b4de9d346ad25faed01e8f Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 16:37:03 +0200 Subject: [PATCH 0618/1068] restore OOBibBase.insertEntry (was renamed to insertCitation) --- .../org/jabref/gui/openoffice/OOBibBase.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 37100a2f93c..915036840a2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1146,7 +1146,7 @@ void assertCitationCharacterFormatIsOK(XTextCursor cursor, } /** - * In insertCitation we receive BibEntry values from the GUI. + * In insertEntry we receive BibEntry values from the GUI. * * In the document we store citations by their citation key. * @@ -1154,10 +1154,10 @@ void assertCitationCharacterFormatIsOK(XTextCursor cursor, * the user. Or the programmer, that we cannot accept such input. * */ - private static String insertCitationGetCitationKey(BibEntry entry) { + private static String insertEntryGetCitationKey(BibEntry entry) { Optional key = entry.getCitationKey(); if (key.isEmpty()) { - throw new RuntimeException("insertCitationGetCitationKey:" + throw new RuntimeException("insertEntryGetCitationKey:" + " cannot cite entries without citation key"); } return key.get(); @@ -1219,14 +1219,14 @@ private static String insertCitationGetCitationKey(BibEntry entry) { * * */ - public void insertCitation(List entries, - BibDatabase database, - List allBases, - OOBibStyle style, - boolean inParenthesis, - boolean withText, - String pageInfo, - boolean sync) + public void insertEntry(List entries, + BibDatabase database, + List allBases, + OOBibStyle style, + boolean inParenthesis, + boolean withText, + String pageInfo, + boolean sync) throws JabRefException, IllegalArgumentException, @@ -1291,7 +1291,7 @@ public void insertCitation(List entries, List citationKeys = entries.stream() - .map(OOBibBase::insertCitationGetCitationKey) + .map(OOBibBase::insertEntryGetCitationKey) .collect(Collectors.toList()); int itcType = citationTypeFromOptions(withText, inParenthesis); From 738088dda49da4990901fdaf144ebd3e890efe42 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 16:37:58 +0200 Subject: [PATCH 0619/1068] compiled --- .../jabref/gui/openoffice/ManageCitationsDialogViewModel.java | 2 +- src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index ef35b9173d5..feeedc32d37 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -49,7 +49,7 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogServ } public void storeSettings() { - List ciationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); + List citationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); try { ooBase.applyCitationEntries(citationEntries); } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException | NoDocumentException | diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 2bee70f393e..f2a27375b47 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -250,6 +250,7 @@ private void initPanel() { } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | NotRemoveableException | IllegalTypeException | InvalidStateException | + PropertyExistException | BibEntryNotFoundException ex) { LOGGER.warn("Problem combining cite markers", ex); } From f71dd5465799e1064a6ccbd1e555abcc1bd07b00 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 16:40:19 +0200 Subject: [PATCH 0620/1068] restore ManageCitationsDialogViewModel.java --- .../gui/openoffice/ManageCitationsDialogViewModel.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index feeedc32d37..e91c6189833 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -49,10 +49,11 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogServ } public void storeSettings() { - List citationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); + List ciationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); try { - ooBase.applyCitationEntries(citationEntries); - } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException | NoDocumentException | + ooBase.applyCitationEntries(ciationEntries); + } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException | + NoDocumentException | IllegalArgumentException ex) { LOGGER.warn("Problem modifying citation", ex); dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex); From 841322023ff77fffbf49a8e1dfd902aa209201f3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 17:09:23 +0200 Subject: [PATCH 0621/1068] restore src/test/resources/org/jabref/logic/openoffice/test.jstyle --- .../resources/org/jabref/logic/openoffice/test.jstyle | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/resources/org/jabref/logic/openoffice/test.jstyle b/src/test/resources/org/jabref/logic/openoffice/test.jstyle index 7d803ea026f..3ecd9bfbf08 100644 --- a/src/test/resources/org/jabref/logic/openoffice/test.jstyle +++ b/src/test/resources/org/jabref/logic/openoffice/test.jstyle @@ -9,8 +9,8 @@ Journal name 2 PROPERTIES Title="References" -IsSortByPosition=true -IsNumberEntries=true +IsSortByPosition="true" +IsNumberEntries="true" ReferenceParagraphFormat="Text body" ReferenceHeaderParagraphFormat="Heading 2" @@ -22,8 +22,8 @@ BracketAfterInList="] " CitationSeparator="; " UniquefierSeparator="," GroupedNumbersSeparator="-" -MinimumGroupingCount=3 -FormatCitations=false +MinimumGroupingCount="3" +FormatCitations="false" CitationCharacterFormat="Default" PageInfoSeparator="; " OxfordComma="," From 4a2f412cb0e85c4a90f87a51ae7e7423ade081e0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 17:28:58 +0200 Subject: [PATCH 0622/1068] restore StyleLoader.java --- .../org/jabref/logic/openoffice/OOBibStyle.java | 7 ++++++- .../jabref/logic/openoffice/StyleLoader.java | 17 +++-------------- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 7d799e95cb4..a31f36f7228 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -427,13 +427,18 @@ private boolean obsReload() throws IOException { * @return true if the file could be parsed as a style file, false otherwise. */ public boolean isValid() { - return valid; + return valid && !getParseLog().hasError(); } /** * May return null. */ public OOBibStyleParser.ParseLog getParseLog() { + if (parseLog == null) { + parseLog = new OOBibStyleParser.ParseLog(); + parseLog.error(filename, 0, + "OOBibStyle: no parseLog"); + } return parseLog; } diff --git a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java b/src/main/java/org/jabref/logic/openoffice/StyleLoader.java index 2ba8c84ab6b..59d5905b5ba 100644 --- a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java +++ b/src/main/java/org/jabref/logic/openoffice/StyleLoader.java @@ -59,16 +59,9 @@ public List getStyles() { public OOBibStyleParser.ParseLog addStyleIfValid(String filename) { Objects.requireNonNull(filename); try { - OOBibStyle newStyle = new OOBibStyle(new File(filename), - layoutFormatterPreferences, - encoding); + OOBibStyle newStyle = new OOBibStyle(new File(filename), layoutFormatterPreferences, encoding); OOBibStyleParser.ParseLog parseLog = newStyle.getParseLog(); - if (parseLog == null) { - parseLog = new OOBibStyleParser.ParseLog(); - parseLog.error(filename, 0, - "OOBibStyle constructor returned with no parseLog"); - } if (externalStyles.contains(newStyle)) { LOGGER.info("External style file " + filename + " already existing."); @@ -76,16 +69,13 @@ public OOBibStyleParser.ParseLog addStyleIfValid(String filename) { "An external style file with the same content," + " including its path" + " is already known (not adding)"); - return parseLog; - } else if (newStyle.isValid() && !parseLog.hasError()) { + } else if (newStyle.isValid()) { externalStyles.add(newStyle); storeExternalStyles(); - return parseLog; } else { String msg = String.format("Style with filename %s is invalid", filename); LOGGER.error(msg); parseLog.error(filename, 0, msg); - return parseLog; } } catch (FileNotFoundException e) { // The file couldn't be found... should we tell anyone? @@ -93,14 +83,13 @@ public OOBibStyleParser.ParseLog addStyleIfValid(String filename) { LOGGER.info(msg, e); OOBibStyleParser.ParseLog parseLog = new OOBibStyleParser.ParseLog(); parseLog.error(filename, 0, msg); - return parseLog; } catch (IOException e) { LOGGER.info("Problem reading external style file " + filename, e); OOBibStyleParser.ParseLog parseLog = new OOBibStyleParser.ParseLog(); String msg = "Problem (IOException) reading external style file " + filename; parseLog.error(filename, 0, msg); - return parseLog; } + return parseLog; } private void loadExternalStyles() { From 9efe306aa747c13d8ddd702df2b4ca38e7c368d5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 21:32:31 +0200 Subject: [PATCH 0623/1068] cleanup --- src/main/resources/l10n/JabRef_en.properties | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 60db86380aa..785c77c6cba 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -2314,8 +2314,6 @@ Unprotect\ terms=Unprotect terms Error\ connecting\ to\ Writer\ document=Error connecting to Writer document You\ need\ to\ open\ Writer\ with\ a\ document\ before\ connecting=You need to open Writer with a document before connecting - - Generate\ a\ new\ key\ for\ imported\ entries\ (overwriting\ their\ default)=Generate a new key for imported entries (overwriting their default) Import\ settings=Import settings Custom\ DOI\ URI=Custom DOI URI From 6b0c23016a99bed08f97413babb8e6ead7e6e7d9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 21:32:52 +0200 Subject: [PATCH 0624/1068] restore default_authoryear.jstyle --- .../openoffice/default_authoryear.jstyle | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/main/resources/resource/openoffice/default_authoryear.jstyle b/src/main/resources/resource/openoffice/default_authoryear.jstyle index 3656f6a9a20..eeb2ca8eeac 100644 --- a/src/main/resources/resource/openoffice/default_authoryear.jstyle +++ b/src/main/resources/resource/openoffice/default_authoryear.jstyle @@ -9,8 +9,8 @@ Journal name 2 PROPERTIES Title="References" -IsSortByPosition = false -IsNumberEntries = false +IsSortByPosition="false" +IsNumberEntries="false" ReferenceParagraphFormat="Text body" ReferenceHeaderParagraphFormat="Heading 2" @@ -18,27 +18,27 @@ CITATION BibTeXKeyCitations=false AuthorField="author/editor" YearField="year" -MaxAuthors=2 -MaxAuthorsFirst=6 +MaxAuthors="2" +MaxAuthorsFirst="6" AuthorSeparator="," -AuthorLastSeparator = " & " -AuthorLastSeparatorInText = " and " +AuthorLastSeparator=" & " +AuthorLastSeparatorInText=" and " EtAlString=" et al." -ItalicEtAl=false +ItalicEtAl="false" YearSeparator=" " InTextYearSeparator=" " BracketBefore="[" BracketAfter="]" -BracketBeforeInList = "[" -BracketAfterInList = "] " -CitationSeparator = "; " -UniquefierSeparator = "," +BracketBeforeInList="[" +BracketAfterInList="] " +CitationSeparator="; " +UniquefierSeparator="," GroupedNumbersSeparator="-" -MinimumGroupingCount=3 -FormatCitations = false -CitationCharacterFormat = "Default" -MultiCiteChronological = true -PageInfoSeparator = "; " +MinimumGroupingCount="3" +FormatCitations="false" +CitationCharacterFormat="Default" +MultiCiteChronological="true" +PageInfoSeparator="; " LAYOUT article=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. From d36a443f55b243dc61b1ef61041ad02011477d42 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 21:32:57 +0200 Subject: [PATCH 0625/1068] restore default_numerical.jstyle --- .../openoffice/default_numerical.jstyle | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/main/resources/resource/openoffice/default_numerical.jstyle b/src/main/resources/resource/openoffice/default_numerical.jstyle index 0442d080e26..047caee3be8 100644 --- a/src/main/resources/resource/openoffice/default_numerical.jstyle +++ b/src/main/resources/resource/openoffice/default_numerical.jstyle @@ -8,24 +8,24 @@ Journal name 1 Journal name 2 PROPERTIES -Title = "References" -IsSortByPosition = true -IsNumberEntries = true -ReferenceParagraphFormat = "Text body" -ReferenceHeaderParagraphFormat = "Heading 2" +Title="References" +IsSortByPosition="true" +IsNumberEntries="true" +ReferenceParagraphFormat="Text body" +ReferenceHeaderParagraphFormat="Heading 2" CITATION -BracketBefore = "[" -BracketAfter = "]" -BracketBeforeInList = "[" -BracketAfterInList = "] " -CitationSeparator = "; " -UniquefierSeparator = "," -GroupedNumbersSeparator = "-" -MinimumGroupingCount = 3 -FormatCitations = false -CitationCharacterFormat = "Default" -PageInfoSeparator = "; " +BracketBefore="[" +BracketAfter="]" +BracketBeforeInList="[" +BracketAfterInList="] " +CitationSeparator="; " +UniquefierSeparator="," +GroupedNumbersSeparator="-" +MinimumGroupingCount="3" +FormatCitations="false" +CitationCharacterFormat="Default" +PageInfoSeparator="; " LAYOUT article=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. From 9052009d597c9c0b6133ebab426604cbf960bf8e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 21:44:29 +0200 Subject: [PATCH 0626/1068] restore OOBibStyleTest.java --- .../java/org/jabref/logic/openoffice/OOBibStyleTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 8a010b502ed..26c9bf03564 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -77,7 +77,8 @@ void testNumerical() throws IOException { @Test void testGetNumCitationMarkerForInText() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); + List empty = null; // Unfortunately these two are both "; " in @@ -208,7 +209,8 @@ void testGetNumCitationMarkerForInText() throws IOException { @Test void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); + layoutFormatterPreferences); + List empty = null; // unresolved citations look like [??] From 9b512fdcd54b7e7bc6bd3365d75d21e2ab6c41b2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 21:56:12 +0200 Subject: [PATCH 0627/1068] restore testWithDefaultAtFirstLIne.jstyle --- .../logic/openoffice/testWithDefaultAtFirstLIne.jstyle | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/resources/org/jabref/logic/openoffice/testWithDefaultAtFirstLIne.jstyle b/src/test/resources/org/jabref/logic/openoffice/testWithDefaultAtFirstLIne.jstyle index 0c146f679db..2a4dcf7a697 100644 --- a/src/test/resources/org/jabref/logic/openoffice/testWithDefaultAtFirstLIne.jstyle +++ b/src/test/resources/org/jabref/logic/openoffice/testWithDefaultAtFirstLIne.jstyle @@ -9,8 +9,8 @@ Journal name 2 PROPERTIES Title="References" -IsSortByPosition=true -IsNumberEntries=true +IsSortByPosition="true" +IsNumberEntries="true" ReferenceParagraphFormat="Text body" ReferenceHeaderParagraphFormat="Heading 2" @@ -22,8 +22,8 @@ BracketAfterInList="] " CitationSeparator="; " UniquefierSeparator="," GroupedNumbersSeparator="-" -MinimumGroupingCount=3 -FormatCitations=false +MinimumGroupingCount="3" +FormatCitations="false" CitationCharacterFormat="Default" PageInfoSeparator="; " OxfordComma="," From 3d8dfe9fe4deeb04e067ce82e715aec92ecc5639 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 23:19:35 +0200 Subject: [PATCH 0628/1068] break the new line --- src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index f2a27375b47..928b9591214 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -271,7 +271,8 @@ private void initPanel() { reportUndefinedCharacterFormat(ex); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | - PropertyExistException | IllegalTypeException | NotRemoveableException | InvalidStateException | + PropertyExistException | IllegalTypeException | NotRemoveableException | + InvalidStateException | BibEntryNotFoundException ex) { LOGGER.warn("Problem uncombining cite markers", ex); } From 682d04426645a7ae3f9d4c37e8bf6aba96c3c423 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 20 Apr 2021 23:20:09 +0200 Subject: [PATCH 0629/1068] keep closer to the old form --- .../org/jabref/gui/openoffice/StyleSelectDialogViewModel.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java index a8f9d3a639b..df7f6fd3651 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java @@ -77,11 +77,9 @@ public void addStyleFile() { parseLog.formatShort()); } } else { - String title = Localization.lang("Invalid style selected"); - String msg = (Localization.lang("You must select a valid style file.") + dialogService.showErrorDialogAndWait(Localization.lang("Invalid style selected"), Localization.lang("You must select a valid style file.") + "\n" + parseLog.formatShort()); - dialogService.showErrorDialogAndWait(title, msg); } }); } From fd186e67287df52989531ddfb22ce5ca749d19b2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 21 Apr 2021 00:30:36 +0200 Subject: [PATCH 0630/1068] compiled --- src/main/java/org/jabref/logic/openoffice/OOBibStyle.java | 2 +- src/main/java/org/jabref/logic/openoffice/StyleLoader.java | 7 ++++--- src/main/resources/l10n/JabRef_en.properties | 1 - 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index a31f36f7228..27e47c6066a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -436,7 +436,7 @@ public boolean isValid() { public OOBibStyleParser.ParseLog getParseLog() { if (parseLog == null) { parseLog = new OOBibStyleParser.ParseLog(); - parseLog.error(filename, 0, + parseLog.error(path, 0, "OOBibStyle: no parseLog"); } return parseLog; diff --git a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java b/src/main/java/org/jabref/logic/openoffice/StyleLoader.java index 59d5905b5ba..48bf1848124 100644 --- a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java +++ b/src/main/java/org/jabref/logic/openoffice/StyleLoader.java @@ -58,10 +58,11 @@ public List getStyles() { */ public OOBibStyleParser.ParseLog addStyleIfValid(String filename) { Objects.requireNonNull(filename); + OOBibStyleParser.ParseLog parseLog; try { OOBibStyle newStyle = new OOBibStyle(new File(filename), layoutFormatterPreferences, encoding); - OOBibStyleParser.ParseLog parseLog = newStyle.getParseLog(); + parseLog = newStyle.getParseLog(); if (externalStyles.contains(newStyle)) { LOGGER.info("External style file " + filename + " already existing."); @@ -81,11 +82,11 @@ public OOBibStyleParser.ParseLog addStyleIfValid(String filename) { // The file couldn't be found... should we tell anyone? String msg = "Cannot find external style file " + filename; LOGGER.info(msg, e); - OOBibStyleParser.ParseLog parseLog = new OOBibStyleParser.ParseLog(); + parseLog = new OOBibStyleParser.ParseLog(); parseLog.error(filename, 0, msg); } catch (IOException e) { LOGGER.info("Problem reading external style file " + filename, e); - OOBibStyleParser.ParseLog parseLog = new OOBibStyleParser.ParseLog(); + parseLog = new OOBibStyleParser.ParseLog(); String msg = "Problem (IOException) reading external style file " + filename; parseLog.error(filename, 0, msg); } diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 785c77c6cba..386fa950596 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1038,7 +1038,6 @@ Connected\ to\ document=Connected to document Insert\ a\ citation\ without\ text\ (the\ entry\ will\ appear\ in\ the\ reference\ list)=Insert a citation without text (the entry will appear in the reference list) Cite\ selected\ entries\ with\ extra\ information=Cite selected entries with extra information Ensure\ that\ the\ bibliography\ is\ up-to-date=Ensure that the bibliography is up-to-date -Your\ OpenOffice/LibreOffice\ document\ references\ citation\ keys\ which\ could\ not\ be\ found\ in\ your\ current\ library.=Your OpenOffice/LibreOffice document references citation keys which could not be found in your current library. Your\ OpenOffice/LibreOffice\ document\ references\ the\ citation\ key\ '%0',\ which\ could\ not\ be\ found\ in\ your\ current\ library.=Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library. From 333f7bbfc65912f4900031b704e842a45a225e4f Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 22 Apr 2021 14:53:14 +0200 Subject: [PATCH 0631/1068] restore OOBibStyle.java --- .../org/jabref/gui/openoffice/OOBibBase.java | 64 +- .../jabref/logic/openoffice/OOBibStyle.java | 1213 ++++++++++------- .../OOBibStyleGetCitationMarker.java | 2 +- .../OOBibStyleGetNumCitationMarker.java | 10 +- .../logic/openoffice/OOBibStyleParser.java | 28 +- .../logic/openoffice/OOBibStyleTest.java | 74 +- 6 files changed, 785 insertions(+), 606 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 915036840a2..ebbc2dcfbe5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -807,7 +807,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes throws BibEntryNotFoundException { - assert style.getBibTeXKeyCitations(); + assert style.isCitationKeyCiteMarkers(); cgs.createPlainBibliographySortedByComparator(OOBibBase.AUTHOR_YEAR_TITLE_COMPARATOR); @@ -844,8 +844,8 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes throws BibEntryNotFoundException { - assert style.getIsNumberEntries(); - assert style.getIsSortByPosition(); + assert style.isNumberEntries(); + assert style.isSortByPosition(); cgs.createNumberedBibliographySortedInOrderOfAppearance(); @@ -858,9 +858,9 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes List numbers = cg.getSortedNumbers(); List pageInfos = cgs.backend.getPageInfosForCitations(cg); citMarkers.put(cgid, - style.getNumCitationMarkerForInText(numbers, - minGroupingCount, - pageInfos)); + style.getNumCitationMarker(numbers, + minGroupingCount, + pageInfos)); } return citMarkers; @@ -873,8 +873,8 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes private Map produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, OOBibStyle style) { - assert style.getIsNumberEntries(); - assert !style.getIsSortByPosition(); + assert style.isNumberEntries(); + assert !style.isSortByPosition(); cgs.createNumberedBibliographySortedByComparator(OOBibBase.AUTHOR_YEAR_TITLE_COMPARATOR); @@ -887,16 +887,16 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes List numbers = cg.getSortedNumbers(); List pageInfos = cgs.backend.getPageInfosForCitations(cg); citMarkers.put(cgid, - style.getNumCitationMarkerForInText(numbers, - minGroupingCount, - pageInfos)); + style.getNumCitationMarker(numbers, + minGroupingCount, + pageInfos)); } return citMarkers; } /** * Produce citMarkers for normal - * (!getBibTeXKeyCitations && !getIsNumberEntries) styles. + * (!isCitationKeyCiteMarkers && !isNumberEntries) styles. * * @param cgs * @param style Bibliography style. @@ -906,8 +906,8 @@ private Map produceCitationMarkersForNormalStyle(Citati throws BibEntryNotFoundException { - assert !style.getBibTeXKeyCitations(); - assert !style.getIsNumberEntries(); + assert !style.isCitationKeyCiteMarkers(); + assert !style.isNumberEntries(); // Citations in (Au1, Au2 2000) form CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); @@ -1019,7 +1019,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti if (withText) { OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, citationText); DocumentConnection.setCharLocaleNone(cursor); - if (style.getFormatCitations()) { + if (style.isFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); DocumentConnection.setCharStyle(cursor, charStyle); } @@ -1112,7 +1112,7 @@ private void createAndFillCitationGroup(CitationGroups cgs, void assertCitationCharacterFormatIsOK(XTextCursor cursor, OOBibStyle style) throws UndefinedCharacterFormatException { - if (!style.getFormatCitations()) { + if (!style.isFormatCitations()) { return; } @@ -1316,7 +1316,7 @@ public void insertEntry(List entries, } // The text we insert - String citeText = (style.getIsNumberEntries() + String citeText = (style.isNumberEntries() ? "[-]" // A dash only. Only refresh later. : style.getCitationMarker(citationMarkerEntries, inParenthesis, @@ -1429,7 +1429,7 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, // doesn't exist, we end up deleting the markers before the // process crashes due to a the missing format, with // catastrophic consequences for the user. - boolean mustTestCharFormat = style.getFormatCitations(); + boolean mustTestCharFormat = style.isFormatCitations(); for (Map.Entry kv : citMarkers.entrySet()) { @@ -1544,10 +1544,10 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d // // Question: is there a case when we do not need order-of-appearance? // - // style.getBibTeXKeyCitations() : ??? - // style.getIsNumberEntries() && style.getIsSortByPosition() : + // style.isCitationKeyCiteMarkers() : ??? + // style.isNumberEntries() && style.isSortByPosition() : // needs order-of-appearance for numbering - // style.getIsNumberEntries() && !style.getIsSortByPosition() : ??? + // style.isNumberEntries() && !style.isSortByPosition() : ??? // produceCitationMarkersForNormalStyle : needs order-of-appearance for uniqueLetters // boolean mapFootnotesToFootnoteMarks = true; @@ -1562,16 +1562,16 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d // fill citMarkers Map uniqueLetters = new HashMap<>(); - if (style.getBibTeXKeyCitations()) { + if (style.isCitationKeyCiteMarkers()) { citMarkers = produceCitationMarkersForIsCitationKeyCiteMarkers(cgs, style); - } else if (style.getIsNumberEntries()) { - if (style.getIsSortByPosition()) { + } else if (style.isNumberEntries()) { + if (style.isSortByPosition()) { citMarkers = produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); } else { citMarkers = produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); } } else { - /* Normal case, (!getBibTeXKeyCitations && !getIsNumberEntries) */ + /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ citMarkers = produceCitationMarkersForNormalStyle(cgs, style); } @@ -1589,7 +1589,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d * Rebuilds the bibliography. * * Note: assumes fresh `jabRefReferenceMarkNamesSortedByPosition` - * if `style.getIsSortByPosition()` + * if `style.isSortByPosition()` */ private void rebuildBibTextSection(DocumentConnection documentConnection, OOBibStyle style, @@ -1638,8 +1638,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, final boolean debugThisFun = false; if (debugThisFun) { - System.out.printf("Ref IsSortByPosition %s\n", style.getIsSortByPosition()); - System.out.printf("Ref IsNumberEntries %s\n", style.getIsNumberEntries()); + System.out.printf("Ref IsSortByPosition %s\n", style.isSortByPosition()); + System.out.printf("Ref IsNumberEntries %s\n", style.isNumberEntries()); } String parStyle = style.getReferenceParagraphFormat(); @@ -1671,7 +1671,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, } // insert marker "[1]" - if (style.getIsNumberEntries()) { + if (style.isNumberEntries()) { if (ck.number.isEmpty()) { throw new RuntimeException("insertFullReferenceAtCursor:" @@ -1683,8 +1683,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, marker); cursor.collapseToEnd(); } else { - // !style.getIsNumberEntries() : emit no prefix - // TODO: We might want [citationKey] prefix for style.getBibTeXKeyCitations(); + // !style.isNumberEntries() : emit no prefix + // TODO: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); } if (ck.db.isEmpty()) { @@ -2577,7 +2577,7 @@ public void checkStylesExistInTheDocument(OOBibStyle style, DocumentConnection d documentConnection, "ReferenceParagraphFormat", pathToStyleFile); - if (style.getFormatCitations()) { + if (style.isFormatCitations()) { checkCharacterStyleExistsInTheDocument(style.getCitationCharacterFormat(), documentConnection, "CitationCharacterFormat", diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index 27e47c6066a..edeb72a5480 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -28,82 +28,50 @@ import org.jabref.model.entry.types.EntryType; /** - * - * This class embodies bibliography formatting for OpenOffice, which - * is composed of the following elements: - * + * This class embodies a bibliography formatting for OpenOffice, which is composed + * of the following elements: *

- * 1) For each type of {@code BibEntry} we need a formatting specification, - * termed {@code Layout} here. - * - * A formatting is an array of elements, each of which is either - * - a piece of constant text, - * - an entry field value, - * - or a tab. - * Each element has a character format associated with it. + * 1) Each OO BIB entry type must have a formatting. A formatting is an array of elements, each + * of which is either a piece of constant text, an entry field value, or a tab. Each element has + * a character format associated with it. *

- * 2) Many field values (e.g. author) need to be formatted before - * input to OpenOffice. - * - * The style has the responsibility of formatting all field - * values. - * - * Formatting is handled by {@code LayoutFormatter} classes. + * 2) Many field values (e.g. author) need to be formatted before input to OpenOffice. The style + * has the responsibility of formatting all field values. Formatting is handled by 0-n + * JabRef LayoutFormatter classes. *

- * 3) A citation marker must be produced for each entry. - * - * For non-numbered styles this operation is performed for each - * {@code BibEntry} by {@code getCitationMarker}, for numbered styles by - * {@code getNumCitationMarkerForInText}. - * + * 3) If the entries are not numbered, a citation marker must be produced for each entry. This + * operation is performed for each JabRef BibEntry. */ public class OOBibStyle implements Comparable { - /** Unlike many others below, UNDEFINED_CITATION_MARKER is not a - * key to properties or citProperties - */ - public static final String UNDEFINED_CITATION_MARKER = "??"; - - /* - * Keys for the PROPERTIES section of a *.jstyle file. - */ - - // getReferenceHeaderText - private static final String REFERENCE_HEADER_TEXT = "Title"; - private static final String REFERENCE_HEADER_PARAGRAPH_FORMAT = "ReferenceHeaderParagraphFormat"; - private static final String REFERENCE_PARAGRAPH_FORMAT = "ReferenceParagraphFormat"; - - private static final String IS_NUMBER_ENTRIES = "IsNumberEntries"; - private static final String IS_SORT_BY_POSITION = "IsSortByPosition"; - - /* - * Keys for the CITATION section of a *.jstyle file. - */ - - /* - * general - */ - private static final String BIBTEX_KEY_CITATIONS = "BibTeXKeyCitations"; - private static final String MULTI_CITE_CHRONOLOGICAL = "MultiCiteChronological"; + public static final String ITALIC_ET_AL = "ItalicEtAl"; + public static final String MULTI_CITE_CHRONOLOGICAL = "MultiCiteChronological"; + public static final String MINIMUM_GROUPING_COUNT = "MinimumGroupingCount"; + public static final String ET_AL_STRING = "EtAlString"; + public static final String MAX_AUTHORS_FIRST = "MaxAuthorsFirst"; + public static final String REFERENCE_HEADER_PARAGRAPH_FORMAT = "ReferenceHeaderParagraphFormat"; + public static final String REFERENCE_PARAGRAPH_FORMAT = "ReferenceParagraphFormat"; - // general / formatting citations - private static final String FORMAT_CITATIONS = "FormatCitations"; + public static final String TITLE = "Title"; + public static final String UNDEFINED_CITATION_MARKER = "??"; + private static final String BRACKET_AFTER_IN_LIST = "BracketAfterInList"; + private static final String BRACKET_BEFORE_IN_LIST = "BracketBeforeInList"; + private static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; + private static final String CITATION_KEY_CITATIONS = "BibTeXKeyCitations"; + private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations"; + private static final String SUPERSCRIPT_CITATIONS = "SuperscriptCitations"; + private static final String BOLD_CITATIONS = "BoldCitations"; + private static final String ITALIC_CITATIONS = "ItalicCitations"; private static final String CITATION_CHARACTER_FORMAT = "CitationCharacterFormat"; + private static final String FORMAT_CITATIONS = "FormatCitations"; + private static final String GROUPED_NUMBERS_SEPARATOR = "GroupedNumbersSeparator"; - - // These two can do wat ItalicCitations, BoldCitations, + // These two can do what ItalicCitations, BoldCitations, // SuperscriptCitations and SubscriptCitations were supposed to do, // as well as underline smallcaps and strikeout. private static final String CITATION_GROUP_MARKUP_BEFORE = "CitationGroupMarkupBefore"; private static final String CITATION_GROUP_MARKUP_AFTER = "CitationGroupMarkupAfter"; - // These are replaced by CitationGroupMarkupBefore and CitationGroupMarkupAfter - // - // private static final String ITALIC_CITATIONS = "ItalicCitations"; - // private static final String BOLD_CITATIONS = "BoldCitations"; - // private static final String SUPERSCRIPT_CITATIONS = "SuperscriptCitations"; - // private static final String SUBSCRIPT_CITATIONS = "SubscriptCitations"; - private static final String AUTHORS_PART_MARKUP_BEFORE = "AuthorsPartMarkupBefore"; private static final String AUTHORS_PART_MARKUP_AFTER = "AuthorsPartMarkupAfter"; @@ -113,342 +81,735 @@ public class OOBibStyle implements Comparable { private static final String AUTHOR_NAME_MARKUP_BEFORE = "AuthorNameMarkupBefore"; private static final String AUTHOR_NAME_MARKUP_AFTER = "AuthorNameMarkupAfter"; - /* - * common (numeric and author-year) + private static final String PAGE_INFO_SEPARATOR = "PageInfoSeparator"; + private static final String CITATION_SEPARATOR = "CitationSeparator"; + private static final String IN_TEXT_YEAR_SEPARATOR = "InTextYearSeparator"; + private static final String MAX_AUTHORS = "MaxAuthors"; + private static final String YEAR_FIELD = "YearField"; + private static final String AUTHOR_FIELD = "AuthorField"; + private static final String BRACKET_AFTER = "BracketAfter"; + private static final String BRACKET_BEFORE = "BracketBefore"; + private static final String IS_NUMBER_ENTRIES = "IsNumberEntries"; + private static final String IS_SORT_BY_POSITION = "IsSortByPosition"; + private static final String SORT_ALGORITHM = "SortAlgorithm"; + private static final String OXFORD_COMMA = "OxfordComma"; + private static final String YEAR_SEPARATOR = "YearSeparator"; + private static final String AUTHOR_LAST_SEPARATOR_IN_TEXT = "AuthorLastSeparatorInText"; + private static final String AUTHOR_LAST_SEPARATOR = "AuthorLastSeparator"; + + private static final String AUTHOR_SEPARATOR = "AuthorSeparator"; + + + /** Messages from the parser. + * + * Since we are parsing by calling the constructor, there is no way to + * return it to the caller there. */ + OOBibStyleParser.ParseLog parseLog; - /** "{[}Smith 2000]" "Smith {[}2000]" "{[}1]" */ - private static final String BRACKET_BEFORE = "BracketBefore"; + private final SortedSet journals = new TreeSet<>(); + // Formatter to be run on fields before they are used as part of citation marker: + private final LayoutFormatter fieldFormatter = new OOPreFormatter(); + // reference layout mapped from entry type: + private final Map bibLayout = new HashMap<>(); + private final Map properties = new HashMap<>(); + private final Map citProperties = new HashMap<>(); + private final boolean fromResource; + private final String path; + private final Charset encoding; + private final LayoutFormatterPreferences prefs; + private String name = ""; + private Layout defaultBibLayout; + private boolean valid; + private File styleFile; + private long styleFileModificationTime = Long.MIN_VALUE; + private String localCopy; + private boolean isDefaultLayoutPresent; - /** "[Smith 2000{]}" "Smith [2000{]}" "[1{]}" */ - private static final String BRACKET_AFTER = "BracketAfter"; + public OOBibStyle(File styleFile, LayoutFormatterPreferences prefs, + Charset encoding) throws IOException { + this.prefs = Objects.requireNonNull(prefs); + this.styleFile = Objects.requireNonNull(styleFile); + this.encoding = Objects.requireNonNull(encoding); + setDefaultProperties(); + reload(); + fromResource = false; + path = styleFile.getPath(); + } - /** Entry labels in bibliography: "{[}1]" */ - private static final String BRACKET_BEFORE_IN_LIST = "BracketBeforeInList"; + public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) throws IOException { + this.prefs = Objects.requireNonNull(prefs); + Objects.requireNonNull(resourcePath); + this.encoding = StandardCharsets.UTF_8; + setDefaultProperties(); + initialize(OOBibStyle.class.getResourceAsStream(resourcePath), resourcePath); + fromResource = true; + path = resourcePath; + } - /** Entry labels in bibliography: "[1{]}" */ - private static final String BRACKET_AFTER_IN_LIST = "BracketAfterInList"; + public Layout getDefaultBibLayout() { + return defaultBibLayout; + } - /** "[Smith 2000a{; }pp 10-13]" "Smith [2000a{; }pp 10-13]" "[1{; }pp 10-13]" */ - private static final String PAGE_INFO_SEPARATOR = "PageInfoSeparator"; + private void setDefaultProperties() { + // Set default property values: + properties.put(TITLE, "Bibliography"); + properties.put(SORT_ALGORITHM, "alphanumeric"); + properties.put(IS_SORT_BY_POSITION, Boolean.FALSE); + properties.put(IS_NUMBER_ENTRIES, Boolean.FALSE); + properties.put(BRACKET_BEFORE, "["); + properties.put(BRACKET_AFTER, "]"); + properties.put(REFERENCE_PARAGRAPH_FORMAT, "Standard"); + properties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1"); + + // Set default properties for the citation marker: + citProperties.put(AUTHOR_FIELD, FieldFactory.serializeOrFields(StandardField.AUTHOR, StandardField.EDITOR)); + + citProperties.put(CITATION_GROUP_MARKUP_BEFORE, ""); + citProperties.put(CITATION_GROUP_MARKUP_AFTER, ""); + + citProperties.put(AUTHORS_PART_MARKUP_BEFORE, ""); + citProperties.put(AUTHORS_PART_MARKUP_AFTER, ""); + + citProperties.put(AUTHOR_NAMES_LIST_MARKUP_BEFORE, ""); + citProperties.put(AUTHOR_NAMES_LIST_MARKUP_AFTER, ""); + + citProperties.put(AUTHOR_NAME_MARKUP_BEFORE, ""); + citProperties.put(AUTHOR_NAME_MARKUP_AFTER, ""); + + citProperties.put(YEAR_FIELD, StandardField.YEAR.getName()); + citProperties.put(MAX_AUTHORS, 3); + citProperties.put(MAX_AUTHORS_FIRST, -1); + citProperties.put(AUTHOR_SEPARATOR, ", "); + citProperties.put(AUTHOR_LAST_SEPARATOR, " & "); + citProperties.put(AUTHOR_LAST_SEPARATOR_IN_TEXT, null); + citProperties.put(ET_AL_STRING, " et al."); + citProperties.put(YEAR_SEPARATOR, ", "); + citProperties.put(IN_TEXT_YEAR_SEPARATOR, " "); + citProperties.put(BRACKET_BEFORE, "("); + citProperties.put(BRACKET_AFTER, ")"); + citProperties.put(CITATION_SEPARATOR, "; "); + citProperties.put(PAGE_INFO_SEPARATOR, "; "); + citProperties.put(GROUPED_NUMBERS_SEPARATOR, "-"); + citProperties.put(MINIMUM_GROUPING_COUNT, 3); + citProperties.put(FORMAT_CITATIONS, Boolean.FALSE); + citProperties.put(CITATION_CHARACTER_FORMAT, "Standard"); + citProperties.put(ITALIC_CITATIONS, Boolean.FALSE); + citProperties.put(BOLD_CITATIONS, Boolean.FALSE); + citProperties.put(SUPERSCRIPT_CITATIONS, Boolean.FALSE); + citProperties.put(SUBSCRIPT_CITATIONS, Boolean.FALSE); + citProperties.put(MULTI_CITE_CHRONOLOGICAL, Boolean.TRUE); + citProperties.put(CITATION_KEY_CITATIONS, Boolean.FALSE); + citProperties.put(ITALIC_ET_AL, Boolean.FALSE); + citProperties.put(OXFORD_COMMA, ""); + } - /** "[Smith 2000{; }Jones 2001]" "Smith [2000{; }Jones [2001]" "[1{; }2]" */ - private static final String CITATION_SEPARATOR = "CitationSeparator"; + public String getName() { + return name; + } - /* - * numeric + public String getPath() { + return path; + } + + public File getFile() { + return styleFile; + } + + public Set getJournals() { + return Collections.unmodifiableSet(journals); + } + + private void initialize(InputStream stream, String filename) throws IOException { + Objects.requireNonNull(stream); + + // remove data from a previous parse + localCopy = null; + name = ""; + journals.clear(); + properties.clear(); + citProperties.clear(); + bibLayout.clear(); + setDefaultBibLayout(null); + setIsDefaultLayoutPresent(false); + setValid(false); + setDefaultProperties(); + this.parseLog = null; + + try (Reader reader = new InputStreamReader(stream, encoding)) { + this.parseLog = OOBibStyleParser.readFormatFile(reader, this, filename); + } + } + + /** + * If this style was initialized from a file on disk, reload the style + * if the file has been modified since it was read. + * + * @throws IOException */ + public void ensureUpToDate() throws IOException { + if (!isUpToDate()) { + reload(); + } + } - /** How many consecutive numbers in "[1; 2; 3]" allows grouping to "[1-3]" */ - private static final String MINIMUM_GROUPING_COUNT = "MinimumGroupingCount"; + /** + * If this style was initialized from a file on disk, reload the style + * information. + * + * @throws IOException + */ + private void reload() throws IOException { + if (styleFile != null) { + this.styleFileModificationTime = styleFile.lastModified(); + try (InputStream stream = new FileInputStream(styleFile)) { + initialize(stream, styleFile.getAbsolutePath()); + } + } + } - /** "[1{-}3]" */ - private static final String GROUPED_NUMBERS_SEPARATOR = "GroupedNumbersSeparator"; + /** + * If this style was initialized from a file on disk, check whether the file + * is unmodified since initialization. + * + * @return true if the file has not been modified, false otherwise. + */ + private boolean isUpToDate() { + if (styleFile == null) { + return true; + } else { + return styleFile.lastModified() == this.styleFileModificationTime; + } + } - /* - * author-year + /** + * After initializing this style from a file, this method can be used to check + * whether the file appeared to be a proper style file. + * + * @return true if the file could be parsed as a style file, false otherwise. */ + public boolean isValid() { + return valid; + } - /** Name of field that contains the authors. May be a list: "author/editor" */ - private static final String AUTHOR_FIELD = "AuthorField"; + public Layout getReferenceFormat(EntryType type) { + Layout l = bibLayout.get(type); + if (l == null) { + return defaultBibLayout; + } else { + return l; + } + } - /** Name of field that contains the year. May be a list "year/anotherFieldWithYear" */ - private static final String YEAR_FIELD = "YearField"; + /** + * Format a number-based citation marker for the given number. + * + * @param number The citation numbers. + * @return The text for the citation. + */ + public String getNumCitationMarker(List number, + int minGroupingCount, + List pageInfosForCitations) { + return OOBibStyleGetNumCitationMarker.getNumCitationMarker(this, + number, + minGroupingCount, + pageInfosForCitations); + } + + /* moved to OOBibStyleGetCitationMarker + public String getCitationMarker(List entries, Map database, boolean inParenthesis, + String[] uniquefiers, int[] unlimAuthors) { + // Look for groups of uniquefied entries that should be combined in the output. + // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). + int piv = -1; + String tmpMarker = null; + if (uniquefiers != null) { + for (int i = 0; i < uniquefiers.length; i++) { + + if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { + // This entry has no uniquefier. + // Check if we just passed a group of more than one entry with uniquefier: + if ((piv > -1) && (i > (piv + 1))) { + // Do the grouping: + group(entries, uniquefiers, piv, i - 1); + } + + piv = -1; + } else { + BibEntry currentEntry = entries.get(i); + if (piv == -1) { + piv = i; + tmpMarker = getAuthorYearParenthesisMarker(Collections.singletonList(currentEntry), database, + null, unlimAuthors); + } else { + // See if this entry can go into a group with the previous one: + String thisMarker = getAuthorYearParenthesisMarker(Collections.singletonList(currentEntry), + database, null, unlimAuthors); + + String authorField = getStringCitProperty(AUTHOR_FIELD); + int maxAuthors = getIntCitProperty(MAX_AUTHORS); + String author = getCitationMarkerField(currentEntry, database.get(currentEntry), + authorField); + AuthorList al = AuthorList.parse(author); + int prevALim = unlimAuthors[i - 1]; // i always at least 1 here + if (!thisMarker.equals(tmpMarker) + || ((al.getNumberOfAuthors() > maxAuthors) && (unlimAuthors[i] != prevALim))) { + // No match. Update piv to exclude the previous entry. But first check if the + // previous entry was part of a group: + if ((piv > -1) && (i > (piv + 1))) { + // Do the grouping: + group(entries, uniquefiers, piv, i - 1); + } + tmpMarker = thisMarker; + piv = i; + } + } + } - /** How many authors to show before switching to "et al." */ - private static final String MAX_AUTHORS = "MaxAuthors"; + } + // Finished with the loop. See if the last entries form a group: + if (piv >= 0) { + // Do the grouping: + group(entries, uniquefiers, piv, uniquefiers.length - 1); + } + } - /** The first appearance of a source may have a higher limit. */ - private static final String MAX_AUTHORS_FIRST = "MaxAuthorsFirst"; + if (inParenthesis) { + return getAuthorYearParenthesisMarker(entries, database, uniquefiers, unlimAuthors); + } else { + return getAuthorYearInTextMarker(entries, database, uniquefiers, unlimAuthors); + } + } + */ - /** "[Smith{, }Jones, and Brown 2000]" */ - private static final String AUTHOR_SEPARATOR = "AuthorSeparator"; + /* removed + private void group(List entries, String[] uniquefiers, int from, int to) { + String separator = getStringCitProperty(UNIQUEFIER_SEPARATOR); + StringBuilder sb = new StringBuilder(uniquefiers[from]); + for (int i = from + 1; i <= to; i++) { + sb.append(separator); + sb.append(uniquefiers[i]); + entries.set(i, null); + } + uniquefiers[from] = sb.toString(); + } + */ + + /* moved to OOBibStyleGetCitationMarker + private String getAuthorYearParenthesisMarker(List entries, Map database, + String[] uniquifiers, int[] unlimAuthors) { + + String authorField = getStringCitProperty(AUTHOR_FIELD); // The bibtex field providing author names, e.g. "author" or "editor". + int maxA = getIntCitProperty(MAX_AUTHORS); // The maximum number of authors to write out in full without using etal. Set to + // -1 to always write out all authors. + String yearSep = getStringCitProperty(YEAR_SEPARATOR); // The String to separate authors from year, e.g. "; ". + String startBrace = getStringCitProperty(BRACKET_BEFORE); // The opening parenthesis. + String endBrace = getStringCitProperty(BRACKET_AFTER); // The closing parenthesis. + String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); // The String to separate citations from each other. + String yearField = getStringCitProperty(YEAR_FIELD); // The bibtex field providing the year, e.g. "year". + String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR); // The String to add between the two last author names, e.g. " & ". + StringBuilder sb = new StringBuilder(startBrace); + for (int j = 0; j < entries.size(); j++) { + BibEntry currentEntry = entries.get(j); + + // Check if this entry has been nulled due to grouping with the previous entry(ies): + if (currentEntry == null) { + continue; + } - /** "[Smith, Jones{,} and Brown 2000]" */ - private static final String OXFORD_COMMA = "OxfordComma"; + if (j > 0) { + sb.append(citationSeparator); + } - /** "[Smith, Jones,{ and }Brown 2000]" */ - private static final String AUTHOR_LAST_SEPARATOR = "AuthorLastSeparator"; + BibDatabase currentDatabase = database.get(currentEntry); + int unlimA = unlimAuthors == null ? -1 : unlimAuthors[j]; + int maxAuthors = unlimA > 0 ? unlimA : maxA; - /** "Smith, Jones,{ and }Brown [2000]" */ - private static final String AUTHOR_LAST_SEPARATOR_IN_TEXT = "AuthorLastSeparatorInText"; + String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); + String authorString = createAuthorList(author, maxAuthors, andString, yearSep); + sb.append(authorString); + String year = getCitationMarkerField(currentEntry, currentDatabase, yearField); + if (year != null) { + sb.append(year); + } + if ((uniquifiers != null) && (uniquifiers[j] != null)) { + sb.append(uniquifiers[j]); + } + } + sb.append(endBrace); + return sb.toString(); + } + */ + + /* moved to OOBibStyleGetCitationMarker + private String getAuthorYearInTextMarker(List entries, Map database, + String[] uniquefiers, + int[] unlimAuthors) { + String authorField = getStringCitProperty(AUTHOR_FIELD); // The bibtex field providing author names, e.g. "author" or "editor". + int maxA = getIntCitProperty(MAX_AUTHORS); // The maximum number of authors to write out in full without using etal. Set to + // -1 to always write out all authors. + String yearSep = getStringCitProperty(IN_TEXT_YEAR_SEPARATOR); // The String to separate authors from year, e.g. "; ". + String startBrace = getStringCitProperty(BRACKET_BEFORE); // The opening parenthesis. + String endBrace = getStringCitProperty(BRACKET_AFTER); // The closing parenthesis. + String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); // The String to separate citations from each other. + String yearField = getStringCitProperty(YEAR_FIELD); // The bibtex field providing the year, e.g. "year". + String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR_IN_TEXT); // The String to add between the two last author names, e.g. " & ". + + if (andString == null) { + // Use the default one if no explicit separator for text is defined + andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR); + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < entries.size(); i++) { + BibEntry currentEntry = entries.get(i); - private static final String ITALIC_ET_AL = "ItalicEtAl"; - /** "[Smith{ et al.} 2000]" */ - private static final String ET_AL_STRING = "EtAlString"; + // Check if this entry has been nulled due to grouping with the previous entry(ies): + if (currentEntry == null) { + continue; + } - /** "[Smith et al.{ }2000]" */ - private static final String YEAR_SEPARATOR = "YearSeparator"; + BibDatabase currentDatabase = database.get(currentEntry); + int unlimA = unlimAuthors == null ? -1 : unlimAuthors[i]; + int maxAuthors = unlimA > 0 ? unlimA : maxA; - /** "Smith et al.{ }[2000]" */ - private static final String IN_TEXT_YEAR_SEPARATOR = "InTextYearSeparator"; + if (i > 0) { + sb.append(citationSeparator); + } + String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); + String authorString = createAuthorList(author, maxAuthors, andString, yearSep); + sb.append(authorString); + sb.append(startBrace); + String year = getCitationMarkerField(currentEntry, currentDatabase, yearField); + if (year != null) { + sb.append(year); + } + if ((uniquefiers != null) && (uniquefiers[i] != null)) { + sb.append(uniquefiers[i]); + } + sb.append(endBrace); + } + return sb.toString(); + } + */ - /** "[Smith et al. 2000a{,}b; pp 10-13]" */ - private static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; - // end of keys + /* moved to OOBibStyleGetCitationMarker + private String getCitationMarkerField(BibEntry entry, BibDatabase database, String fields) { + Objects.requireNonNull(entry, "Entry cannot be null"); + Objects.requireNonNull(database, "database cannot be null"); - // private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); + Set authorFields = FieldFactory.parseOrFields(getStringCitProperty(AUTHOR_FIELD)); + for (Field field : FieldFactory.parseOrFields(fields)) { + Optional content = entry.getResolvedFieldOrAlias(field, database); - /** Formatter to be run on fields before they are used as part of citation marker. - * - * Usage: String output = fieldFormatter.format(input); - * - * Input: LaTeX, output: unicode with a small set of HTML tags - * indicating character formatting. - * - * Note: OOPreFormatter is stateless, the above call is equivalent to - * - * String output = OOPreFormatter.latexToUnicodeWithHtmlTags(input); + if ((content.isPresent()) && !content.get().trim().isEmpty()) { + if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content.get())) { + return "{" + fieldFormatter.format(content.get()) + "}"; + } + return fieldFormatter.format(content.get()); + } + } + // No luck? Return an empty string: + return ""; + } + */ + + /* moved to OOBibStyleGetCitationMarker + private String getAuthorLastName(AuthorList al, int number) { + StringBuilder sb = new StringBuilder(); + + if (al.getNumberOfAuthors() > number) { + Author a = al.getAuthor(number); + a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> sb.append(von).append(' ')); + sb.append(a.getLast().orElse("")); + } + + return sb.toString(); + } + */ + + /* removed + public String insertPageInfo(String citation, String pageInfo) { + String bracketAfter = getStringCitProperty(BRACKET_AFTER); + if (citation.endsWith(bracketAfter)) { + String first = citation.substring(0, citation.length() - bracketAfter.length()); + return first + getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo + bracketAfter; + } else { + return citation + getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo; + } + } + */ + + /** + * Convenience method for checking the property for whether we use number citations or + * author-year citations. * + * @return true if we use numbered citations, false otherwise. */ - protected final LayoutFormatter fieldFormatter = new OOPreFormatter(); + public boolean isNumberEntries() { + return (Boolean) getProperty(IS_NUMBER_ENTRIES); + } - /* - * Used or modified in OOBibStyleParser.readFormatFile() + /** + * Convenience method for checking the property for whether we sort the bibliography + * according to their order of appearance in the text. + * + * @return true to sort by appearance, false to sort alphabetically. */ - String localCopy; + public boolean isSortByPosition() { + return (Boolean) getProperty(IS_SORT_BY_POSITION); + } - String obsName = ""; - final SortedSet journals = new TreeSet<>(); + /** + * Convenience method for checking whether citation markers should be italicized. + * Will only be relevant if isFormatCitations() returns true. + * + * @return true to indicate that citations should be in italics. + */ + public boolean isItalicCitations() { + return (Boolean) citProperties.get(ITALIC_CITATIONS); + } - final Map obsProperties = new HashMap<>(); - final Map obsCitProperties = new HashMap<>(); + /** + * Convenience method for checking whether citation markers should be bold. + * Will only be relevant if isFormatCitations() returns true. + * + * @return true to indicate that citations should be in bold. + */ + public boolean isBoldCitations() { + return (Boolean) citProperties.get(BOLD_CITATIONS); + } - // reference layout mapped from entry type: - final Map bibLayout = new HashMap<>(); - Layout defaultBibLayout; - boolean isDefaultLayoutPresent; + /** + * Convenience method for checking whether citation markers formatted + * according to the results of the isItalicCitations() and + * isBoldCitations() methods. + * + * @return true to indicate that citations should be in italics. + */ + public boolean isFormatCitations() { + return (Boolean) citProperties.get(FORMAT_CITATIONS); + } - final LayoutFormatterPreferences prefs; - boolean valid; + public boolean isCitationKeyCiteMarkers() { + return (Boolean) citProperties.get(CITATION_KEY_CITATIONS); + } - /** Messages from that parser. + /** + * Get boolean property. * - * Since we are parsing from the constructor, there is no way to - * return it to the caller there. + * @param key The property key + * @return the value */ - OOBibStyleParser.ParseLog parseLog; + public boolean getBooleanCitProperty(String key) { + return (Boolean) citProperties.get(key); + } + public int getIntCitProperty(String key) { + return (Integer) citProperties.get(key); + } - private final boolean fromResource; - private final String path; - private final Charset encoding; + public String getStringCitProperty(String key) { + return (String) citProperties.get(key); + } - private File styleFile; - private long styleFileModificationTime = Long.MIN_VALUE; + public String getCitationCharacterFormat() { + return getStringCitProperty(CITATION_CHARACTER_FORMAT); + } /** - * Construct from user-provided style file. + * Get a style property. + * + * @param propName The property name. + * @return The property value, or null if it doesn't exist. */ - public OOBibStyle(File styleFile, - LayoutFormatterPreferences prefs, - Charset encoding) throws IOException { - this.prefs = Objects.requireNonNull(prefs); - this.styleFile = Objects.requireNonNull(styleFile); - this.encoding = Objects.requireNonNull(encoding); - // setDefaultProperties(); // moved into initialize() - obsReload(); - fromResource = false; - path = styleFile.getPath(); + public Object getProperty(String propName) { + return properties.get(propName); } /** - * Construct from resource. + * Indicate if it is an internal style + * + * @return True if an internal style */ - public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) throws IOException { - this.prefs = Objects.requireNonNull(prefs); - Objects.requireNonNull(resourcePath); - this.encoding = StandardCharsets.UTF_8; - // setDefaultProperties(); // moved into initialize() - initialize(OOBibStyle.class.getResourceAsStream(resourcePath), resourcePath); - fromResource = true; - path = resourcePath; + public boolean isInternalStyle() { + return fromResource; } - private void setDefaultProperties() { - // Set default property values: - obsProperties.put(REFERENCE_HEADER_TEXT, "Bibliography"); - obsProperties.put(REFERENCE_HEADER_PARAGRAPH_FORMAT, "Heading 1"); - - // Note: was default, but that is not known to LO - obsProperties.put(REFERENCE_PARAGRAPH_FORMAT, "Standard"); - - obsProperties.put(IS_NUMBER_ENTRIES, Boolean.FALSE); - obsProperties.put(IS_SORT_BY_POSITION, Boolean.FALSE); - - // Set default obsCitProperties for the citation marker: + public String getLocalCopy() { + return localCopy; + } - /* - * Character formatting. - */ - obsCitProperties.put(FORMAT_CITATIONS, Boolean.FALSE); - // was "Default", but that is not knowm to LO - obsCitProperties.put(CITATION_CHARACTER_FORMAT, "Standard"); + @Override + public int compareTo(OOBibStyle other) { + return getName().compareTo(other.getName()); + } - obsCitProperties.put(CITATION_GROUP_MARKUP_BEFORE, ""); - obsCitProperties.put(CITATION_GROUP_MARKUP_AFTER, ""); + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof OOBibStyle) { + OOBibStyle otherStyle = (OOBibStyle) o; + return Objects.equals(path, otherStyle.path) + && Objects.equals(name, otherStyle.name) + && Objects.equals(citProperties, otherStyle.citProperties) + && Objects.equals(properties, otherStyle.properties) + // Do not ignore a reload if the user + // changed the LAYOUT section. + && Objects.equals(Objects.hashCode(localCopy), + Objects.hashCode(otherStyle.localCopy)); + } + return false; + } - obsCitProperties.put(AUTHORS_PART_MARKUP_BEFORE, ""); - obsCitProperties.put(AUTHORS_PART_MARKUP_AFTER, ""); + @Override + public int hashCode() { + return Objects.hash(path, name, citProperties, properties, localCopy); + } + + /* moved to OOBibStyleGetCitationMarker as formatAuthorList + private String createAuthorList(String author, int maxAuthors, String andString, + String yearSep) { + Objects.requireNonNull(author); + String etAlString = getStringCitProperty(ET_AL_STRING); // The String to represent authors that are not mentioned, e.g. " et al." + String authorSep = getStringCitProperty(AUTHOR_SEPARATOR); // The String to add between author names except the last two, e.g. ", ". + String oxfordComma = getStringCitProperty(OXFORD_COMMA); // The String to put after the second to last author in case of three or more authors + StringBuilder sb = new StringBuilder(); + AuthorList al = AuthorList.parse(author); + if (!al.isEmpty()) { + sb.append(getAuthorLastName(al, 0)); + } + if ((al.getNumberOfAuthors() > 1) && ((al.getNumberOfAuthors() <= maxAuthors) || (maxAuthors < 0))) { + int j = 1; + while (j < (al.getNumberOfAuthors() - 1)) { + sb.append(authorSep); + sb.append(getAuthorLastName(al, j)); + j++; + } + if (al.getNumberOfAuthors() > 2) { + sb.append(oxfordComma); + } + sb.append(andString); + sb.append(getAuthorLastName(al, al.getNumberOfAuthors() - 1)); + } else if (al.getNumberOfAuthors() > maxAuthors) { + sb.append(etAlString); + } + sb.append(yearSep); + return sb.toString(); + } + */ - obsCitProperties.put(AUTHOR_NAMES_LIST_MARKUP_BEFORE, ""); - obsCitProperties.put(AUTHOR_NAMES_LIST_MARKUP_AFTER, ""); + /* moved to OOBibStyleParser.java + enum BibStyleMode { + NONE, + LAYOUT, + PROPERTIES, + CITATION, + NAME, + JOURNALS + } + */ - obsCitProperties.put(AUTHOR_NAME_MARKUP_BEFORE, ""); - obsCitProperties.put(AUTHOR_NAME_MARKUP_AFTER, ""); + /** The String to represent authors that are not mentioned, + * e.g. " et al." + */ + public String getEtAlString() { + return getStringCitProperty(OOBibStyle.ET_AL_STRING); + } - obsCitProperties.put(AUTHOR_FIELD, - FieldFactory.serializeOrFields(StandardField.AUTHOR, - StandardField.EDITOR)); - obsCitProperties.put(YEAR_FIELD, StandardField.YEAR.getName()); - obsCitProperties.put(MAX_AUTHORS, 3); - obsCitProperties.put(MAX_AUTHORS_FIRST, -1); - obsCitProperties.put(AUTHOR_SEPARATOR, ", "); - obsCitProperties.put(AUTHOR_LAST_SEPARATOR, " & "); - obsCitProperties.put(AUTHOR_LAST_SEPARATOR_IN_TEXT, null); - obsCitProperties.put(ET_AL_STRING, " et al."); - obsCitProperties.put(YEAR_SEPARATOR, ", "); - obsCitProperties.put(IN_TEXT_YEAR_SEPARATOR, " "); + /** The String to add between author names except the last two: + * "[Smith{, }Jones and Brown]" + */ + protected String getAuthorSeparator() { + return getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR); + } - obsCitProperties.put(BRACKET_BEFORE, "("); - obsCitProperties.put(BRACKET_AFTER, ")"); + /** The String to put after the second to last author in case + * of three or more authors: (A, B{,} and C) + */ + protected String getOxfordComma() { + return getStringCitProperty(OOBibStyle.OXFORD_COMMA); + } - obsCitProperties.put(CITATION_SEPARATOR, "; "); - obsCitProperties.put(PAGE_INFO_SEPARATOR, "; "); - obsCitProperties.put(GROUPED_NUMBERS_SEPARATOR, "-"); - obsCitProperties.put(MINIMUM_GROUPING_COUNT, 3); + /** + * Title for the bibliography. + */ + public String getReferenceHeaderText() { + return getStringProperty(OOBibStyle.TITLE); + } - obsCitProperties.put(MULTI_CITE_CHRONOLOGICAL, Boolean.TRUE); - obsCitProperties.put(BIBTEX_KEY_CITATIONS, Boolean.FALSE); // "BibTeXKeyCitations" - obsCitProperties.put(OXFORD_COMMA, ""); + /** + * Name of paragraph format (within OO/LO) to be used for + * the title of the bibliography. + */ + public String getReferenceHeaderParagraphFormat() { + return getStringProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT); + } - // Obsolete, keep for backward compat. - obsCitProperties.put(ITALIC_ET_AL, Boolean.FALSE); + /** + * Name of paragraph format (within OO/LO) to be used for + * the entries in the bibliography. + */ + public String getReferenceParagraphFormat() { + return getStringProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); } - // public Layout getDefaultBibLayout() { - // return defaultBibLayout; - // } + protected LayoutFormatter getFieldFormatter() { + return fieldFormatter; + } - public String getName() { - return obsName; + protected Map getBibLayout() { + return bibLayout; } - public String getPath() { - return path; + protected Map getProperties() { + return properties; } - public File getFile() { - return styleFile; + protected Map getCitProperties() { + return citProperties; } - public Set getJournals() { - return Collections.unmodifiableSet(journals); + protected void addJournal(String s) { + journals.add(s); } - /** - * Note: current values are not reset: there may remain data from - * earlier versions of the input. This may be confusing for the - * user (modified file until it works, but next time it fails again). - */ - private void initialize(InputStream stream, String filename) throws IOException { - Objects.requireNonNull(stream); + protected void setLocalCopy(String s) { + localCopy = s; + } - // remove data from a previous parse - localCopy = null; - obsName = ""; - journals.clear(); - obsProperties.clear(); - obsCitProperties.clear(); - bibLayout.clear(); - defaultBibLayout = null; - isDefaultLayoutPresent = false; - valid = false; - setDefaultProperties(); - this.parseLog = null; + protected void setName(String s) { + name = s; + } - // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html - // - // The try-with-resources Statement - // - try (Reader reader = new InputStreamReader(stream, encoding)) { - this.parseLog = OOBibStyleParser.readFormatFile(reader, this, filename); - // System.out.print(pp.format()); - } + protected boolean getIsDefaultLayoutPresent() { + return isDefaultLayoutPresent; } - /** - * If this style was initialized from a file on disk, check whether the file - * is unmodified since initialization. - * - * @return true if the file has not been modified, false otherwise. - */ - private boolean isUpToDate() { - if (styleFile == null) { - return true; - } else { - return styleFile.lastModified() == this.styleFileModificationTime; - } + protected void setIsDefaultLayoutPresent(boolean b) { + isDefaultLayoutPresent = b; } - /** - * If this style was initialized from a file on disk, reload the style - * if the file has been modified since it was read. - */ - public void ensureUpToDate() throws IOException { - if (!isUpToDate()) { - obsReload(); - } + protected void setValid(boolean b) { + valid = b; } - /** - * If this style was initialized from a file on disk, reload the style - * information. - * - * @return true if reloaded - */ - private boolean obsReload() throws IOException { - if (styleFile != null) { - this.styleFileModificationTime = styleFile.lastModified(); - try (InputStream stream = new FileInputStream(styleFile)) { - initialize(stream, styleFile.getAbsolutePath()); - } - return true; - } else { - return false; - } + protected LayoutFormatterPreferences getPrefs() { + return prefs; } - /** - * After initializing this style from a file, this method can be used to check - * whether the file appeared to be a proper style file. - * - * @return true if the file could be parsed as a style file, false otherwise. - */ - public boolean isValid() { - return valid && !getParseLog().hasError(); + protected void setDefaultBibLayout(Layout l) { + defaultBibLayout = l; } /** - * May return null. + * Format a number-based bibliography label for the given number. */ - public OOBibStyleParser.ParseLog getParseLog() { - if (parseLog == null) { - parseLog = new OOBibStyleParser.ParseLog(); - parseLog.error(path, 0, - "OOBibStyle: no parseLog"); - } - return parseLog; - } - - public Layout getReferenceFormat(EntryType type) { - Layout l = bibLayout.get(type); - if (l == null) { - return defaultBibLayout; - } else { - return l; - } + public String getNumCitationMarkerForBibliography(int number) { + return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, + number); } public static String regularizePageInfo(String p) { @@ -509,36 +870,6 @@ public static int comparePageInfo(String a, String b) { return aa.compareTo(bb); } - /** - * See {@see getNumCitationMarkerCommon} for details. - */ - public String getNumCitationMarkerForInText(List numbers, - int minGroupingCount, - List pageInfosForCitations) { - return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForInText(this, - numbers, - minGroupingCount, - pageInfosForCitations); - } - - /** - * Create a numeric marker for use in the bibliography as label for the entry. - * - * To support for example numbers in superscript without brackets for the text, - * but "[1]" form for the bibliography, the style can provide - * the optional "BracketBeforeInList" and "BracketAfterInList" strings - * to be used in the bibliography instead of "BracketBefore" and "BracketAfter" - * - * @return "[${number}]" where - * "[" stands for BRACKET_BEFORE_IN_LIST (with fallback BRACKET_BEFORE) - * "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER) - * "${number}" stands for the formatted number. - */ - public String getNumCitationMarkerForBibliography(int number) { - return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, - number); - } - public String getNormalizedCitationMarker(CitationMarkerEntry ce) { return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, ce, Optional.empty()); } @@ -554,12 +885,21 @@ public enum NonUniqueCitationMarker { THROWS } + public OOBibStyleParser.ParseLog getParseLog() { + if (parseLog == null) { + parseLog = new OOBibStyleParser.ParseLog(); + parseLog.error(path, 0, "OOBibStyle: no parseLog"); + setValid(false); + } + return parseLog; + } + /** - * Format the marker for an the in-text citation according to - * this style. - * - * Uniquefier letters are added as provided by - * CitationMarkerEntry.getUniqueLetter(). + * Format the marker for the in-text citation according to this + * BIB style. Uniquefier letters are added as provided by the + * citationMarkerEntries argument. If successive entries within + * the citation are uniquefied from each other, this method will + * perform a grouping of these entries. * * If successive entries within the citation are uniquefied from * each other, this method will perform a grouping of these @@ -591,99 +931,12 @@ public String getCitationMarker(List citationMarkerEntries, nonUniqueCitationMarkerHandling); } - /** - * Indicate if it is an internal style - * - * @return True if an internal style - */ - public boolean isInternalStyle() { - return fromResource; - } - - public String getLocalCopy() { - return localCopy; - } - - @Override - public int compareTo(OOBibStyle other) { - return getName().compareTo(other.getName()); - } - - private String nullToEmpty(String s) { - return (s == null ? "" : s); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o instanceof OOBibStyle) { - OOBibStyle otherStyle = (OOBibStyle) o; - return (Objects.equals(path, otherStyle.path) - && (nullToEmpty(localCopy) - .equals(nullToEmpty(otherStyle.localCopy)))); - // return (Objects.equals(path, otherStyle.path) - // && Objects.equals(obsName, otherStyle.obsName) - // && Objects.equals(obsCitProperties, otherStyle.obsCitProperties) - // && Objects.equals(obsProperties, otherStyle.obsProperties) - // // bibLayout does no count? - // ); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(path, obsName, obsCitProperties, obsProperties); - } - /* * * Property getters * */ - // /** - // * Get a style property. - // * - // * @param propName The property name. - // * @return The property value, or null if it doesn't exist. - // */ - // private Object getProperty(String propName) { - // return obsProperties.get(propName); - // } - - private boolean getBooleanProperty(String propName) { - return (Boolean) obsProperties.get(propName); - } - - private String getStringProperty(String propName) { - return (String) obsProperties.get(propName); - } - - // private int getIntProperty(String key) { - // return (Integer) obsProperties.get(key); - // } - - /** - * Get boolean property. - * - * @param key The property key - * @return the value - */ - private boolean getBooleanCitProperty(String key) { - return (Boolean) obsCitProperties.get(key); - } - - private int getIntCitProperty(String key) { - return (Integer) obsCitProperties.get(key); - } - - public String getStringCitProperty(String key) { - return (String) obsCitProperties.get(key); - } - /** * Minimal number of consecutive citation numbers needed to start * replacing with an range like "10-13". @@ -699,43 +952,17 @@ public String getGroupedNumbersSeparator() { return getStringCitProperty(OOBibStyle.GROUPED_NUMBERS_SEPARATOR); } - /** - * Shall we use number citations or author-year citations. - * - * @return true if we use numbered citations, false otherwise. - */ - public boolean getIsNumberEntries() { - return getBooleanProperty(IS_NUMBER_ENTRIES); - } - - /** - * Shall we sort the bibliography entries according to their order - * of first appearance in the text. - * - * @return true to sort by order of appearance, false to sort alphabetically. - */ - public boolean getIsSortByPosition() { - return getBooleanProperty(IS_SORT_BY_POSITION); + private boolean getBooleanProperty(String propName) { + return (Boolean) properties.get(propName); } - /* - * Character formatting - */ - - /** - * Should citation markers be formatted - * according to getCitationCharacterFormat()? - * - * @return true to indicate that citations should be formatted to - * getCitationCharacterFormat(). - */ - public boolean getFormatCitations() { - return (Boolean) obsCitProperties.get(FORMAT_CITATIONS); + private String getStringProperty(String propName) { + return (String) properties.get(propName); } - public String getCitationCharacterFormat() { - return getStringCitProperty(CITATION_CHARACTER_FORMAT); - } + // private int getIntProperty(String key) { + // return (Integer) properties.get(key); + // } /** * Should citation markers be italicized? @@ -776,14 +1003,6 @@ public String getAuthorNameMarkupAfter() { return getStringCitProperty(AUTHOR_NAME_MARKUP_AFTER); } - /* - * - */ - public boolean getBibTeXKeyCitations() { - // "BibTeXKeyCitations" - return (Boolean) obsCitProperties.get(BIBTEX_KEY_CITATIONS); - } - public boolean getMultiCiteChronological() { // "MultiCiteChronological" return this.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL); @@ -887,48 +1106,8 @@ public String getBracketAfterInListWithFallBack() { getBracketAfter()); } - /** The String to represent authors that are not mentioned, - * e.g. " et al." - */ - public String getEtAlString() { - return getStringCitProperty(OOBibStyle.ET_AL_STRING); - } - - /** The String to add between author names except the last two: - * "[Smith{, }Jones and Brown]" - */ - protected String getAuthorSeparator() { - return getStringCitProperty(OOBibStyle.AUTHOR_SEPARATOR); - } - - /** The String to put after the second to last author in case - * of three or more authors: (A, B{,} and C) - */ - protected String getOxfordComma() { - return getStringCitProperty(OOBibStyle.OXFORD_COMMA); - } - - /** - * Title for the bibliography. - */ - public String getReferenceHeaderText() { - return getStringProperty(OOBibStyle.REFERENCE_HEADER_TEXT); - } - - /** - * Name of paragraph format (within OO/LO) to be used for - * the title of the bibliography. - */ - public String getReferenceHeaderParagraphFormat() { - return getStringProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT); - } - - /** - * Name of paragraph format (within OO/LO) to be used for - * the entries in the bibliography. - */ - public String getReferenceParagraphFormat() { - return getStringProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT); + private String nullToEmpty(String s) { + return (s == null ? "" : s); } } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java index c54c5f423ac..bad385448d3 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java @@ -276,7 +276,7 @@ private static String getCitationMarkerField(OOBibStyle style, } FieldAndContent fc = optionalFieldAndContent.get(); - String result = style.fieldFormatter.format(fc.content); + String result = style.getFieldFormatter().format(fc.content); // If the field we found is mentioned in authorFieldNames and // content has a pair of braces around it, we add a pair of diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java index e23d0c569b7..c840bb043fc 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java @@ -43,10 +43,10 @@ private enum CitationMarkerPurpose { /** * See {@see getNumCitationMarkerCommon} for details. */ - public static String getNumCitationMarkerForInText(OOBibStyle style, - List numbers, - int minGroupingCount, - List pageInfosForCitations) { + public static String getNumCitationMarker(OOBibStyle style, + List numbers, + int minGroupingCount, + List pageInfosForCitations) { return getNumCitationMarkerCommon(style, numbers, minGroupingCount, @@ -80,7 +80,7 @@ public static String getNumCitationMarkerForBibliography(OOBibStyle style, * Format a number-based citation marker for the given number or numbers. * * This is the common implementation behind - * getNumCitationMarkerForInText and + * getNumCitationMarker and * getNumCitationMarkerForBibliography. The latter could be easily * separated unless there is (or going to be) a need for handling * multiple numbers or page info by getNumCitationMarkerForBibliography. diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java index 6195fe4d814..c92d82a1836 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java @@ -209,7 +209,7 @@ private static Map makeKnownCitationProperties() { Map res = new HashMap(); res.put("MultiCiteChronological", PropertyType.BOOL); - res.put("BibTeXKeyCitations", PropertyType.BOOL); // BIBTEX_KEY_CITATIONS + res.put("BibTeXKeyCitations", PropertyType.BOOL); res.put("BracketBefore", PropertyType.STRING); res.put("BracketAfter", PropertyType.STRING); @@ -448,7 +448,7 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa } // Store a local copy for viewing - style.localCopy = sb.toString(); + style.setLocalCopy(sb.toString()); // Add EOL and a fake an empty line at the end. In case // IN_LAYOUT_SECTION_MULTILINE is terminated by EOF, @@ -508,7 +508,7 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa return logger; } else { // ok - style.obsName = trimmedLine; + style.setName(trimmedLine); mode = BibStyleMode.BEFORE_JOURNALS_SECTION; continue; } @@ -522,7 +522,7 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa String msg = String.format("Expected \"%s\", got \"%s\"", JOURNALS_MARK, line); if (patient) { logger.warn(fileName, lineNumber, msg); - style.obsName = trimmedLine; // mimic old behaviour + style.setName(trimmedLine); // mimic old behaviour continue; } else { logger.error(fileName, lineNumber, @@ -545,7 +545,7 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa return logger; } } else { - style.journals.add(trimmedLine); + style.addJournal(trimmedLine); continue; } @@ -566,7 +566,7 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa ParseLogLevel res = handlePropertiesLine(trimmedLine, fileName, lineNumber, - style.obsProperties, + style.getProperties(), PROPERTY_WARNINGS, KNOWN_PROPERTIES, logger, @@ -595,7 +595,7 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa ParseLogLevel res = handlePropertiesLine(trimmedLine, fileName, lineNumber, - style.obsCitProperties, + style.getCitProperties(), CITATION_PROPERTY_WARNINGS, KNOWN_CITATION_PROPERTIES, logger, @@ -671,11 +671,11 @@ public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileNa logger.error(fileName, lineNumber, "Did not reach LAYOUT section at EOF"); return logger; } - if (!style.isDefaultLayoutPresent) { + if (!style.getIsDefaultLayoutPresent()) { logger.error(fileName, lineNumber, "File did not provide a \"default\" layout."); return logger; } - style.valid = true; + style.setValid(!logger.hasError()); return logger; } @@ -821,7 +821,7 @@ private static ParseLogLevel handleLayoutLineParts(String name, StringReader reader = new StringReader(formatString); Layout layout; try { - layout = new LayoutHelper(reader, style.prefs).getLayoutFromText(); + layout = new LayoutHelper(reader, style.getPrefs()).getLayoutFromText(); } catch (IOException ex) { // LOGGER.warn("Cannot parse bibliography structure", ex); String msg = String.format("Cannot parse bibliography structure. %s", ex.getMessage()); @@ -835,11 +835,11 @@ private static ParseLogLevel handleLayoutLineParts(String name, * Note: Adding the second DEFAULT_MARK to bibLayout may be unintended. * */ - if (!style.isDefaultLayoutPresent && name.equals(DEFAULT_MARK)) { - style.isDefaultLayoutPresent = true; - style.defaultBibLayout = layout; + if (!style.getIsDefaultLayoutPresent() && name.equals(DEFAULT_MARK)) { + style.setIsDefaultLayoutPresent(true); + style.setDefaultBibLayout(layout); } else { - style.bibLayout.put(type, layout); + style.getBibLayout().put(type, layout); } return ParseLogLevel.OK; } diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 26c9bf03564..47bac7f1718 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -44,10 +44,10 @@ void testAuthorYear() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, layoutFormatterPreferences); assertTrue(style.isValid()); assertTrue(style.isInternalStyle()); - assertFalse(style.getBibTeXKeyCitations()); - assertFalse(style.getFormatCitations()); - assertFalse(style.getIsNumberEntries()); - assertFalse(style.getIsSortByPosition()); + assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.isFormatCitations()); + assertFalse(style.isNumberEntries()); + assertFalse(style.isSortByPosition()); } @Test @@ -57,10 +57,10 @@ void testAuthorYearAsFile() throws URISyntaxException, IOException { OOBibStyle style = new OOBibStyle(defFile, layoutFormatterPreferences, StandardCharsets.UTF_8); assertTrue(style.isValid()); assertFalse(style.isInternalStyle()); - assertFalse(style.getBibTeXKeyCitations()); - assertFalse(style.getFormatCitations()); - assertFalse(style.getIsNumberEntries()); - assertFalse(style.getIsSortByPosition()); + assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.isFormatCitations()); + assertFalse(style.isNumberEntries()); + assertFalse(style.isSortByPosition()); } @Test @@ -68,14 +68,14 @@ void testNumerical() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); assertTrue(style.isValid()); - assertFalse(style.getBibTeXKeyCitations()); - assertFalse(style.getFormatCitations()); - assertTrue(style.getIsNumberEntries()); - assertTrue(style.getIsSortByPosition()); + assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.isFormatCitations()); + assertTrue(style.isNumberEntries()); + assertTrue(style.isSortByPosition()); } @Test - void testGetNumCitationMarkerForInText() throws IOException { + void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); @@ -91,64 +91,64 @@ void testGetNumCitationMarkerForInText() throws IOException { * but "[1] " with space after "]" for the bibliography. */ assertEquals("[1]", - style.getNumCitationMarkerForInText(Arrays.asList(1), + style.getNumCitationMarker(Arrays.asList(1), -1, empty)); // Identical numeric entries are joined. assertEquals("[1; 2]", - style.getNumCitationMarkerForInText(Arrays.asList(1,2,1,2), + style.getNumCitationMarker(Arrays.asList(1,2,1,2), 3, empty)); // ... unless minGroupingCount <= 0 assertEquals("[1; 1; 2; 2]", - style.getNumCitationMarkerForInText(Arrays.asList(1,2,1,2), + style.getNumCitationMarker(Arrays.asList(1,2,1,2), 0, empty)); // ... or have different pageInfos assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", - style.getNumCitationMarkerForInText(Arrays.asList(1,1,2,2,3,3), + style.getNumCitationMarker(Arrays.asList(1,1,2,2,3,3), 1, Arrays.asList("p1a","p1b","p2","p2",null,null))); // Consecutive numbers can become a range ... assertEquals("[1-3]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, /* minGroupingCount */ empty)); // ... unless minGroupingCount is too high assertEquals("[1; 2; 3]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + style.getNumCitationMarker(Arrays.asList(1, 2, 3), 4, /* minGroupingCount */ empty)); // ... or if minGroupingCount <= 0 assertEquals("[1; 2; 3]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + style.getNumCitationMarker(Arrays.asList(1, 2, 3), 0, /* minGroupingCount */ empty)); // ... a pageInfo needs to be emitted assertEquals("[1; p1; 2-3]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, /* minGroupingCount */ Arrays.asList("p1",null,null))); // null and "" pageInfos are taken as equal. // Due to trimming, " " is the same as well. assertEquals("[1]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 1, 1), + style.getNumCitationMarker(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ Arrays.asList("",null," "))); // pageInfos are trimmed assertEquals("[1; p1]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 1, 1), + style.getNumCitationMarker(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ Arrays.asList("p1"," p1","p1 "))); // The citation numbers come out sorted assertEquals("[3-5; 7; 10-12]", - style.getNumCitationMarkerForInText(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, empty)); @@ -156,7 +156,7 @@ void testGetNumCitationMarkerForInText() throws IOException { // (but they inhibit ranges where they are, even if they are identical, // but not empty-or-null) assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", - style.getNumCitationMarkerForInText(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, Arrays.asList("px", "p7", "p3", "p4", "px", "px", "p5"))); @@ -164,34 +164,34 @@ void testGetNumCitationMarkerForInText() throws IOException { // pageInfo sorting (for the same number) assertEquals("[1; 1; a; 1; b]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 1, 1), + style.getNumCitationMarker(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ Arrays.asList("","b","a "))); // pageInfo sorting (for the same number) is not numeric. assertEquals("[1; p100; 1; p20; 1; p9]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 1, 1), + style.getNumCitationMarker(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ Arrays.asList("p20","p9","p100"))); assertEquals("[1-3]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, /* minGroupingCount */ empty)); assertEquals("[1; 2; 3]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, empty)); assertEquals("[1; 2; 3]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3), + style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, empty)); assertEquals("[1; 3; 12]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 12, 3), + style.getNumCitationMarker(Arrays.asList(1, 12, 3), 1, empty)); assertEquals("[3-5; 7; 10-12]", - style.getNumCitationMarkerForInText(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, empty)); /* @@ -215,24 +215,24 @@ void testGetNumCitationMarkerUndefined() throws IOException { // unresolved citations look like [??] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", - style.getNumCitationMarkerForInText(Arrays.asList(0), + style.getNumCitationMarker(Arrays.asList(0), 1, empty)); // pageInfo is shown for unresolved citations assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; p1]", - style.getNumCitationMarkerForInText(Arrays.asList(0), + style.getNumCitationMarker(Arrays.asList(0), 1, Arrays.asList("p1"))); // unresolved citations sorted to the front assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4]", - style.getNumCitationMarkerForInText(Arrays.asList(4, 2, 3, 0), + style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, empty)); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3]", - style.getNumCitationMarkerForInText(Arrays.asList(1, 2, 3, 0), + style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, empty)); @@ -241,7 +241,7 @@ void testGetNumCitationMarkerUndefined() throws IOException { + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", - style.getNumCitationMarkerForInText(Arrays.asList(0, 0, 0), + style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, empty)); From a5b325320aa375a5e0583115327485ca3b535a5f Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 22 Apr 2021 21:42:00 +0200 Subject: [PATCH 0632/1068] restore orig parser --- .../StyleSelectDialogViewModel.java | 24 +- .../jabref/logic/openoffice/OOBibStyle.java | 198 +++- .../logic/openoffice/OOBibStyleParser.java | 846 ------------------ .../jabref/logic/openoffice/StyleLoader.java | 28 +- src/main/resources/l10n/JabRef_en.properties | 2 +- .../openoffice/default_authoryear.jstyle | 2 +- .../logic/openoffice/OOBibStyleTest.java | 48 +- .../openoffice/example_style_file.jstyle | 402 --------- .../openoffice/multilineLayoutRule.jstyle | 401 --------- .../jabref/logic/openoffice/parseError.jstyle | 6 - .../logic/openoffice/parserWarning.jstyle | 44 - 11 files changed, 180 insertions(+), 1821 deletions(-) delete mode 100644 src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java delete mode 100644 src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle delete mode 100644 src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle delete mode 100644 src/test/resources/org/jabref/logic/openoffice/parseError.jstyle delete mode 100644 src/test/resources/org/jabref/logic/openoffice/parserWarning.jstyle diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java index df7f6fd3651..80c7b97c8de 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java @@ -23,7 +23,6 @@ import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.OOBibStyle; -import org.jabref.logic.openoffice.OOBibStyleParser; import org.jabref.logic.openoffice.OpenOfficePreferences; import org.jabref.logic.openoffice.StyleLoader; import org.jabref.logic.util.StandardFileType; @@ -67,21 +66,14 @@ public void addStyleFile() { .build(); Optional path = dialogService.showFileOpenDialog(fileDialogConfiguration); path.map(Path::toAbsolutePath).map(Path::toString).ifPresent(stylePath -> { - OOBibStyleParser.ParseLog parseLog = loader.addStyleIfValid(stylePath); - if (!parseLog.hasError()) { - preferences.setCurrentStyle(stylePath); - styles.setAll(loadStyles()); - selectedItem.setValue(getStyleOrDefault(stylePath)); - if (!parseLog.isEmpty()) { - dialogService.showInformationDialogAndWait("Parse log", - parseLog.formatShort()); - } - } else { - dialogService.showErrorDialogAndWait(Localization.lang("Invalid style selected"), Localization.lang("You must select a valid style file.") - + "\n" - + parseLog.formatShort()); - } - }); + if (loader.addStyleIfValid(stylePath)) { + preferences.setCurrentStyle(stylePath); + styles.setAll(loadStyles()); + selectedItem.setValue(getStyleOrDefault(stylePath)); + } else { + dialogService.showErrorDialogAndWait(Localization.lang("Invalid style selected"), Localization.lang("You must select a valid style file. Your style is probably missing a line for the type \"default\".")); + } + }); } public List loadStyles() { diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java index edeb72a5480..dba8c71bee6 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java @@ -6,6 +6,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; +import java.io.StringReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -18,14 +19,20 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; +import java.util.regex.Pattern; import org.jabref.logic.layout.Layout; import org.jabref.logic.layout.LayoutFormatter; import org.jabref.logic.layout.LayoutFormatterPreferences; +import org.jabref.logic.layout.LayoutHelper; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryType; +import org.jabref.model.entry.types.EntryTypeFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * This class embodies a bibliography formatting for OpenOffice, which is composed @@ -54,6 +61,13 @@ public class OOBibStyle implements Comparable { public static final String TITLE = "Title"; public static final String UNDEFINED_CITATION_MARKER = "??"; + private static final Pattern NUM_PATTERN = Pattern.compile("-?\\d+"); + private static final String LAYOUT_MRK = "LAYOUT"; + private static final String PROPERTIES_MARK = "PROPERTIES"; + private static final String CITATION_MARK = "CITATION"; + private static final String NAME_MARK = "NAME"; + private static final String JOURNALS_MARK = "JOURNALS"; + private static final String DEFAULT_MARK = "default"; private static final String BRACKET_AFTER_IN_LIST = "BracketAfterInList"; private static final String BRACKET_BEFORE_IN_LIST = "BracketBeforeInList"; private static final String UNIQUEFIER_SEPARATOR = "UniquefierSeparator"; @@ -99,14 +113,9 @@ public class OOBibStyle implements Comparable { private static final String AUTHOR_SEPARATOR = "AuthorSeparator"; + private static final Pattern QUOTED = Pattern.compile("\".*\""); - /** Messages from the parser. - * - * Since we are parsing by calling the constructor, there is no way to - * return it to the caller there. - */ - OOBibStyleParser.ParseLog parseLog; - + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyle.class); private final SortedSet journals = new TreeSet<>(); // Formatter to be run on fields before they are used as part of citation marker: private final LayoutFormatter fieldFormatter = new OOPreFormatter(); @@ -142,7 +151,7 @@ public OOBibStyle(String resourcePath, LayoutFormatterPreferences prefs) throws Objects.requireNonNull(resourcePath); this.encoding = StandardCharsets.UTF_8; setDefaultProperties(); - initialize(OOBibStyle.class.getResourceAsStream(resourcePath), resourcePath); + initialize(OOBibStyle.class.getResourceAsStream(resourcePath)); fromResource = true; path = resourcePath; } @@ -220,24 +229,11 @@ public Set getJournals() { return Collections.unmodifiableSet(journals); } - private void initialize(InputStream stream, String filename) throws IOException { + private void initialize(InputStream stream) throws IOException { Objects.requireNonNull(stream); - // remove data from a previous parse - localCopy = null; - name = ""; - journals.clear(); - properties.clear(); - citProperties.clear(); - bibLayout.clear(); - setDefaultBibLayout(null); - setIsDefaultLayoutPresent(false); - setValid(false); - setDefaultProperties(); - this.parseLog = null; - try (Reader reader = new InputStreamReader(stream, encoding)) { - this.parseLog = OOBibStyleParser.readFormatFile(reader, this, filename); + readFormatFile(reader); } } @@ -263,7 +259,7 @@ private void reload() throws IOException { if (styleFile != null) { this.styleFileModificationTime = styleFile.lastModified(); try (InputStream stream = new FileInputStream(styleFile)) { - initialize(stream, styleFile.getAbsolutePath()); + initialize(stream); } } } @@ -282,6 +278,81 @@ private boolean isUpToDate() { } } + private void readFormatFile(Reader in) throws IOException { + + // First read all the contents of the file: + StringBuilder sb = new StringBuilder(); + int c; + while ((c = in.read()) != -1) { + sb.append((char) c); + } + + // Store a local copy for viewing + localCopy = sb.toString(); + + // Break into separate lines: + String[] lines = sb.toString().split("\n"); + BibStyleMode mode = BibStyleMode.NONE; + + for (String line1 : lines) { + String line = line1; + if (!line.isEmpty() && (line.charAt(line.length() - 1) == '\r')) { + line = line.substring(0, line.length() - 1); + } + // Check for empty line or comment: + if (line.trim().isEmpty() || (line.charAt(0) == '#')) { + continue; + } + // Check if we should change mode: + switch (line) { + case NAME_MARK: + mode = BibStyleMode.NAME; + continue; + case LAYOUT_MRK: + mode = BibStyleMode.LAYOUT; + continue; + case PROPERTIES_MARK: + mode = BibStyleMode.PROPERTIES; + continue; + case CITATION_MARK: + mode = BibStyleMode.CITATION; + continue; + case JOURNALS_MARK: + mode = BibStyleMode.JOURNALS; + continue; + default: + break; + } + + switch (mode) { + case NAME: + if (!line.trim().isEmpty()) { + name = line.trim(); + } + break; + case LAYOUT: + handleStructureLine(line); + break; + case PROPERTIES: + handlePropertiesLine(line, properties); + break; + case CITATION: + handlePropertiesLine(line, citProperties); + break; + case JOURNALS: + handleJournalsLine(line); + break; + default: + break; + } + } + // Set validity boolean based on whether we found anything interesting + // in the file: + if ((mode != BibStyleMode.NONE) && isDefaultLayoutPresent) { + valid = true; + } + } + /** * After initializing this style from a file, this method can be used to check * whether the file appeared to be a proper style file. @@ -292,6 +363,66 @@ public boolean isValid() { return valid; } + /** + * Parse a line providing bibliography structure information for an entry type. + * + * @param line The string containing the structure description. + */ + private void handleStructureLine(String line) { + int index = line.indexOf('='); + if ((index > 0) && (index < (line.length() - 1))) { + + try { + String formatString = line.substring(index + 1); + Layout layout = new LayoutHelper(new StringReader(formatString), this.prefs).getLayoutFromText(); + EntryType type = EntryTypeFactory.parse(line.substring(0, index)); + + if (!isDefaultLayoutPresent && line.substring(0, index).equals(OOBibStyle.DEFAULT_MARK)) { + isDefaultLayoutPresent = true; + defaultBibLayout = layout; + } else { + bibLayout.put(type, layout); + } + } catch (IOException ex) { + LOGGER.warn("Cannot parse bibliography structure", ex); + } + } + } + + /** + * Parse a line providing a property name and value. + * + * @param line The line containing the formatter names. + */ + private void handlePropertiesLine(String line, Map map) { + int index = line.indexOf('='); + if ((index > 0) && (index <= (line.length() - 1))) { + String propertyName = line.substring(0, index).trim(); + String value = line.substring(index + 1); + if ((value.trim().length() > 1) && QUOTED.matcher(value.trim()).matches()) { + value = value.trim().substring(1, value.trim().length() - 1); + } + Object toSet = value; + if (NUM_PATTERN.matcher(value).matches()) { + toSet = Integer.parseInt(value); + } else if ("true".equalsIgnoreCase(value.trim())) { + toSet = Boolean.TRUE; + } else if ("false".equalsIgnoreCase(value.trim())) { + toSet = Boolean.FALSE; + } + map.put(propertyName, toSet); + } + } + + /** + * Parse a line providing a journal name for which this style is valid. + */ + private void handleJournalsLine(String line) { + if (!line.trim().isEmpty()) { + journals.add(line.trim()); + } + } + public Layout getReferenceFormat(EntryType type) { Layout l = bibLayout.get(type); if (l == null) { @@ -655,18 +786,14 @@ public boolean equals(Object o) { return Objects.equals(path, otherStyle.path) && Objects.equals(name, otherStyle.name) && Objects.equals(citProperties, otherStyle.citProperties) - && Objects.equals(properties, otherStyle.properties) - // Do not ignore a reload if the user - // changed the LAYOUT section. - && Objects.equals(Objects.hashCode(localCopy), - Objects.hashCode(otherStyle.localCopy)); + && Objects.equals(properties, otherStyle.properties); } return false; } @Override public int hashCode() { - return Objects.hash(path, name, citProperties, properties, localCopy); + return Objects.hash(path, name, citProperties, properties); } /* moved to OOBibStyleGetCitationMarker as formatAuthorList @@ -701,7 +828,6 @@ private String createAuthorList(String author, int maxAuthors, String andString, } */ - /* moved to OOBibStyleParser.java enum BibStyleMode { NONE, LAYOUT, @@ -710,7 +836,6 @@ enum BibStyleMode { NAME, JOURNALS } - */ /** The String to represent authors that are not mentioned, * e.g. " et al." @@ -885,15 +1010,6 @@ public enum NonUniqueCitationMarker { THROWS } - public OOBibStyleParser.ParseLog getParseLog() { - if (parseLog == null) { - parseLog = new OOBibStyleParser.ParseLog(); - parseLog.error(path, 0, "OOBibStyle: no parseLog"); - setValid(false); - } - return parseLog; - } - /** * Format the marker for the in-text citation according to this * BIB style. Uniquefier letters are added as provided by the diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java b/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java deleted file mode 100644 index c92d82a1836..00000000000 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleParser.java +++ /dev/null @@ -1,846 +0,0 @@ -package org.jabref.logic.openoffice; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.jabref.logic.layout.Layout; -import org.jabref.logic.layout.LayoutHelper; -import org.jabref.model.entry.types.EntryType; -import org.jabref.model.entry.types.EntryTypeFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Parse a "*.jstyle" file - */ - -public class OOBibStyleParser { - - // Emit warning instead of error if possible. - private static boolean patient = true; - - // Section names - private static final String NAME_MARK = "NAME"; - private static final String JOURNALS_MARK = "JOURNALS"; - private static final String PROPERTIES_MARK = "PROPERTIES"; - private static final String CITATION_MARK = "CITATION"; - private static final String LAYOUT_MARK = "LAYOUT"; - - // name of default layout - private static final String DEFAULT_MARK = "default"; - - private static final Pattern QUOTED = Pattern.compile("\".*\""); - private static final Pattern NUM_PATTERN = Pattern.compile("-?\\d+"); - private static final Pattern LAYOUT_MULTILINE_STARTER = - Pattern.compile("^\\s*([^\\s=]+)\\s*[=]\\s*[|](.*)[|]\\s*$"); - private static final Pattern LAYOUT_MULTILINE_CONTINUATION = Pattern.compile("^\\s*[|](.*)[|]\\s*$"); - - private static final Set SECTION_NAMES = - Set.of(NAME_MARK, JOURNALS_MARK, PROPERTIES_MARK, CITATION_MARK, LAYOUT_MARK); - - /* - * Keys in the PROPERTIES section that we warn about. - */ - private static final Map PROPERTY_WARNINGS = - Map.of(// Appeared in setDefaultProperties, otherwise unknown. - "SortAlgorithm", "SortAlgorithm is not used"); - - /* - * Keys in the CITATION section we warn about. - */ - private static final Map CITATION_PROPERTY_WARNINGS = makeCitationPropertyWarnings(); - private static final Map KNOWN_PROPERTIES = makeKnownProperties(); - private static final Map KNOWN_CITATION_PROPERTIES = - makeKnownCitationProperties(); - - private static final Logger LOGGER = LoggerFactory.getLogger(OOBibStyleParser.class); - - enum PropertyType { - BOOL, - INT, - STRING, - IGNORE // ignore silently, unless also in WARNINGS - } - - private static boolean hasQuotes(String s) { - return (s.length() >= 2) && QUOTED.matcher(s).matches(); - } - - private static String dropQuotes(String s) { - if (hasQuotes(s)) { - return s.substring(1, s.length() - 1); - } - return s; - } - - /** - * Add property with name {@code propertyName} to {@code destProperties} - * - * @param type The expected type of the value. Directs decoding - * from the string {@code value}. The {@code IGNORE} type directs to silently skip - * decoding and assignment. - * - * @param whatIsIt "property" or "citation property".. - */ - private static ParseLogLevel addProperty(String propertyName, - String value, // already trimmed - PropertyType type, - Map destProperties, - String fileName, - int lineNumber, - ParseLog logger, - String whatIsIt) { - final String quotedTrue = "\"true\""; - final String quotedFalse = "\"false\""; - - switch (type) { - case IGNORE: - return ParseLogLevel.OK; - case BOOL: - switch (value) { - case "true": - destProperties.put(propertyName, Boolean.TRUE); - return ParseLogLevel.OK; - case "false": - destProperties.put(propertyName, Boolean.FALSE); - return ParseLogLevel.OK; - default: - String msg = String.format("Boolean %s '%s'" - + " expects true or false as value, got '%s'", - whatIsIt, - propertyName, value); - if (patient) { - if (value.equals(quotedTrue)) { - destProperties.put(propertyName, Boolean.TRUE); - logger.warn(fileName, lineNumber, msg); - return ParseLogLevel.WARN; - } - if (value.equals(quotedFalse)) { - destProperties.put(propertyName, Boolean.FALSE); - logger.warn(fileName, lineNumber, msg); - return ParseLogLevel.WARN; - } - } - logger.error(fileName, lineNumber, msg); - return ParseLogLevel.ERROR; - } - - case INT: - if (NUM_PATTERN.matcher(value).matches()) { - destProperties.put(propertyName, Integer.parseInt(value)); - return ParseLogLevel.OK; - } else { - String msg = String.format("Integer %s '%s'" - + " expects number matching '-?[0-9]+' as value, got '%s'", - whatIsIt, - propertyName, value); - if (patient) { - if (NUM_PATTERN.matcher(dropQuotes(value)).matches()) { - destProperties.put(propertyName, Integer.parseInt(dropQuotes(value))); - logger.warn(fileName, lineNumber, msg); - return ParseLogLevel.WARN; - } - } - logger.error(fileName, lineNumber, msg); - return ParseLogLevel.ERROR; - } - - case STRING: - boolean isQuoted = hasQuotes(value); - if (isQuoted) { - destProperties.put(propertyName, dropQuotes(value)); - return ParseLogLevel.OK; - } else { - String msg = String.format("String %s '%s'" - + " expects double quotes around value, got '%s'", - whatIsIt, - propertyName, value); - if (patient) { - destProperties.put(propertyName, dropQuotes(value)); - logger.warn(fileName, lineNumber, msg); - return ParseLogLevel.WARN; - } else { - logger.error(fileName, lineNumber, msg); - return ParseLogLevel.ERROR; - } - } - } - throw new RuntimeException(""); - } - - private static Map makeKnownProperties() { - Map res = new HashMap(); - res.put("Title", PropertyType.STRING); - res.put("IsNumberEntries", PropertyType.BOOL); - res.put("IsSortByPosition", PropertyType.BOOL); - res.put("ReferenceHeaderParagraphFormat", PropertyType.STRING); - res.put("ReferenceParagraphFormat", PropertyType.STRING); - return Collections.unmodifiableMap(res); - } - - private static Map makeCitationPropertyWarnings() { - - Map res = new HashMap(); - /* ItalicCitations was only recognized, but not used in JabRef5.2. */ - res.put("ItalicCitations", - "ItalicCitations is not implemented, use CitationGroupMarkupBefore/After"); - res.put("BoldCitations", - "BoldCitations is not implemented, use CitationGroupMarkupBefore/After"); - res.put("SuperscriptCitations", - "SuperscriptCitations is not implemented, use CitationGroupMarkupBefore/After"); - res.put("SubscriptCitations", - "SubscriptCitations is not implemented, use CitationGroupMarkupBefore/After"); - - res.put("BibtexKeyCitations", "Found 'BibtexKeyCitations' instead of 'BibTeXKeyCitations'"); - return Collections.unmodifiableMap(res); - } - - private static Map makeKnownCitationProperties() { - - Map res = new HashMap(); - res.put("MultiCiteChronological", PropertyType.BOOL); - res.put("BibTeXKeyCitations", PropertyType.BOOL); - - res.put("BracketBefore", PropertyType.STRING); - res.put("BracketAfter", PropertyType.STRING); - res.put("BracketBeforeInList", PropertyType.STRING); - res.put("BracketAfterInList", PropertyType.STRING); - - res.put("CitationSeparator", PropertyType.STRING); - res.put("PageInfoSeparator", PropertyType.STRING); - - res.put("GroupedNumbersSeparator", PropertyType.STRING); - res.put("MinimumGroupingCount", PropertyType.INT); - - res.put("AuthorField", PropertyType.STRING); - res.put("YearField", PropertyType.STRING); - res.put("MaxAuthors", PropertyType.INT); - res.put("MaxAuthorsFirst", PropertyType.INT); - res.put("AuthorSeparator", PropertyType.STRING); - res.put("AuthorLastSeparator", PropertyType.STRING); - res.put("AuthorLastSeparatorInText", PropertyType.STRING); - res.put("EtAlString", PropertyType.STRING); - res.put("YearSeparator", PropertyType.STRING); - res.put("InTextYearSeparator", PropertyType.STRING); - res.put("FormatCitations", PropertyType.BOOL); - res.put("CitationCharacterFormat", PropertyType.STRING); - res.put("OxfordComma", PropertyType.STRING); - res.put("UniquefierSeparator", PropertyType.STRING); - - res.put("CitationGroupMarkupBefore", PropertyType.STRING); - res.put("CitationGroupMarkupAfter", PropertyType.STRING); - - res.put("AuthorsPartMarkupBefore", PropertyType.STRING); - res.put("AuthorsPartMarkupAfter", PropertyType.STRING); - - res.put("AuthorNamesListMarkupBefore", PropertyType.STRING); - res.put("AuthorNamesListMarkupAfter", PropertyType.STRING); - - res.put("AuthorNameMarkupBefore", PropertyType.STRING); - res.put("AuthorNameMarkupAfter", PropertyType.STRING); - - // - res.put("ItalicCitations", PropertyType.IGNORE); - res.put("BoldCitations", PropertyType.IGNORE); - res.put("SuperscriptCitations", PropertyType.IGNORE); - res.put("SubscriptCitations", PropertyType.IGNORE); - - res.put("ItalicEtAl", PropertyType.BOOL); - return Collections.unmodifiableMap(res); - } - - private static boolean endsWithCharacter(String s, char c) { - return !s.isEmpty() && (s.charAt(s.length() - 1) == c); - } - - private static String dropLastCharacter(String s) { - return s.substring(0, s.length() - 1); - } - - private static enum BibStyleMode { - BEFORE_NAME_SECTION, - IN_NAME_SECTION, - BEFORE_JOURNALS_SECTION, - IN_JOURNALS_SECTION, - IN_PROPERTIES_SECTION, - IN_CITATION_SECTION, - IN_LAYOUT_SECTION, - IN_LAYOUT_SECTION_MULTILINE - } - - /** Also used as return code */ - static enum ParseLogLevel { - ERROR, - WARN, - INFO, - OK // no message - } - - static class ParseLogEntry { - public final ParseLogLevel level; - public final String fileName; - public final int lineNumber; - public final String message; - - ParseLogEntry(ParseLogLevel level, String fileName, int lineNumber, String message) { - this.level = level; - this.fileName = fileName; - this.lineNumber = lineNumber; - this.message = message; - } - - public String format() { - StringBuilder sb = new StringBuilder(); - ParseLogEntry e = this; - sb.append(e.fileName); - sb.append(":"); - sb.append(e.lineNumber); - sb.append(":"); - switch (e.level) { - case ERROR: - sb.append("error:"); - break; - case WARN: - sb.append("warning:"); - break; - case INFO: - sb.append("info:"); - break; - case OK: - sb.append("unexpected 'OK'"); - break; - } - sb.append(e.message); - sb.append("\n"); - return sb.toString(); - } - - public String formatShort() { - StringBuilder sb = new StringBuilder(); - ParseLogEntry e = this; - sb.append("line"); - sb.append(":"); - sb.append(e.lineNumber); - sb.append(":"); - switch (e.level) { - case ERROR: - sb.append("error:"); - break; - case WARN: - sb.append("warning:"); - break; - case INFO: - sb.append("info:"); - break; - case OK: - sb.append("unexpected 'OK'"); - break; - } - sb.append(e.message); - sb.append("\n"); - return sb.toString(); - } - } - - public static class ParseLog { - List entries; - - ParseLog() { - this.entries = new ArrayList<>(); - } - - void log(ParseLogLevel level, String fileName, int lineNumber, String message) { - this.entries.add(new ParseLogEntry(level, fileName, lineNumber, message)); - } - - void error(String fileName, int lineNumber, String message) { - this.entries.add(new ParseLogEntry(ParseLogLevel.ERROR, fileName, lineNumber, message)); - } - - void warn(String fileName, int lineNumber, String message) { - this.entries.add(new ParseLogEntry(ParseLogLevel.WARN, fileName, lineNumber, message)); - } - - void info(String fileName, int lineNumber, String message) { - this.entries.add(new ParseLogEntry(ParseLogLevel.INFO, fileName, lineNumber, message)); - } - - public int size() { - return entries.size(); - } - - public boolean isEmpty() { - return entries.isEmpty(); - } - - public String format() { - StringBuilder sb = new StringBuilder(); - for (ParseLogEntry e : entries) { - sb.append(e.format()); - } - return sb.toString(); - } - - // omits file path - public String formatShort() { - StringBuilder sb = new StringBuilder(); - for (ParseLogEntry e : entries) { - sb.append(e.formatShort()); - } - return sb.toString(); - } - - public boolean hasError() { - for (ParseLogEntry e : entries) { - if (e.level == ParseLogLevel.ERROR) { - return true; - } - } - return false; - } - } - - /** - * Parse a *.jstyle file from {@code in}. - * - * - Does not reset style, only adds things. - * - * - Expects a fixed order of sections (NAME,JOURNALS,PROPERTIES,CITATION,LAYOUT) - * - * - Only known properties and citation properties are accepted, and only with the - * type defined in KNOWN_PROPERTIES and KNOWN_CITATION_PROPERTIES. - * - boolean and integer values must not be quoted, strings must. - * - Unparsable lines are not ignored. - * - * - To reduce friction, (OOBibStyleParser.patient == true) turns - * "unparsable lines", "extra quotes", "missing quotes", "unknown property" - * into a warning (instead of error). - * - * - To avoid the necessity of long lines in the LAYOUT section, - * if the RHS matches "|.*|", than we switch to multiline LAYOUT mode - * for the given entry, and collect lines matching to "|.*|" into the value. - * We expect an empty line to terminate the multiline rule. - * The "|" characters are stripped and the rest are concatenated before - * using the value. - * - */ - public static ParseLog readFormatFile(Reader in, OOBibStyle style, String fileName) - throws - IOException { - - ParseLog logger = new ParseLog(); - - // First read all the contents of the file: - StringBuilder sb = new StringBuilder(); - int c; - while ((c = in.read()) != -1) { - sb.append((char) c); - } - - // Store a local copy for viewing - style.setLocalCopy(sb.toString()); - - // Add EOL and a fake an empty line at the end. In case - // IN_LAYOUT_SECTION_MULTILINE is terminated by EOF, - // this will trigger closing. - // Break into separate lines: - sb.append("\n \n "); - String[] lines = sb.toString().split("\n"); - - BibStyleMode mode = BibStyleMode.BEFORE_NAME_SECTION; - int lineNumber = 0; - - // For multiline LAYOUT rules - int layoutLineCollectorStartLine = -1; - String layoutLineCollectorName = "***"; - List layoutLineCollectorValue = new ArrayList<>(); - - for (String line1 : lines) { - String line = line1; - lineNumber++; - - // Drop "\r" from end of line - if (endsWithCharacter(line, '\r')) { - line = dropLastCharacter(line); - } - - final String trimmedLine = line.trim(); - - // Skip empty lines, unless we are in IN_LAYOUT_SECTION_MULTILINE - if (trimmedLine.isEmpty() && (mode != BibStyleMode.IN_LAYOUT_SECTION_MULTILINE)) { - continue; - } - - // Skip comment: - if (line.length() > 0 && line.charAt(0) == '#') { - continue; - } - - /* We only get here if we do have something (not empty line or comment) */ - switch (mode) { - - case BEFORE_NAME_SECTION: - switch (trimmedLine) { - case NAME_MARK: - mode = BibStyleMode.IN_NAME_SECTION; - continue; - default: - logger.error(fileName, lineNumber, - String.format("Expected \"%s\", got \"%s\"", NAME_MARK, line)); - return logger; - } - - case IN_NAME_SECTION: - if (SECTION_NAMES.contains(trimmedLine)) { - logger.error(fileName, lineNumber, - "Expected name of style, found section name" - + String.format("'%s'", trimmedLine)); - return logger; - } else { - // ok - style.setName(trimmedLine); - mode = BibStyleMode.BEFORE_JOURNALS_SECTION; - continue; - } - - case BEFORE_JOURNALS_SECTION: - switch (trimmedLine) { - case JOURNALS_MARK: - mode = BibStyleMode.IN_JOURNALS_SECTION; - continue; - default: - String msg = String.format("Expected \"%s\", got \"%s\"", JOURNALS_MARK, line); - if (patient) { - logger.warn(fileName, lineNumber, msg); - style.setName(trimmedLine); // mimic old behaviour - continue; - } else { - logger.error(fileName, lineNumber, - String.format("Expected \"%s\", got \"%s\"", JOURNALS_MARK, line)); - return logger; - } - } - - case IN_JOURNALS_SECTION: - if (SECTION_NAMES.contains(trimmedLine)) { - if (trimmedLine.equals(PROPERTIES_MARK)) { - mode = BibStyleMode.IN_PROPERTIES_SECTION; - continue; - } else { - logger.error(fileName, lineNumber, - String.format("Expected journal name or '%s'," - + " found section name '%s'", - PROPERTIES_MARK, - trimmedLine)); - return logger; - } - } else { - style.addJournal(trimmedLine); - continue; - } - - case IN_PROPERTIES_SECTION: - if (SECTION_NAMES.contains(trimmedLine)) { - if (trimmedLine.equals(CITATION_MARK)) { - mode = BibStyleMode.IN_CITATION_SECTION; - continue; - } else { - logger.error(fileName, lineNumber, - String.format("Expected property setting or '%s'," - + " found section name '%s'", - CITATION_MARK, - trimmedLine)); - return logger; - } - } else { - ParseLogLevel res = handlePropertiesLine(trimmedLine, - fileName, - lineNumber, - style.getProperties(), - PROPERTY_WARNINGS, - KNOWN_PROPERTIES, - logger, - "property"); - if (res == ParseLogLevel.ERROR) { - return logger; - } else { - continue; - } - } - - case IN_CITATION_SECTION: - if (SECTION_NAMES.contains(trimmedLine)) { - if (trimmedLine.equals(LAYOUT_MARK)) { - mode = BibStyleMode.IN_LAYOUT_SECTION; - continue; - } else { - logger.error(fileName, lineNumber, - String.format("Expected citation property setting or '%s'," - + " found section name '%s'", - LAYOUT_MARK, - trimmedLine)); - return logger; - } - } else { - ParseLogLevel res = handlePropertiesLine(trimmedLine, - fileName, - lineNumber, - style.getCitProperties(), - CITATION_PROPERTY_WARNINGS, - KNOWN_CITATION_PROPERTIES, - logger, - "citation property"); - if (res == ParseLogLevel.ERROR) { - return logger; - } else { - continue; - } - } - - case IN_LAYOUT_SECTION: - Matcher ms = LAYOUT_MULTILINE_STARTER.matcher(line); - if (ms.find()) { - layoutLineCollectorStartLine = lineNumber; - layoutLineCollectorName = ms.group(1); - layoutLineCollectorValue = new ArrayList<>(); - layoutLineCollectorValue.add(ms.group(2)); - mode = BibStyleMode.IN_LAYOUT_SECTION_MULTILINE; - continue; - } else { - ParseLogLevel res = handleLayoutLine(line, style, fileName, lineNumber, logger); - if (res == ParseLogLevel.ERROR) { - return logger; - } else { - continue; - } - } - case IN_LAYOUT_SECTION_MULTILINE: - Matcher mc = LAYOUT_MULTILINE_CONTINUATION.matcher(line); - if (mc.find()) { - layoutLineCollectorValue.add(mc.group(1)); - continue; - } else if (trimmedLine.equals("")) { - ParseLogLevel res = handleLayoutLineParts(layoutLineCollectorName, - String.join("", layoutLineCollectorValue), - style, - fileName, - layoutLineCollectorStartLine, - logger); - - layoutLineCollectorName = "***"; - layoutLineCollectorValue = new ArrayList<>(); - layoutLineCollectorStartLine = -1; - - mode = BibStyleMode.IN_LAYOUT_SECTION; - - if (res == ParseLogLevel.ERROR) { - return logger; - } else { - continue; - } - } else { - logger.error(fileName, - lineNumber, - "line is neither empty, nor |.*|" - + " while expecting multiline LAYOUT rule continuation."); - return logger; - } - - default: - throw new RuntimeException("Unexpected mode in OOBibStyleParser.readFormatFile"); - } - } - - // Set validity boolean based on whether we found every section - // in the file. - if (mode == BibStyleMode.IN_LAYOUT_SECTION_MULTILINE) { - logger.error(fileName, lineNumber, "Reached end of file inside a multiline LAYOUT rule."); - return logger; - } - if (mode != BibStyleMode.IN_LAYOUT_SECTION && mode != BibStyleMode.IN_LAYOUT_SECTION_MULTILINE) { - logger.error(fileName, lineNumber, "Did not reach LAYOUT section at EOF"); - return logger; - } - if (!style.getIsDefaultLayoutPresent()) { - logger.error(fileName, lineNumber, "File did not provide a \"default\" layout."); - return logger; - } - style.setValid(!logger.hasError()); - return logger; - } - - /** - * Parse a line providing a property name and value. - * - * @param trimmedLine A line containing a propery setting. - * - * Format: "{propertyName}={value}" - */ - private static ParseLogLevel handlePropertiesLine(String trimmedLine, - String fileName, - int lineNumber, - Map properties, - Map WARNINGS, - Map KNOWN, - ParseLog logger, - String whatIsIt) { - int index = trimmedLine.indexOf('='); - ParseLogLevel softError = (patient ? ParseLogLevel.WARN : ParseLogLevel.ERROR); - if (index < 0) { - logger.log(softError, - fileName, lineNumber, - String.format("Expected %s setting," - + " but the line does not contain '='", - whatIsIt)); - return softError; - } - - String propertyName = trimmedLine.substring(0, index).trim(); - String value = trimmedLine.substring(index + 1).trim(); - - if ("".equals(propertyName)) { - logger.log(softError, fileName, lineNumber, - String.format("Empty %s name", whatIsIt)); - return softError; - } - - if (WARNINGS.containsKey(propertyName)) { - String msg = WARNINGS.get(propertyName); - // LOGGER.warn(msg); - logger.warn(fileName, lineNumber, msg); - // Do not return yet. Warning does not preclude using the value. - // return ParseLogLevel.WARN; - } - - PropertyType type = KNOWN.get(propertyName); - if (type == null) { - String msg = String.format("Unknown %s: '%s'", whatIsIt, propertyName); - logger.log(softError, fileName, lineNumber, msg); - return softError; - } else { - ParseLogLevel res = addProperty(propertyName, - value, - type, - properties, - fileName, lineNumber, logger, whatIsIt); - return res; - } - } - - /** - * Parse a line providing bibliography structure information for an entry type. - * - * @param line The string containing the structure description. - * - * Expecting a line from below the "LAYOUT" tag in *.jstyle, - * in "name=RHS" form. Silently ignores lines not matching this pattern. - * - * The "name" part is passed to {@code EntryTypeFactory.parse(name);} - * The "RHS" part is passed to {@code new LayoutHelper( ..., style.prefs).getLayoutFromText();} - * - * See - * https://docs.jabref.org/collaborative-work/export/customexports - * for a description of what can go into the RHS. - */ - private static ParseLogLevel handleLayoutLine(String line, - OOBibStyle style, - String fileName, - int lineNumber, - ParseLog logger) { - /* - * uses: - * style.prefs - * style.isDefaultLayoutPresent = x - * style.defaultBibLayout = x - * style.bibLayout.put() - * - */ - // "^([^=]+)[=](.+)$" With formatString = $2; name = $1; - - /* - * Split the line at the first '='. - * Do nothing if either half is empty, or "=" is not present. - * - * Note: maye should signal somehow that this line was not processed. - * - */ - int index = line.indexOf('='); - if (index < 0) { - logger.error(fileName, lineNumber, - "Expected format definition," - + " but the line does not contain '='"); - return ParseLogLevel.ERROR; - } - - if (index == 0) { - logger.error(fileName, lineNumber, - "Expected entry type name or default," - + " but the line is empty before '='"); - return ParseLogLevel.ERROR; - } - - if (index >= (line.length() - 1)) { - logger.error(fileName, lineNumber, - "Expected entry layout definition," - + " but the line is empty after '='"); - return ParseLogLevel.ERROR; - } - - String name = line.substring(0, index); - String formatString = line.substring(index + 1); - return handleLayoutLineParts(name, - formatString, - style, - fileName, - lineNumber, - logger); - } - - private static ParseLogLevel handleLayoutLineParts(String name, - String formatString, - OOBibStyle style, - String fileName, - int lineNumber, - ParseLog logger) { - - // Parse name: actually look up in a closed list, or - // return {@code new UnknownEntryType(typeName)} - EntryType type = EntryTypeFactory.parse(name); - - // Parse the formatString. Apparently does not depend on EntryType. - StringReader reader = new StringReader(formatString); - Layout layout; - try { - layout = new LayoutHelper(reader, style.getPrefs()).getLayoutFromText(); - } catch (IOException ex) { - // LOGGER.warn("Cannot parse bibliography structure", ex); - String msg = String.format("Cannot parse bibliography structure. %s", ex.getMessage()); - logger.error(fileName, lineNumber, msg); - return ParseLogLevel.ERROR; - } - - /* At the first DEFAULT_MARK, put into defaultBibLayout, otherwise - * add to bibLayout. - * - * Note: Adding the second DEFAULT_MARK to bibLayout may be unintended. - * - */ - if (!style.getIsDefaultLayoutPresent() && name.equals(DEFAULT_MARK)) { - style.setIsDefaultLayoutPresent(true); - style.setDefaultBibLayout(layout); - } else { - style.getBibLayout().put(type, layout); - } - return ParseLogLevel.OK; - } -} diff --git a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java b/src/main/java/org/jabref/logic/openoffice/StyleLoader.java index 48bf1848124..4d3b30537db 100644 --- a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java +++ b/src/main/java/org/jabref/logic/openoffice/StyleLoader.java @@ -53,44 +53,28 @@ public List getStyles() { * Adds the given style to the list of styles * * @param filename The filename of the style - * @return parse log. result.hasError() is false if the style is added, true otherwise. - * // was: True if the added style is valid, false otherwise + * @return True if the added style is valid, false otherwise */ - public OOBibStyleParser.ParseLog addStyleIfValid(String filename) { + public boolean addStyleIfValid(String filename) { Objects.requireNonNull(filename); - OOBibStyleParser.ParseLog parseLog; try { OOBibStyle newStyle = new OOBibStyle(new File(filename), layoutFormatterPreferences, encoding); - - parseLog = newStyle.getParseLog(); - if (externalStyles.contains(newStyle)) { LOGGER.info("External style file " + filename + " already existing."); - parseLog.error(filename, 0, - "An external style file with the same content," - + " including its path" - + " is already known (not adding)"); } else if (newStyle.isValid()) { externalStyles.add(newStyle); storeExternalStyles(); + return true; } else { - String msg = String.format("Style with filename %s is invalid", filename); - LOGGER.error(msg); - parseLog.error(filename, 0, msg); + LOGGER.error(String.format("Style with filename %s is invalid", filename)); } } catch (FileNotFoundException e) { // The file couldn't be found... should we tell anyone? - String msg = "Cannot find external style file " + filename; - LOGGER.info(msg, e); - parseLog = new OOBibStyleParser.ParseLog(); - parseLog.error(filename, 0, msg); + LOGGER.info("Cannot find external style file " + filename, e); } catch (IOException e) { LOGGER.info("Problem reading external style file " + filename, e); - parseLog = new OOBibStyleParser.ParseLog(); - String msg = "Problem (IOException) reading external style file " + filename; - parseLog.error(filename, 0, msg); } - return parseLog; + return false; } private void loadExternalStyles() { diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 386fa950596..e18a911fec5 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1383,7 +1383,7 @@ Internal\ style=Internal style Add\ style\ file=Add style file Current\ style\ is\ '%0'=Current style is '%0' Remove\ style=Remove style -You\ must\ select\ a\ valid\ style\ file.=You must select a valid style file. +You\ must\ select\ a\ valid\ style\ file.\ Your\ style\ is\ probably\ missing\ a\ line\ for\ the\ type\ "default".=You must select a valid style file. Your style is probably missing a line for the type "default". Invalid\ style\ selected=Invalid style selected Reload=Reload diff --git a/src/main/resources/resource/openoffice/default_authoryear.jstyle b/src/main/resources/resource/openoffice/default_authoryear.jstyle index eeb2ca8eeac..e0c5b2443d3 100644 --- a/src/main/resources/resource/openoffice/default_authoryear.jstyle +++ b/src/main/resources/resource/openoffice/default_authoryear.jstyle @@ -15,7 +15,7 @@ ReferenceParagraphFormat="Text body" ReferenceHeaderParagraphFormat="Heading 2" CITATION -BibTeXKeyCitations=false +BibtexKeyCitations=false AuthorField="author/editor" YearField="year" MaxAuthors="2" diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java index 47bac7f1718..ad4678c5305 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java @@ -45,7 +45,9 @@ void testAuthorYear() throws IOException { assertTrue(style.isValid()); assertTrue(style.isInternalStyle()); assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.isBoldCitations()); assertFalse(style.isFormatCitations()); + assertFalse(style.isItalicCitations()); assertFalse(style.isNumberEntries()); assertFalse(style.isSortByPosition()); } @@ -58,7 +60,9 @@ void testAuthorYearAsFile() throws URISyntaxException, IOException { assertTrue(style.isValid()); assertFalse(style.isInternalStyle()); assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.isBoldCitations()); assertFalse(style.isFormatCitations()); + assertFalse(style.isItalicCitations()); assertFalse(style.isNumberEntries()); assertFalse(style.isSortByPosition()); } @@ -69,7 +73,9 @@ void testNumerical() throws IOException { layoutFormatterPreferences); assertTrue(style.isValid()); assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.isBoldCitations()); assertFalse(style.isFormatCitations()); + assertFalse(style.isItalicCitations()); assertTrue(style.isNumberEntries()); assertTrue(style.isSortByPosition()); } @@ -699,11 +705,6 @@ void testEmptyEntryMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - OOBibStyleParser.ParseLog pl = style.getParseLog(); - assertTrue( pl != null ); - assertTrue( !pl.hasError() ); - assertTrue( "[".equals(style.getBracketBefore()) ); - BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); @@ -747,7 +748,7 @@ void testGetCitationMarkerUniquefiers() throws IOException { database.insertEntry(entry2); - // Without uniquefiers this is a problem, getCitationMarker cannot + // Without uniquefiers this is a problem getCitationMarker cannot // solve, since it does not see the whole picture (citations outside its scope). // It can throw a RuntimeException or forgive and provide a flawed presentation. // @@ -929,40 +930,5 @@ void testIsValidWithDefaultSectionAtTheStart() throws Exception { assertTrue(style.isValid()); } - @Test - void testParseError() throws Exception { - OOBibStyle style = new OOBibStyle("parseError.jstyle", - layoutFormatterPreferences); - assertFalse(style.isValid()); - OOBibStyleParser.ParseLog pl = style.getParseLog(); - assertTrue(pl.hasError()); - } - - @Test - void testParserWarning() throws Exception { - OOBibStyle style = new OOBibStyle("parserWarning.jstyle", - layoutFormatterPreferences); - assertTrue(style.isValid()); - OOBibStyleParser.ParseLog pl = style.getParseLog(); - assertFalse(pl.hasError()); - } - - @Test - void testParseMultilineRules() throws Exception { - OOBibStyle style = new OOBibStyle("multilineLayoutRule.jstyle", - layoutFormatterPreferences); - assertTrue(style.isValid()); - OOBibStyleParser.ParseLog pl = style.getParseLog(); - assertFalse(pl.hasError()); - } - - @Test - void testParseExample() throws Exception { - OOBibStyle style = new OOBibStyle("example_style_file.jstyle", - layoutFormatterPreferences); - assertTrue(style.isValid()); - OOBibStyleParser.ParseLog pl = style.getParseLog(); - assertFalse(pl.hasError()); - } } diff --git a/src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle b/src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle deleted file mode 100644 index f79880b8a44..00000000000 --- a/src/test/resources/org/jabref/logic/openoffice/example_style_file.jstyle +++ /dev/null @@ -1,402 +0,0 @@ -# -# This is an example style file for the OpenOffice integration part of -# JabRef. -# -# The format of *.jstyle files are describe here: -# https://docs.jabref.org/cite/openofficeintegration#the-style-file -# -# The format of the rules in teh LAYOUT section is detailed here: -# https://docs.jabref.org/collaborative-work/export/customexports -# -# -# This is a comment, due to # at the beginning of the line. -# Comments and empty lines are ignored. -# -# Definitions: -# "citation" : reference to a source in the text -# -# "citation group" : one or more citations grouped together, -# typically in a pair or parentheses. -# -# Technically each citation is in a group, -# single citations are in their own -# single-element groups. -# -# in-text in-parenthesis and hidden citations: -# -# JabRef allows to mark individual citation groups as -# -# in-parenthesis: "[Smith et al. 2000]" (this is the default form), or -# in-text: "Smith et al. [2000]" form. -# These two are only relevant for author-year citation styles. -# -# hidden citations are not shown in the text, but appear in -# the bibliography. They can be used to type your own -# citations in the text, but still get help in -# building the bibliography. -# -# Some settings below allow a different value to be set for -# in-text citations. -# -# Implementation note: -# -# The "Merge" button in the GUI only merges -# in-parenthesis citation groups. -# -# However selecting multiple sources and clicking "Cite in-text" -# will create a group of multiple in-text citations. -# -# Even a group of multiple hidden citations can be created by -# "Insert empty citation". -# -# Note on paragraph and character styles in LibreOffice: -# -# This concerns ReferenceHeaderParagraphFormat, -# ReferenceParagraphFormat and, if FormatCitations is true, -# CitationCharacterFormat below. -# -# (1) JabRef does not manipulate named styles in LibreOffice. -# -# If the jstyle file refers to a style that does not exist in the -# document, the user has to create the style in LibreOffice or -# edit the the name in jstyle file. -# -# (2) Styles in LibreOffice have two names. One is the "Display name" -# shown to users, the other is the "internal name". -# -# Locally one could use either, but the "Display name" depends on -# the locale, thus would fail for other users. -# -# The "Refresh bibliography" now checks if the jstyle asks to -# apply a style by display name, and asks to change it. It will -# show the corresponding internal name, which otherwise I -# do not know how to get. -# -# New: the text emitted into the document, may contain some HTML-like -# tags. This was true before for the bibliography entries -# (controlled by the LAYOUT section), not it includes the title -# of the bibliography (Title below), the citations in the text and -# entry labels (for numeric styles). -# -# A sample of the available tags is inserted into the Title below. -# -# This makes ItalicEtAl obsolete, since EtAlString may contain " et al." -# -# Also raises the question how to describe which tags surround what. -# -# -NAME -# The NAME section provides a name for the style. -# It consists of a single (non-empty, non-comment) line. - -Example style file for JabRef-oo plugin. - -JOURNALS -# The JOURNALS section lists journal names, one per line. -Journal name 1 -Journal name 2 - -PROPERTIES - -## The PROPERTIES and CITATION sections provide name=value pairs. -## The names are fixed, also the type of the corresponding values. - -## There are three value types: -## boolean: true or false -## integer: like -1 or 113 -## string: like "Hello there" - -## Title: string, the title of the bibliography. -## default: "Bibliography" -Title = "References b: bold i: italic (tt: does not work) SmallCaps sup sub u s" - -## ReferenceHeaderParagraphFormat : string. -## The paragraph style for the title of the bibliography. -## Should name a paragraph style known by OpenOffice/LibreOffice -## default: "Heading 1" -## example: ReferenceHeaderParagraphFormat = "Heading 2" - -## ReferenceParagraphFormat : string. -## The paragraph style for the bibliography entries. -## default: "Standard" -## example: ReferenceParagraphFormat="Text body" -ReferenceParagraphFormat="Text body" - -## IsNumberEntries : boolean, default: false -## If true, than this style uses numbered citations. -## If false, author-year style. -## -## Since numbered citations have different parts than -## author-year citations, the value of IsNumberEntries -## affects which properties are relevant. -## -## Note: if BibTeXKeyCitations is true (below, in the CITATION -## section), then IsNumberEntries is irrelevant. -## -IsNumberEntries = false - -## IsSortByPosition : boolean, default: false. -## -## Determines how the bibliography is sorted. -## -## If true, the entries will be sorted according to the order in which -## they are cited. Note: within a citation group -## -## If false, the entries will be sorted alphabetically by authors. -## -## Only relevant for numbered citations. -## -IsSortByPosition = false - -CITATION - -## This section contains settings related to individual citations and -## citation groups. - -## BibTeXKeyCitations : boolean, default: false -## If true, citations are represented by their BibTex keys. -## In this case IsNumberEntries is irrelevant. -# BibTeXKeyCitations=false - -## MultiCiteChronological: boolean, default: true -## If true, citations in a citation group are -## sorted by (year,author,title), otherwise by (author,year,title). -## -## Relevant with author-year and BibTeXKeyCitations. -## -## Its relevance for numbered citations is less obviuous, because just -## before we emit a citaion group, we sort the numbers appearing in -## the group. -## -## For IsNumberEntries + IsSortByPosition, it affects the citations -## position within citation groups, which may be observable in the -## numbering. -## -## For IsNumberEntries + !IsSortByPosition, the numbering comes from -## sorting the bibliography, thus MultiCiteChronological does not have -## an effect. -## -MultiCiteChronological=true - -## Character formatting of citation groups. - -## FormatCitations: boolean, default: false -## Decides if CitationCharacterFormat below should be applied. -## -## Note: when switching from a style with FormatCitations==true to one -## with FormatCitations==false, the character style established -## by the first is not removed from the citations. Applying a -## style with CitationCharacterFormat = "Standard" might help to -## avoid doing by hand. -## -FormatCitations = false - -## CitationCharacterFormat : string. -## default: "Standard" -## -## A character format to apply to citation groups, as known to -## LibreOffice. -## -## example: CitationCharacterFormat = "Standard" -## example: CitationCharacterFormat = "Emphasis" -## example: CitationCharacterFormat = "Example" -# CitationCharacterFormat = "Standard" -# CitationCharacterFormat="JR_citation" - -## -## The following correspond to direct character formatting. -## They are not controlled by FormatCitations. -## - -## CitationGroupMarkupBefore: string, default: "" -## CitationGroupMarkupAfter: string, default: "" -## -## Purpose: what is to be injected before and after a citation group. -## Providing both ends allows for example labeling. -CitationGroupMarkupBefore = "" -CitationGroupMarkupAfter = "" - -## AuthorsPartMarkup : "Au et al." -AuthorsPartMarkupBefore = "" -AuthorsPartMarkupAfter = "" - -# AuthorNamesListMarkup : excludes " et al.", includes names and separators -AuthorNamesListMarkupBefore = "" -AuthorNamesListMarkupAfter = "" - -# AuthorNameMarkup : "Au" excludes AuthorSeparator -AuthorNameMarkupBefore = "" -AuthorNameMarkupAfter = "" - -## These probably could be done, if there is a need: -# CitationMarkup = "" -# YearMarkup = "" -# UniquefierListMarkup = "" # "a,b" -# UniquefierMarkup = "" # excludes UniquefierSeparator -# NunberRangeMarkup = "" # "1" or "2-3" -# NumberMarkup = "" # excludes GroupedNumbersSeparator -# PageInfoMarkup="" # Does not include PageInfoSeparator - -## -## For text fragments below, examples show the location -## by bracketing the relevant part with "{}" -## - -## BracketBefore : string, default: "(" -## Location: "{[}Smith 2000]" "Smith {[}2000]" "{[}1]" "{[}bibtextkey]" -BracketBefore="[" - -## BracketAfter : string, default: ")" -## Location: "[Smith 2000{]}" "Smith [2000{]}" "[1{]}" "[bibtextkey{]}" -BracketAfter="]" - -## BracketBeforeInList : string, default: not set. -## If not set, BracketBefore is used instead. -## Purpose: for numbered styles, used in the entry labels in the bibliography. -## Location: "{[}1]" -## Not relevant for BibTeXKeyCitations and author-year. -BracketBeforeInList="[" - -## BracketAfterInList : string, default: not set. -## If not set, BracketAfter is used instead. -## Purpose: for numbered styles, used in the entry labels in the bibliography. -## Location: "[1{]}" -## Not relevant for BibTeXKeyCitations and author-year. -BracketAfterInList="] " - -## PageInfoSeparator : string, default: "; " -## Location: "[Smith 2000a{; }pp 10-13]" "Smith [2000a{; }pp 10-13]" "[1{; }pp 10-13]" -## Not used for BibTeXKeyCitations (maybe it should be) -PageInfoSeparator = "; " - -## CitationSeparator : string, default: "; " -## Location: between citations in the same citation group. -## "[Smith 2000{; }Jones 2001]" "Smith [2000{; }Jones [2001]" "[1{; }2]" -CitationSeparator="; " - -## -## Settings that only apply to numeric citation style. -## - -## MinimumGroupingCount : int, default: 3 -## Purpose: How many consecutive numbers in "[1; 2; 3]" allows grouping to "[1-3]" -MinimumGroupingCount=3 - -## GroupedNumbersSeparator : string, default: "-" -## Purpose: for numeric style, when consecutive numbers collapsed to a -## range, this is used as the separator between range start -## and range end. -## Location: "[1{-}3]" -GroupedNumbersSeparator="-" - -## -## Settings that only apply to author-year style. -## - -## AuthorField : string, default: "author/editor" -## -## Purpose: When looking for authors, which bibtex fields to look in? -## -## The field names are separated by "/", the first field that -## exists and is not empty applies. -AuthorField="author/editor" - -## YearField : string, default: "year" -## -## Purpose: When looking for the year, which bibtex fields to look in? -## -## The field names are separated by "/", the first field that -## exists and is not empty applies. -## -YearField="year" - -## MaxAuthors : int, default: 3 -## Purpose: How many author names to show in citations? -## If there are more, "FirstAuthor et al." will be used instead. -## Special value: -1 encodes "unlimited" -MaxAuthors=2 - -## MaxAuthorsFirst : int, default: -1 -## Purpose: some styles require a different value of MaxAuthors for -## the first appearance of a source. -## Special value: -1 encodes "unlimited" -## -MaxAuthorsFirst=6 - -## AuthorSeparator : string, default: ", " -## Location: "[Smith{, }Jones, and Brown 2000]" -AuthorSeparator=", " - -## OxfordComma : string, default: "" -## Location: "[Smith, Jones{,} and Brown 2000]" -# example: OxfordComma = "," - -## AuthorLastSeparator : string default: " & " -## Location: "[Smith, Jones,{ and }Brown 2000]" */ -AuthorLastSeparator=" and " - -## AuthorLastSeparatorInText : string, default: not set. -## If not set, AuthorLastSeparator is used instead. -## Purpose: for in-text "Author (year)" citations, -## allows alternative value for AuthorLastSeparator. -## Location: "Smith, Jones,{ and }Brown [2000]" -AuthorLastSeparatorInText=" and " - -## EtAlString : string, default: "et al." -## Location: "[Smith{ et al.} 2000]" "Smith{ et al.} [2000]" -## Purpose: if there are more authors than allowed by MaxAuthors, -## only the first author name is shown. EtAlString indicates -## the omission of the other names. -EtAlString=" et al." - -## YearSeparator : string, default: ", " -## Location: just after the authors, for in-parenthesis citations: "[Smith et al.{ }2000]" -YearSeparator=" " - -## InTextYearSeparator : string, default: " " -## Location: "Smith et al.{ }[2000]" -InTextYearSeparator=" " - -## UniquefierSeparator : string, default: "," -## Location: "[Smith et al. 2000a{,}b; pp 10-13]" -UniquefierSeparator="," - -LAYOUT -## -## The LAYOUT section provides formatting rules for the bibliography entries. -## -## In the name=value pairs below, "name" is either a bibtex entry type (article, ...) -## or "default" (fallback in case there is no formatting provided for a bibtex entry type. -## -## The default entry is required. -## -## Note: -## (1) White spaces are significant in the rules. -## -## (2) You can split the value to multiple lines. -## Each part must be between two "|" characters. -## Each part (except the first) has its own line. -## An empty line terminates the rule. -## See below at the book and incollection rules. -## -article=\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. - -book = |\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| - |\begin{editor}| - |\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.)| - |\end{editor},| - | \year\uniq. \title. \publisher, \address.| - -incollection = || -|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| -# We can add comments between the lines (still has to start at the first column). -| (\year\uniq). \title.| -| In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.),| -| \booktitle, \publisher.| - -inbook=\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author} (\year\uniq). \chapter. In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.), \title, \publisher. - -phdthesis=\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author} (\year\uniq). \title, \school. - -default=\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. - diff --git a/src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle b/src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle deleted file mode 100644 index 0f94711436b..00000000000 --- a/src/test/resources/org/jabref/logic/openoffice/multilineLayoutRule.jstyle +++ /dev/null @@ -1,401 +0,0 @@ -# -# This is an example style file for the OpenOffice integration part of -# JabRef. -# -# The format of *.jstyle files are describe here: -# https://docs.jabref.org/cite/openofficeintegration#the-style-file -# -# The format of the rules in teh LAYOUT section is detailed here: -# https://docs.jabref.org/collaborative-work/export/customexports -# -# -# This is a comment, due to # at the beginning of the line. -# Comments and empty lines are ignored. -# -# Definitions: -# "citation" : reference to a source in the text -# -# "citation group" : one or more citations grouped together, -# typically in a pair or parentheses. -# -# Technically each citation is in a group, -# single citations are in their own -# single-element groups. -# -# in-text in-parenthesis and hidden citations: -# -# JabRef allows to mark individual citation groups as -# -# in-parenthesis: "[Smith et al. 2000]" (this is the default form), or -# in-text: "Smith et al. [2000]" form. -# These two are only relevant for author-year citation styles. -# -# hidden citations are not shown in the text, but appear in -# the bibliography. They can be used to type your own -# citations in the text, but still get help in -# building the bibliography. -# -# Some settings below allow a different value to be set for -# in-text citations. -# -# Implementation note: -# -# The "Merge" button in the GUI only merges -# in-parenthesis citation groups. -# -# However selecting multiple sources and clicking "Cite in-text" -# will create a group of multiple in-text citations. -# -# Even a group of multiple hidden citations can be created by -# "Insert empty citation". -# -# Note on paragraph and character styles in LibreOffice: -# -# This concerns ReferenceHeaderParagraphFormat, -# ReferenceParagraphFormat and, if FormatCitations is true, -# CitationCharacterFormat below. -# -# (1) JabRef does not manipulate named styles in LibreOffice. -# -# If the jstyle file refers to a style that does not exist in the -# document, the user has to create the style in LibreOffice or -# edit the the name in jstyle file. -# -# (2) Styles in LibreOffice have two names. One is the "Display name" -# shown to users, the other is the "internal name". -# -# Locally one could use either, but the "Display name" depends on -# the locale, thus would fail for other users. -# -# The "Refresh bibliography" now checks if the jstyle asks to -# apply a style by display name, and asks to change it. It will -# show the corresponding internal name, which otherwise I -# do not know how to get. -# -# -NAME -# The NAME section provides a name for the style. -# It consists of a single (non-empty, non-comment) line. - -Multiline LAYOUT rule example. - -JOURNALS -# The JOURNALS section lists journal names, one per line. -Journal name 1 -Journal name 2 - -PROPERTIES - -## The PROPERTIES and CITATION sections provide name=value pairs. -## The names are fixed, also the type of the corresponding values. - -## There are three value types: -## boolean: true or false -## integer: like -1 or 113 -## string: like "Hello there" - -## Title: string, the title of the bibliography. -## default: "Bibliography" -Title = "References" - -## ReferenceHeaderParagraphFormat : string. -## The paragraph style for the title of the bibliography. -## Should name a paragraph style known by OpenOffice/LibreOffice -## default: "Heading 1" -## example: ReferenceHeaderParagraphFormat = "Heading 2" - -## ReferenceParagraphFormat : string. -## The paragraph style for the bibliography entries. -## default: "Standard" -## example: ReferenceParagraphFormat="Text body" -ReferenceParagraphFormat="Text body" - -## IsNumberEntries : boolean, default: false -## If true, than this style uses numbered citations. -## If false, author-year style. -## -## Since numbered citations have different parts than -## author-year citations, the value of IsNumberEntries -## affects which properties are relevant. -## -## Note: if BibTeXKeyCitations is true (below, in the CITATION -## section), then IsNumberEntries is irrelevant. -## -IsNumberEntries = false - -## IsSortByPosition : boolean, default: false. -## -## Determines how the bibliography is sorted. -## -## If true, the entries will be sorted according to the order in which -## they are cited. Note: within a citation group -## -## If false, the entries will be sorted alphabetically by authors. -## -## Only relevant for numbered citations. -## -IsSortByPosition = false - -CITATION - -## This section contains settings related to individual citations and -## citation groups. - -## BibTeXKeyCitations : boolean, default: false -## If true, citations are represented by their BibTex keys. -## In this case IsNumberEntries is irrelevant. -# BibTeXKeyCitations=false - -## MultiCiteChronological: boolean, default: true -## If true, citations in a citation group are -## sorted by (year,author,title), otherwise by (author,year,title). -## -## Relevant with author-year and BibTeXKeyCitations. -## -## Its relevance for numbered citations is less obviuous, because just -## before we emit a citaion group, we sort the numbers appearing in -## the group. -## -## For IsNumberEntries + IsSortByPosition, it affects the citations -## position within citation groups, which may be observable in the -## numbering. -## -## For IsNumberEntries + !IsSortByPosition, the numbering comes from -## sorting the bibliography, thus MultiCiteChronological does not have -## an effect. -## -MultiCiteChronological=true - -## Character formatting of citation groups. - -## FormatCitations: boolean, default: false -## Decides if CitationCharacterFormat below should be applied. -## -## Note: when switching from a style with FormatCitations==true to one -## with FormatCitations==false, the character style established -## by the first is not removed from the citations. Applying a -## style with CitationCharacterFormat = "Standard" might help to -## avoid doing by hand. -## -FormatCitations = false - -## CitationCharacterFormat : string. -## default: "Standard" -## -## A character format to apply to citation groups, as known to -## LibreOffice. -## -## example: CitationCharacterFormat = "Standard" -## example: CitationCharacterFormat = "Emphasis" -## example: CitationCharacterFormat = "Example" -# CitationCharacterFormat = "Standard" -# CitationCharacterFormat="JR_citation" - -## -## The following correspond to direct character formatting. -## They are not controlled by FormatCitations. -## - -## -## For text fragments below, examples show the location -## by bracketing the relevant part with "{}" -## - -## BracketBefore : string, default: "(" -## Location: "{[}Smith 2000]" "Smith {[}2000]" "{[}1]" "{[}bibtextkey]" -BracketBefore="[" - -## BracketAfter : string, default: ")" -## Location: "[Smith 2000{]}" "Smith [2000{]}" "[1{]}" "[bibtextkey{]}" -BracketAfter="]" - -## BracketBeforeInList : string, default: not set. -## If not set, BracketBefore is used instead. -## Purpose: for numbered styles, used in the entry labels in the bibliography. -## Location: "{[}1]" -## Not relevant for BibTeXKeyCitations and author-year. -BracketBeforeInList="[" - -## BracketAfterInList : string, default: not set. -## If not set, BracketAfter is used instead. -## Purpose: for numbered styles, used in the entry labels in the bibliography. -## Location: "[1{]}" -## Not relevant for BibTeXKeyCitations and author-year. -BracketAfterInList="] " - -## PageInfoSeparator : string, default: "; " -## Location: "[Smith 2000a{; }pp 10-13]" "Smith [2000a{; }pp 10-13]" "[1{; }pp 10-13]" -## Not used for BibTeXKeyCitations (maybe it should be) -PageInfoSeparator = "; " - -## CitationSeparator : string, default: "; " -## Location: between citations in the same citation group. -## "[Smith 2000{; }Jones 2001]" "Smith [2000{; }Jones [2001]" "[1{; }2]" -CitationSeparator="; " - -## -## Settings that only apply to numeric citation style. -## - -## MinimumGroupingCount : int, default: 3 -## Purpose: How many consecutive numbers in "[1; 2; 3]" allows grouping to "[1-3]" -MinimumGroupingCount=3 - -## GroupedNumbersSeparator : string, default: "-" -## Purpose: for numeric style, when consecutive numbers collapsed to a -## range, this is used as the separator between range start -## and range end. -## Location: "[1{-}3]" -GroupedNumbersSeparator="-" - -## -## Settings that only apply to author-year style. -## - -## AuthorField : string, default: "author/editor" -## -## Purpose: When looking for authors, which bibtex fields to look in? -## -## The field names are separated by "/", the first field that -## exists and is not empty applies. -AuthorField="author/editor" - -## YearField : string, default: "year" -## -## Purpose: When looking for the year, which bibtex fields to look in? -## -## The field names are separated by "/", the first field that -## exists and is not empty applies. -## -YearField="year" - -## MaxAuthors : int, default: 3 -## Purpose: How many author names to show in citations? -## If there are more, "FirstAuthor et al." will be used instead. -## Special value: -1 encodes "unlimited" -MaxAuthors=2 - -## MaxAuthorsFirst : int, default: -1 -## Purpose: some styles require a different value of MaxAuthors for -## the first appearance of a source. -## Special value: -1 encodes "unlimited" -## -MaxAuthorsFirst=6 - -## AuthorSeparator : string, default: ", " -## Location: "[Smith{, }Jones, and Brown 2000]" -AuthorSeparator=", " - -## OxfordComma : string, default: "" -## Location: "[Smith, Jones{,} and Brown 2000]" -# example: OxfordComma = "," - -## AuthorLastSeparator : string default: " & " -## Location: "[Smith, Jones,{ and }Brown 2000]" */ -AuthorLastSeparator=" & " - -## AuthorLastSeparatorInText : string, default: not set. -## If not set, AuthorLastSeparator is used instead. -## Purpose: for in-text "Author (year)" citations, -## allows alternative value for AuthorLastSeparator. -## Location: "Smith, Jones,{ and }Brown [2000]" -AuthorLastSeparatorInText=" and " - -## EtAlString : string, default: "et al." -## Location: "[Smith{ et al.} 2000]" "Smith{ et al.} [2000]" -## Purpose: if there are more authors than allowed by MaxAuthors, -## only the first author name is shown. EtAlString indicates -## the omission of the other names. -EtAlString=" et al." - -## YearSeparator : string, default: ", " -## Location: just after the authors, for in-parenthesis citations: "[Smith et al.{ }2000]" -YearSeparator=" " - -## InTextYearSeparator : string, default: " " -## Location: "Smith et al.{ }[2000]" -InTextYearSeparator=" " - -## UniquefierSeparator : string, default: "," -## Location: "[Smith et al. 2000a{,}b; pp 10-13]" -UniquefierSeparator="," - -LAYOUT -## -## The LAYOUT section provides formatting rules for the bibliography entries. -## -## In the name=value pairs below, "name" is either a bibtex entry type (article, ...) -## or "default" (fallback in case there is no formatting provided for a bibtex entry type. -## -## The default entry is required. -## -## Note: no line breaks are allowed within a rule. -## -## We could relax this like below. If value starts with "|", -## then line breaks are allowed. An empty line ends the entry. -## Each line, after trimming must be surrounded by "|" and "|". -## As with strings in property values: we only care about the first and last -## characters: within the line "|" may appear, does not need quoting. -## The main purpose of the "|" marks is to make the spaces within visible -## and separable from those used for indentation. -## -## Conversion from old style: -## (1) put || around the value -## (2) Wherever you want a line break, insert || and a linebreak between. -## -## Conversion to old style: -## (1) collect value from RHS and following lines, -## until an empty line occurs. -## (2) Trim each line, check and remove || around, concatenate. -## -## Detection: after trimming RHS starts and ends with | -## Ambiguity: when the RHS would start and end with | anyway. -## Solution: an extra pair of | around converts to new style. -## -article=|| -# We can add comments between the lines (still has to start at the first column). -# This could be a place to describe what AuthorAndsReplacer does, -# and https://docs.jabref.org/collaborative-work/export/customexports -# does not explain. -# http://www.massapi.com/class/au/AuthorAndsReplacer.html explains. -|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| -| (\year\uniq).| -| \title,| -| \journal| -| \volume| -# Does FormatPagesForHTML include some HTML tags? -# https://docs.jabref.org/collaborative-work/export/customexports -# says: FormatPagesForHTML : replaces "--" with "-". -|\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}.| - -book=|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| - |\begin{editor}| - |\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.)| - |\end{editor},| - | \year\uniq.| - | \title.| - | \publisher,| - | \address.| - -incollection=|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| - | (\year\uniq).| - | \title.| - | In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.),| - | \booktitle,| - | \publisher.| - -inbook=|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| - | (\year\uniq).| - | \chapter.| - | In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.),| - | \title, \publisher.| - -phdthesis=|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| - | (\year\uniq).| - | \title, \school.| - -default=|\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\author}| - | (\year\uniq).| - | \title,| - | \journal \volume| - |\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}.| diff --git a/src/test/resources/org/jabref/logic/openoffice/parseError.jstyle b/src/test/resources/org/jabref/logic/openoffice/parseError.jstyle deleted file mode 100644 index 928ea6e7736..00000000000 --- a/src/test/resources/org/jabref/logic/openoffice/parseError.jstyle +++ /dev/null @@ -1,6 +0,0 @@ -# SPDX-License-Identifier: MIT - -NAME -A style to provoke a parsing error. - - diff --git a/src/test/resources/org/jabref/logic/openoffice/parserWarning.jstyle b/src/test/resources/org/jabref/logic/openoffice/parserWarning.jstyle deleted file mode 100644 index 242ce6f277d..00000000000 --- a/src/test/resources/org/jabref/logic/openoffice/parserWarning.jstyle +++ /dev/null @@ -1,44 +0,0 @@ -# SPDX-License-Identifier: MIT - -NAME -A style provoking a parser warning. - -JOURNALS -Journal name 1 -Journal name 2 - -PROPERTIES -Title = "References" - -# warning: do not quote boolean values. -IsSortByPosition = "true" - -IsNumberEntries = true -ReferenceParagraphFormat = "Text body" -ReferenceHeaderParagraphFormat = "Heading 2" - -CITATION -BracketBefore = "[" -BracketAfter = "]" -BracketBeforeInList = "[" -BracketAfterInList = "] " -CitationSeparator = "; " -UniquefierSeparator = "," -GroupedNumbersSeparator = "-" -MinimumGroupingCount = 3 -FormatCitations = false -CitationCharacterFormat = "Default" -PageInfoSeparator = "; " - -LAYOUT -article=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. - -book=\format[Authors(LastFirst,Semicolon)]{\author}\begin{editor}\format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.)\end{editor}, \year\uniq. \title. \publisher, \address. - -incollection=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title. In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.), \booktitle, \publisher. - -inbook=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \chapter. In: \format[AuthorLastFirst,AuthorAbbreviator,AuthorAndsReplacer]{\editor} (Ed.), \title, \publisher. - -phdthesis=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title, \school. - -default=\format[Authors(LastFirst,Semicolon)]{\author} (\year\uniq). \title, \journal \volume\begin{pages} : \format[FormatPagesForHTML]{\pages}\end{pages}. From a3322e1d9a3603ac2eb23dae87271971c43adeb1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 22 Apr 2021 22:35:27 +0200 Subject: [PATCH 0633/1068] more diff-minimization --- .../org/jabref/logic/openoffice/OOUtil.java | 94 ++++++------------- 1 file changed, 27 insertions(+), 67 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 814abb17153..8419ce0c784 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -59,13 +59,6 @@ private OOUtil() { /** * Format the reference part of a bibliography entry using a Layout. * - * The label (if any) and paragraph style are not added here. - * - * param parStyle The name of the paragraph style to use. - * - * Not used here, for now we leave application of - * the paragraph style to the caller. - * * @param layout The Layout to format the reference with. * @param entry The entry to insert. * @param database The database the entry belongs to. @@ -76,13 +69,7 @@ private OOUtil() { public static String formatFullReference(Layout layout, BibEntry entry, BibDatabase database, - String uniquefier) - throws - // TODO: are any of these thrown? - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException { + String uniquefier) { // Backup the value of the uniq field, just in case the entry already has it: Optional oldUniqVal = entry.getField(UNIQUEFIER_FIELD); @@ -103,25 +90,21 @@ public static String formatFullReference(Layout layout, } else { entry.clearField(UNIQUEFIER_FIELD); } + return formattedText; } /** - * Insert a text in OOFormattedText - * (where character formatting is indicated by HTML-like tags), into - * at the position given by an {@code XTextCursor}. + * Insert a text with formatting indicated by HTML-like tags, into a text at the position given by a cursor. * - * Process {@code ltext} in chunks between HTML-tags, while - * updating current formatting state at HTML-tags. - * - * @param cursor The cursor giving the insert location. Not modified. + * @param position The cursor giving the insert location. Not modified. * @param lText The marked-up text to insert. * @throws WrappedTargetException * @throws PropertyVetoException * @throws UnknownPropertyException * @throws IllegalArgumentException */ - public static void insertOOFormattedTextAtCurrentLocation(XTextCursor cursor, + public static void insertOOFormattedTextAtCurrentLocation(XTextCursor position, String lText) throws UnknownPropertyException, @@ -129,9 +112,8 @@ public static void insertOOFormattedTextAtCurrentLocation(XTextCursor cursor, WrappedTargetException, IllegalArgumentException { - XText text = cursor.getText(); - // copy the cursor - XTextCursor myCursor = cursor.getText().createTextCursorByRange(cursor); + XText text = position.getText(); + XTextCursor cursor = text.createTextCursorByRange(position); List formatting = new ArrayList<>(); // We need to extract formatting. Use a simple regexp search iteration: @@ -140,7 +122,7 @@ public static void insertOOFormattedTextAtCurrentLocation(XTextCursor cursor, while (m.find()) { String currentSubstring = lText.substring(piv, m.start()); if (!currentSubstring.isEmpty()) { - OOUtil.insertTextAtCurrentLocation(text, myCursor, currentSubstring, formatting); + OOUtil.insertTextAtCurrentLocation(text, cursor, currentSubstring, formatting); } String tag = m.group(); // Handle tags: @@ -182,39 +164,25 @@ public static void insertOOFormattedTextAtCurrentLocation(XTextCursor cursor, } if (piv < lText.length()) { - OOUtil.insertTextAtCurrentLocation(text, myCursor, lText.substring(piv), formatting); + OOUtil.insertTextAtCurrentLocation(text, cursor, lText.substring(piv), formatting); } + } - public static void insertParagraphBreak(XText text, XTextCursor cursor) - throws - IllegalArgumentException { + public static void insertParagraphBreak(XText text, XTextCursor cursor) throws IllegalArgumentException { text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); cursor.collapseToEnd(); } - /** - * Set cursor range content to {@code string}, apply {@code - * formatting} to it, {@code cursor.collapseToEnd()}. - * - * Insert {@code string} into {@code text} at {@code cursor}, while removing the content - * of the cursor's range. The cursor's content is {@code string} now. - * - * Apply character direct formatting from {@code formatting}. - * Features not in {@code formatting} are removed by setting to NONE. - * - * Finally: {@code cursor.collapseToEnd();} - */ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, String string, List formatting) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException { - text.insertString(cursor, string, true); // Access the property set of the cursor, and set the currently selected text // (which is the string we just inserted) to be bold - XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); - + XPropertySet xCursorProps = UnoRuntime.queryInterface( + XPropertySet.class, cursor); if (formatting.contains(Formatting.BOLD)) { xCursorProps.setPropertyValue(CHAR_WEIGHT, com.sun.star.awt.FontWeight.BOLD); @@ -249,30 +217,21 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S xCursorProps.setPropertyValue("CharFontPitch", com.sun.star.awt.FontPitch.VARIABLE); } */ - - /* - * short CharEscapement. - * specifies the percentage by which to raise/lower superscript/subscript characters. - * Negative values denote subscripts and positive values superscripts. - * - * byte CharEscapementHeight - * This is the relative height used for subscript or superscript characters in units of percent. - * The value 100 denotes the original height of the characters. - * - * From LibreOffice: - * SuperScript: 33 and 58 - * SubScript: 10 and 58 - * - */ if (formatting.contains(Formatting.SUBSCRIPT)) { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) -10); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, (byte) 58); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, + (short) -10); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, + (byte) 58); } else if (formatting.contains(Formatting.SUPERSCRIPT)) { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) 33); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, (byte) 58); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, + (short) 33); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, + (byte) 58); } else { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) 0); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, (byte) 100); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, + (byte) 0); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, + (byte) 100); } if (formatting.contains(Formatting.UNDERLINE)) { @@ -291,7 +250,8 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S public static Object getProperty(Object o, String property) throws UnknownPropertyException, WrappedTargetException { - XPropertySet props = UnoRuntime.queryInterface(XPropertySet.class, o); + XPropertySet props = UnoRuntime.queryInterface( + XPropertySet.class, o); return props.getPropertyValue(property); } } From 066b567b9dd35958975cd02187e8759d3f679c2a Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 23 Apr 2021 09:19:28 +0200 Subject: [PATCH 0634/1068] drop BibEntryNotFoundException --- .../openoffice/BibEntryNotFoundException.java | 16 ---------------- .../org/jabref/gui/openoffice/OOBibBase.java | 18 +++--------------- .../jabref/gui/openoffice/OpenOfficePanel.java | 18 +++--------------- 3 files changed, 6 insertions(+), 46 deletions(-) delete mode 100644 src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java diff --git a/src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java b/src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java deleted file mode 100644 index b3db5f8f9e7..00000000000 --- a/src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.jabref.gui.openoffice; - -class BibEntryNotFoundException extends Exception { - - private final String citationKey; - - public BibEntryNotFoundException(String citationKey, String message) { - super(message); - - this.citationKey = citationKey; - } - - public String getCitationKey() { - return citationKey; - } -} diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ebbc2dcfbe5..ca9622b2406 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -803,9 +803,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes */ private static Map produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroups cgs, - OOBibStyle style) - throws - BibEntryNotFoundException { + OOBibStyle style) { assert style.isCitationKeyCiteMarkers(); @@ -840,9 +838,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes */ private static Map produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, - OOBibStyle style) - throws - BibEntryNotFoundException { + OOBibStyle style) { assert style.isNumberEntries(); assert style.isSortByPosition(); @@ -902,9 +898,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes * @param style Bibliography style. */ private Map produceCitationMarkersForNormalStyle(CitationGroups cgs, - OOBibStyle style) - throws - BibEntryNotFoundException { + OOBibStyle style) { assert !style.isCitationKeyCiteMarkers(); assert !style.isNumberEntries(); @@ -1240,7 +1234,6 @@ public void insertEntry(List entries, PropertyVetoException, IOException, CreationException, - BibEntryNotFoundException, UndefinedParagraphFormatException, NoDocumentException, InvalidStateException { @@ -1523,7 +1516,6 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d WrappedTargetException, IllegalArgumentException, NoSuchElementException, - BibEntryNotFoundException, NoDocumentException, UnknownPropertyException, JabRefException { @@ -1891,7 +1883,6 @@ public void combineCiteMarkers(List databases, PropertyExistException, IllegalTypeException, CreationException, - BibEntryNotFoundException, NoDocumentException, JabRefException, InvalidStateException { @@ -2247,7 +2238,6 @@ public void unCombineCiteMarkers(List databases, PropertyExistException, IllegalTypeException, CreationException, - BibEntryNotFoundException, NoDocumentException, JabRefException, InvalidStateException { @@ -2392,7 +2382,6 @@ public ExportCitedHelperResult exportCitedHelper(List databases, PropertyVetoException, IOException, CreationException, - BibEntryNotFoundException, InvalidStateException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); @@ -2605,7 +2594,6 @@ public List updateDocumentActionHelper(List databases, UndefinedParagraphFormatException, NoDocumentException, UndefinedCharacterFormatException, - BibEntryNotFoundException, IOException, JabRefException, InvalidStateException { diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 928b9591214..5b0f3c51bb2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -222,11 +222,6 @@ private void initPanel() { LOGGER.warn("Problem with style file", ex); dialogService.showErrorDialogAndWait(Localization.lang("No valid style file defined"), Localization.lang("You must select either a valid style file, or use one of the default styles.")); - } catch (BibEntryNotFoundException ex) { - LOGGER.debug("BibEntry not found", ex); - dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), Localization.lang( - "Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - ex.getCitationKey())); } catch (com.sun.star.lang.IllegalArgumentException | PropertyVetoException | UnknownPropertyException | WrappedTargetException | NoSuchElementException | InvalidStateException | CreationException ex) { @@ -250,8 +245,7 @@ private void initPanel() { } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | NotRemoveableException | IllegalTypeException | InvalidStateException | - PropertyExistException | - BibEntryNotFoundException ex) { + PropertyExistException ex) { LOGGER.warn("Problem combining cite markers", ex); } }); @@ -272,8 +266,7 @@ private void initPanel() { } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | PropertyExistException | IllegalTypeException | NotRemoveableException | - InvalidStateException | - BibEntryNotFoundException ex) { + InvalidStateException ex) { LOGGER.warn("Problem uncombining cite markers", ex); } }); @@ -352,11 +345,6 @@ private void exportEntries() { this.frame.addTab(databaseContext, true); } catch (NoDocumentException ex) { showNoDocumentErrorMessage(); - } catch (BibEntryNotFoundException ex) { - LOGGER.debug("BibEntry not found", ex); - dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), - Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - ex.getCitationKey())); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | UndefinedCharacterFormatException | NoSuchElementException | WrappedTargetException | IOException | InvalidStateException | @@ -590,7 +578,7 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP ex.getLocalizedMessage()); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | - BibEntryNotFoundException | IllegalTypeException | PropertyExistException | + IllegalTypeException | PropertyExistException | InvalidStateException | NotRemoveableException ex) { LOGGER.warn("Could not insert entry", ex); From 372fdf2ecd5b1d7c3cbb5b04d01ed1c85c32a534 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 25 Apr 2021 22:13:04 +0200 Subject: [PATCH 0635/1068] refactor: separating oostyle from openoffice oostyle produces citation markers and bibliography: does not need to know about the word processor in use --- .../openoffice/CitationEntryViewModel.java | 2 +- .../ManageCitationsDialogViewModel.java | 4 +- .../org/jabref/gui/openoffice/OOBibBase.java | 120 ++++-------------- .../gui/openoffice/OpenOfficePanel.java | 7 +- .../gui/openoffice/StyleSelectDialogView.java | 4 +- .../StyleSelectDialogViewModel.java | 4 +- .../openoffice/StyleSelectItemViewModel.java | 2 +- .../org/jabref/logic/layout/LayoutEntry.java | 2 +- .../oostyle}/Citation.java | 16 +-- .../oostyle}/CitationDatabaseLookup.java | 8 +- .../CitationEntry.java | 2 +- .../oostyle}/CitationGroup.java | 39 +++--- .../oostyle}/CitationGroupID.java | 8 +- .../oostyle}/CitationGroups.java | 40 +++--- .../CitationMarkerEntry.java | 2 +- .../CitationMarkerEntryImpl.java | 2 +- .../oostyle}/CitationPath.java | 8 +- .../oostyle}/CitationSort.java | 3 +- .../oostyle}/CitedKey.java | 16 +-- .../oostyle}/CitedKeys.java | 10 +- .../{openoffice => oostyle}/OOBibStyle.java | 2 +- .../OOBibStyleGetCitationMarker.java | 2 +- .../OOBibStyleGetNumCitationMarker.java | 2 +- .../OOPreFormatter.java | 2 +- .../{openoffice => oostyle}/StyleLoader.java | 3 +- .../UndefinedBibtexEntry.java | 2 +- .../{gui => logic}/openoffice/Backend52.java | 44 ++++++- .../{gui => logic}/openoffice/Codec52.java | 2 +- .../{gui => logic}/openoffice/Compat.java | 4 +- .../openoffice/CreationException.java | 4 +- .../openoffice/DocumentConnection.java | 18 ++- .../openoffice/NoDocumentException.java | 4 +- .../org/jabref/logic/openoffice/OOUtil.java | 87 ++++++++++++- .../openoffice/RangeForOverlapCheck.java | 21 +-- .../openoffice/RangeKeyedMap.java | 4 +- .../openoffice/RangeKeyedMapList.java | 14 +- .../{gui => logic}/openoffice/RangeSort.java | 10 +- .../openoffice/RangeSortVisual.java | 4 +- .../openoffice/StorageBase.java | 6 +- .../openoffice/StorageBaseRefMark.java | 5 +- .../UndefinedCharacterFormatException.java | 4 +- .../jabref/preferences/JabRefPreferences.java | 2 +- .../CitationEntryTest.java | 2 +- .../OOBibStyleTest.java | 2 +- .../OOPreFormatterTest.java | 2 +- .../StyleLoaderTest.java | 3 +- .../logic/{openoffice => oostyle}/test.jstyle | 0 .../testWithDefaultAtFirstLIne.jstyle | 0 48 files changed, 302 insertions(+), 252 deletions(-) rename src/main/java/org/jabref/{gui/openoffice => logic/oostyle}/Citation.java (79%) rename src/main/java/org/jabref/{gui/openoffice => logic/oostyle}/CitationDatabaseLookup.java (82%) rename src/main/java/org/jabref/logic/{openoffice => oostyle}/CitationEntry.java (97%) rename src/main/java/org/jabref/{gui/openoffice => logic/oostyle}/CitationGroup.java (73%) rename src/main/java/org/jabref/{gui/openoffice => logic/oostyle}/CitationGroupID.java (60%) rename src/main/java/org/jabref/{gui/openoffice => logic/oostyle}/CitationGroups.java (97%) rename src/main/java/org/jabref/logic/{openoffice => oostyle}/CitationMarkerEntry.java (97%) rename src/main/java/org/jabref/logic/{openoffice => oostyle}/CitationMarkerEntryImpl.java (99%) rename src/main/java/org/jabref/{gui/openoffice => logic/oostyle}/CitationPath.java (66%) rename src/main/java/org/jabref/{gui/openoffice => logic/oostyle}/CitationSort.java (95%) rename src/main/java/org/jabref/{gui/openoffice => logic/oostyle}/CitedKey.java (82%) rename src/main/java/org/jabref/{gui/openoffice => logic/oostyle}/CitedKeys.java (88%) rename src/main/java/org/jabref/logic/{openoffice => oostyle}/OOBibStyle.java (99%) rename src/main/java/org/jabref/logic/{openoffice => oostyle}/OOBibStyleGetCitationMarker.java (99%) rename src/main/java/org/jabref/logic/{openoffice => oostyle}/OOBibStyleGetNumCitationMarker.java (99%) rename src/main/java/org/jabref/logic/{openoffice => oostyle}/OOPreFormatter.java (99%) rename src/main/java/org/jabref/logic/{openoffice => oostyle}/StyleLoader.java (98%) rename src/main/java/org/jabref/logic/{openoffice => oostyle}/UndefinedBibtexEntry.java (93%) rename src/main/java/org/jabref/{gui => logic}/openoffice/Backend52.java (90%) rename src/main/java/org/jabref/{gui => logic}/openoffice/Codec52.java (99%) rename src/main/java/org/jabref/{gui => logic}/openoffice/Compat.java (94%) rename src/main/java/org/jabref/{gui => logic}/openoffice/CreationException.java (72%) rename src/main/java/org/jabref/{gui => logic}/openoffice/DocumentConnection.java (98%) rename src/main/java/org/jabref/{gui => logic}/openoffice/NoDocumentException.java (72%) rename src/main/java/org/jabref/{gui => logic}/openoffice/RangeForOverlapCheck.java (60%) rename src/main/java/org/jabref/{gui => logic}/openoffice/RangeKeyedMap.java (96%) rename src/main/java/org/jabref/{gui => logic}/openoffice/RangeKeyedMapList.java (92%) rename src/main/java/org/jabref/{gui => logic}/openoffice/RangeSort.java (83%) rename src/main/java/org/jabref/{gui => logic}/openoffice/RangeSortVisual.java (99%) rename src/main/java/org/jabref/{gui => logic}/openoffice/StorageBase.java (95%) rename src/main/java/org/jabref/{gui => logic}/openoffice/StorageBaseRefMark.java (99%) rename src/main/java/org/jabref/{gui => logic}/openoffice/UndefinedCharacterFormatException.java (78%) rename src/test/java/org/jabref/logic/{openoffice => oostyle}/CitationEntryTest.java (98%) rename src/test/java/org/jabref/logic/{openoffice => oostyle}/OOBibStyleTest.java (99%) rename src/test/java/org/jabref/logic/{openoffice => oostyle}/OOPreFormatterTest.java (98%) rename src/test/java/org/jabref/logic/{openoffice => oostyle}/StyleLoaderTest.java (98%) rename src/test/resources/org/jabref/logic/{openoffice => oostyle}/test.jstyle (100%) rename src/test/resources/org/jabref/logic/{openoffice => oostyle}/testWithDefaultAtFirstLIne.jstyle (100%) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java index 028990a6bc8..cd64684fc13 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java @@ -3,7 +3,7 @@ import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; -import org.jabref.logic.openoffice.CitationEntry; +import org.jabref.logic.oostyle.CitationEntry; public class CitationEntryViewModel { diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index e91c6189833..0e3db44c326 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -9,7 +9,9 @@ import org.jabref.gui.DialogService; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.openoffice.CitationEntry; +import org.jabref.logic.oostyle.CitationEntry; +import org.jabref.logic.openoffice.CreationException; +import org.jabref.logic.openoffice.NoDocumentException; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ca9622b2406..7d6074847c8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -23,12 +23,26 @@ import org.jabref.logic.bibtex.comparator.FieldComparatorStack; import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; -import org.jabref.logic.openoffice.CitationEntry; -import org.jabref.logic.openoffice.CitationMarkerEntry; -import org.jabref.logic.openoffice.CitationMarkerEntryImpl; -import org.jabref.logic.openoffice.OOBibStyle; -import org.jabref.logic.openoffice.OOPreFormatter; +import org.jabref.logic.oostyle.Citation; +import org.jabref.logic.oostyle.CitationEntry; +import org.jabref.logic.oostyle.CitationGroup; +import org.jabref.logic.oostyle.CitationGroupID; +import org.jabref.logic.oostyle.CitationGroups; +import org.jabref.logic.oostyle.CitationMarkerEntry; +import org.jabref.logic.oostyle.CitationMarkerEntryImpl; +import org.jabref.logic.oostyle.CitationPath; +import org.jabref.logic.oostyle.CitedKey; +import org.jabref.logic.oostyle.CitedKeys; +import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.oostyle.OOPreFormatter; +import org.jabref.logic.openoffice.Backend52; +import org.jabref.logic.openoffice.CreationException; +import org.jabref.logic.openoffice.DocumentConnection; +import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.OOUtil; +import org.jabref.logic.openoffice.RangeForOverlapCheck; +import org.jabref.logic.openoffice.RangeKeyedMapList; +import org.jabref.logic.openoffice.UndefinedCharacterFormatException; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; @@ -400,6 +414,8 @@ private static T unoQI(Class zInterface, /** * @param requireSeparation Report range pairs that only share a boundary. * @param reportAtMost Limit number of overlaps reported (0 for no limit) + * + * TODO: move to org.jabref.logic.openoffice */ public void checkRangeOverlaps(CitationGroups cgs, DocumentConnection documentConnection, @@ -490,92 +506,7 @@ public List getCitationEntries() DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); CitationGroups cgs = new CitationGroups(documentConnection); - - int n = cgs.numberOfCitationGroups(); - List citations = new ArrayList<>(n); - for (CitationGroupID cgid : cgs.getCitationGroupIDs()) { - String name = cgid.asString(); - String context = this.getCitationContext(cgs, cgid, documentConnection, 30, 30, true); - CitationEntry entry = new CitationEntry(name, - context, - cgs.getPageInfo(cgid)); - citations.add(entry); - } - return citations; - } - - /** - * Get the text belonging to refMarkName with up to - * charBefore and charAfter characters of context. - * - * The actual context may be smaller than requested. - * - * @param cgs - * @param cgid - * @param documentConnection - * @param charBefore Number of characters requested. - * @param charAfter Number of characters requested. - * @param htmlMarkup If true, the text belonging to the - * reference mark is surrounded by bold html tag. - */ - private String getCitationContext(CitationGroups cgs, - CitationGroupID cgid, - DocumentConnection documentConnection, - int charBefore, - int charAfter, - boolean htmlMarkup) - throws - WrappedTargetException, - NoDocumentException, - CreationException { - - XTextCursor cursor = (cgs - .getRawCursorForCitationGroup(cgid, documentConnection) - .orElseThrow(RuntimeException::new)); - - String citPart = cursor.getString(); - - // extend cursor range left - int flex = 8; - for (int i = 0; i < charBefore; i++) { - try { - cursor.goLeft((short) 1, true); - // If we are close to charBefore and see a space, - // then cut here. Might avoid cutting a word in half. - if ((i >= (charBefore - flex)) - && Character.isWhitespace(cursor.getString().charAt(0))) { - break; - } - } catch (IndexOutOfBoundsException ex) { - LOGGER.warn("Problem going left", ex); - } - } - - int lengthWithBefore = cursor.getString().length(); - int addedBefore = lengthWithBefore - citPart.length(); - - cursor.collapseToStart(); - for (int i = 0; i < (charAfter + lengthWithBefore); i++) { - try { - cursor.goRight((short) 1, true); - if (i >= ((charAfter + lengthWithBefore) - flex)) { - String strNow = cursor.getString(); - if (Character.isWhitespace(strNow.charAt(strNow.length() - 1))) { - break; - } - } - } catch (IndexOutOfBoundsException ex) { - LOGGER.warn("Problem going right", ex); - } - } - - String result = cursor.getString(); - if (htmlMarkup) { - result = (result.substring(0, addedBefore) - + "" + citPart + "" - + result.substring(lengthWithBefore)); - } - return result.trim(); + return cgs.backend.getCitationEntries(documentConnection, cgs); } /** @@ -696,9 +627,8 @@ private String normalizedCitationMarkerForNormalStyle(CitedKey ck, /** * Fills {@code sortedCitedKeys//normCitMarker} */ - private void - createNormalizedCitationMarkersForNormalStyle(CitedKeys sortedCitedKeys, - OOBibStyle style) { + private void createNormalizedCitationMarkersForNormalStyle(CitedKeys sortedCitedKeys, + OOBibStyle style) { for (CitedKey ck : sortedCitedKeys.data.values()) { ck.normCitMarker = Optional.of(normalizedCitationMarkerForNormalStyle(ck, style)); @@ -1698,7 +1628,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, for (CitationPath p : ck.where) { CitationGroupID cgid = p.group; CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - String refMarkName = cg.referenceMarkName; + String refMarkName = cg.getMarkName(); if (i > 0) { OOUtil.insertTextAtCurrentLocation(documentConnection.xText, diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 5b0f3c51bb2..d735421d896 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -45,10 +45,13 @@ import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.help.HelpFile; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.openoffice.OOBibStyle; +import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.oostyle.StyleLoader; +import org.jabref.logic.openoffice.CreationException; +import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; -import org.jabref.logic.openoffice.StyleLoader; +import org.jabref.logic.openoffice.UndefinedCharacterFormatException; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java index 60a5bb84de5..4570487d0ac 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java @@ -20,8 +20,8 @@ import org.jabref.gui.util.ViewModelTableRowFactory; import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.TextBasedPreviewLayout; -import org.jabref.logic.openoffice.OOBibStyle; -import org.jabref.logic.openoffice.StyleLoader; +import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.oostyle.StyleLoader; import org.jabref.logic.util.TestEntry; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.types.StandardEntryType; diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java index 80c7b97c8de..4e93b2ffccf 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java @@ -22,9 +22,9 @@ import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.openoffice.OOBibStyle; +import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.oostyle.StyleLoader; import org.jabref.logic.openoffice.OpenOfficePreferences; -import org.jabref.logic.openoffice.StyleLoader; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.PreferencesService; diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java index 72890122d4f..1dc1c3bf1f3 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java @@ -9,7 +9,7 @@ import javafx.scene.Node; import org.jabref.gui.icon.IconTheme; -import org.jabref.logic.openoffice.OOBibStyle; +import org.jabref.logic.oostyle.OOBibStyle; public class StyleSelectItemViewModel { diff --git a/src/main/java/org/jabref/logic/layout/LayoutEntry.java b/src/main/java/org/jabref/logic/layout/LayoutEntry.java index cef0e5dcb0a..2e1edd91103 100644 --- a/src/main/java/org/jabref/logic/layout/LayoutEntry.java +++ b/src/main/java/org/jabref/logic/layout/LayoutEntry.java @@ -80,7 +80,7 @@ import org.jabref.logic.layout.format.WrapContent; import org.jabref.logic.layout.format.WrapFileLinks; import org.jabref.logic.layout.format.XMLChars; -import org.jabref.logic.openoffice.OOPreFormatter; +import org.jabref.logic.oostyle.OOPreFormatter; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; diff --git a/src/main/java/org/jabref/gui/openoffice/Citation.java b/src/main/java/org/jabref/logic/oostyle/Citation.java similarity index 79% rename from src/main/java/org/jabref/gui/openoffice/Citation.java rename to src/main/java/org/jabref/logic/oostyle/Citation.java index 6d105db7d82..51b9c42f4e0 100644 --- a/src/main/java/org/jabref/gui/openoffice/Citation.java +++ b/src/main/java/org/jabref/logic/oostyle/Citation.java @@ -1,22 +1,22 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.oostyle; import java.util.Optional; import org.jabref.model.entry.BibEntry; -class Citation implements CitationSort.ComparableCitation { +public class Citation implements CitationSort.ComparableCitation { /** key in database */ - String citationKey; + public String citationKey; /** Result from database lookup. Optional.empty() if not found. */ - Optional db; + public Optional db; /** The number used for numbered citation styles . */ - Optional number; + public Optional number; /** Letter that makes the in-text citation unique. */ - Optional uniqueLetter; + public Optional uniqueLetter; /** pageInfo: For Compat.DataModel.JabRef53 */ - Optional pageInfo; + public Optional pageInfo; /* missing: something that differentiates this from other * citations of the same citationKey. In particular, a @@ -27,7 +27,7 @@ class Citation implements CitationSort.ComparableCitation { // TODO: Citation constructor needs dataModel, to check // if usage of pageInfo confirms to expectations. - Citation(String citationKey) { + public Citation(String citationKey) { this.citationKey = citationKey; this.db = Optional.empty(); this.number = Optional.empty(); diff --git a/src/main/java/org/jabref/gui/openoffice/CitationDatabaseLookup.java b/src/main/java/org/jabref/logic/oostyle/CitationDatabaseLookup.java similarity index 82% rename from src/main/java/org/jabref/gui/openoffice/CitationDatabaseLookup.java rename to src/main/java/org/jabref/logic/oostyle/CitationDatabaseLookup.java index a2b0af44e6b..ef5bda5dd3b 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationDatabaseLookup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationDatabaseLookup.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.oostyle; import java.util.List; import java.util.Optional; @@ -6,11 +6,11 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -class CitationDatabaseLookup { +public class CitationDatabaseLookup { public static class Result { - BibEntry entry; - BibDatabase database; + public final BibEntry entry; + public final BibDatabase database; Result(BibEntry entry, BibDatabase database) { this.entry = entry; this.database = database; diff --git a/src/main/java/org/jabref/logic/openoffice/CitationEntry.java b/src/main/java/org/jabref/logic/oostyle/CitationEntry.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/CitationEntry.java rename to src/main/java/org/jabref/logic/oostyle/CitationEntry.java index 33f3c34662a..c643a7089f2 100644 --- a/src/main/java/org/jabref/logic/openoffice/CitationEntry.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationEntry.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.util.Objects; import java.util.Optional; diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java similarity index 73% rename from src/main/java/org/jabref/gui/openoffice/CitationGroup.java rename to src/main/java/org/jabref/logic/oostyle/CitationGroup.java index 5e614d78126..43d4d9de54e 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.oostyle; import java.util.ArrayList; import java.util.Comparator; @@ -7,31 +7,32 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import org.jabref.logic.openoffice.StorageBase; import org.jabref.model.entry.BibEntry; -class CitationGroup { - CitationGroupID cgid; - StorageBase.NamedRange cgRangeStorage; // knows referenceMarkName - int itcType; - List citations; - List localOrder; +public class CitationGroup { + public CitationGroupID cgid; + public StorageBase.NamedRange cgRangeStorage; // knows referenceMarkName + public int itcType; + public List citations; + public List localOrder; /** For Compat.DataModel.JabRef52 pageInfo belongs to the group */ - Optional pageInfo; + public Optional pageInfo; /** * Locator in document, replaced with cgRangeStorage * TODO: replace referenceMarkName with - * getReferenceMarkName(){ return backed.cgRangeStorage.getName(); } + * getMarkName(){ return backed.cgRangeStorage.getName(); } */ String referenceMarkName; - CitationGroup(CitationGroupID cgid, - StorageBase.NamedRange cgRangeStorage, - int itcType, - List citations, - Optional pageInfo, - String referenceMarkName) { + public CitationGroup(CitationGroupID cgid, + StorageBase.NamedRange cgRangeStorage, + int itcType, + List citations, + Optional pageInfo, + String referenceMarkName) { this.cgid = cgid; this.cgRangeStorage = cgRangeStorage; this.itcType = itcType; @@ -41,12 +42,16 @@ class CitationGroup { this.localOrder = makeIndices(citations.size()); } + public String getMarkName() { + return cgRangeStorage.getName(); + } + /** Integers 0..(n-1) */ static List makeIndices(int n) { return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); } - List getSortedCitations() { + public List getSortedCitations() { List res = new ArrayList<>(citations.size()); for (int i : localOrder) { res.add(citations.get(i)); @@ -54,7 +59,7 @@ List getSortedCitations() { return res; } - List getSortedNumbers() { + public List getSortedNumbers() { List cits = getSortedCitations(); return (cits.stream() .map(cit -> cit.number.orElseThrow(RuntimeException::new)) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroupID.java b/src/main/java/org/jabref/logic/oostyle/CitationGroupID.java similarity index 60% rename from src/main/java/org/jabref/gui/openoffice/CitationGroupID.java rename to src/main/java/org/jabref/logic/oostyle/CitationGroupID.java index 743e9847b1a..baed10bd647 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroupID.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroupID.java @@ -1,18 +1,18 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.oostyle; /** * Identifies a citation group in a document. */ -class CitationGroupID { +public class CitationGroupID { String id; - CitationGroupID(String id) { + public CitationGroupID(String id) { this.id = id; } /** * CitationEntry needs refMark or other identifying string */ - String asString() { + public String asString() { return id; } } diff --git a/src/main/java/org/jabref/gui/openoffice/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java similarity index 97% rename from src/main/java/org/jabref/gui/openoffice/CitationGroups.java rename to src/main/java/org/jabref/logic/oostyle/CitationGroups.java index bdeb7571d94..75f96b0a9cc 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.oostyle; import java.util.ArrayList; import java.util.Comparator; @@ -14,6 +14,16 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; +import org.jabref.logic.openoffice.Backend52; +import org.jabref.logic.openoffice.Compat; +import org.jabref.logic.openoffice.CreationException; +import org.jabref.logic.openoffice.DocumentConnection; +import org.jabref.logic.openoffice.NoDocumentException; +import org.jabref.logic.openoffice.RangeForOverlapCheck; +import org.jabref.logic.openoffice.RangeKeyedMap; +import org.jabref.logic.openoffice.RangeKeyedMapList; +import org.jabref.logic.openoffice.RangeSort; +import org.jabref.logic.openoffice.RangeSortVisual; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; @@ -24,20 +34,15 @@ import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextRange; -import com.sun.star.uno.UnoRuntime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * At the start of GUI actions we may want to check the state of the document. + * CitationGroups : the set of citation groups in the document. * - * Operations: - * createCitationGroup - * deleteCitationGroup * */ - -class CitationGroups { +public class CitationGroups { private static final Logger LOGGER = LoggerFactory.getLogger(CitationGroups.class); @@ -220,7 +225,7 @@ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { return new CitedKeys(res); } - Optional getBibliography() { + public Optional getBibliography() { return bibliography; } @@ -716,7 +721,7 @@ public void cleanFillCursorForCitationGroup(DocumentConnection documentConnectio * * result.size() == nRefMarks */ - List citationRanges(DocumentConnection documentConnection) + public List citationRanges(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException { @@ -751,7 +756,7 @@ List citationRanges(DocumentConnection documentConnection) * footnote marks does not depend on how do we mark or * structure those ranges. */ - List footnoteMarkRanges(DocumentConnection documentConnection) + public List footnoteMarkRanges(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException { @@ -780,7 +785,7 @@ List footnoteMarkRanges(DocumentConnection documentConnect xs.add(new RangeForOverlapCheck(footnoteMarkRange.get(), base.i, // cgid :: identifies of citation group RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + base.description)); + "FootnoteMark for " + base.format())); } } return xs; @@ -798,15 +803,4 @@ public void xshow() { : String.format("%d", globalOrder.get().size()))); } - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if - * available, otherwise null. - */ - private static T unoQI(Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - } diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java rename to src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java index f6b6ce64475..67b6eadc991 100644 --- a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java rename to src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java index e172d8f5614..c277143c507 100644 --- a/src/main/java/org/jabref/logic/openoffice/CitationMarkerEntryImpl.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.util.Objects; import java.util.Optional; diff --git a/src/main/java/org/jabref/gui/openoffice/CitationPath.java b/src/main/java/org/jabref/logic/oostyle/CitationPath.java similarity index 66% rename from src/main/java/org/jabref/gui/openoffice/CitationPath.java rename to src/main/java/org/jabref/logic/oostyle/CitationPath.java index 71ea7e4af5b..bf655ef97e4 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationPath.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationPath.java @@ -1,12 +1,12 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.oostyle; /** * Identifies a citation with the citation group containing it and * its storage index within. */ -class CitationPath { - CitationGroupID group; - int storageIndexInGroup; +public class CitationPath { + public final CitationGroupID group; + public final int storageIndexInGroup; CitationPath(CitationGroupID group, int storageIndexInGroup) { this.group = group; diff --git a/src/main/java/org/jabref/gui/openoffice/CitationSort.java b/src/main/java/org/jabref/logic/oostyle/CitationSort.java similarity index 95% rename from src/main/java/org/jabref/gui/openoffice/CitationSort.java rename to src/main/java/org/jabref/logic/oostyle/CitationSort.java index 76f406606e3..7492f033924 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationSort.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationSort.java @@ -1,9 +1,8 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.oostyle; import java.util.Comparator; import java.util.Optional; -import org.jabref.logic.openoffice.OOBibStyle; import org.jabref.model.entry.BibEntry; class CitationSort { diff --git a/src/main/java/org/jabref/gui/openoffice/CitedKey.java b/src/main/java/org/jabref/logic/oostyle/CitedKey.java similarity index 82% rename from src/main/java/org/jabref/gui/openoffice/CitedKey.java rename to src/main/java/org/jabref/logic/oostyle/CitedKey.java index c24b45ea78d..590b214b579 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitedKey.java +++ b/src/main/java/org/jabref/logic/oostyle/CitedKey.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.oostyle; import java.util.LinkedHashSet; import java.util.List; @@ -7,13 +7,13 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -class CitedKey implements CitationSort.ComparableCitation { - String citationKey; - LinkedHashSet where; - Optional db; - Optional number; // For Numbered citation styles. - Optional uniqueLetter; // For AuthorYear citation styles. - Optional normCitMarker; // For AuthorYear citation styles. +public class CitedKey implements CitationSort.ComparableCitation { + public String citationKey; + public LinkedHashSet where; + public Optional db; + public Optional number; // For Numbered citation styles. + public Optional uniqueLetter; // For AuthorYear citation styles. + public Optional normCitMarker; // For AuthorYear citation styles. CitedKey(String citationKey, CitationPath p, Citation cit) { this.citationKey = citationKey; diff --git a/src/main/java/org/jabref/gui/openoffice/CitedKeys.java b/src/main/java/org/jabref/logic/oostyle/CitedKeys.java similarity index 88% rename from src/main/java/org/jabref/gui/openoffice/CitedKeys.java rename to src/main/java/org/jabref/logic/oostyle/CitedKeys.java index a865b790bb0..153f3104255 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitedKeys.java +++ b/src/main/java/org/jabref/logic/oostyle/CitedKeys.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.oostyle; import java.util.ArrayList; import java.util.Comparator; @@ -9,12 +9,12 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -class CitedKeys { +public class CitedKeys { /** * Order-preserving map from citation keys to associated data. */ - LinkedHashMap data; + public LinkedHashMap data; CitedKeys(LinkedHashMap data) { this.data = data; @@ -48,7 +48,7 @@ void numberCitedKeysInCurrentOrder() { } } - void lookupInDatabases(List databases) { + public void lookupInDatabases(List databases) { for (CitedKey ck : this.data.values()) { ck.lookupInDatabases(databases); } @@ -66,7 +66,7 @@ void distributeNumbers(CitationGroups cgs) { } } - void distributeUniqueLetters(CitationGroups cgs) { + public void distributeUniqueLetters(CitationGroups cgs) { for (CitedKey ck : this.data.values()) { ck.distributeUniqueLetter(cgs); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/OOBibStyle.java rename to src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index dba8c71bee6..9036190e8ea 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java rename to src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index bad385448d3..61a929d5660 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.util.ArrayList; import java.util.Collections; diff --git a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java rename to src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index c840bb043fc..bb25875dbca 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.util.ArrayList; import java.util.Collections; diff --git a/src/main/java/org/jabref/logic/openoffice/OOPreFormatter.java b/src/main/java/org/jabref/logic/oostyle/OOPreFormatter.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/OOPreFormatter.java rename to src/main/java/org/jabref/logic/oostyle/OOPreFormatter.java index 131b8ea374a..1c413234c8f 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOPreFormatter.java +++ b/src/main/java/org/jabref/logic/oostyle/OOPreFormatter.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.util.Map; import java.util.Objects; diff --git a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java b/src/main/java/org/jabref/logic/oostyle/StyleLoader.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/StyleLoader.java rename to src/main/java/org/jabref/logic/oostyle/StyleLoader.java index 4d3b30537db..14ea2c5e5b1 100644 --- a/src/main/java/org/jabref/logic/openoffice/StyleLoader.java +++ b/src/main/java/org/jabref/logic/oostyle/StyleLoader.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.io.File; import java.io.FileNotFoundException; @@ -10,6 +10,7 @@ import java.util.Objects; import org.jabref.logic.layout.LayoutFormatterPreferences; +import org.jabref.logic.openoffice.OpenOfficePreferences; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/logic/openoffice/UndefinedBibtexEntry.java b/src/main/java/org/jabref/logic/oostyle/UndefinedBibtexEntry.java similarity index 93% rename from src/main/java/org/jabref/logic/openoffice/UndefinedBibtexEntry.java rename to src/main/java/org/jabref/logic/oostyle/UndefinedBibtexEntry.java index 6533d61326e..e9c74f3a942 100644 --- a/src/main/java/org/jabref/logic/openoffice/UndefinedBibtexEntry.java +++ b/src/main/java/org/jabref/logic/oostyle/UndefinedBibtexEntry.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; diff --git a/src/main/java/org/jabref/gui/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java similarity index 90% rename from src/main/java/org/jabref/gui/openoffice/Backend52.java rename to src/main/java/org/jabref/logic/openoffice/Backend52.java index 0d9d4305cb3..cdf877b1546 100644 --- a/src/main/java/org/jabref/gui/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; import java.util.ArrayList; import java.util.HashSet; @@ -7,19 +7,26 @@ import java.util.Set; import java.util.stream.Collectors; +import org.jabref.logic.oostyle.Citation; +import org.jabref.logic.oostyle.CitationEntry; +import org.jabref.logic.oostyle.CitationGroup; +import org.jabref.logic.oostyle.CitationGroupID; +import org.jabref.logic.oostyle.CitationGroups; + import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextRange; -class Backend52 { +public class Backend52 { public final Compat.DataModel dataModel; public final StorageBase.NamedRangeManager citationStorageManager; // uses: Codec52 - Backend52() { + public Backend52() { this.dataModel = Compat.DataModel.JabRef52; this.citationStorageManager = new StorageBaseRefMark.Manager(); } @@ -253,8 +260,8 @@ Optional getJabRef52PageInfoFromList(List pageInfosForCitations) * @param pageInfo Nullable. * @return JabRef53 style pageInfo list */ - static List fakePageInfosForCitations(String pageInfo, - int nCitations) { + public static List fakePageInfosForCitations(String pageInfo, + int nCitations) { List pageInfosForCitations = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { if (i == nCitations - 1) { @@ -429,5 +436,32 @@ public void cleanFillCursorForCitationGroup(CitationGroup cg, cg.cgRangeStorage.cleanFillCursor(documentConnection); } + public static List getCitationEntries(DocumentConnection documentConnection, + CitationGroups cgs) + throws + UnknownPropertyException, + WrappedTargetException, + NoDocumentException, + CreationException { + + // One context per CitationGroup: Backend52 (DataModel.JabRef52) + // For DataModel.JabRef53 (Backend53) we need one context per Citation + int n = cgs.numberOfCitationGroups(); + List citations = new ArrayList<>(n); + for (CitationGroupID cgid : cgs.getCitationGroupIDs()) { + String name = cgid.asString(); + XTextCursor cursor = (cgs + .getRawCursorForCitationGroup(cgid, documentConnection) + .orElseThrow(RuntimeException::new)); + String context = OOUtil.getCursorStringWithContext(documentConnection, + cursor, 30, 30, true); + CitationEntry entry = new CitationEntry(name, + context, + cgs.getPageInfo(cgid)); + citations.add(entry); + } + return citations; + } + } // end Backend52 diff --git a/src/main/java/org/jabref/gui/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/Codec52.java similarity index 99% rename from src/main/java/org/jabref/gui/openoffice/Codec52.java rename to src/main/java/org/jabref/logic/openoffice/Codec52.java index 71a5b5cd8d9..2f03ddc2cd2 100644 --- a/src/main/java/org/jabref/gui/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/Codec52.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; import java.util.Arrays; import java.util.List; diff --git a/src/main/java/org/jabref/gui/openoffice/Compat.java b/src/main/java/org/jabref/logic/openoffice/Compat.java similarity index 94% rename from src/main/java/org/jabref/gui/openoffice/Compat.java rename to src/main/java/org/jabref/logic/openoffice/Compat.java index 68565031791..b3d2ea17b86 100644 --- a/src/main/java/org/jabref/gui/openoffice/Compat.java +++ b/src/main/java/org/jabref/logic/openoffice/Compat.java @@ -1,6 +1,6 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; -class Compat { +public class Compat { /** What is the data stored? */ public enum DataModel { diff --git a/src/main/java/org/jabref/gui/openoffice/CreationException.java b/src/main/java/org/jabref/logic/openoffice/CreationException.java similarity index 72% rename from src/main/java/org/jabref/gui/openoffice/CreationException.java rename to src/main/java/org/jabref/logic/openoffice/CreationException.java index 62c1fb0dafa..d688afa5ae0 100644 --- a/src/main/java/org/jabref/gui/openoffice/CreationException.java +++ b/src/main/java/org/jabref/logic/openoffice/CreationException.java @@ -1,10 +1,10 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; /** * Exception used to indicate that the plugin attempted to set a character format that is * not defined in the current OpenOffice document. */ -class CreationException extends Exception { +public class CreationException extends Exception { public CreationException(String message) { super(message); diff --git a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java similarity index 98% rename from src/main/java/org/jabref/gui/openoffice/DocumentConnection.java rename to src/main/java/org/jabref/logic/openoffice/DocumentConnection.java index 67a88ce628d..a9cdaa2bc73 100644 --- a/src/main/java/org/jabref/gui/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java @@ -1,13 +1,10 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; -import org.jabref.logic.openoffice.OOUtil; -import org.jabref.logic.openoffice.UndefinedParagraphFormatException; - import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.Property; @@ -64,7 +61,7 @@ /** * Document-connection related variables. */ -class DocumentConnection { +public class DocumentConnection { /** https://wiki.openoffice.org/wiki/Documentation/BASIC_Guide/ * Structure_of_Text_Documents#Character_Properties * "CharStyleName" is an OpenOffice Property name. @@ -92,7 +89,7 @@ class DocumentConnection { public XPropertyContainer userProperties; public XPropertySet propertySet; - DocumentConnection(XTextDocument mxDoc) { + public DocumentConnection(XTextDocument mxDoc) { this.mxDoc = mxDoc; this.xCurrentComponent = unoQI(XComponent.class, mxDoc); this.mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); @@ -366,6 +363,13 @@ public boolean documentConnectionMissing() { return missing; } + public static Object getProperty(Object o, String property) + throws UnknownPropertyException, WrappedTargetException { + XPropertySet props = UnoRuntime.queryInterface( + XPropertySet.class, o); + return props.getPropertyValue(property); + } + /** * @param doc The XTextDocument we want the title for. Null allowed. * @return The title or Optional.empty() @@ -378,7 +382,7 @@ public static Optional getDocumentTitle(XTextDocument doc) { try { XFrame frame = doc.getCurrentController().getFrame(); - Object frameTitleObj = OOUtil.getProperty(frame, "Title"); + Object frameTitleObj = getProperty(frame, "Title"); String frameTitleString = String.valueOf(frameTitleObj); return Optional.of(frameTitleString); } catch (UnknownPropertyException | WrappedTargetException e) { diff --git a/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java b/src/main/java/org/jabref/logic/openoffice/NoDocumentException.java similarity index 72% rename from src/main/java/org/jabref/gui/openoffice/NoDocumentException.java rename to src/main/java/org/jabref/logic/openoffice/NoDocumentException.java index 05d5f6d06ac..28d6ba7aced 100644 --- a/src/main/java/org/jabref/gui/openoffice/NoDocumentException.java +++ b/src/main/java/org/jabref/logic/openoffice/NoDocumentException.java @@ -1,10 +1,10 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; /** * Exception used to indicate that the plugin attempted to set a character format that is * not defined in the current OpenOffice document. */ -class NoDocumentException extends Exception { +public class NoDocumentException extends Exception { public NoDocumentException(String message) { super(message); diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 8419ce0c784..658e45e86d4 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -21,6 +21,8 @@ import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Utility methods for processing OO Writer documents. @@ -28,6 +30,8 @@ @AllowedToUseAwt("Requires AWT for changing document properties") public class OOUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(OOUtil.class); + private static final String CHAR_STRIKEOUT = "CharStrikeout"; private static final String CHAR_UNDERLINE = "CharUnderline"; private static final String PARA_STYLE_NAME = "ParaStyleName"; @@ -65,6 +69,8 @@ private OOUtil() { * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. * * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation() + * + * TODO: this is not OO-specific, should be in oostyle */ public static String formatFullReference(Layout layout, BibEntry entry, @@ -248,10 +254,81 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S cursor.collapseToEnd(); } - public static Object getProperty(Object o, String property) - throws UnknownPropertyException, WrappedTargetException { - XPropertySet props = UnoRuntime.queryInterface( - XPropertySet.class, o); - return props.getPropertyValue(property); + /** + * Get the text belonging to cursor with up to + * charBefore and charAfter characters of context. + * + * The actual context may be smaller than requested. + * + * @param documentConnection + * @param cursor + * @param charBefore Number of characters requested. + * @param charAfter Number of characters requested. + * @param htmlMarkup If true, the text belonging to the + * reference mark is surrounded by bold html tag. + * + * TODO: This method could go to OOUtil, except that it refers to + * DocumentConnection, which is in "gui". DocumentConnection + * should go to "logic" as well. As well as many others, ... + * + * TODO: there is also a potential distinction between OO-specific + * parts and those that could participate in for example a Word + * panel. Is the GUI itself dependent on using OO/LO? Hard to + * tell. + */ + public static String getCursorStringWithContext(DocumentConnection documentConnection, + XTextCursor cursor, + int charBefore, + int charAfter, + boolean htmlMarkup) + throws + WrappedTargetException, + NoDocumentException, + CreationException { + + String citPart = cursor.getString(); + + // extend cursor range left + int flex = 8; + for (int i = 0; i < charBefore; i++) { + try { + cursor.goLeft((short) 1, true); + // If we are close to charBefore and see a space, + // then cut here. Might avoid cutting a word in half. + if ((i >= (charBefore - flex)) + && Character.isWhitespace(cursor.getString().charAt(0))) { + break; + } + } catch (IndexOutOfBoundsException ex) { + LOGGER.warn("Problem going left", ex); + } + } + + int lengthWithBefore = cursor.getString().length(); + int addedBefore = lengthWithBefore - citPart.length(); + + cursor.collapseToStart(); + for (int i = 0; i < (charAfter + lengthWithBefore); i++) { + try { + cursor.goRight((short) 1, true); + if (i >= ((charAfter + lengthWithBefore) - flex)) { + String strNow = cursor.getString(); + if (Character.isWhitespace(strNow.charAt(strNow.length() - 1))) { + break; + } + } + } catch (IndexOutOfBoundsException ex) { + LOGGER.warn("Problem going right", ex); + } + } + + String result = cursor.getString(); + if (htmlMarkup) { + result = (result.substring(0, addedBefore) + + "" + citPart + "" + + result.substring(lengthWithBefore)); + } + return result.trim(); } + } diff --git a/src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java b/src/main/java/org/jabref/logic/openoffice/RangeForOverlapCheck.java similarity index 60% rename from src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java rename to src/main/java/org/jabref/logic/openoffice/RangeForOverlapCheck.java index b54d0a59ac3..2e639afdde5 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeForOverlapCheck.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeForOverlapCheck.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; import com.sun.star.text.XTextRange; @@ -16,23 +16,24 @@ * corresponding tables. * */ -class RangeForOverlapCheck { - final static int REFERENCE_MARK_KIND = 0; - final static int FOOTNOTE_MARK_KIND = 1; +public class RangeForOverlapCheck { + public final static int REFERENCE_MARK_KIND = 0; + public final static int FOOTNOTE_MARK_KIND = 1; - XTextRange range; - int kind; - T i; // TODO: rename to content if identifier or cgid - String description; + public final XTextRange range; + public final int kind; + public final T i; // TODO: rename to content if identifier or cgid + private final String description; - RangeForOverlapCheck(XTextRange range, T i, int kind, String description) { + public RangeForOverlapCheck(XTextRange range, T i, int kind, String description) { this.range = range; this.kind = kind; this.i = i; this.description = description; } - String format() { + public String format() { return description; } + } diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java similarity index 96% rename from src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java rename to src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java index 09fa2d344a6..af85875532e 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMap.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; import java.util.ArrayList; import java.util.HashMap; @@ -27,7 +27,7 @@ * single XTextRange. The class RangeKeyedMapList solves this. * */ -class RangeKeyedMap { +public class RangeKeyedMap { private final Map> xxs; public RangeKeyedMap() { diff --git a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java similarity index 92% rename from src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java rename to src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java index ada90642611..bc1b579b8f1 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; import java.util.ArrayList; import java.util.List; @@ -6,7 +6,7 @@ import com.sun.star.text.XTextRange; -class RangeKeyedMapList { +public class RangeKeyedMapList { RangeKeyedMap> xxs; public RangeKeyedMapList() { @@ -54,7 +54,7 @@ public List flatListOfValues() { return result; } - enum OverlapKind { + public enum OverlapKind { TOUCH, OVERLAP, EQUAL_RANGE @@ -66,9 +66,9 @@ enum OverlapKind { * You probably want {@code V} to include information * identifying the ranges. */ - class RangeOverlap { - OverlapKind kind; - List vs; + public class RangeOverlap { + public final OverlapKind kind; + public final List vs; public RangeOverlap(OverlapKind kind, List vs) { this.kind = kind; @@ -85,7 +85,7 @@ public RangeOverlap(OverlapKind kind, List vs) { * @param atMost Limit the number of records returneed to atMost. * Zero or negative {@code atMost} means no limit. */ - List findOverlappingRanges(int atMost, boolean includeTouching) { + public List findOverlappingRanges(int atMost, boolean includeTouching) { List res = new ArrayList<>(); for (TreeMap> xs : xxs.partitionValues()) { List oxs = new ArrayList<>(xs.keySet()); diff --git a/src/main/java/org/jabref/gui/openoffice/RangeSort.java b/src/main/java/org/jabref/logic/openoffice/RangeSort.java similarity index 83% rename from src/main/java/org/jabref/gui/openoffice/RangeSort.java rename to src/main/java/org/jabref/logic/openoffice/RangeSort.java index 1821cd3ac44..c945e878059 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeSort.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSort.java @@ -1,8 +1,8 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; import com.sun.star.text.XTextRange; -class RangeSort { +public class RangeSort { /** * This is what {@code visualSort} needs in its input. @@ -27,9 +27,9 @@ public static class RangeSortEntry implements RangeSortable { public int indexInPosition; public T content; - RangeSortEntry(XTextRange range, - int indexInPosition, - T content) { + public RangeSortEntry(XTextRange range, + int indexInPosition, + T content) { this.range = range; this.indexInPosition = indexInPosition; this.content = content; diff --git a/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java similarity index 99% rename from src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java rename to src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index f14fc69684d..9d7d76ca4d4 100644 --- a/src/main/java/org/jabref/gui/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; import java.util.ArrayList; import java.util.Arrays; @@ -29,7 +29,7 @@ * of the first column of the first page. * */ -class RangeSortVisual { +public class RangeSortVisual { private static final Logger LOGGER = LoggerFactory.getLogger(RangeSortVisual.class); diff --git a/src/main/java/org/jabref/gui/openoffice/StorageBase.java b/src/main/java/org/jabref/logic/openoffice/StorageBase.java similarity index 95% rename from src/main/java/org/jabref/gui/openoffice/StorageBase.java rename to src/main/java/org/jabref/logic/openoffice/StorageBase.java index cdb4ae31a87..ba159f91fc6 100644 --- a/src/main/java/org/jabref/gui/openoffice/StorageBase.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBase.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; import java.util.List; import java.util.Optional; @@ -8,7 +8,7 @@ import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextRange; -class StorageBase { +public class StorageBase { interface HasName { public String getName(); @@ -66,7 +66,7 @@ public void removeFromDocument(DocumentConnection documentConnection) NoSuchElementException; } - interface NamedRange extends HasName, HasTextRange { + public interface NamedRange extends HasName, HasTextRange { // nothing new here } diff --git a/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java similarity index 99% rename from src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java rename to src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index c069a47abf0..cf7ed4dc6e8 100644 --- a/src/main/java/org/jabref/gui/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -1,4 +1,4 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; import java.util.List; import java.util.Optional; @@ -56,8 +56,7 @@ String getId() { * This could be generalized to insert arbitrary text safely * between two reference marks. But we do not need that now. */ - private static XTextCursor - safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { + private static XTextCursor safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { // Start with an empty cursor at position.getStart(); XText text = position.getText(); XTextCursor cursor = text.createTextCursorByRange(position.getStart()); diff --git a/src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java b/src/main/java/org/jabref/logic/openoffice/UndefinedCharacterFormatException.java similarity index 78% rename from src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java rename to src/main/java/org/jabref/logic/openoffice/UndefinedCharacterFormatException.java index 4ab29ca2fa5..62e969646ef 100644 --- a/src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java +++ b/src/main/java/org/jabref/logic/openoffice/UndefinedCharacterFormatException.java @@ -1,10 +1,10 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; /** * Exception used to indicate that the plugin attempted to set a character format that is * not defined in the current OpenOffice document. */ -class UndefinedCharacterFormatException extends Exception { +public class UndefinedCharacterFormatException extends Exception { private final String formatName; diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java index c146effc262..c903fe1e5bf 100644 --- a/src/main/java/org/jabref/preferences/JabRefPreferences.java +++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java @@ -86,8 +86,8 @@ import org.jabref.logic.layout.format.FileLinkPreferences; import org.jabref.logic.layout.format.NameFormatterPreferences; import org.jabref.logic.net.ProxyPreferences; +import org.jabref.logic.oostyle.StyleLoader; import org.jabref.logic.openoffice.OpenOfficePreferences; -import org.jabref.logic.openoffice.StyleLoader; import org.jabref.logic.preferences.DOIPreferences; import org.jabref.logic.preferences.OwnerPreferences; import org.jabref.logic.preferences.TimestampPreferences; diff --git a/src/test/java/org/jabref/logic/openoffice/CitationEntryTest.java b/src/test/java/org/jabref/logic/oostyle/CitationEntryTest.java similarity index 98% rename from src/test/java/org/jabref/logic/openoffice/CitationEntryTest.java rename to src/test/java/org/jabref/logic/oostyle/CitationEntryTest.java index b1cd1d100a7..f702bc64ece 100644 --- a/src/test/java/org/jabref/logic/openoffice/CitationEntryTest.java +++ b/src/test/java/org/jabref/logic/oostyle/CitationEntryTest.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.util.Optional; diff --git a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java similarity index 99% rename from src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java rename to src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index ad4678c5305..b0b2f0c1c0d 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.io.File; import java.io.IOException; diff --git a/src/test/java/org/jabref/logic/openoffice/OOPreFormatterTest.java b/src/test/java/org/jabref/logic/oostyle/OOPreFormatterTest.java similarity index 98% rename from src/test/java/org/jabref/logic/openoffice/OOPreFormatterTest.java rename to src/test/java/org/jabref/logic/oostyle/OOPreFormatterTest.java index 8b76fbeacd0..fb0ad8e5391 100644 --- a/src/test/java/org/jabref/logic/openoffice/OOPreFormatterTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOPreFormatterTest.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import org.junit.jupiter.api.Test; diff --git a/src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java b/src/test/java/org/jabref/logic/oostyle/StyleLoaderTest.java similarity index 98% rename from src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java rename to src/test/java/org/jabref/logic/oostyle/StyleLoaderTest.java index be5e3768a01..17f4104a001 100644 --- a/src/test/java/org/jabref/logic/openoffice/StyleLoaderTest.java +++ b/src/test/java/org/jabref/logic/oostyle/StyleLoaderTest.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; import java.net.URISyntaxException; import java.nio.charset.Charset; @@ -9,6 +9,7 @@ import java.util.List; import org.jabref.logic.layout.LayoutFormatterPreferences; +import org.jabref.logic.openoffice.OpenOfficePreferences; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/resources/org/jabref/logic/openoffice/test.jstyle b/src/test/resources/org/jabref/logic/oostyle/test.jstyle similarity index 100% rename from src/test/resources/org/jabref/logic/openoffice/test.jstyle rename to src/test/resources/org/jabref/logic/oostyle/test.jstyle diff --git a/src/test/resources/org/jabref/logic/openoffice/testWithDefaultAtFirstLIne.jstyle b/src/test/resources/org/jabref/logic/oostyle/testWithDefaultAtFirstLIne.jstyle similarity index 100% rename from src/test/resources/org/jabref/logic/openoffice/testWithDefaultAtFirstLIne.jstyle rename to src/test/resources/org/jabref/logic/oostyle/testWithDefaultAtFirstLIne.jstyle From 80abb33b63e720ae9fbde5fcc02acd70e45fb871 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 26 Apr 2021 11:05:28 +0200 Subject: [PATCH 0636/1068] moved backend out of CitationGroups, to OOFrontend --- .../ManageCitationsDialogViewModel.java | 2 +- .../org/jabref/gui/openoffice/OOBibBase.java | 285 +++----- .../jabref/logic/oostyle/CitationGroups.java | 520 +------------- .../logic/{openoffice => oostyle}/Compat.java | 2 +- .../jabref/logic/openoffice/Backend52.java | 39 +- .../jabref/logic/openoffice/OOFrontend.java | 632 ++++++++++++++++++ 6 files changed, 771 insertions(+), 709 deletions(-) rename src/main/java/org/jabref/logic/{openoffice => oostyle}/Compat.java (96%) create mode 100644 src/main/java/org/jabref/logic/openoffice/OOFrontend.java diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 0e3db44c326..d73ed902176 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -55,7 +55,7 @@ public void storeSettings() { try { ooBase.applyCitationEntries(ciationEntries); } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException | - NoDocumentException | + NoDocumentException | WrappedTargetException | IllegalArgumentException ex) { LOGGER.warn("Problem modifying citation", ex); dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex); diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7d6074847c8..a1a3c5ddde9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -39,9 +39,8 @@ import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.DocumentConnection; import org.jabref.logic.openoffice.NoDocumentException; +import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.OOUtil; -import org.jabref.logic.openoffice.RangeForOverlapCheck; -import org.jabref.logic.openoffice.RangeKeyedMapList; import org.jabref.logic.openoffice.UndefinedCharacterFormatException; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; import org.jabref.model.database.BibDatabase; @@ -410,93 +409,6 @@ private static T unoQI(Class zInterface, * And fills the bibliography (presentation) * * **************************************/ - - /** - * @param requireSeparation Report range pairs that only share a boundary. - * @param reportAtMost Limit number of overlaps reported (0 for no limit) - * - * TODO: move to org.jabref.logic.openoffice - */ - public void checkRangeOverlaps(CitationGroups cgs, - DocumentConnection documentConnection, - boolean requireSeparation, - int reportAtMost) - throws - NoDocumentException, - WrappedTargetException, - JabRefException { - - final boolean debugPartitions = false; - - List xs = cgs.citationRanges(documentConnection); - xs.addAll(cgs.footnoteMarkRanges(documentConnection)); - - RangeKeyedMapList xall = new RangeKeyedMapList<>(); - for (RangeForOverlapCheck x : xs) { - XTextRange key = x.range; - xall.add(key, x); - } - - List.RangeOverlap> ovs = - xall.findOverlappingRanges(reportAtMost, requireSeparation); - - // checkSortedPartitionForOverlap(requireSeparation, oxs); - if (ovs.size() > 0) { - String msg = ""; - for (RangeKeyedMapList.RangeOverlap e : ovs) { - String l = (": " - + (e.vs.stream() - .map(v -> String.format("'%s'", v.format())) - .collect(Collectors.joining(", "))) - + "\n"); - - switch (e.kind) { - case EQUAL_RANGE: msg = msg + Localization.lang("Found identical ranges") + l; - break; - case OVERLAP: msg = msg + Localization.lang("Found overlapping ranges") + l; - break; - case TOUCH: msg = msg + Localization.lang("Found touching ranges") + l; - break; - } - } - throw new JabRefException("Found overlapping or touching ranges", msg); - } - } - - /** - * GUI: Get a list of CitationEntry objects corresponding to citations - * in the document. - * - * Called from: ManageCitationsDialogViewModel constructor. - * - * @return A list with entries corresponding to citations in the - * text, in arbitrary order (same order as from - * getJabRefReferenceMarkNames). - * - * Note: visual or alphabetic order could be more - * manageable for the user. We could provide these - * here, but switching between them needs change on - * GUI (adding a toggle or selector). - * - * Note: CitationEntry implements Comparable, where - * compareTo() and equals() are based on refMarkName. - * The order used in the "Manage citations" dialog - * does not seem to use that. - * - * The 1st is labeled "Citation" (show citation in bold, - * and some context around it). - * - * The columns can be sorted by clicking on the column title. - * For the "Citation" column, the sorting is based on the content, - * (the context before the citation), not on the citation itself. - * - * In the "Extra information ..." column some visual indication - * of the editable part could be helpful. - * - * Wish: selecting an entry (or a button in the line) in - * the GUI could move the cursor in the document to - * the entry. - */ public List getCitationEntries() throws UnknownPropertyException, @@ -505,8 +417,8 @@ public List getCitationEntries() CreationException { DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - CitationGroups cgs = new CitationGroups(documentConnection); - return cgs.backend.getCitationEntries(documentConnection, cgs); + OOFrontend fr = new OOFrontend(documentConnection); + return fr.getCitationEntries(documentConnection); } /** @@ -541,17 +453,12 @@ public void applyCitationEntries(List citationEntries) PropertyExistException, IllegalTypeException, IllegalArgumentException, - NoDocumentException { + NoDocumentException, + WrappedTargetException { DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - - for (CitationEntry entry : citationEntries) { - Optional pageInfo = entry.getPageInfo(); - if (pageInfo.isPresent()) { - documentConnection.setCustomProperty(entry.getRefMarkName(), - pageInfo.get()); - } - } + OOFrontend fr = new OOFrontend(documentConnection); + fr.applyCitationEntries(documentConnection, citationEntries); } /* *************************************** @@ -782,7 +689,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); - List pageInfos = cgs.backend.getPageInfosForCitations(cg); + List pageInfos = cgs.getPageInfosForCitations(cg); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, @@ -811,7 +718,7 @@ private static int citationTypeFromOptions(boolean withText, boolean inParenthes for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); - List pageInfos = cgs.backend.getPageInfosForCitations(cg); + List pageInfos = cgs.getPageInfosForCitations(cg); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, @@ -852,7 +759,7 @@ private Map produceCitationMarkersForNormalStyle(Citati CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List cits = cg.getSortedCitations(); final int nCitedEntries = cits.size(); - List pageInfosForCitations = cgs.backend.getPageInfosForCitations(cg); + List pageInfosForCitations = cgs.getPageInfosForCitations(cg); List citationMarkerEntries = new ArrayList<>(nCitedEntries); @@ -919,10 +826,7 @@ private Map produceCitationMarkersForNormalStyle(Citati return citMarkers; } - private static void fillCitationMarkInCursor(DocumentConnection documentConnection, - CitationGroups cgs, - CitationGroupID cgid, - XTextCursor cursor, + private static void fillCitationMarkInCursor(XTextCursor cursor, String citationText, boolean withText, OOBibStyle style) @@ -933,9 +837,6 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti IllegalArgumentException, UndefinedCharacterFormatException { - Objects.requireNonNull(documentConnection); - Objects.requireNonNull(cgs); - Objects.requireNonNull(cgid); Objects.requireNonNull(cursor); Objects.requireNonNull(citationText); Objects.requireNonNull(style); @@ -955,7 +856,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti /** * Inserts a citation group in the document: creates and fills it. * - * @param cgs + * @param fr * @param documentConnection Connection to a document. * @param citationKeys BibTeX keys of * @param pageInfosForCitations @@ -972,7 +873,8 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti * coming after. But is not wanted when we recreate a * reference mark. */ - private void createAndFillCitationGroup(CitationGroups cgs, + private void createAndFillCitationGroup(OOFrontend fr, + // CitationGroups cgs, DocumentConnection documentConnection, List citationKeys, List pageInfosForCitations, @@ -995,27 +897,24 @@ private void createAndFillCitationGroup(CitationGroups cgs, NoDocumentException, IllegalTypeException { - CitationGroupID cgid = cgs.createCitationGroup(documentConnection, - citationKeys, - pageInfosForCitations, - itcType, - position, - insertSpaceAfter, - !withText /* withoutBrackets */); + CitationGroupID cgid = fr.createCitationGroup(documentConnection, + citationKeys, + pageInfosForCitations, + itcType, + position, + insertSpaceAfter, + !withText /* withoutBrackets */); if (withText) { - XTextCursor c2 = cgs.getFillCursorForCitationGroup(documentConnection, - cgid); + XTextCursor c2 = fr.getFillCursorForCitationGroup(documentConnection, + cgid); - fillCitationMarkInCursor(documentConnection, - cgs, - cgid, - c2, + fillCitationMarkInCursor(c2, citationText, withText, style); - cgs.cleanFillCursorForCitationGroup(documentConnection, cgid); + fr.cleanFillCursorForCitationGroup(documentConnection, cgid); } position.collapseToEnd(); } @@ -1180,7 +1079,8 @@ public void insertEntry(List entries, final int nEntries = entries.size(); DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - CitationGroups cgs = new CitationGroups(documentConnection); + OOFrontend fr = new OOFrontend(documentConnection); + // CitationGroups cgs = new CitationGroups(documentConnection); // TODO: imposeLocalOrder boolean useUndoContext = true; @@ -1249,7 +1149,7 @@ public void insertEntry(List entries, citeText = "[?]"; } - createAndFillCitationGroup(cgs, + createAndFillCitationGroup(fr, documentConnection, citationKeys, pageInfosForCitations, @@ -1267,18 +1167,20 @@ public void insertEntry(List entries, if (sync) { // To account for numbering and for uniqueLetters, we // must refresh the cite markers: + OOFrontend fr2 = new OOFrontend(documentConnection); + fr2.imposeGlobalOrder(documentConnection); ProduceCitationMarkersResult x = - produceCitationMarkers(documentConnection, allBases, style); + produceCitationMarkers(fr2.cgs, allBases, style); try { documentConnection.lockControllers(); applyNewCitationMarkers(documentConnection, - x.cgs, + fr2, x.citMarkers, style); // Insert it at the current position: rebuildBibTextSection(documentConnection, style, - x.cgs, + fr2, x.getBibliography()); } finally { documentConnection.unlockControllers(); @@ -1322,7 +1224,7 @@ public void insertEntry(List entries, * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. * * @param documentConnection - * @param cgs + * @param fr * * @param citMarkers Corresponding text for each reference mark, * that replaces the old text. @@ -1331,7 +1233,7 @@ public void insertEntry(List entries, * */ private void applyNewCitationMarkers(DocumentConnection documentConnection, - CitationGroups cgs, + OOFrontend fr, Map citMarkers, OOBibStyle style) throws @@ -1342,6 +1244,7 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, WrappedTargetException, PropertyVetoException { + CitationGroups cgs = fr.cgs; final boolean hadBibSection = (documentConnection .getBookmarkRange(OOBibBase.BIB_SECTION_NAME) .isPresent()); @@ -1368,23 +1271,20 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, if (withText) { - XTextCursor cursor = cgs.getFillCursorForCitationGroup(documentConnection, - cgid); + XTextCursor cursor = fr.getFillCursorForCitationGroup(documentConnection, + cgid); if (mustTestCharFormat) { assertCitationCharacterFormatIsOK(cursor, style); mustTestCharFormat = false; } - fillCitationMarkInCursor(documentConnection, - cgs, - cgid, - cursor, + fillCitationMarkInCursor(cursor, citationText, withText, style); - cgs.cleanFillCursorForCitationGroup(documentConnection, cgid); + fr.cleanFillCursorForCitationGroup(documentConnection, cgid); } if (hadBibSection @@ -1439,46 +1339,19 @@ public List getUnresolvedKeys() { } } - private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection documentConnection, + private ProduceCitationMarkersResult produceCitationMarkers(CitationGroups cgs, List databases, - OOBibStyle style) - throws - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - NoDocumentException, - UnknownPropertyException, - JabRefException { + OOBibStyle style) { - CitationGroups cgs = new CitationGroups(documentConnection); + if (!cgs.hasGlobalOrder()) { + throw new RuntimeException("produceCitationMarkers: globalOrder is misssing in cgs"); + } cgs.lookupEntriesInDatabases(databases); // requires cgs.lookupEntryInDatabases: needs BibEntry data cgs.imposeLocalOrderByComparator(comparatorForMulticite(style)); - // Normally we sort the reference marks according to their - // order of appearance. - // - // This only depends on location of ranges and footnote marks - // in the text. Does not touch localOrder, only order between - // reference marks. - // - // Question: is there a case when we do not need order-of-appearance? - // - // style.isCitationKeyCiteMarkers() : ??? - // style.isNumberEntries() && style.isSortByPosition() : - // needs order-of-appearance for numbering - // style.isNumberEntries() && !style.isSortByPosition() : ??? - // produceCitationMarkersForNormalStyle : needs order-of-appearance for uniqueLetters - // - boolean mapFootnotesToFootnoteMarks = true; - List sortedCitationGroupIDs = - cgs.getVisuallySortedCitationGroupIDs(documentConnection, - mapFootnotesToFootnoteMarks); - cgs.setGlobalOrder(sortedCitationGroupIDs); - // localOrder and globalOrder together gives us order-of-appearance of citations - Map citMarkers; // fill citMarkers @@ -1515,7 +1388,7 @@ private ProduceCitationMarkersResult produceCitationMarkers(DocumentConnection d */ private void rebuildBibTextSection(DocumentConnection documentConnection, OOBibStyle style, - CitationGroups cgs, + OOFrontend fr, CitedKeys bibliography) throws NoSuchElementException, @@ -1529,7 +1402,7 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, clearBibTextSectionContent2(documentConnection); populateBibTextSection(documentConnection, - cgs, + fr, bibliography, style); } @@ -1738,7 +1611,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) * Assumes the section named `OOBibBase.BIB_SECTION_NAME` exists. */ private void populateBibTextSection(DocumentConnection documentConnection, - CitationGroups cgs, + OOFrontend fr, CitedKeys bibliography, OOBibStyle style) throws @@ -1775,7 +1648,7 @@ private void populateBibTextSection(DocumentConnection documentConnection, // emit body insertFullReferenceAtCursor(documentConnection, cursor, - cgs, + fr.cgs, bibliography, style); @@ -1824,7 +1697,7 @@ public void combineCiteMarkers(List databases, final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - CitationGroups cgs = new CitationGroups(documentConnection); + OOFrontend fr = new OOFrontend(documentConnection); try { documentConnection.enterUndoContext("Merge citations"); @@ -1832,8 +1705,8 @@ public void combineCiteMarkers(List databases, boolean madeModifications = false; List referenceMarkNames = - cgs.getCitationGroupIDsSortedWithinPartitions(documentConnection, - false /* mapFootnotesToFootnoteMarks */); + fr.getCitationGroupIDsSortedWithinPartitions(documentConnection, + false /* mapFootnotesToFootnoteMarks */); final int nRefMarks = referenceMarkNames.size(); @@ -1867,9 +1740,9 @@ public void combineCiteMarkers(List databases, XTextRange prevRange = null; for (CitationGroupID cgid : referenceMarkNames) { - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + CitationGroup cg = fr.cgs.getCitationGroupOrThrow(cgid); - XTextRange currentRange = (cgs + XTextRange currentRange = (fr .getMarkRange(documentConnection, cgid) .orElseThrow(RuntimeException::new)); @@ -2084,11 +1957,11 @@ public void combineCiteMarkers(List databases, // but it is not clear how should we handle them here. // We delegate the problem to the backend. List pageInfosForCitations = - cgs.backend.combinePageInfos(joinableGroup); + fr.backend.combinePageInfos(joinableGroup); // Remove the old citation groups from the document. for (int gj = 0; gj < joinableGroup.size(); gj++) { - cgs.removeCitationGroups(joinableGroup, documentConnection); + fr.removeCitationGroups(joinableGroup, documentConnection); } XTextCursor textCursor = joinableGroupsCursors.get(gi); @@ -2105,7 +1978,7 @@ public void combineCiteMarkers(List databases, * be) */ boolean insertSpaceAfter = false; - createAndFillCitationGroup(cgs, + createAndFillCitationGroup(fr, documentConnection, citationKeys, pageInfosForCitations, @@ -2126,7 +1999,9 @@ public void combineCiteMarkers(List databases, } if (madeModifications) { - ProduceCitationMarkersResult x = produceCitationMarkers(documentConnection, + OOFrontend fr2 = new OOFrontend(documentConnection); + fr2.imposeGlobalOrder(documentConnection); + ProduceCitationMarkersResult x = produceCitationMarkers(fr.cgs, databases, style); try { @@ -2134,7 +2009,7 @@ public void combineCiteMarkers(List databases, documentConnection.lockControllers(); } applyNewCitationMarkers(documentConnection, - x.cgs, + fr, x.citMarkers, style); } finally { @@ -2178,14 +2053,14 @@ public void unCombineCiteMarkers(List databases, final boolean useLockControllers = true; DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - CitationGroups cgs = new CitationGroups(documentConnection); + OOFrontend fr = new OOFrontend(documentConnection); try { documentConnection.enterUndoContext("Separate citations"); boolean madeModifications = false; // {@code names} does not need to be sorted. - List names = new ArrayList<>(cgs.getCitationGroupIDs()); + List names = new ArrayList<>(fr.cgs.getCitationGroupIDs()); try { if (useLockControllers) { @@ -2197,8 +2072,8 @@ public void unCombineCiteMarkers(List databases, while (pivot < (names.size())) { CitationGroupID cgid = names.get(pivot); - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - XTextRange range1 = (cgs + CitationGroup cg = fr.cgs.getCitationGroupOrThrow(cgid); + XTextRange range1 = (fr .getMarkRange(documentConnection, cgid) .orElseThrow(RuntimeException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); @@ -2214,7 +2089,7 @@ public void unCombineCiteMarkers(List databases, } // Note: JabRef52 returns cg.pageInfo for the last citation. - List pageInfosForCitations = cgs.backend.getPageInfosForCitations(cg); + List pageInfosForCitations = fr.cgs.getPageInfosForCitations(cg); List cits = cg.citations; if (cits.size() <= 1) { @@ -2225,7 +2100,7 @@ public void unCombineCiteMarkers(List databases, List keys = cits.stream().map(cit -> cit.citationKey).collect(Collectors.toList()); - cgs.removeCitationGroup(cg, documentConnection); + fr.removeCitationGroup(cg, documentConnection); // Now we own the content of cits @@ -2238,7 +2113,7 @@ public void unCombineCiteMarkers(List databases, // We just reread below. boolean insertSpaceAfter = (i != last); - createAndFillCitationGroup(cgs, + createAndFillCitationGroup(fr, documentConnection, keys.subList(i, i + 1), // citationKeys, pageInfosForCitations.subList(i, i + 1), // pageInfos, @@ -2262,13 +2137,15 @@ public void unCombineCiteMarkers(List databases, } if (madeModifications) { + OOFrontend fr2 = new OOFrontend(documentConnection); + fr2.imposeGlobalOrder(documentConnection); ProduceCitationMarkersResult x = - produceCitationMarkers(documentConnection, databases, style); + produceCitationMarkers(fr.cgs, databases, style); try { if (useLockControllers) { documentConnection.lockControllers(); } - applyNewCitationMarkers(documentConnection, x.cgs, x.citMarkers, style); + applyNewCitationMarkers(documentConnection, fr2, x.citMarkers, style); } finally { if (useLockControllers) { documentConnection.unlockControllers(); @@ -2344,8 +2221,8 @@ private ExportCitedHelperResult generateDatabase(List databases, NoDocumentException, UnknownPropertyException { - CitationGroups cgs = new CitationGroups(documentConnection); - CitedKeys cks = cgs.getCitedKeys(); + OOFrontend fr = new OOFrontend(documentConnection); + CitedKeys cks = fr.cgs.getCitedKeys(); cks.lookupInDatabases(databases); List unresolvedKeys = new ArrayList<>(); @@ -2537,14 +2414,18 @@ public List updateDocumentActionHelper(List databases, documentConnection.enterUndoContext("Refresh bibliography"); boolean requireSeparation = false; - CitationGroups cgs = new CitationGroups(documentConnection); + // CitationGroups cgs = new CitationGroups(documentConnection); + OOFrontend fr = new OOFrontend(documentConnection); // Check Range overlaps int maxReportedOverlaps = 10; - checkRangeOverlaps(cgs, this.xDocumentConnection, requireSeparation, maxReportedOverlaps); + fr.checkRangeOverlaps(this.xDocumentConnection, + requireSeparation, + maxReportedOverlaps); final boolean useLockControllers = true; - ProduceCitationMarkersResult x = produceCitationMarkers(documentConnection, + fr.imposeGlobalOrder(documentConnection); + ProduceCitationMarkersResult x = produceCitationMarkers(fr.cgs, databases, style); try { @@ -2552,12 +2433,12 @@ public List updateDocumentActionHelper(List databases, documentConnection.lockControllers(); } applyNewCitationMarkers(documentConnection, - x.cgs, + fr, x.citMarkers, style); rebuildBibTextSection(documentConnection, style, - x.cgs, + fr, x.getBibliography()); return x.getUnresolvedKeys(); } finally { diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 75f96b0a9cc..6cd1a178a48 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -1,39 +1,17 @@ package org.jabref.logic.oostyle; -import java.util.ArrayList; import java.util.Comparator; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.TreeMap; -import java.util.stream.Collectors; -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.Backend52; -import org.jabref.logic.openoffice.Compat; -import org.jabref.logic.openoffice.CreationException; -import org.jabref.logic.openoffice.DocumentConnection; -import org.jabref.logic.openoffice.NoDocumentException; -import org.jabref.logic.openoffice.RangeForOverlapCheck; -import org.jabref.logic.openoffice.RangeKeyedMap; -import org.jabref.logic.openoffice.RangeKeyedMapList; -import org.jabref.logic.openoffice.RangeSort; -import org.jabref.logic.openoffice.RangeSortVisual; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import com.sun.star.beans.IllegalTypeException; -import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextRange; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,7 +24,7 @@ public class CitationGroups { private static final Logger LOGGER = LoggerFactory.getLogger(CitationGroups.class); - public final Backend52 backend; + private final Compat.DataModel dataModel; /** * Original CitationGroups Data @@ -74,22 +52,11 @@ public class CitationGroups { /** * Constructor */ - public CitationGroups(DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException { + public CitationGroups(Compat.DataModel dataModel, + Map citationGroups) { - // TODO: dataModel should come from looking at the - // document and preferences. - // - this.backend = new Backend52(); - - // Get the citationGroupNames - List citationGroupNames = this.backend.getJabRefReferenceMarkNames(documentConnection); - - this.citationGroups = readCitationGroupsFromDocument(this.backend, - documentConnection, - citationGroupNames); + this.dataModel = dataModel; + this.citationGroups = citationGroups; // Now we have almost every information from the document about citations. // What is left out: the ranges controlled by the reference marks. @@ -99,34 +66,6 @@ public CitationGroups(DocumentConnection documentConnection) this.bibliography = Optional.empty(); } - public Compat.DataModel getDataModel() { - return backend.dataModel; - } - - public Optional healthReport(DocumentConnection documentConnection) - throws - NoDocumentException { - return backend.healthReport(documentConnection); - } - - private static Map - readCitationGroupsFromDocument(Backend52 backend, - DocumentConnection documentConnection, - List citationGroupNames) - throws - WrappedTargetException, - NoDocumentException { - - Map citationGroups = new HashMap<>(); - for (int i = 0; i < citationGroupNames.size(); i++) { - final String name = citationGroupNames.get(i); - CitationGroup cg = - backend.readCitationGroupFromDocumentOrThrow(documentConnection, name); - citationGroups.put(cg.cgid, cg); - } - return citationGroups; - } - public void setDatabaseLookupResults(Set where, Optional db) { for (CitationPath p : where) { @@ -200,6 +139,10 @@ public CitedKeys getCitedKeys() { return new CitedKeys(res); } + public boolean hasGlobalOrder() { + return globalOrder.isPresent(); + } + /** * CitedKeys created iterating citations in (globalOrder,localOrder) */ @@ -275,188 +218,6 @@ public Set getCitationGroupIDs() { return citationGroups.keySet(); } - /** - * Creates a list of {@code - * RangeSortable} values for - * our {@code CitationGroup} values. Originally designed to be - * passed to {@code visualSort}. - * - * The elements of the returned list are actually of type {@code - * RangeSortEntry}. - * - * The result is sorted within {@code XTextRange.getText()} - * partitions of the citation groups according to their {@code - * XTextRange} (before mapping to footnote marks). - * - * In the result, RangeSortable.getIndexInPosition() contains - * unique indexes within the original partition (not after - * mapFootnotesToFootnoteMarks). - * - * @param cgs The source of CitationGroup values. - * @param documentConnection Connection to the document. - * @param mapFootnotesToFootnoteMarks If true, replace ranges in - * footnotes with the range of the corresponding footnote - * mark. This is used for numbering the citations. - * - */ - private static List> - createVisualSortInput(CitationGroups cgs, - DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - NoDocumentException, - WrappedTargetException { - - List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); - - List vses = new ArrayList<>(); - for (CitationGroupID cgid : cgids) { - XTextRange range = (cgs - .getMarkRange(documentConnection, cgid) - .orElseThrow(RuntimeException::new)); - vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); - } - - /* - * At this point we are almost ready to return vses. - * - * For example we may want to number citations in a footnote - * as if it appeared where the footnote mark is. - * - * The following code replaces ranges within footnotes with - * the range for the corresponding footnote mark. - * - * This brings further ambiguity if we have multiple - * citations within the same footnote: for the comparison - * they become indistinguishable. Numbering between them is - * not controlled. Also combineCiteMarkers will see them in - * the wrong order (if we use this comparison), and will not - * be able to merge. To avoid these, we sort textually within - * each .getText() partition and add indexInPosition - * accordingly. - * - */ - - // Sort within partitions - RangeKeyedMapList> xxs - = new RangeKeyedMapList<>(); - - for (RangeSort.RangeSortEntry v : vses) { - xxs.add(v.getRange(), v); - } - - // build final list - List> res = new ArrayList<>(); - - for (TreeMap>> - xs : xxs.partitionValues()) { - - List oxs = new ArrayList<>(xs.keySet()); - - int indexInPartition = 0; - for (int i = 0; i < oxs.size(); i++) { - XTextRange a = oxs.get(i); - List> avs = xs.get(a); - for (int j = 0; j < avs.size(); j++) { - RangeSort.RangeSortEntry v = avs.get(j); - v.indexInPosition = indexInPartition++; - if (mapFootnotesToFootnoteMarks) { - Optional fmr = DocumentConnection.getFootnoteMarkRange(v.getRange()); - // Adjust range if we are inside a footnote: - if (fmr.isPresent()) { - v.range = fmr.get(); - } - } - res.add(v); - } - } - } - // convert - // List> - // to - // List> - return res.stream().map(e -> e).collect(Collectors.toList()); - } - - /** - * Return JabRef reference mark names sorted by their visual positions. - * - * @param mapFootnotesToFootnoteMarks If true, sort reference - * marks in footnotes as if they appeared at the - * corresponding footnote mark. - * - * @return JabRef reference mark names sorted by these positions. - * - * Limitation: for two column layout visual (top-down, - * left-right) order does not match the expected (textual) - * order. - * - */ - public List getVisuallySortedCitationGroupIDs(DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - WrappedTargetException, - NoDocumentException, - JabRefException { - CitationGroups cgs = this; - List> vses = - createVisualSortInput(cgs, - documentConnection, - mapFootnotesToFootnoteMarks); - - if (vses.size() != cgs.citationGroups.size()) { - throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " vses.size() != cgs.citationGroups.size()"); - } - - String messageOnFailureToObtainAFunctionalXTextViewCursor = - Localization.lang("Please move the cursor into the document text.") - + "\n" - + Localization.lang("To get the visual positions of your citations" - + " I need to move the cursor around," - + " but could not get it."); - List> sorted = - RangeSortVisual.visualSort(vses, - documentConnection, - messageOnFailureToObtainAFunctionalXTextViewCursor); - - if (sorted.size() != cgs.citationGroups.size()) { - // This Fired - throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " sorted.size() != cgs.citationGroups.size()"); - } - - return (sorted.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList())); - } - - /** - * Calculate and return citation group IDs in visual order. - */ - public List - getCitationGroupIDsSortedWithinPartitions(DocumentConnection documentConnection, - boolean mapFootnotesToFootnoteMarks) - throws - NoDocumentException, - WrappedTargetException { - // This is like getVisuallySortedCitationGroupIDs, - // but we skip the visualSort part. - CitationGroups cgs = this; - List> vses = - CitationGroups.createVisualSortInput(cgs, - documentConnection, - mapFootnotesToFootnoteMarks); - - if (vses.size() != cgs.citationGroups.size()) { - throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" - + " vses.size() != cgs.citationGroups.size()"); - } - return (vses.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList())); - } - /** * Citation group IDs in {@code globalOrder} */ @@ -494,7 +255,7 @@ public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { } private Optional getReferenceMarkName(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.referenceMarkName); + return getCitationGroup(cgid).map(cg -> cg.getMarkName()); } private Optional getItcType(CitationGroupID cgid) { @@ -511,6 +272,15 @@ public Optional getPageInfo(CitationGroupID cgid) { .flatMap(x -> x)); } + public List getPageInfosForCitations(CitationGroup cg) { + return Backend52.getPageInfosForCitations(this.dataModel, cg); + } + + public List getPageInfosForCitations(CitationGroupID cgid) { + CitationGroup cg = getCitationGroupOrThrow(cgid); + return getPageInfosForCitations(cg); + } + public Optional> getCitations(CitationGroupID cgid) { return getCitationGroup(cgid).map(cg -> cg.citations); } @@ -523,129 +293,17 @@ public List getSortedCitations(CitationGroupID cgid) { return cg.get().getSortedCitations(); } - /** - * Create a citation group for the given citation keys, at the - * end of position. - * - * To reduce the difference from the original representation, we - * only insist on having at least two characters inside reference - * marks. These may be ZERO_WIDTH_SPACE characters or other - * placeholder not likely to appear in a citation mark. - * - * This placeholder is only needed if the citation mark is - * otherwise empty (e.g. when we just create it). - * - * getFillCursorForCitationGroup yields a bracketed cursor, that - * can be used to fill in / overwrite the value inside. - * - * After each getFillCursorForCitationGroup, we require a call to - * cleanFillCursorForCitationGroup, which removes the brackets, - * unless if it would make the content less than two - * characters. If we need only one placeholder, we keep the left - * bracket. If we need two, then the content is empty. The - * removeBracketsFromEmpty parameter of - * cleanFillCursorForCitationGroup overrides this, and for empty - * citations it will remove the brackets, leaving an empty - * reference mark. The idea behind this is that we do not need to - * refill empty marks (itcTypes INVISIBLE_CIT), and the caller - * can tell us that we are dealing with one of these. - * - * Thus the only user-visible difference in citation marks is - * that instead of empty marks we use two brackets, for - * single-character marks we add a left bracket before. - * - * Character-attribute inheritance: updates inherit from the - * first character inside, not from the left. - * - * On return {@code position} is collapsed, and is after the - * inserted space, or at the end of the reference mark. - * - * @param documentConnection Connection to document. - * @param citationKeys - * @param pageInfosForCitations - * @param itcType - * @param position Collapsed to its end. - * @param insertSpaceAfter If true, we insert a space after the mark, that - * carries on format of characters from - * the original position. - * - * @param withoutBrackets Force empty reference mark (no brackets). - * For use with INVISIBLE_CIT. - * - */ - public CitationGroupID createCitationGroup(DocumentConnection documentConnection, - List citationKeys, - List pageInfosForCitations, - int itcType, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) - throws - CreationException, - NoDocumentException, - WrappedTargetException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException { - - CitationGroup cg = backend.createCitationGroup(documentConnection, - citationKeys, - pageInfosForCitations, - itcType, - position, - insertSpaceAfter, - withoutBrackets); + public void afterCreateCitationGroup(CitationGroup cg) { // add to our data this.citationGroups.put(cg.cgid, cg); // invalidate globalOrder. // TODO: look out for localOrder! this.globalOrder = Optional.empty(); - - return cg.cgid; } - public void removeCitationGroups(List cgs, DocumentConnection documentConnection) - throws - WrappedTargetException, - NoDocumentException, - NoSuchElementException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException { - - for (CitationGroup cg : cgs) { - removeCitationGroup(cg, documentConnection); - } - } + public void afterRemoveCitationGroup(CitationGroup cg) { - /** - * Remove {@code cg} both from {@code this} and the document. - * - * Note: we invalidate the extra data we are storing - * (bibliography). - * - * Update would be complicated, since we do not know how the - * bibliography was generated: it was partially done outside - * CitationGroups, and we did not store how. - * - * So we stay with invalidating. - * Note: localOrder, numbering, uniqueLetters are not adjusted, - * it is easier to reread everything for a refresh. - * - */ - public void removeCitationGroup(CitationGroup cg, - DocumentConnection documentConnection) - throws - WrappedTargetException, - NoDocumentException, - NoSuchElementException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException { - - // Apply - backend.removeCitationGroup(cg, documentConnection); this.citationGroups.remove(cg.cgid); // Update what we can. @@ -655,142 +313,6 @@ public void removeCitationGroup(CitationGroup cg, // Could also: reset citation.number, citation.uniqueLetter. } - /** - * ranges controlled by citation groups should not overlap with each other. - * - * @param cgid : Must be known, throws if not. - * @return Null if the reference mark is missing. - * - */ - public Optional getMarkRange(DocumentConnection documentConnection, - CitationGroupID cgid) - throws - NoDocumentException, - WrappedTargetException { - - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return backend.getMarkRange(cg, documentConnection); - } - - /** - * Cursor for the reference marks as is, not prepared for filling, - * but does not need cleanFillCursorForCitationGroup either. - */ - public Optional getRawCursorForCitationGroup(CitationGroupID cgid, - DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - Optional cg = this.getCitationGroup(cgid); - if (cg.isEmpty()) { - return Optional.empty(); - } - return backend.getRawCursorForCitationGroup(cg.get(), documentConnection); - } - - public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, - CitationGroupID cgid) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return backend.getFillCursorForCitationGroup(cg, documentConnection); - } - - /** - * Remove brackets, but if the result would become empty, leave - * them; if the result would be a single characer, leave the left bracket. - */ - public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, - CitationGroupID cgid) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - backend.cleanFillCursorForCitationGroup(cg, documentConnection); - } - - /** - * @return A RangeForOverlapCheck for each citation group. - * - * result.size() == nRefMarks - */ - public List citationRanges(DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException { - - List xs = new ArrayList<>(numberOfCitationGroups()); - - List cgids = new ArrayList<>(this.getCitationGroupIDs()); - - for (CitationGroupID cgid : cgids) { - XTextRange r = this.getMarkRange(documentConnection, cgid).orElseThrow(RuntimeException::new); - CitationGroup cg = this.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - String name = cg.cgRangeStorage.getName(); - xs.add(new RangeForOverlapCheck(r, - cgid, - RangeForOverlapCheck.REFERENCE_MARK_KIND, - name)); - } - return xs; - } - - /** - * @return A range for each footnote mark where the footnote - * contains at least one citation group. - * - * Purpose: We do not want markers of footnotes containing - * reference marks to overlap with reference - * marks. Overwriting these footnote marks might kill our - * reference marks in the footnote. - * - * Note: Here we directly communicate to the document, not - * through the backend. This is because mapping ranges to - * footnote marks does not depend on how do we mark or - * structure those ranges. - */ - public List footnoteMarkRanges(DocumentConnection documentConnection) - throws - NoDocumentException, - WrappedTargetException { - - // Avoid inserting the same mark twice. - // Could use RangeSet if we had that. - RangeKeyedMap seen = new RangeKeyedMap<>(); - - List xs = new ArrayList<>(); - - List citRanges = citationRanges(documentConnection); - - for (RangeForOverlapCheck base : citRanges) { - XTextRange r = base.range; - - Optional footnoteMarkRange = DocumentConnection.getFootnoteMarkRange(r); - - if (footnoteMarkRange.isEmpty()) { - // not in footnote - continue; - } - - boolean seenContains = seen.containsKey(footnoteMarkRange.get()); - if (!seenContains) { - seen.put(footnoteMarkRange.get(), true); - xs.add(new RangeForOverlapCheck(footnoteMarkRange.get(), - base.i, // cgid :: identifies of citation group - RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + base.format())); - } - } - return xs; - } - /** * This is for debugging, can be removed. */ diff --git a/src/main/java/org/jabref/logic/openoffice/Compat.java b/src/main/java/org/jabref/logic/oostyle/Compat.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/Compat.java rename to src/main/java/org/jabref/logic/oostyle/Compat.java index b3d2ea17b86..bd8fa27bf7f 100644 --- a/src/main/java/org/jabref/logic/openoffice/Compat.java +++ b/src/main/java/org/jabref/logic/oostyle/Compat.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.oostyle; public class Compat { diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index cdf877b1546..31c9f9dc418 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -12,6 +12,7 @@ import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; +import org.jabref.logic.oostyle.Compat; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -286,7 +287,7 @@ public static List fakePageInfosForCitations(String pageInfo, * * TODO: we may want class DataModel52, DataModel53 and split this. */ - static List getPageInfosForCitations(Compat.DataModel dataModel, CitationGroup cg) { + public static List getPageInfosForCitations(Compat.DataModel dataModel, CitationGroup cg) { switch (dataModel) { case JabRef52: // check conformance to dataModel @@ -369,7 +370,7 @@ public List combinePageInfos(List joinableGroup) { * */ public List getPageInfosForCitations(CitationGroup cg) { - return getPageInfosForCitations(this.dataModel, cg); + return Backend52.getPageInfosForCitations(this.dataModel, cg); } public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) @@ -436,8 +437,8 @@ public void cleanFillCursorForCitationGroup(CitationGroup cg, cg.cgRangeStorage.cleanFillCursor(documentConnection); } - public static List getCitationEntries(DocumentConnection documentConnection, - CitationGroups cgs) + public List getCitationEntries(DocumentConnection documentConnection, + CitationGroups cgs) throws UnknownPropertyException, WrappedTargetException, @@ -449,9 +450,10 @@ public static List getCitationEntries(DocumentConnection document int n = cgs.numberOfCitationGroups(); List citations = new ArrayList<>(n); for (CitationGroupID cgid : cgs.getCitationGroupIDs()) { + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); String name = cgid.asString(); - XTextCursor cursor = (cgs - .getRawCursorForCitationGroup(cgid, documentConnection) + XTextCursor cursor = (this + .getRawCursorForCitationGroup(cg, documentConnection) .orElseThrow(RuntimeException::new)); String context = OOUtil.getCursorStringWithContext(documentConnection, cursor, 30, 30, true); @@ -463,5 +465,30 @@ public static List getCitationEntries(DocumentConnection document return citations; } + public void applyCitationEntries(DocumentConnection documentConnection, + List citationEntries) + throws + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException, + NoDocumentException { + switch (dataModel) { + case JabRef52: + for (CitationEntry entry : citationEntries) { + Optional pageInfo = entry.getPageInfo(); + if (pageInfo.isPresent()) { + documentConnection.setCustomProperty(entry.getRefMarkName(), + pageInfo.get()); + } + } + break; + case JabRef53: + //xx + throw new RuntimeException("applyCitationEntries for JabRef53 is not implemented yet"); + } + } + } // end Backend52 diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java new file mode 100644 index 00000000000..dfabbd407f6 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -0,0 +1,632 @@ +package org.jabref.logic.openoffice; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.TreeMap; +import java.util.stream.Collectors; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.logic.oostyle.CitationEntry; +import org.jabref.logic.oostyle.CitationGroup; +import org.jabref.logic.oostyle.CitationGroupID; +import org.jabref.logic.oostyle.CitationGroups; +import org.jabref.logic.oostyle.Compat; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextRange; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class OOFrontend { + private static final Logger LOGGER = LoggerFactory.getLogger(OOFrontend.class); + public final Backend52 backend; + public final CitationGroups cgs; + + public OOFrontend(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + // TODO: dataModel should come from looking at the + // document and preferences. + // + this.backend = new Backend52(); + + // Get the citationGroupNames + List citationGroupNames = this.backend.getJabRefReferenceMarkNames(documentConnection); + + Map citationGroups = + readCitationGroupsFromDocument(this.backend, + documentConnection, + citationGroupNames); + this.cgs = new CitationGroups(backend.dataModel, citationGroups); + } + + public Compat.DataModel getDataModel() { + return backend.dataModel; + } + + public Optional healthReport(DocumentConnection documentConnection) + throws + NoDocumentException { + return backend.healthReport(documentConnection); + } + + private static Map + readCitationGroupsFromDocument(Backend52 backend, + DocumentConnection documentConnection, + List citationGroupNames) + throws + WrappedTargetException, + NoDocumentException { + + Map citationGroups = new HashMap<>(); + for (int i = 0; i < citationGroupNames.size(); i++) { + final String name = citationGroupNames.get(i); + CitationGroup cg = + backend.readCitationGroupFromDocumentOrThrow(documentConnection, name); + citationGroups.put(cg.cgid, cg); + } + return citationGroups; + } + + /** + * Creates a list of {@code RangeSortable} values for + * our {@code CitationGroup} values. Originally designed to be + * passed to {@code visualSort}. + * + * The elements of the returned list are actually of type {@code RangeSortEntry}. + * + * The result is sorted within {@code XTextRange.getText()} + * partitions of the citation groups according to their {@code XTextRange} + * (before mapping to footnote marks). + * + * In the result, RangeSortable.getIndexInPosition() contains + * unique indexes within the original partition (not after + * mapFootnotesToFootnoteMarks). + * + * @param documentConnection Connection to the document. + * @param mapFootnotesToFootnoteMarks If true, replace ranges in + * footnotes with the range of the corresponding footnote + * mark. This is used for numbering the citations. + * + */ + private List> + createVisualSortInput(DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + NoDocumentException, + WrappedTargetException { + + List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); + + List vses = new ArrayList<>(); + for (CitationGroupID cgid : cgids) { + XTextRange range = (this + .getMarkRange(documentConnection, cgid) + .orElseThrow(RuntimeException::new)); + vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); + } + + /* + * At this point we are almost ready to return vses. + * + * For example we may want to number citations in a footnote + * as if it appeared where the footnote mark is. + * + * The following code replaces ranges within footnotes with + * the range for the corresponding footnote mark. + * + * This brings further ambiguity if we have multiple + * citations within the same footnote: for the comparison + * they become indistinguishable. Numbering between them is + * not controlled. Also combineCiteMarkers will see them in + * the wrong order (if we use this comparison), and will not + * be able to merge. To avoid these, we sort textually within + * each .getText() partition and add indexInPosition + * accordingly. + * + */ + + // Sort within partitions + RangeKeyedMapList> xxs + = new RangeKeyedMapList<>(); + + for (RangeSort.RangeSortEntry v : vses) { + xxs.add(v.getRange(), v); + } + + // build final list + List> res = new ArrayList<>(); + + for (TreeMap>> + xs : xxs.partitionValues()) { + + List oxs = new ArrayList<>(xs.keySet()); + + int indexInPartition = 0; + for (int i = 0; i < oxs.size(); i++) { + XTextRange a = oxs.get(i); + List> avs = xs.get(a); + for (int j = 0; j < avs.size(); j++) { + RangeSort.RangeSortEntry v = avs.get(j); + v.indexInPosition = indexInPartition++; + if (mapFootnotesToFootnoteMarks) { + Optional fmr = DocumentConnection.getFootnoteMarkRange(v.getRange()); + // Adjust range if we are inside a footnote: + if (fmr.isPresent()) { + v.range = fmr.get(); + } + } + res.add(v); + } + } + } + // convert + // List> + // to + // List> + return res.stream().map(e -> e).collect(Collectors.toList()); + } + + /** + * Return JabRef reference mark names sorted by their visual positions. + * + * @param mapFootnotesToFootnoteMarks If true, sort reference + * marks in footnotes as if they appeared at the + * corresponding footnote mark. + * + * @return JabRef reference mark names sorted by these positions. + * + * Limitation: for two column layout visual (top-down, + * left-right) order does not match the expected (textual) + * order. + * + */ + private List getVisuallySortedCitationGroupIDs(DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + WrappedTargetException, + NoDocumentException, + JabRefException { + + List> vses = + createVisualSortInput(documentConnection, + mapFootnotesToFootnoteMarks); + + if (vses.size() != this.cgs.numberOfCitationGroups()) { + throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + + " vses.size() != cgs.citationGroups.size()"); + } + + String messageOnFailureToObtainAFunctionalXTextViewCursor = + Localization.lang("Please move the cursor into the document text.") + + "\n" + + Localization.lang("To get the visual positions of your citations" + + " I need to move the cursor around," + + " but could not get it."); + List> sorted = + RangeSortVisual.visualSort(vses, + documentConnection, + messageOnFailureToObtainAFunctionalXTextViewCursor); + + if (sorted.size() != this.cgs.numberOfCitationGroups()) { + // This Fired + throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + + " sorted.size() != cgs.numberOfCitationGroups()"); + } + + return (sorted.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList())); + } + + /** + * Calculate and return citation group IDs in visual order. + */ + public List + getCitationGroupIDsSortedWithinPartitions(DocumentConnection documentConnection, + boolean mapFootnotesToFootnoteMarks) + throws + NoDocumentException, + WrappedTargetException { + // This is like getVisuallySortedCitationGroupIDs, + // but we skip the visualSort part. + List> vses = + createVisualSortInput(documentConnection, + mapFootnotesToFootnoteMarks); + + if (vses.size() != this.cgs.numberOfCitationGroups()) { + throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" + + " vses.size() != cgs.numberOfCitationGroups()"); + } + return (vses.stream() + .map(e -> e.getContent()) + .collect(Collectors.toList())); + } + + /** + * Create a citation group for the given citation keys, at the + * end of position. + * + * To reduce the difference from the original representation, we + * only insist on having at least two characters inside reference + * marks. These may be ZERO_WIDTH_SPACE characters or other + * placeholder not likely to appear in a citation mark. + * + * This placeholder is only needed if the citation mark is + * otherwise empty (e.g. when we just create it). + * + * getFillCursorForCitationGroup yields a bracketed cursor, that + * can be used to fill in / overwrite the value inside. + * + * After each getFillCursorForCitationGroup, we require a call to + * cleanFillCursorForCitationGroup, which removes the brackets, + * unless if it would make the content less than two + * characters. If we need only one placeholder, we keep the left + * bracket. If we need two, then the content is empty. The + * removeBracketsFromEmpty parameter of + * cleanFillCursorForCitationGroup overrides this, and for empty + * citations it will remove the brackets, leaving an empty + * reference mark. The idea behind this is that we do not need to + * refill empty marks (itcTypes INVISIBLE_CIT), and the caller + * can tell us that we are dealing with one of these. + * + * Thus the only user-visible difference in citation marks is + * that instead of empty marks we use two brackets, for + * single-character marks we add a left bracket before. + * + * Character-attribute inheritance: updates inherit from the + * first character inside, not from the left. + * + * On return {@code position} is collapsed, and is after the + * inserted space, or at the end of the reference mark. + * + * @param documentConnection Connection to document. + * @param citationKeys + * @param pageInfosForCitations + * @param itcType + * @param position Collapsed to its end. + * @param insertSpaceAfter If true, we insert a space after the mark, that + * carries on format of characters from + * the original position. + * + * @param withoutBrackets Force empty reference mark (no brackets). + * For use with INVISIBLE_CIT. + * + */ + public CitationGroupID createCitationGroup(DocumentConnection documentConnection, + List citationKeys, + List pageInfosForCitations, + int itcType, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) + throws + CreationException, + NoDocumentException, + WrappedTargetException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException { + + CitationGroup cg = backend.createCitationGroup(documentConnection, + citationKeys, + pageInfosForCitations, + itcType, + position, + insertSpaceAfter, + withoutBrackets); + + this.cgs.afterCreateCitationGroup(cg); + return cg.cgid; + } + + /** + * Remove {@code cg} both from {@code cgs} and the document. + * + * Note: we invalidate the extra data we are storing + * (bibliography). + * + * Update would be complicated, since we do not know how the + * bibliography was generated: it was partially done outside + * CitationGroups, and we did not store how. + * + * So we stay with invalidating. + * Note: localOrder, numbering, uniqueLetters are not adjusted, + * it is easier to reread everything for a refresh. + * + */ + public void removeCitationGroup(CitationGroup cg, + DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException { + + // Apply + backend.removeCitationGroup(cg, documentConnection); + this.cgs.afterRemoveCitationGroup(cg); + } + + public void removeCitationGroups(List xcgs, DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException { + + for (CitationGroup cg : xcgs) { + removeCitationGroup(cg, documentConnection); + } + } + + /** + * ranges controlled by citation groups should not overlap with each other. + * + * @param cgid : Must be known, throws if not. + * @return Null if the reference mark is missing. + * + */ + public Optional getMarkRange(DocumentConnection documentConnection, + CitationGroupID cgid) + throws + NoDocumentException, + WrappedTargetException { + + CitationGroup cg = this.cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + return backend.getMarkRange(cg, documentConnection); + } + + /** + * Cursor for the reference marks as is, not prepared for filling, + * but does not need cleanFillCursorForCitationGroup either. + */ + public Optional getRawCursorForCitationGroup(CitationGroupID cgid, + DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + Optional cg = this.cgs.getCitationGroup(cgid); + if (cg.isEmpty()) { + return Optional.empty(); + } + return backend.getRawCursorForCitationGroup(cg.get(), documentConnection); + } + + public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, + CitationGroupID cgid) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + CitationGroup cg = this.cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + return backend.getFillCursorForCitationGroup(cg, documentConnection); + } + + /** + * Remove brackets, but if the result would become empty, leave + * them; if the result would be a single characer, leave the left bracket. + */ + public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, + CitationGroupID cgid) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + + CitationGroup cg = this.cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + backend.cleanFillCursorForCitationGroup(cg, documentConnection); + } + + /** + * @return A RangeForOverlapCheck for each citation group. + * + * result.size() == nRefMarks + */ + public List citationRanges(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + List xs = new ArrayList<>(cgs.numberOfCitationGroups()); + + List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); + + for (CitationGroupID cgid : cgids) { + XTextRange r = this.getMarkRange(documentConnection, cgid).orElseThrow(RuntimeException::new); + CitationGroup cg = cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + String name = cg.cgRangeStorage.getName(); + xs.add(new RangeForOverlapCheck(r, + cgid, + RangeForOverlapCheck.REFERENCE_MARK_KIND, + name)); + } + return xs; + } + + /** + * @return A range for each footnote mark where the footnote + * contains at least one citation group. + * + * Purpose: We do not want markers of footnotes containing + * reference marks to overlap with reference + * marks. Overwriting these footnote marks might kill our + * reference marks in the footnote. + * + * Note: Here we directly communicate to the document, not + * through the backend. This is because mapping ranges to + * footnote marks does not depend on how do we mark or + * structure those ranges. + */ + public List footnoteMarkRanges(DocumentConnection documentConnection) + throws + NoDocumentException, + WrappedTargetException { + + // Avoid inserting the same mark twice. + // Could use RangeSet if we had that. + RangeKeyedMap seen = new RangeKeyedMap<>(); + + List xs = new ArrayList<>(); + + List citRanges = citationRanges(documentConnection); + + for (RangeForOverlapCheck base : citRanges) { + XTextRange r = base.range; + + Optional footnoteMarkRange = DocumentConnection.getFootnoteMarkRange(r); + + if (footnoteMarkRange.isEmpty()) { + // not in footnote + continue; + } + + boolean seenContains = seen.containsKey(footnoteMarkRange.get()); + if (!seenContains) { + seen.put(footnoteMarkRange.get(), true); + xs.add(new RangeForOverlapCheck(footnoteMarkRange.get(), + base.i, // cgid :: identifies of citation group + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + base.format())); + } + } + return xs; + } + + /** + * @param requireSeparation Report range pairs that only share a boundary. + * @param reportAtMost Limit number of overlaps reported (0 for no limit) + * + */ + public void checkRangeOverlaps(DocumentConnection documentConnection, + boolean requireSeparation, + int reportAtMost) + throws + NoDocumentException, + WrappedTargetException, + JabRefException { + + final boolean debugPartitions = false; + + List xs = citationRanges(documentConnection); + xs.addAll(footnoteMarkRanges(documentConnection)); + + RangeKeyedMapList xall = new RangeKeyedMapList<>(); + for (RangeForOverlapCheck x : xs) { + XTextRange key = x.range; + xall.add(key, x); + } + + List.RangeOverlap> ovs = + xall.findOverlappingRanges(reportAtMost, requireSeparation); + + // checkSortedPartitionForOverlap(requireSeparation, oxs); + if (ovs.size() > 0) { + String msg = ""; + for (RangeKeyedMapList.RangeOverlap e : ovs) { + String l = (": " + + (e.vs.stream() + .map(v -> String.format("'%s'", v.format())) + .collect(Collectors.joining(", "))) + + "\n"); + + switch (e.kind) { + case EQUAL_RANGE: msg = msg + Localization.lang("Found identical ranges") + l; + break; + case OVERLAP: msg = msg + Localization.lang("Found overlapping ranges") + l; + break; + case TOUCH: msg = msg + Localization.lang("Found touching ranges") + l; + break; + } + } + throw new JabRefException("Found overlapping or touching ranges", msg); + } + } + + /** + * GUI: Get a list of CitationEntry objects corresponding to citations + * in the document. + * + * Called from: ManageCitationsDialogViewModel constructor. + * + * @return A list with entries corresponding to citations in the + * text, in arbitrary order (same order as from + * getJabRefReferenceMarkNames). + * + * Note: visual or alphabetic order could be more + * manageable for the user. We could provide these + * here, but switching between them needs change on + * GUI (adding a toggle or selector). + * + * Note: CitationEntry implements Comparable, where + * compareTo() and equals() are based on refMarkName. + * The order used in the "Manage citations" dialog + * does not seem to use that. + * + * The 1st is labeled "Citation" (show citation in bold, + * and some context around it). + * + * The columns can be sorted by clicking on the column title. + * For the "Citation" column, the sorting is based on the content, + * (the context before the citation), not on the citation itself. + * + * In the "Extra information ..." column some visual indication + * of the editable part could be helpful. + * + * Wish: selecting an entry (or a button in the line) in + * the GUI could move the cursor in the document to + * the entry. + */ + public List getCitationEntries(DocumentConnection documentConnection) + throws + UnknownPropertyException, + WrappedTargetException, + NoDocumentException, + CreationException { + return this.backend.getCitationEntries(documentConnection, cgs); + } + + public void applyCitationEntries(DocumentConnection documentConnection, + List citationEntries) + throws + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException, + NoDocumentException { + this.backend.applyCitationEntries(documentConnection, citationEntries); + } + + public void imposeGlobalOrder(DocumentConnection documentConnection) + throws + WrappedTargetException, + NoDocumentException, + JabRefException { + + boolean mapFootnotesToFootnoteMarks = true; + List sortedCitationGroupIDs = + getVisuallySortedCitationGroupIDs(documentConnection, + mapFootnotesToFootnoteMarks); + cgs.setGlobalOrder(sortedCitationGroupIDs); + } +} From 8b766372a274aa7143ca05795db4004ecbcc80a5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 26 Apr 2021 11:52:18 +0200 Subject: [PATCH 0637/1068] pageInfo dependence on DataModel moved to Compat --- .../org/jabref/gui/openoffice/OOBibBase.java | 4 +- .../jabref/logic/oostyle/CitationGroups.java | 3 +- .../java/org/jabref/logic/oostyle/Compat.java | 119 ++++++++++++ .../jabref/logic/openoffice/Backend52.java | 171 +++--------------- 4 files changed, 151 insertions(+), 146 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a1a3c5ddde9..183478b6f83 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -33,9 +33,9 @@ import org.jabref.logic.oostyle.CitationPath; import org.jabref.logic.oostyle.CitedKey; import org.jabref.logic.oostyle.CitedKeys; +import org.jabref.logic.oostyle.Compat; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOPreFormatter; -import org.jabref.logic.openoffice.Backend52; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.DocumentConnection; import org.jabref.logic.openoffice.NoDocumentException; @@ -1122,7 +1122,7 @@ public void insertEntry(List entries, assertCitationCharacterFormatIsOK(cursor, style); // JabRef53 style pageInfo list - List pageInfosForCitations = Backend52.fakePageInfosForCitations(pageInfo, nEntries); + List pageInfosForCitations = Compat.fakePageInfosForCitations(pageInfo, nEntries); List citationMarkerEntries = new ArrayList<>(entries.size()); for (int i = 0; i < nEntries; i++) { diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 6cd1a178a48..851fae008b6 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -8,7 +8,6 @@ import java.util.Optional; import java.util.Set; -import org.jabref.logic.openoffice.Backend52; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; @@ -273,7 +272,7 @@ public Optional getPageInfo(CitationGroupID cgid) { } public List getPageInfosForCitations(CitationGroup cg) { - return Backend52.getPageInfosForCitations(this.dataModel, cg); + return Compat.getPageInfosForCitations(this.dataModel, cg); } public List getPageInfosForCitations(CitationGroupID cgid) { diff --git a/src/main/java/org/jabref/logic/oostyle/Compat.java b/src/main/java/org/jabref/logic/oostyle/Compat.java index bd8fa27bf7f..6a507ec829d 100644 --- a/src/main/java/org/jabref/logic/oostyle/Compat.java +++ b/src/main/java/org/jabref/logic/oostyle/Compat.java @@ -1,5 +1,10 @@ package org.jabref.logic.oostyle; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + public class Compat { /** What is the data stored? */ @@ -31,4 +36,118 @@ public enum DataModel { */ JabRef53 } + + /** + * Return the last pageInfo from the list, if there is one. + */ + public static Optional getJabRef52PageInfoFromList(List pageInfosForCitations) { + if (pageInfosForCitations == null) { + return Optional.empty(); + } + int n = pageInfosForCitations.size(); + if (n == 0) { + return Optional.empty(); + } + return Optional.ofNullable(pageInfosForCitations.get(n - 1)); + } + + /** + * @param pageInfo Nullable. + * @return JabRef53 style pageInfo list + */ + public static List fakePageInfosForCitations(String pageInfo, + int nCitations) { + List pageInfosForCitations = new ArrayList<>(nCitations); + for (int i = 0; i < nCitations; i++) { + if (i == nCitations - 1) { + pageInfosForCitations.add(pageInfo); + } else { + pageInfosForCitations.add(null); + } + } + return pageInfosForCitations; + } + + /** + * @return List of nullable pageInfo values, one for each citation. + * Result contains null for missing pageInfo values. + * The list itself is not null. + * + * For Compat.DataModel.JabRef52 the last citation gets + * the CitationGroup.pageInfo + * + * The result is passed to OOBibStyle.getCitationMarker or + * OOBibStyle.getNumCitationMarker + * + * TODO: we may want class DataModel52, DataModel53 and split this. + */ + public static List getPageInfosForCitations(Compat.DataModel dataModel, CitationGroup cg) { + switch (dataModel) { + case JabRef52: + // check conformance to dataModel + for (int i = 0; i < cg.citations.size(); i++) { + if (cg.citations.get(i).pageInfo.isPresent()) { + throw new RuntimeException("getPageInfosForCitations:" + + " found Citation.pageInfo under JabRef52 dataModel"); + } + } + // A list of null values, except the last that comes from this.pageInfo + return Compat.fakePageInfosForCitations(cg.pageInfo.orElse(null), + cg.citations.size()); + case JabRef53: + // check conformance to dataModel + if (cg.pageInfo.isPresent()) { + throw new RuntimeException("getPageInfosForCitations:" + + " found CitationGroup.pageInfo under JabRef53 dataModel"); + } + // pageInfo values from citations, empty mapped to null. + return (cg.citations.stream() + .map(cit -> cit.pageInfo.orElse(null)) + .collect(Collectors.toList())); + + default: + throw new RuntimeException("getPageInfosForCitations:" + + "unhandled dataModel"); + } + } + + /** + * @return A list with one nullable pageInfo entry for each citation in + * joinableGroups. + * + * TODO: JabRef52 combinePageInfos is not reversible. Should warn + * user to check the result. Or ask what to do. + */ + public static List combinePageInfos(Compat.DataModel dataModel, + List joinableGroup) { + switch (dataModel) { + case JabRef52: + // collect to cgPageInfos + List> cgPageInfos = (joinableGroup.stream() + .map(cg -> cg.pageInfo) + .collect(Collectors.toList())); + + // Try to do something of the cgPageInfos. + String cgPageInfo = (cgPageInfos.stream() + .filter(pi -> pi.isPresent()) + .map(pi -> pi.get()) + .distinct() + .collect(Collectors.joining("; "))); + + int nCitations = (joinableGroup.stream() + .map(cg -> cg.citations.size()) + .mapToInt(Integer::intValue).sum()); + + return Compat.fakePageInfosForCitations(cgPageInfo, nCitations); + + case JabRef53: + return (joinableGroup.stream() + .flatMap(cg -> (cg.citations.stream() + .map(cit -> cit.pageInfo.orElse(null)))) + .collect(Collectors.toList())); + default: + throw new RuntimeException("unhandled dataModel here"); + } + } + } diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 31c9f9dc418..1cc220662d3 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -224,7 +224,7 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, switch (dataModel) { case JabRef52: - Optional pageInfo = getJabRef52PageInfoFromList(pageInfosForCitations); + Optional pageInfo = Compat.getJabRef52PageInfoFromList(pageInfosForCitations); if (pageInfo.isPresent() && !pageInfo.get().equals("")) { documentConnection.setCustomProperty(refMarkName, pageInfo.get()); } else { @@ -243,134 +243,11 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, } } - /** - * Return the last pageInfo from the list, if there is one. - */ - Optional getJabRef52PageInfoFromList(List pageInfosForCitations) { - if (pageInfosForCitations == null) { - return Optional.empty(); - } - int n = pageInfosForCitations.size(); - if (n == 0) { - return Optional.empty(); - } - return Optional.ofNullable(pageInfosForCitations.get(n - 1)); - } - - /** - * @param pageInfo Nullable. - * @return JabRef53 style pageInfo list - */ - public static List fakePageInfosForCitations(String pageInfo, - int nCitations) { - List pageInfosForCitations = new ArrayList<>(nCitations); - for (int i = 0; i < nCitations; i++) { - if (i == nCitations - 1) { - pageInfosForCitations.add(pageInfo); - } else { - pageInfosForCitations.add(null); - } - } - return pageInfosForCitations; - } - - /** - * @return List of nullable pageInfo values, one for each citation. - * Result contains null for missing pageInfo values. - * The list itself is not null. - * - * For Compat.DataModel.JabRef52 the last citation gets - * the CitationGroup.pageInfo - * - * The result is passed to OOBibStyle.getCitationMarker or - * OOBibStyle.getNumCitationMarker - * - * TODO: we may want class DataModel52, DataModel53 and split this. - */ - public static List getPageInfosForCitations(Compat.DataModel dataModel, CitationGroup cg) { - switch (dataModel) { - case JabRef52: - // check conformance to dataModel - for (int i = 0; i < cg.citations.size(); i++) { - if (cg.citations.get(i).pageInfo.isPresent()) { - throw new RuntimeException("getPageInfosForCitations:" - + " found Citation.pageInfo under JabRef52 dataModel"); - } - } - // A list of null values, except the last that comes from this.pageInfo - return Backend52.fakePageInfosForCitations(cg.pageInfo.orElse(null), - cg.citations.size()); - case JabRef53: - // check conformance to dataModel - if (cg.pageInfo.isPresent()) { - throw new RuntimeException("getPageInfosForCitations:" - + " found CitationGroup.pageInfo under JabRef53 dataModel"); - } - // pageInfo values from citations, empty mapped to null. - return (cg.citations.stream() - .map(cit -> cit.pageInfo.orElse(null)) - .collect(Collectors.toList())); - - default: - throw new RuntimeException("getPageInfosForCitations:" - + "unhandled dataModel"); - } - } - - /** - * @return A list with one nullable pageInfo entry for each citation in - * joinableGroups. - * - * TODO: JabRef52 combinePageInfos is not reversible. Should warn - * user to check the result. Or ask what to do. - */ - static List combinePageInfos(Compat.DataModel dataModel, - List joinableGroup) { - switch (dataModel) { - case JabRef52: - // collect to cgPageInfos - List> cgPageInfos = (joinableGroup.stream() - .map(cg -> cg.pageInfo) - .collect(Collectors.toList())); - - // Try to do something of the cgPageInfos. - String cgPageInfo = (cgPageInfos.stream() - .filter(pi -> pi.isPresent()) - .map(pi -> pi.get()) - .distinct() - .collect(Collectors.joining("; "))); - - int nCitations = (joinableGroup.stream() - .map(cg -> cg.citations.size()) - .mapToInt(Integer::intValue).sum()); - - return Backend52.fakePageInfosForCitations(cgPageInfo, nCitations); - - case JabRef53: - return (joinableGroup.stream() - .flatMap(cg -> (cg.citations.stream() - .map(cit -> cit.pageInfo.orElse(null)))) - .collect(Collectors.toList())); - default: - throw new RuntimeException("unhandled dataModel here"); - } - } - /** * */ public List combinePageInfos(List joinableGroup) { - return combinePageInfos(this.dataModel, joinableGroup); - } - - /* - * @return A list of nullable pageInfo values, one for each citation. - * Result contains null for missing pageInfo values. - * The list itself is not null. - * - */ - public List getPageInfosForCitations(CitationGroup cg) { - return Backend52.getPageInfosForCitations(this.dataModel, cg); + return Compat.combinePageInfos(this.dataModel, joinableGroup); } public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) @@ -445,24 +322,32 @@ public List getCitationEntries(DocumentConnection documentConnect NoDocumentException, CreationException { - // One context per CitationGroup: Backend52 (DataModel.JabRef52) - // For DataModel.JabRef53 (Backend53) we need one context per Citation - int n = cgs.numberOfCitationGroups(); - List citations = new ArrayList<>(n); - for (CitationGroupID cgid : cgs.getCitationGroupIDs()) { - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - String name = cgid.asString(); - XTextCursor cursor = (this - .getRawCursorForCitationGroup(cg, documentConnection) - .orElseThrow(RuntimeException::new)); - String context = OOUtil.getCursorStringWithContext(documentConnection, - cursor, 30, 30, true); - CitationEntry entry = new CitationEntry(name, - context, - cgs.getPageInfo(cgid)); - citations.add(entry); + switch (dataModel) { + case JabRef52: + // One context per CitationGroup: Backend52 (DataModel.JabRef52) + // For DataModel.JabRef53 (Backend53) we need one context per Citation + int n = cgs.numberOfCitationGroups(); + List citations = new ArrayList<>(n); + for (CitationGroupID cgid : cgs.getCitationGroupIDs()) { + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + String name = cgid.asString(); + XTextCursor cursor = (this + .getRawCursorForCitationGroup(cg, documentConnection) + .orElseThrow(RuntimeException::new)); + String context = OOUtil.getCursorStringWithContext(documentConnection, + cursor, 30, 30, true); + CitationEntry entry = new CitationEntry(name, + context, + cgs.getPageInfo(cgid)); + citations.add(entry); + } + return citations; + case JabRef53: + //xx + throw new RuntimeException("getCitationEntries for JabRef53 is not implemented yet"); + default: + throw new RuntimeException("getCitationEntries: unhandled dataModel "); } - return citations; } public void applyCitationEntries(DocumentConnection documentConnection, @@ -487,6 +372,8 @@ public void applyCitationEntries(DocumentConnection documentConnection, case JabRef53: //xx throw new RuntimeException("applyCitationEntries for JabRef53 is not implemented yet"); + default: + throw new RuntimeException("applyCitationEntries: unhandled dataModel "); } } From ef5ea559e4c7b570652c277c48d752c6be7a9122 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 26 Apr 2021 13:50:26 +0200 Subject: [PATCH 0638/1068] drop CitationGroup.refMarkName --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 3 +-- .../java/org/jabref/logic/oostyle/CitationGroup.java | 11 +---------- .../java/org/jabref/logic/oostyle/CitationGroups.java | 4 ---- .../java/org/jabref/logic/openoffice/Backend52.java | 6 ++---- 4 files changed, 4 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 183478b6f83..361690e28e3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1501,7 +1501,6 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, for (CitationPath p : ck.where) { CitationGroupID cgid = p.group; CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - String refMarkName = cg.getMarkName(); if (i > 0) { OOUtil.insertTextAtCurrentLocation(documentConnection.xText, @@ -1510,7 +1509,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, Collections.emptyList()); } documentConnection - .insertGetreferenceToPageNumberOfReferenceMark(refMarkName, cursor); + .insertGetreferenceToPageNumberOfReferenceMark(cg.getMarkName(), cursor); i++; } documentConnection.refresh(); diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index 43d4d9de54e..bd2b6c67b3e 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -20,25 +20,16 @@ public class CitationGroup { /** For Compat.DataModel.JabRef52 pageInfo belongs to the group */ public Optional pageInfo; - /** - * Locator in document, replaced with cgRangeStorage - * TODO: replace referenceMarkName with - * getMarkName(){ return backed.cgRangeStorage.getName(); } - */ - String referenceMarkName; - public CitationGroup(CitationGroupID cgid, StorageBase.NamedRange cgRangeStorage, int itcType, List citations, - Optional pageInfo, - String referenceMarkName) { + Optional pageInfo) { this.cgid = cgid; this.cgRangeStorage = cgRangeStorage; this.itcType = itcType; this.citations = citations; this.pageInfo = pageInfo; - this.referenceMarkName = referenceMarkName; this.localOrder = makeIndices(citations.size()); } diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 851fae008b6..3002b59e060 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -253,10 +253,6 @@ public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { return e; } - private Optional getReferenceMarkName(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.getMarkName()); - } - private Optional getItcType(CitationGroupID cgid) { return getCitationGroup(cgid).map(cg -> cg.itcType); } diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 1cc220662d3..1846fa66289 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -127,8 +127,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc sr.get(), ov.itcType, citations, - pageInfo, - refMarkName); + pageInfo); return cg; } @@ -235,8 +234,7 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, sr, itcType, citations, - pageInfo, - refMarkName); + pageInfo); return cg; default: throw new RuntimeException("Backend52 requires JabRef52 dataModel"); From 6b79cf6341ca2652675a1b5e4e0984e8cd51c5d6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 26 Apr 2021 14:31:56 +0200 Subject: [PATCH 0639/1068] add OOProcess --- .../org/jabref/gui/openoffice/OOBibBase.java | 521 +----------------- .../org/jabref/logic/oostyle/CitedKeys.java | 2 +- .../org/jabref/logic/oostyle/OOProcess.java | 472 ++++++++++++++++ 3 files changed, 493 insertions(+), 502 deletions(-) create mode 100644 src/main/java/org/jabref/logic/oostyle/OOProcess.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 361690e28e3..ec358950006 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4,23 +4,17 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; import java.util.stream.Collectors; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; -import org.jabref.logic.bibtex.comparator.FieldComparator; -import org.jabref.logic.bibtex.comparator.FieldComparatorStack; import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; import org.jabref.logic.oostyle.Citation; @@ -36,6 +30,7 @@ import org.jabref.logic.oostyle.Compat; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOPreFormatter; +import org.jabref.logic.oostyle.OOProcess; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.DocumentConnection; import org.jabref.logic.openoffice.NoDocumentException; @@ -86,20 +81,7 @@ class OOBibBase { private static final String BIB_SECTION_END_NAME = "JR_bib_end"; - /* Types of in-text citation. (itcType) - * Their numeric values are used in reference mark names. - */ - private static final int AUTHORYEAR_PAR = 1; - private static final int AUTHORYEAR_INTEXT = 2; - private static final int INVISIBLE_CIT = 3; - - private static final Comparator AUTHOR_YEAR_TITLE_COMPARATOR = - makeAuthorYearTitleComparator(); - private static final Comparator YEAR_AUTHOR_TITLE_COMPARATOR = - makeYearAuthorTitleComparator(); - - private static final Logger LOGGER = - LoggerFactory.getLogger(OOBibBase.class); + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); /* variables */ private final DialogService dialogService; @@ -125,30 +107,6 @@ public OOBibBase(Path loPath, this.xDesktop = simpleBootstrap(loPath); } - private static Comparator makeAuthorYearTitleComparator() { - FieldComparator a = new FieldComparator(StandardField.AUTHOR); - FieldComparator y = new FieldComparator(StandardField.YEAR); - FieldComparator t = new FieldComparator(StandardField.TITLE); - - List> ayt = new ArrayList<>(3); - ayt.add(a); - ayt.add(y); - ayt.add(t); - return new FieldComparatorStack<>(ayt); - } - - private static Comparator makeYearAuthorTitleComparator() { - FieldComparator y = new FieldComparator(StandardField.YEAR); - FieldComparator a = new FieldComparator(StandardField.AUTHOR); - FieldComparator t = new FieldComparator(StandardField.TITLE); - - List> yat = new ArrayList<>(3); - yat.add(y); - yat.add(a); - yat.add(t); - return new FieldComparatorStack<>(yat); - } - /* ***************************** * * Establish connection @@ -384,8 +342,7 @@ private static T unoQI(Class zInterface, * the presentation (citation marks) * * How: - * database lookup yields: (BibEntry,whichDatabase) - * (UndefinedBibtexEntry,null) if not found + * database lookup * * Local order * presentation order within groups from (style,BibEntry) @@ -461,371 +418,6 @@ public void applyCitationEntries(List citationEntries) fr.applyCitationEntries(documentConnection, citationEntries); } - /* *************************************** - * - * Local order: Presentation order within citation groups - * - * **************************************/ - - /** - * The comparator used to sort within a group of merged - * citations. - * - * The term used here is "multicite". The option controlling the - * order is "MultiCiteChronological" in style files. - * - * Yes, they are always sorted one way or another. - */ - private Comparator comparatorForMulticite(OOBibStyle style) { - if (style.getMultiCiteChronological()) { - return OOBibBase.YEAR_AUTHOR_TITLE_COMPARATOR; - } else { - return OOBibBase.AUTHOR_YEAR_TITLE_COMPARATOR; - } - } - - /* *************************************** - * - * Global order: by first appearance or by bibliography order - * - * **************************************/ - - /* bibliography order */ - - /** - * Return a TreeMap(entryComparator) copy of entries. - * - * For sorting the bibliography. - */ - SortedMap sortEntriesByComparator(Map entries, - Comparator entryComparator) { - - SortedMap newMap = new TreeMap<>(entryComparator); - for (Map.Entry kv : entries.entrySet()) { - newMap.put(kv.getKey(), - kv.getValue()); - } - return newMap; - } - - /* *************************************** - * - * Make them unique: uniqueLetters or numbers - * - * **************************************/ - - private String normalizedCitationMarkerForNormalStyle(CitedKey ck, - OOBibStyle style) { - if (ck.db.isEmpty()) { - return String.format("(Unresolved(%s))", ck.citationKey); - } - // We need "normalized" (in parenthesis) markers - // for uniqueness checking purposes: - // createNormalizedCitationMarker - CitationMarkerEntry ce = new CitationMarkerEntryImpl(ck.citationKey, - ck.db.map(e -> e.entry), - ck.db.map(e -> e.database), - Optional.empty(), // uniqueLetter - Optional.empty(), // pageInfo - false /* isFirstAppearanceOfSource */); - return style.getNormalizedCitationMarker(ce); - } - - /** - * Fills {@code sortedCitedKeys//normCitMarker} - */ - private void createNormalizedCitationMarkersForNormalStyle(CitedKeys sortedCitedKeys, - OOBibStyle style) { - - for (CitedKey ck : sortedCitedKeys.data.values()) { - ck.normCitMarker = Optional.of(normalizedCitationMarkerForNormalStyle(ck, style)); - } - } - - /** - * For each cited source make the citation keys unique by setting - * the uniqueLetter fields to letters ("a", "b") or Optional.empty() - * - * precondition: sortedCitedKeys already has normalized citation markers. - * precondition: sortedCitedKeys is sorted (according to the order we want the letters to be assigned) - * - * Expects to see data for all cited sources here. - * Clears uniqueLetters before filling. - * - * On return: Each citedKey in sortedCitedKeys has uniqueLetter set as needed. - * The same values are copied to the corresponding citations in cgs. - * - * Depends on: style, citations and their order. - */ - void createUniqueLetters(CitedKeys sortedCitedKeys, - CitationGroups cgs) { - - // ncm2clks: ncm (normCitMarker) to clks (clashing keys : list of citation keys fighting for it). - // - // The entries in the clks lists preserve firstAppearance order - // from sortedCitedKeys.data.values(). - // - // The index of the citationKey in this order will decide which - // unique letter it receives. - // - Map> ncm2clks = new HashMap<>(); - for (CitedKey ck : sortedCitedKeys.values()) { - String ncm = ck.normCitMarker.get(); - String citationKey = ck.citationKey; - - if (!ncm2clks.containsKey(ncm)) { - // Found new normCitMarker - List clks = new ArrayList<>(1); - ncm2clks.put(ncm, clks); - clks.add(citationKey); - } else { - List clks = ncm2clks.get(ncm); - if (!clks.contains(citationKey)) { - // First appearance of citationKey, add to list. - clks.add(citationKey); - } - } - } - - // Clear old uniqueLetter values. - for (CitedKey ck : sortedCitedKeys.data.values()) { - ck.uniqueLetter = Optional.empty(); - } - - // For sets of citation keys figthing for a normCitMarker - // add unique letters to the year. - for (List clks : ncm2clks.values()) { - if (clks.size() <= 1) { - continue; // No fight, no letters. - } - // Multiple citation keys: they get their letters according to their order in clks. - int nextUniqueLetter = 'a'; - for (String citationKey : clks) { - // uniqueLetters.put(citationKey, String.valueOf((char) nextUniqueLetter)); - String ul = String.valueOf((char) nextUniqueLetter); - sortedCitedKeys.data.get(citationKey).uniqueLetter = Optional.of(ul); - nextUniqueLetter++; - } - } - sortedCitedKeys.distributeUniqueLetters(cgs); - } - - /* *************************************** - * - * Calculate presentation of citation groups - * (create citMarkers) - * - * **************************************/ - - /** - * Given the withText and inParenthesis options, - * return the corresponding itcType. - * - * @param withText False means invisible citation (no text). - * @param inParenthesis True means "(Au and Thor 2000)". - * False means "Au and Thor (2000)". - */ - private static int citationTypeFromOptions(boolean withText, boolean inParenthesis) { - if (!withText) { - return OOBibBase.INVISIBLE_CIT; - } - return (inParenthesis - ? OOBibBase.AUTHORYEAR_PAR - : OOBibBase.AUTHORYEAR_INTEXT); - } - - /** - * Produce citation markers for the case when the citation - * markers are the citation keys themselves, separated by commas. - */ - private static Map - produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroups cgs, - OOBibStyle style) { - - assert style.isCitationKeyCiteMarkers(); - - cgs.createPlainBibliographySortedByComparator(OOBibBase.AUTHOR_YEAR_TITLE_COMPARATOR); - - Map citMarkers = new HashMap<>(); - - for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - List cits = cgs.getSortedCitations(cgid); - String citMarker = - style.getCitationGroupMarkupBefore() - + (cits.stream() - .map(cit -> cit.citationKey) - .collect(Collectors.joining(","))) - + style.getCitationGroupMarkupAfter(); - citMarkers.put(cgid, citMarker); - } - return citMarkers; - } - - /** - * Produce citation markers for the case of numbered citations - * with bibliography sorted by first appearance in the text. - * - * @param cgs - * @param style - * - * @return Numbered citation markers for each CitationGroupID. - * Numbering is according to first appearance. - * Assumes global order and local order ae already applied. - * - */ - private static Map - produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, - OOBibStyle style) { - - assert style.isNumberEntries(); - assert style.isSortByPosition(); - - cgs.createNumberedBibliographySortedInOrderOfAppearance(); - - final int minGroupingCount = style.getMinimumGroupingCount(); - - Map citMarkers = new HashMap<>(); - - for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - List numbers = cg.getSortedNumbers(); - List pageInfos = cgs.getPageInfosForCitations(cg); - citMarkers.put(cgid, - style.getNumCitationMarker(numbers, - minGroupingCount, - pageInfos)); - } - - return citMarkers; - } - - /** - * Produce citation markers for the case of numbered citations - * when the bibliography is not sorted by position. - */ - private Map - produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, - OOBibStyle style) { - assert style.isNumberEntries(); - assert !style.isSortByPosition(); - - cgs.createNumberedBibliographySortedByComparator(OOBibBase.AUTHOR_YEAR_TITLE_COMPARATOR); - - final int minGroupingCount = style.getMinimumGroupingCount(); - - Map citMarkers = new HashMap<>(); - - for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - List numbers = cg.getSortedNumbers(); - List pageInfos = cgs.getPageInfosForCitations(cg); - citMarkers.put(cgid, - style.getNumCitationMarker(numbers, - minGroupingCount, - pageInfos)); - } - return citMarkers; - } - - /** - * Produce citMarkers for normal - * (!isCitationKeyCiteMarkers && !isNumberEntries) styles. - * - * @param cgs - * @param style Bibliography style. - */ - private Map produceCitationMarkersForNormalStyle(CitationGroups cgs, - OOBibStyle style) { - - assert !style.isCitationKeyCiteMarkers(); - assert !style.isNumberEntries(); - // Citations in (Au1, Au2 2000) form - - CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); - - createNormalizedCitationMarkersForNormalStyle(sortedCitedKeys, style); - createUniqueLetters(sortedCitedKeys, cgs); // calls distributeUniqueLetters(cgs) - cgs.createPlainBibliographySortedByComparator(OOBibBase.AUTHOR_YEAR_TITLE_COMPARATOR); - - // Finally, go through all citation markers, and update - // those referring to entries in our current list: - final int maxAuthorsFirst = style.getMaxAuthorsFirst(); - - Set seenBefore = new HashSet<>(); - - Map citMarkers = new HashMap<>(); - - for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - List cits = cg.getSortedCitations(); - final int nCitedEntries = cits.size(); - List pageInfosForCitations = cgs.getPageInfosForCitations(cg); - - List citationMarkerEntries = new ArrayList<>(nCitedEntries); - - boolean hasUnresolved = false; - for (int j = 0; j < nCitedEntries; j++) { - Citation cit = cits.get(j); - String currentKey = cit.citationKey; - boolean isFirst = false; - if (!seenBefore.contains(currentKey)) { - isFirst = true; - seenBefore.add(currentKey); - } - Optional uniqueLetterForKey = cit.uniqueLetter; - if (cit.db.isEmpty()) { - hasUnresolved = true; - } - Optional database = cit.db.map(e -> e.database); - Optional bibEntry = cit.db.map(e -> e.entry); - - CitationMarkerEntry cm = - new CitationMarkerEntryImpl(currentKey, - bibEntry, - database, - uniqueLetterForKey, - Optional.ofNullable(pageInfosForCitations.get(j)), - isFirst); - citationMarkerEntries.add(cm); - } - - // TODO: Now we can pass CitationMarkerEntry values with unresolved - // keys to style.getCitationMarker, - // maybe the fall back to ungrouped citations here is - // not needed anymore. - - if (hasUnresolved) { - /* - * Some entries are unresolved. - */ - String s = ""; - for (int j = 0; j < nCitedEntries; j++) { - - CitationMarkerEntry cm = citationMarkerEntries.get(j); - if (cm.getBibEntry().isPresent()) { - s = (s - + style.getCitationMarker(citationMarkerEntries.subList(j, j + 1), - cg.itcType == OOBibBase.AUTHORYEAR_PAR, - OOBibStyle.NonUniqueCitationMarker.THROWS)); - } else { - s = s + String.format("(Unresolved(%s))", cm.getCitationKey()); - } - } - citMarkers.put(cgid, s); - } else { - /* - * All entries are resolved. - */ - String citMarker = style.getCitationMarker(citationMarkerEntries, - cg.itcType == OOBibBase.AUTHORYEAR_PAR, - OOBibStyle.NonUniqueCitationMarker.THROWS); - citMarkers.put(cgid, citMarker); - } - } - - return citMarkers; - } - private static void fillCitationMarkInCursor(XTextCursor cursor, String citationText, boolean withText, @@ -1117,7 +709,7 @@ public void insertEntry(List entries, .map(OOBibBase::insertEntryGetCitationKey) .collect(Collectors.toList()); - int itcType = citationTypeFromOptions(withText, inParenthesis); + int itcType = OOProcess.citationTypeFromOptions(withText, inParenthesis); assertCitationCharacterFormatIsOK(cursor, style); @@ -1169,8 +761,8 @@ public void insertEntry(List entries, // must refresh the cite markers: OOFrontend fr2 = new OOFrontend(documentConnection); fr2.imposeGlobalOrder(documentConnection); - ProduceCitationMarkersResult x = - produceCitationMarkers(fr2.cgs, allBases, style); + OOProcess.ProduceCitationMarkersResult x = + OOProcess.produceCitationMarkers(fr2.cgs, allBases, style); try { documentConnection.lockControllers(); applyNewCitationMarkers(documentConnection, @@ -1267,7 +859,7 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - boolean withText = (cg.itcType != OOBibBase.INVISIBLE_CIT); + boolean withText = (cg.itcType != OOProcess.INVISIBLE_CIT); if (withText) { @@ -1299,81 +891,6 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, } } - /** - * The main field is citMarkers, the rest is for reuse in caller. - */ - static class ProduceCitationMarkersResult { - - CitationGroups cgs; - - /** citation markers */ - Map citMarkers; - - ProduceCitationMarkersResult(CitationGroups cgs, - Map citMarkers) { - this.cgs = cgs; - this.citMarkers = citMarkers; - if (cgs.getBibliography().isEmpty()) { - throw new RuntimeException("ProduceCitationMarkersResult.constructor:" - + " cgs does not have a bibliography"); - } - } - - public CitedKeys getBibliography() { - if (cgs.getBibliography().isEmpty()) { - throw new RuntimeException("ProduceCitationMarkersResult.getBibliography:" - + " cgs does not have a bibliography"); - } - return cgs.getBibliography().get(); - } - - public List getUnresolvedKeys() { - CitedKeys bib = getBibliography(); - List unresolvedKeys = new ArrayList<>(); - for (CitedKey ck : bib.values()) { - if (ck.db.isEmpty()) { - unresolvedKeys.add(ck.citationKey); - } - } - return unresolvedKeys; - } - } - - private ProduceCitationMarkersResult produceCitationMarkers(CitationGroups cgs, - List databases, - OOBibStyle style) { - - if (!cgs.hasGlobalOrder()) { - throw new RuntimeException("produceCitationMarkers: globalOrder is misssing in cgs"); - } - - cgs.lookupEntriesInDatabases(databases); - - // requires cgs.lookupEntryInDatabases: needs BibEntry data - cgs.imposeLocalOrderByComparator(comparatorForMulticite(style)); - - Map citMarkers; - - // fill citMarkers - Map uniqueLetters = new HashMap<>(); - - if (style.isCitationKeyCiteMarkers()) { - citMarkers = produceCitationMarkersForIsCitationKeyCiteMarkers(cgs, style); - } else if (style.isNumberEntries()) { - if (style.isSortByPosition()) { - citMarkers = produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); - } else { - citMarkers = produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); - } - } else { - /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ - citMarkers = produceCitationMarkersForNormalStyle(cgs, style); - } - - return new ProduceCitationMarkersResult(cgs, /* has bibliography as a side effect */ - citMarkers); - } - /* ************************************************** * * Bibliography: needs uniqueLetters or numbers @@ -1751,7 +1268,7 @@ public void combineCiteMarkers(List databases, */ // Only combine (Author 2000) type citations - if (cg.itcType != OOBibBase.AUTHORYEAR_PAR + if (cg.itcType != OOProcess.AUTHORYEAR_PAR // allow "Author (2000)" // && itcTypes[i] != OOBibBase.AUTHORYEAR_INTEXT ) { @@ -1845,7 +1362,7 @@ public void combineCiteMarkers(List databases, * * Can it start a new group? */ - boolean canStartGroup = (cg.itcType == OOBibBase.AUTHORYEAR_PAR); + boolean canStartGroup = (cg.itcType == OOProcess.AUTHORYEAR_PAR); if (!addToGroup) { // close currentGroup @@ -2000,9 +1517,10 @@ public void combineCiteMarkers(List databases, if (madeModifications) { OOFrontend fr2 = new OOFrontend(documentConnection); fr2.imposeGlobalOrder(documentConnection); - ProduceCitationMarkersResult x = produceCitationMarkers(fr.cgs, - databases, - style); + OOProcess.ProduceCitationMarkersResult x = + OOProcess.produceCitationMarkers(fr.cgs, + databases, + style); try { if (useLockControllers) { documentConnection.lockControllers(); @@ -2116,7 +1634,7 @@ public void unCombineCiteMarkers(List databases, documentConnection, keys.subList(i, i + 1), // citationKeys, pageInfosForCitations.subList(i, i + 1), // pageInfos, - OOBibBase.AUTHORYEAR_PAR, // itcType, + OOProcess.AUTHORYEAR_PAR, // itcType, "tmp", textCursor, true, /* withText. @@ -2138,8 +1656,8 @@ public void unCombineCiteMarkers(List databases, if (madeModifications) { OOFrontend fr2 = new OOFrontend(documentConnection); fr2.imposeGlobalOrder(documentConnection); - ProduceCitationMarkersResult x = - produceCitationMarkers(fr.cgs, databases, style); + OOProcess.ProduceCitationMarkersResult x = + OOProcess.produceCitationMarkers(fr.cgs, databases, style); try { if (useLockControllers) { documentConnection.lockControllers(); @@ -2424,9 +1942,10 @@ public List updateDocumentActionHelper(List databases, final boolean useLockControllers = true; fr.imposeGlobalOrder(documentConnection); - ProduceCitationMarkersResult x = produceCitationMarkers(fr.cgs, - databases, - style); + OOProcess.ProduceCitationMarkersResult x = + OOProcess.produceCitationMarkers(fr.cgs, + databases, + style); try { if (useLockControllers) { documentConnection.lockControllers(); diff --git a/src/main/java/org/jabref/logic/oostyle/CitedKeys.java b/src/main/java/org/jabref/logic/oostyle/CitedKeys.java index 153f3104255..47f2e3fb9f5 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/logic/oostyle/CitedKeys.java @@ -43,7 +43,7 @@ void sortByComparator(Comparator entryComparator) { void numberCitedKeysInCurrentOrder() { int i = 1; for (CitedKey ck : data.values()) { - ck.number = Optional.of(i); // was: -1 for UndefinedBibtexEntry + ck.number = Optional.of(i); // was: -1 for unresolved i++; } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java new file mode 100644 index 00000000000..85bb02b4233 --- /dev/null +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -0,0 +1,472 @@ +package org.jabref.logic.oostyle; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import org.jabref.logic.bibtex.comparator.FieldComparator; +import org.jabref.logic.bibtex.comparator.FieldComparatorStack; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.StandardField; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class OOProcess { + /* Types of in-text citation. (itcType) + * Their numeric values are used in reference mark names. + */ + public static final int AUTHORYEAR_PAR = 1; + public static final int AUTHORYEAR_INTEXT = 2; + public static final int INVISIBLE_CIT = 3; + + private static final Comparator AUTHOR_YEAR_TITLE_COMPARATOR = + makeAuthorYearTitleComparator(); + private static final Comparator YEAR_AUTHOR_TITLE_COMPARATOR = + makeYearAuthorTitleComparator(); + + private static final Logger LOGGER = LoggerFactory.getLogger(OOProcess.class); + + private static Comparator makeAuthorYearTitleComparator() { + FieldComparator a = new FieldComparator(StandardField.AUTHOR); + FieldComparator y = new FieldComparator(StandardField.YEAR); + FieldComparator t = new FieldComparator(StandardField.TITLE); + + List> ayt = new ArrayList<>(3); + ayt.add(a); + ayt.add(y); + ayt.add(t); + return new FieldComparatorStack<>(ayt); + } + + private static Comparator makeYearAuthorTitleComparator() { + FieldComparator y = new FieldComparator(StandardField.YEAR); + FieldComparator a = new FieldComparator(StandardField.AUTHOR); + FieldComparator t = new FieldComparator(StandardField.TITLE); + + List> yat = new ArrayList<>(3); + yat.add(y); + yat.add(a); + yat.add(t); + return new FieldComparatorStack<>(yat); + } + + /** + * The comparator used to sort within a group of merged + * citations. + * + * The term used here is "multicite". The option controlling the + * order is "MultiCiteChronological" in style files. + * + * Yes, they are always sorted one way or another. + */ + private static Comparator comparatorForMulticite(OOBibStyle style) { + if (style.getMultiCiteChronological()) { + return OOProcess.YEAR_AUTHOR_TITLE_COMPARATOR; + } else { + return OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR; + } + } + + /* *************************************** + * + * Make them unique: uniqueLetters or numbers + * + * **************************************/ + + private static String normalizedCitationMarkerForNormalStyle(CitedKey ck, + OOBibStyle style) { + if (ck.db.isEmpty()) { + return String.format("(Unresolved(%s))", ck.citationKey); + } + // We need "normalized" (in parenthesis) markers + // for uniqueness checking purposes: + // createNormalizedCitationMarker + CitationMarkerEntry ce = new CitationMarkerEntryImpl(ck.citationKey, + ck.db.map(e -> e.entry), + ck.db.map(e -> e.database), + Optional.empty(), // uniqueLetter + Optional.empty(), // pageInfo + false /* isFirstAppearanceOfSource */); + return style.getNormalizedCitationMarker(ce); + } + + /** + * Fills {@code sortedCitedKeys//normCitMarker} + */ + private static void createNormalizedCitationMarkersForNormalStyle(CitedKeys sortedCitedKeys, + OOBibStyle style) { + + for (CitedKey ck : sortedCitedKeys.data.values()) { + ck.normCitMarker = Optional.of(normalizedCitationMarkerForNormalStyle(ck, style)); + } + } + + /** + * For each cited source make the citation keys unique by setting + * the uniqueLetter fields to letters ("a", "b") or Optional.empty() + * + * precondition: sortedCitedKeys already has normalized citation markers. + * precondition: sortedCitedKeys is sorted (according to the order we want the letters to be assigned) + * + * Expects to see data for all cited sources here. + * Clears uniqueLetters before filling. + * + * On return: Each citedKey in sortedCitedKeys has uniqueLetter set as needed. + * The same values are copied to the corresponding citations in cgs. + * + * Depends on: style, citations and their order. + */ + private static void createUniqueLetters(CitedKeys sortedCitedKeys, + CitationGroups cgs) { + + // ncm2clks: ncm (normCitMarker) to clks (clashing keys : list of citation keys fighting for it). + // + // The entries in the clks lists preserve firstAppearance order + // from sortedCitedKeys.data.values(). + // + // The index of the citationKey in this order will decide which + // unique letter it receives. + // + Map> ncm2clks = new HashMap<>(); + for (CitedKey ck : sortedCitedKeys.values()) { + String ncm = ck.normCitMarker.get(); + String citationKey = ck.citationKey; + + if (!ncm2clks.containsKey(ncm)) { + // Found new normCitMarker + List clks = new ArrayList<>(1); + ncm2clks.put(ncm, clks); + clks.add(citationKey); + } else { + List clks = ncm2clks.get(ncm); + if (!clks.contains(citationKey)) { + // First appearance of citationKey, add to list. + clks.add(citationKey); + } + } + } + + // Clear old uniqueLetter values. + for (CitedKey ck : sortedCitedKeys.data.values()) { + ck.uniqueLetter = Optional.empty(); + } + + // For sets of citation keys figthing for a normCitMarker + // add unique letters to the year. + for (List clks : ncm2clks.values()) { + if (clks.size() <= 1) { + continue; // No fight, no letters. + } + // Multiple citation keys: they get their letters according to their order in clks. + int nextUniqueLetter = 'a'; + for (String citationKey : clks) { + // uniqueLetters.put(citationKey, String.valueOf((char) nextUniqueLetter)); + String ul = String.valueOf((char) nextUniqueLetter); + sortedCitedKeys.data.get(citationKey).uniqueLetter = Optional.of(ul); + nextUniqueLetter++; + } + } + sortedCitedKeys.distributeUniqueLetters(cgs); + } + + /* *************************************** + * + * Calculate presentation of citation groups + * (create citMarkers) + * + * **************************************/ + + /** + * Given the withText and inParenthesis options, + * return the corresponding itcType. + * + * @param withText False means invisible citation (no text). + * @param inParenthesis True means "(Au and Thor 2000)". + * False means "Au and Thor (2000)". + */ + public static int citationTypeFromOptions(boolean withText, boolean inParenthesis) { + if (!withText) { + return OOProcess.INVISIBLE_CIT; + } + return (inParenthesis + ? OOProcess.AUTHORYEAR_PAR + : OOProcess.AUTHORYEAR_INTEXT); + } + + /** + * Produce citation markers for the case when the citation + * markers are the citation keys themselves, separated by commas. + */ + private static Map + produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroups cgs, + OOBibStyle style) { + + assert style.isCitationKeyCiteMarkers(); + + cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); + + Map citMarkers = new HashMap<>(); + + for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + List cits = cgs.getSortedCitations(cgid); + String citMarker = + style.getCitationGroupMarkupBefore() + + (cits.stream() + .map(cit -> cit.citationKey) + .collect(Collectors.joining(","))) + + style.getCitationGroupMarkupAfter(); + citMarkers.put(cgid, citMarker); + } + return citMarkers; + } + + /** + * Produce citation markers for the case of numbered citations + * with bibliography sorted by first appearance in the text. + * + * @param cgs + * @param style + * + * @return Numbered citation markers for each CitationGroupID. + * Numbering is according to first appearance. + * Assumes global order and local order ae already applied. + * + */ + private static Map + produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, + OOBibStyle style) { + + assert style.isNumberEntries(); + assert style.isSortByPosition(); + + cgs.createNumberedBibliographySortedInOrderOfAppearance(); + + final int minGroupingCount = style.getMinimumGroupingCount(); + + Map citMarkers = new HashMap<>(); + + for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + List numbers = cg.getSortedNumbers(); + List pageInfos = cgs.getPageInfosForCitations(cg); + citMarkers.put(cgid, + style.getNumCitationMarker(numbers, + minGroupingCount, + pageInfos)); + } + + return citMarkers; + } + + /** + * Produce citation markers for the case of numbered citations + * when the bibliography is not sorted by position. + */ + private static Map + produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, + OOBibStyle style) { + assert style.isNumberEntries(); + assert !style.isSortByPosition(); + + cgs.createNumberedBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); + + final int minGroupingCount = style.getMinimumGroupingCount(); + + Map citMarkers = new HashMap<>(); + + for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + List numbers = cg.getSortedNumbers(); + List pageInfos = cgs.getPageInfosForCitations(cg); + citMarkers.put(cgid, + style.getNumCitationMarker(numbers, + minGroupingCount, + pageInfos)); + } + return citMarkers; + } + + /** + * Produce citMarkers for normal + * (!isCitationKeyCiteMarkers && !isNumberEntries) styles. + * + * @param cgs + * @param style Bibliography style. + */ + private static Map + produceCitationMarkersForNormalStyle(CitationGroups cgs, + OOBibStyle style) { + + assert !style.isCitationKeyCiteMarkers(); + assert !style.isNumberEntries(); + // Citations in (Au1, Au2 2000) form + + CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); + + createNormalizedCitationMarkersForNormalStyle(sortedCitedKeys, style); + createUniqueLetters(sortedCitedKeys, cgs); // calls distributeUniqueLetters(cgs) + cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); + + // Finally, go through all citation markers, and update + // those referring to entries in our current list: + final int maxAuthorsFirst = style.getMaxAuthorsFirst(); + + Set seenBefore = new HashSet<>(); + + Map citMarkers = new HashMap<>(); + + for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + List cits = cg.getSortedCitations(); + final int nCitedEntries = cits.size(); + List pageInfosForCitations = cgs.getPageInfosForCitations(cg); + + List citationMarkerEntries = new ArrayList<>(nCitedEntries); + + boolean hasUnresolved = false; + for (int j = 0; j < nCitedEntries; j++) { + Citation cit = cits.get(j); + String currentKey = cit.citationKey; + boolean isFirst = false; + if (!seenBefore.contains(currentKey)) { + isFirst = true; + seenBefore.add(currentKey); + } + Optional uniqueLetterForKey = cit.uniqueLetter; + if (cit.db.isEmpty()) { + hasUnresolved = true; + } + Optional database = cit.db.map(e -> e.database); + Optional bibEntry = cit.db.map(e -> e.entry); + + CitationMarkerEntry cm = + new CitationMarkerEntryImpl(currentKey, + bibEntry, + database, + uniqueLetterForKey, + Optional.ofNullable(pageInfosForCitations.get(j)), + isFirst); + citationMarkerEntries.add(cm); + } + + // TODO: Now we can pass CitationMarkerEntry values with unresolved + // keys to style.getCitationMarker, + // maybe the fall back to ungrouped citations here is + // not needed anymore. + + if (hasUnresolved) { + /* + * Some entries are unresolved. + */ + String s = ""; + for (int j = 0; j < nCitedEntries; j++) { + + CitationMarkerEntry cm = citationMarkerEntries.get(j); + if (cm.getBibEntry().isPresent()) { + s = (s + + style.getCitationMarker(citationMarkerEntries.subList(j, j + 1), + cg.itcType == OOProcess.AUTHORYEAR_PAR, + OOBibStyle.NonUniqueCitationMarker.THROWS)); + } else { + s = s + String.format("(Unresolved(%s))", cm.getCitationKey()); + } + } + citMarkers.put(cgid, s); + } else { + /* + * All entries are resolved. + */ + String citMarker = style.getCitationMarker(citationMarkerEntries, + cg.itcType == OOProcess.AUTHORYEAR_PAR, + OOBibStyle.NonUniqueCitationMarker.THROWS); + citMarkers.put(cgid, citMarker); + } + } + + return citMarkers; + } + + /** + * The main field is citMarkers, the rest is for reuse in caller. + */ + public static class ProduceCitationMarkersResult { + + public CitationGroups cgs; + + /** citation markers */ + public Map citMarkers; + + ProduceCitationMarkersResult(CitationGroups cgs, + Map citMarkers) { + this.cgs = cgs; + this.citMarkers = citMarkers; + if (cgs.getBibliography().isEmpty()) { + throw new RuntimeException("ProduceCitationMarkersResult.constructor:" + + " cgs does not have a bibliography"); + } + } + + public CitedKeys getBibliography() { + if (cgs.getBibliography().isEmpty()) { + throw new RuntimeException("ProduceCitationMarkersResult.getBibliography:" + + " cgs does not have a bibliography"); + } + return cgs.getBibliography().get(); + } + + public List getUnresolvedKeys() { + CitedKeys bib = getBibliography(); + List unresolvedKeys = new ArrayList<>(); + for (CitedKey ck : bib.values()) { + if (ck.db.isEmpty()) { + unresolvedKeys.add(ck.citationKey); + } + } + return unresolvedKeys; + } + } + + public static ProduceCitationMarkersResult produceCitationMarkers(CitationGroups cgs, + List databases, + OOBibStyle style) { + + if (!cgs.hasGlobalOrder()) { + throw new RuntimeException("produceCitationMarkers: globalOrder is misssing in cgs"); + } + + cgs.lookupEntriesInDatabases(databases); + + // requires cgs.lookupEntryInDatabases: needs BibEntry data + cgs.imposeLocalOrderByComparator(comparatorForMulticite(style)); + + Map citMarkers; + + // fill citMarkers + Map uniqueLetters = new HashMap<>(); + + if (style.isCitationKeyCiteMarkers()) { + citMarkers = produceCitationMarkersForIsCitationKeyCiteMarkers(cgs, style); + } else if (style.isNumberEntries()) { + if (style.isSortByPosition()) { + citMarkers = produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); + } else { + citMarkers = produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); + } + } else { + /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ + citMarkers = produceCitationMarkersForNormalStyle(cgs, style); + } + + return new ProduceCitationMarkersResult(cgs, /* has bibliography as a side effect */ + citMarkers); + } + +} From ffa95c7c121ba82492abe7cfd9468ced8137d1e8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 26 Apr 2021 14:32:11 +0200 Subject: [PATCH 0640/1068] drop unused UndefinedBibtexEntry.java --- .../logic/oostyle/UndefinedBibtexEntry.java | 21 ------------------- 1 file changed, 21 deletions(-) delete mode 100644 src/main/java/org/jabref/logic/oostyle/UndefinedBibtexEntry.java diff --git a/src/main/java/org/jabref/logic/oostyle/UndefinedBibtexEntry.java b/src/main/java/org/jabref/logic/oostyle/UndefinedBibtexEntry.java deleted file mode 100644 index e9c74f3a942..00000000000 --- a/src/main/java/org/jabref/logic/oostyle/UndefinedBibtexEntry.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.jabref.logic.oostyle; - -import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.StandardField; - -/** - * Subclass of BibEntry for representing entries referenced in a document that can't be found in JabRef's current database. - */ -public class UndefinedBibtexEntry extends BibEntry { - - private final String key; - - public UndefinedBibtexEntry(String key) { - this.key = key; - setField(StandardField.AUTHOR, OOBibStyle.UNDEFINED_CITATION_MARKER); - } - - public String getKey() { - return key; - } -} From 28d126ed4fd0cd303a3628477a6a462ce1c430cb Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 26 Apr 2021 18:30:57 +0200 Subject: [PATCH 0641/1068] use OOFormattedText for citation markers and pageInfo --- .../org/jabref/gui/openoffice/OOBibBase.java | 55 ++++++----- .../org/jabref/logic/oostyle/Citation.java | 4 +- .../jabref/logic/oostyle/CitationGroup.java | 6 +- .../jabref/logic/oostyle/CitationGroups.java | 6 +- .../logic/oostyle/CitationMarkerEntry.java | 2 +- .../oostyle/CitationMarkerEntryImpl.java | 9 +- .../jabref/logic/oostyle/CitationSort.java | 2 +- .../org/jabref/logic/oostyle/CitedKey.java | 4 +- .../java/org/jabref/logic/oostyle/Compat.java | 29 +++--- .../org/jabref/logic/oostyle/OOBibStyle.java | 43 ++++---- .../oostyle/OOBibStyleGetCitationMarker.java | 53 +++++----- .../OOBibStyleGetNumCitationMarker.java | 37 +++---- .../org/jabref/logic/oostyle/OOFormat.java | 52 ++++++++++ .../jabref/logic/oostyle/OOFormattedText.java | 28 ++++++ .../org/jabref/logic/oostyle/OOProcess.java | 47 ++++----- .../jabref/logic/openoffice/Backend52.java | 18 ++-- .../jabref/logic/openoffice/OOFrontend.java | 3 +- .../org/jabref/logic/openoffice/OOUtil.java | 55 +---------- .../jabref/logic/oostyle/OOBibStyleTest.java | 99 +++++++++++-------- 19 files changed, 312 insertions(+), 240 deletions(-) create mode 100644 src/main/java/org/jabref/logic/oostyle/OOFormat.java create mode 100644 src/main/java/org/jabref/logic/oostyle/OOFormattedText.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ec358950006..166d60c009c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -29,6 +29,8 @@ import org.jabref.logic.oostyle.CitedKeys; import org.jabref.logic.oostyle.Compat; import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.oostyle.OOFormat; +import org.jabref.logic.oostyle.OOFormattedText; import org.jabref.logic.oostyle.OOPreFormatter; import org.jabref.logic.oostyle.OOProcess; import org.jabref.logic.openoffice.CreationException; @@ -419,7 +421,7 @@ public void applyCitationEntries(List citationEntries) } private static void fillCitationMarkInCursor(XTextCursor cursor, - String citationText, + OOFormattedText citationText, boolean withText, OOBibStyle style) throws @@ -469,9 +471,9 @@ private void createAndFillCitationGroup(OOFrontend fr, // CitationGroups cgs, DocumentConnection documentConnection, List citationKeys, - List pageInfosForCitations, + List pageInfosForCitations, int itcType, - String citationText, + OOFormattedText citationText, XTextCursor position, boolean withText, OOBibStyle style, @@ -714,7 +716,8 @@ public void insertEntry(List entries, assertCitationCharacterFormatIsOK(cursor, style); // JabRef53 style pageInfo list - List pageInfosForCitations = Compat.fakePageInfosForCitations(pageInfo, nEntries); + List pageInfosForCitations = + Compat.fakePageInfosForCitations(pageInfo, nEntries); List citationMarkerEntries = new ArrayList<>(entries.size()); for (int i = 0; i < nEntries; i++) { @@ -731,14 +734,15 @@ public void insertEntry(List entries, } // The text we insert - String citeText = (style.isNumberEntries() - ? "[-]" // A dash only. Only refresh later. - : style.getCitationMarker(citationMarkerEntries, - inParenthesis, - OOBibStyle.NonUniqueCitationMarker.FORGIVEN)); - - if (citeText.equals("")) { - citeText = "[?]"; + OOFormattedText citeText = + (style.isNumberEntries() + ? OOFormattedText.fromString("[-]") // A dash only. Only refresh later. + : style.getCitationMarker(citationMarkerEntries, + inParenthesis, + OOBibStyle.NonUniqueCitationMarker.FORGIVEN)); + + if ("".equals(OOFormattedText.toString(citeText))) { + citeText = OOFormattedText.fromString("[?]"); } createAndFillCitationGroup(fr, @@ -826,7 +830,7 @@ public void insertEntry(List entries, */ private void applyNewCitationMarkers(DocumentConnection documentConnection, OOFrontend fr, - Map citMarkers, + Map citMarkers, OOBibStyle style) throws NoDocumentException, @@ -849,12 +853,12 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, // catastrophic consequences for the user. boolean mustTestCharFormat = style.isFormatCitations(); - for (Map.Entry kv : citMarkers.entrySet()) { + for (Map.Entry kv : citMarkers.entrySet()) { CitationGroupID cgid = kv.getKey(); Objects.requireNonNull(cgid); - String citationText = kv.getValue(); + OOFormattedText citationText = kv.getValue(); Objects.requireNonNull(citationText); CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); @@ -991,7 +995,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, } int number = ck.number.get(); - String marker = style.getNumCitationMarkerForBibliography(number); + OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, marker); cursor.collapseToEnd(); } else { @@ -1001,7 +1005,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, if (ck.db.isEmpty()) { // Unresolved entry - String referenceDetails = String.format("Unresolved(%s)", ck.citationKey); + OOFormattedText referenceDetails = + OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, referenceDetails); cursor.collapseToEnd(); // Try to list citations: @@ -1045,10 +1050,10 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, Layout layout = style.getReferenceFormat(bibentry.getType()); layout.setPostFormatter(POSTFORMATTER); - String formattedText = OOUtil.formatFullReference(layout, - bibentry, - ck.db.get().database, - ck.uniqueLetter.orElse(null)); + OOFormattedText formattedText = OOFormat.formatFullReference(layout, + bibentry, + ck.db.get().database, + ck.uniqueLetter.orElse(null)); // Insert the formatted text: OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, formattedText); @@ -1472,7 +1477,7 @@ public void combineCiteMarkers(List databases, // cgPageInfos belong to the CitationGroup (DataModel JabRef52), // but it is not clear how should we handle them here. // We delegate the problem to the backend. - List pageInfosForCitations = + List pageInfosForCitations = fr.backend.combinePageInfos(joinableGroup); // Remove the old citation groups from the document. @@ -1499,7 +1504,7 @@ public void combineCiteMarkers(List databases, citationKeys, pageInfosForCitations, itcType, // OOBibBase.AUTHORYEAR_PAR - "tmp", + OOFormattedText.fromString("tmp"), textCursor, true, // withText style, @@ -1606,7 +1611,7 @@ public void unCombineCiteMarkers(List databases, } // Note: JabRef52 returns cg.pageInfo for the last citation. - List pageInfosForCitations = fr.cgs.getPageInfosForCitations(cg); + List pageInfosForCitations = fr.cgs.getPageInfosForCitations(cg); List cits = cg.citations; if (cits.size() <= 1) { @@ -1635,7 +1640,7 @@ public void unCombineCiteMarkers(List databases, keys.subList(i, i + 1), // citationKeys, pageInfosForCitations.subList(i, i + 1), // pageInfos, OOProcess.AUTHORYEAR_PAR, // itcType, - "tmp", + OOFormattedText.fromString("tmp"), textCursor, true, /* withText. * Should be itcType != OOBibBase.INVISIBLE_CIT */ diff --git a/src/main/java/org/jabref/logic/oostyle/Citation.java b/src/main/java/org/jabref/logic/oostyle/Citation.java index 51b9c42f4e0..5084a827f74 100644 --- a/src/main/java/org/jabref/logic/oostyle/Citation.java +++ b/src/main/java/org/jabref/logic/oostyle/Citation.java @@ -16,7 +16,7 @@ public class Citation implements CitationSort.ComparableCitation { public Optional uniqueLetter; /** pageInfo: For Compat.DataModel.JabRef53 */ - public Optional pageInfo; + public Optional pageInfo; /* missing: something that differentiates this from other * citations of the same citationKey. In particular, a @@ -41,7 +41,7 @@ public String getCitationKey() { } @Override - public Optional getPageInfo() { + public Optional getPageInfo() { return pageInfo; } diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index bd2b6c67b3e..0a6e230adc6 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -18,13 +18,13 @@ public class CitationGroup { public List localOrder; /** For Compat.DataModel.JabRef52 pageInfo belongs to the group */ - public Optional pageInfo; + public Optional pageInfo; public CitationGroup(CitationGroupID cgid, StorageBase.NamedRange cgRangeStorage, int itcType, List citations, - Optional pageInfo) { + Optional pageInfo) { this.cgid = cgid; this.cgRangeStorage = cgRangeStorage; this.itcType = itcType; @@ -77,7 +77,7 @@ public Optional getBibEntry() { } @Override - public Optional getPageInfo() { + public Optional getPageInfo() { return c.pageInfo; } } diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 3002b59e060..d891479e308 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -261,17 +261,17 @@ public int numberOfCitationGroups() { return citationGroups.size(); } - public Optional getPageInfo(CitationGroupID cgid) { + public Optional getPageInfo(CitationGroupID cgid) { return (getCitationGroup(cgid) .map(cg -> cg.pageInfo) .flatMap(x -> x)); } - public List getPageInfosForCitations(CitationGroup cg) { + public List getPageInfosForCitations(CitationGroup cg) { return Compat.getPageInfosForCitations(this.dataModel, cg); } - public List getPageInfosForCitations(CitationGroupID cgid) { + public List getPageInfosForCitations(CitationGroupID cgid) { CitationGroup cg = getCitationGroupOrThrow(cgid); return getPageInfosForCitations(cg); } diff --git a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java index 67b6eadc991..5dc96fc889b 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java @@ -50,7 +50,7 @@ public interface CitationMarkerEntry { * pageInfo for this citation, provided by the user. * May be empty, for none. */ - Optional getPageInfo(); + Optional getPageInfo(); /** * @return true if this citation is the first appearance of the diff --git a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java index c277143c507..530aca912fb 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java @@ -17,14 +17,14 @@ public class CitationMarkerEntryImpl implements CitationMarkerEntry { final Optional bibEntry; final Optional database; final Optional uniqueLetter; - final Optional pageInfo; + final Optional pageInfo; final boolean isFirstAppearanceOfSource; public CitationMarkerEntryImpl(String citationKey, Optional bibEntry, Optional database, Optional uniqueLetter, - Optional pageInfo, + Optional pageInfo, boolean isFirstAppearanceOfSource) { Objects.requireNonNull(citationKey); this.citationKey = citationKey; @@ -57,7 +57,8 @@ public CitationMarkerEntryImpl(String citationKey, Optional bibEntry = Optional.ofNullable(bibEntryQ); Optional database = Optional.ofNullable(databaseQ); Optional uniqueLetter = Optional.ofNullable(uniqueLetterQ); - Optional pageInfo = Optional.ofNullable(pageInfoQ); + Optional pageInfo = + Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); if (bibEntry.isEmpty() && database.isPresent()) { throw new RuntimeException("CitationMarkerEntryImpl:" @@ -96,7 +97,7 @@ public Optional getUniqueLetter() { } @Override - public Optional getPageInfo() { + public Optional getPageInfo() { return pageInfo; } diff --git a/src/main/java/org/jabref/logic/oostyle/CitationSort.java b/src/main/java/org/jabref/logic/oostyle/CitationSort.java index 7492f033924..b2d58e36197 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationSort.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationSort.java @@ -12,7 +12,7 @@ interface ComparableCitation { public Optional getBibEntry(); - public Optional getPageInfo(); + public Optional getPageInfo(); } static class CitationComparator implements Comparator { diff --git a/src/main/java/org/jabref/logic/oostyle/CitedKey.java b/src/main/java/org/jabref/logic/oostyle/CitedKey.java index 590b214b579..fca035f02ce 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/logic/oostyle/CitedKey.java @@ -13,7 +13,7 @@ public class CitedKey implements CitationSort.ComparableCitation { public Optional db; public Optional number; // For Numbered citation styles. public Optional uniqueLetter; // For AuthorYear citation styles. - public Optional normCitMarker; // For AuthorYear citation styles. + public Optional normCitMarker; // For AuthorYear citation styles. CitedKey(String citationKey, CitationPath p, Citation cit) { this.citationKey = citationKey; @@ -43,7 +43,7 @@ public Optional getBibEntry() { * @return null */ @Override - public Optional getPageInfo() { + public Optional getPageInfo() { return Optional.empty(); } diff --git a/src/main/java/org/jabref/logic/oostyle/Compat.java b/src/main/java/org/jabref/logic/oostyle/Compat.java index 6a507ec829d..9be42d2f360 100644 --- a/src/main/java/org/jabref/logic/oostyle/Compat.java +++ b/src/main/java/org/jabref/logic/oostyle/Compat.java @@ -40,7 +40,8 @@ public enum DataModel { /** * Return the last pageInfo from the list, if there is one. */ - public static Optional getJabRef52PageInfoFromList(List pageInfosForCitations) { + public static Optional + getJabRef52PageInfoFromList(List pageInfosForCitations) { if (pageInfosForCitations == null) { return Optional.empty(); } @@ -55,12 +56,12 @@ public static Optional getJabRef52PageInfoFromList(List pageInfo * @param pageInfo Nullable. * @return JabRef53 style pageInfo list */ - public static List fakePageInfosForCitations(String pageInfo, - int nCitations) { - List pageInfosForCitations = new ArrayList<>(nCitations); + public static List fakePageInfosForCitations(String pageInfo, + int nCitations) { + List pageInfosForCitations = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { if (i == nCitations - 1) { - pageInfosForCitations.add(pageInfo); + pageInfosForCitations.add(OOFormattedText.fromString(pageInfo)); } else { pageInfosForCitations.add(null); } @@ -81,7 +82,8 @@ public static List fakePageInfosForCitations(String pageInfo, * * TODO: we may want class DataModel52, DataModel53 and split this. */ - public static List getPageInfosForCitations(Compat.DataModel dataModel, CitationGroup cg) { + public static List getPageInfosForCitations(Compat.DataModel dataModel, + CitationGroup cg) { switch (dataModel) { case JabRef52: // check conformance to dataModel @@ -92,7 +94,8 @@ public static List getPageInfosForCitations(Compat.DataModel dataModel, } } // A list of null values, except the last that comes from this.pageInfo - return Compat.fakePageInfosForCitations(cg.pageInfo.orElse(null), + OOFormattedText pi = cg.pageInfo.orElse(null); + return Compat.fakePageInfosForCitations(OOFormattedText.toString(pi), cg.citations.size()); case JabRef53: // check conformance to dataModel @@ -118,19 +121,19 @@ public static List getPageInfosForCitations(Compat.DataModel dataModel, * TODO: JabRef52 combinePageInfos is not reversible. Should warn * user to check the result. Or ask what to do. */ - public static List combinePageInfos(Compat.DataModel dataModel, - List joinableGroup) { + public static List combinePageInfos(Compat.DataModel dataModel, + List joinableGroup) { switch (dataModel) { case JabRef52: // collect to cgPageInfos - List> cgPageInfos = (joinableGroup.stream() - .map(cg -> cg.pageInfo) - .collect(Collectors.toList())); + List> cgPageInfos = (joinableGroup.stream() + .map(cg -> cg.pageInfo) + .collect(Collectors.toList())); // Try to do something of the cgPageInfos. String cgPageInfo = (cgPageInfos.stream() .filter(pi -> pi.isPresent()) - .map(pi -> pi.get()) + .map(pi -> OOFormattedText.toString(pi.get())) .distinct() .collect(Collectors.joining("; "))); diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 9036190e8ea..a4d653e5ebc 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -438,9 +438,9 @@ public Layout getReferenceFormat(EntryType type) { * @param number The citation numbers. * @return The text for the citation. */ - public String getNumCitationMarker(List number, - int minGroupingCount, - List pageInfosForCitations) { + public OOFormattedText getNumCitationMarker(List number, + int minGroupingCount, + List pageInfosForCitations) { return OOBibStyleGetNumCitationMarker.getNumCitationMarker(this, number, minGroupingCount, @@ -861,8 +861,8 @@ protected String getOxfordComma() { /** * Title for the bibliography. */ - public String getReferenceHeaderText() { - return getStringProperty(OOBibStyle.TITLE); + public OOFormattedText getReferenceHeaderText() { + return OOFormattedText.fromString(getStringProperty(OOBibStyle.TITLE)); } /** @@ -932,20 +932,20 @@ protected void setDefaultBibLayout(Layout l) { /** * Format a number-based bibliography label for the given number. */ - public String getNumCitationMarkerForBibliography(int number) { + public OOFormattedText getNumCitationMarkerForBibliography(int number) { return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, number); } - public static String regularizePageInfo(String p) { + public static OOFormattedText regularizePageInfo(OOFormattedText p) { if (p == null) { return null; } - String pt = p.trim(); + String pt = OOFormattedText.toString(p).trim(); if (pt.equals("")) { return null; } else { - return pt; + return OOFormattedText.fromString(pt); } } @@ -953,10 +953,11 @@ public static String regularizePageInfo(String p) { * Make sure that (1) we have exactly one entry for each * citation, (2) each entry is either null or is not empty when trimmed. */ - public static List regularizePageInfosForCitations(List pageInfosForCitations, - int nCitations) { + public static List + regularizePageInfosForCitations(List pageInfosForCitations, + int nCitations) { if (pageInfosForCitations == null) { - List res = new ArrayList<>(nCitations); + List res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { res.add(null); } @@ -966,9 +967,9 @@ public static List regularizePageInfosForCitations(List pageInfo throw new RuntimeException("regularizePageInfosForCitations:" + " pageInfosForCitations.size() != nCitations"); } - List res = new ArrayList<>(nCitations); + List res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { - String p = pageInfosForCitations.get(i); + OOFormattedText p = pageInfosForCitations.get(i); res.add(regularizePageInfo(p)); } return res; @@ -980,9 +981,9 @@ public static List regularizePageInfosForCitations(List pageInfo * * null comes before non-null */ - public static int comparePageInfo(String a, String b) { - String aa = regularizePageInfo(a); - String bb = regularizePageInfo(b); + public static int comparePageInfo(OOFormattedText a, OOFormattedText b) { + String aa = OOFormattedText.toString(regularizePageInfo(a)); + String bb = OOFormattedText.toString(regularizePageInfo(b)); if (aa == null && bb == null) { return 0; } @@ -995,7 +996,7 @@ public static int comparePageInfo(String a, String b) { return aa.compareTo(bb); } - public String getNormalizedCitationMarker(CitationMarkerEntry ce) { + public OOFormattedText getNormalizedCitationMarker(CitationMarkerEntry ce) { return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, ce, Optional.empty()); } @@ -1038,9 +1039,9 @@ public enum NonUniqueCitationMarker { * * @return The formatted citation. */ - public String getCitationMarker(List citationMarkerEntries, - boolean inParenthesis, - NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { + public OOFormattedText getCitationMarker(List citationMarkerEntries, + boolean inParenthesis, + NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { return OOBibStyleGetCitationMarker.getCitationMarker(this, citationMarkerEntries, inParenthesis, diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 61a929d5660..c173873d399 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -377,11 +377,11 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, * @return The formatted citation. * */ - private static String getAuthorYearParenthesisMarker(OOBibStyle style, - AuthorYearMarkerPurpose purpose, - List ces, - boolean[] startsNewGroup, - Optional maxAuthorsOverride) { + private static OOFormattedText getAuthorYearParenthesisMarker(OOBibStyle style, + AuthorYearMarkerPurpose purpose, + List ces, + boolean[] startsNewGroup, + Optional maxAuthorsOverride) { boolean inParenthesis = (purpose == AuthorYearMarkerPurpose.IN_PARENTHESIS || purpose == AuthorYearMarkerPurpose.NORMALIZED); @@ -483,10 +483,11 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, sb.append(uniqueLetter); } - String pageInfo = OOBibStyle.regularizePageInfo(ce.getPageInfo().orElse(null)); + OOFormattedText pageInfo = + OOBibStyle.regularizePageInfo(ce.getPageInfo().orElse(null)); if (pageInfo != null) { sb.append(pageInfoSeparator); - sb.append(pageInfo); + sb.append(OOFormattedText.toString(pageInfo)); } } @@ -500,7 +501,7 @@ private static String getAuthorYearParenthesisMarker(OOBibStyle style, sb.append(endBrace); } sb.append(style.getCitationGroupMarkupAfter()); - return sb.toString(); + return OOFormattedText.fromString(sb.toString()); } // "" is more convenient to compare for equality than null-or-String @@ -521,9 +522,9 @@ private static String nullToEmptyString(String s) { * * Note: now includes some markup. */ - public static String getNormalizedCitationMarker(OOBibStyle style, - CitationMarkerEntry ce, - Optional maxAuthorsOverride) { + public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, + CitationMarkerEntry ce, + Optional maxAuthorsOverride) { boolean[] startsNewGroup = {true}; return getAuthorYearParenthesisMarker(style, AuthorYearMarkerPurpose.NORMALIZED, @@ -561,7 +562,7 @@ public static String getNormalizedCitationMarker(OOBibStyle style, * Note: only consecutive citations are checked. * */ - public static String + public static OOFormattedText getCitationMarker(OOBibStyle style, List citationMarkerEntries, boolean inParenthesis, @@ -584,11 +585,11 @@ public static String getNormalizedCitationMarker(OOBibStyle style, // We also assume, that identical entries have the same uniqueLetters. // - List normalizedMarkers = new ArrayList<>(nEntries); + List normalizedMarkers = new ArrayList<>(nEntries); for (CitationMarkerEntry citationMarkerEntry : citationMarkerEntries) { - String nm = getNormalizedCitationMarker(style, - citationMarkerEntry, - Optional.empty()); + OOFormattedText nm = getNormalizedCitationMarker(style, + citationMarkerEntry, + Optional.empty()); normalizedMarkers.add(nm); } @@ -616,8 +617,8 @@ public static String getNormalizedCitationMarker(OOBibStyle style, for (int i = 1; i < nEntries; i++) { CitationMarkerEntry ce1 = citationMarkerEntries.get(i - 1); CitationMarkerEntry ce2 = citationMarkerEntries.get(i); - String nm1 = normalizedMarkers.get(i - 1); - String nm2 = normalizedMarkers.get(i); + String nm1 = OOFormattedText.toString(normalizedMarkers.get(i - 1)); + String nm2 = OOFormattedText.toString(normalizedMarkers.get(i)); BibEntry bibEntry1 = ce1.getBibEntry().orElse(null); BibEntry bibEntry2 = ce2.getBibEntry().orElse(null); @@ -667,17 +668,21 @@ public static String getNormalizedCitationMarker(OOBibStyle style, } else { // prevShown >= need // Check with extended normalizedMarkers. - String nmx1 = getNormalizedCitationMarker(style, ce1, Optional.of(prevShown)); - String nmx2 = getNormalizedCitationMarker(style, ce2, Optional.of(prevShown)); + OOFormattedText fnmx1 = + getNormalizedCitationMarker(style, ce1, Optional.of(prevShown)); + String nmx1 = OOFormattedText.toString(fnmx1); + OOFormattedText fnmx2 = + getNormalizedCitationMarker(style, ce2, Optional.of(prevShown)); + String nmx2 = OOFormattedText.toString(fnmx2); firstAppearanceInhibitsJoin = !nmx2.equals(nmx1); } } } - String pi2 = - nullToEmptyString(OOBibStyle.regularizePageInfo(ce2.getPageInfo().orElse(null))); - String pi1 = - nullToEmptyString(OOBibStyle.regularizePageInfo(ce1.getPageInfo().orElse(null))); + OOFormattedText fpi2 = OOBibStyle.regularizePageInfo(ce2.getPageInfo().orElse(null)); + OOFormattedText fpi1 = OOBibStyle.regularizePageInfo(ce1.getPageInfo().orElse(null)); + String pi2 = nullToEmptyString(OOFormattedText.toString(fpi2)); + String pi1 = nullToEmptyString(OOFormattedText.toString(fpi1)); String ul2 = ce2.getUniqueLetter().orElse(null); String ul1 = ce1.getUniqueLetter().orElse(null); diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index bb25875dbca..120a1653a0a 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -13,8 +13,8 @@ class OOBibStyleGetNumCitationMarker { */ private static class NumberWithPageInfo { int num; - String pageInfo; - NumberWithPageInfo(int num, String pageInfo) { + OOFormattedText pageInfo; + NumberWithPageInfo(int num, OOFormattedText pageInfo) { this.num = num; this.pageInfo = pageInfo; } @@ -43,10 +43,10 @@ private enum CitationMarkerPurpose { /** * See {@see getNumCitationMarkerCommon} for details. */ - public static String getNumCitationMarker(OOBibStyle style, - List numbers, - int minGroupingCount, - List pageInfosForCitations) { + public static OOFormattedText getNumCitationMarker(OOBibStyle style, + List numbers, + int minGroupingCount, + List pageInfosForCitations) { return getNumCitationMarkerCommon(style, numbers, minGroupingCount, @@ -67,8 +67,8 @@ public static String getNumCitationMarker(OOBibStyle style, * "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER) * "${number}" stands for the formatted number. */ - public static String getNumCitationMarkerForBibliography(OOBibStyle style, - int number) { + public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle style, + int number) { return getNumCitationMarkerCommon(style, Collections.singletonList(number), 0, @@ -116,11 +116,12 @@ public static String getNumCitationMarkerForBibliography(OOBibStyle style, * @return The text for the citation. * */ - private static String getNumCitationMarkerCommon(OOBibStyle style, - List numbers, - int minGroupingCount, - CitationMarkerPurpose purpose, - List pageInfosForCitations) { + private static OOFormattedText + getNumCitationMarkerCommon(OOBibStyle style, + List numbers, + int minGroupingCount, + CitationMarkerPurpose purpose, + List pageInfosForCitations) { final boolean joinIsDisabled = (minGroupingCount <= 0); final int notFoundInDatabases = 0; @@ -166,7 +167,7 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, : OOBibStyle.UNDEFINED_CITATION_MARKER); sb.append(bracketAfter); sb.append(style.getCitationGroupMarkupAfter()); - return sb.toString(); + return OOFormattedText.fromString(sb.toString()); } } @@ -179,7 +180,7 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, * get here, and {@code purpose==BIBLIOGRAPHY}, then we just fill * pageInfos with null values. */ - List pageInfos = + List pageInfos = OOBibStyle.regularizePageInfosForCitations((purpose == CitationMarkerPurpose.BIBLIOGRAPHY ? null : pageInfosForCitations), @@ -244,9 +245,9 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, ? OOBibStyle.UNDEFINED_CITATION_MARKER : String.valueOf(num)); // Emit pageInfo - String pageInfo = block.get(0).pageInfo; + OOFormattedText pageInfo = block.get(0).pageInfo; if (pageInfo != null) { - sb.append(style.getPageInfoSeparator() + pageInfo); + sb.append(style.getPageInfoSeparator() + OOFormattedText.toString(pageInfo)); } } else { // block has at least 2 elements @@ -379,7 +380,7 @@ private static String getNumCitationMarkerCommon(OOBibStyle style, // Emit: "]" sb.append(bracketAfter); - return sb.toString(); + return OOFormattedText.fromString(sb.toString()); } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java new file mode 100644 index 00000000000..8eb73f36b93 --- /dev/null +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -0,0 +1,52 @@ +package org.jabref.logic.oostyle; + +import java.util.Optional; + +import org.jabref.logic.layout.Layout; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; +import org.jabref.model.entry.field.UnknownField; + +public class OOFormat { + private static final Field UNIQUEFIER_FIELD = new UnknownField("uniq"); + /** + * Format the reference part of a bibliography entry using a Layout. + * + * @param layout The Layout to format the reference with. + * @param entry The entry to insert. + * @param database The database the entry belongs to. + * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. + * + * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation() + * + * TODO: this is not OO-specific, should be in oostyle + */ + public static OOFormattedText formatFullReference(Layout layout, + BibEntry entry, + BibDatabase database, + String uniquefier) { + + // Backup the value of the uniq field, just in case the entry already has it: + Optional oldUniqVal = entry.getField(UNIQUEFIER_FIELD); + + // Set the uniq field with the supplied uniquefier: + if (uniquefier == null) { + entry.clearField(UNIQUEFIER_FIELD); + } else { + entry.setField(UNIQUEFIER_FIELD, uniquefier); + } + + // Do the layout for this entry: + OOFormattedText formattedText = OOFormattedText.fromString(layout.doLayout(entry, database)); + + // Afterwards, reset the old value: + if (oldUniqVal.isPresent()) { + entry.setField(UNIQUEFIER_FIELD, oldUniqVal.get()); + } else { + entry.clearField(UNIQUEFIER_FIELD); + } + + return formattedText; + } +} diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormattedText.java b/src/main/java/org/jabref/logic/oostyle/OOFormattedText.java new file mode 100644 index 00000000000..84f9075f478 --- /dev/null +++ b/src/main/java/org/jabref/logic/oostyle/OOFormattedText.java @@ -0,0 +1,28 @@ +package org.jabref.logic.oostyle; + +public class OOFormattedText { + + private final String data; + + private OOFormattedText(String data) { + this.data = data; + } + + public static OOFormattedText fromString(String s) { + if (s == null) { + return null; + } + return new OOFormattedText(s); + } + + public static String toString(OOFormattedText s) { + if (s == null) { + return null; + } + return s.data; + } + + public String asString() { + return data; + } +} diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 85bb02b4233..33f17f2e028 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -81,10 +81,10 @@ private static Comparator comparatorForMulticite(OOBibStyle style) { * * **************************************/ - private static String normalizedCitationMarkerForNormalStyle(CitedKey ck, - OOBibStyle style) { + private static OOFormattedText normalizedCitationMarkerForNormalStyle(CitedKey ck, + OOBibStyle style) { if (ck.db.isEmpty()) { - return String.format("(Unresolved(%s))", ck.citationKey); + return OOFormattedText.fromString(String.format("(Unresolved(%s))", ck.citationKey)); } // We need "normalized" (in parenthesis) markers // for uniqueness checking purposes: @@ -137,7 +137,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, // Map> ncm2clks = new HashMap<>(); for (CitedKey ck : sortedCitedKeys.values()) { - String ncm = ck.normCitMarker.get(); + String ncm = OOFormattedText.toString(ck.normCitMarker.get()); String citationKey = ck.citationKey; if (!ncm2clks.containsKey(ncm)) { @@ -205,7 +205,7 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi * Produce citation markers for the case when the citation * markers are the citation keys themselves, separated by commas. */ - private static Map + private static Map produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroups cgs, OOBibStyle style) { @@ -213,7 +213,7 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { List cits = cgs.getSortedCitations(cgid); @@ -223,7 +223,7 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi .map(cit -> cit.citationKey) .collect(Collectors.joining(","))) + style.getCitationGroupMarkupAfter(); - citMarkers.put(cgid, citMarker); + citMarkers.put(cgid, OOFormattedText.fromString(citMarker)); } return citMarkers; } @@ -240,7 +240,7 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi * Assumes global order and local order ae already applied. * */ - private static Map + private static Map produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, OOBibStyle style) { @@ -251,12 +251,12 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi final int minGroupingCount = style.getMinimumGroupingCount(); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); - List pageInfos = cgs.getPageInfosForCitations(cg); + List pageInfos = cgs.getPageInfosForCitations(cg); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, @@ -270,7 +270,7 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi * Produce citation markers for the case of numbered citations * when the bibliography is not sorted by position. */ - private static Map + private static Map produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, OOBibStyle style) { assert style.isNumberEntries(); @@ -280,12 +280,12 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi final int minGroupingCount = style.getMinimumGroupingCount(); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getSortedNumbers(); - List pageInfos = cgs.getPageInfosForCitations(cg); + List pageInfos = cgs.getPageInfosForCitations(cg); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, @@ -301,7 +301,7 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi * @param cgs * @param style Bibliography style. */ - private static Map + private static Map produceCitationMarkersForNormalStyle(CitationGroups cgs, OOBibStyle style) { @@ -321,13 +321,13 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi Set seenBefore = new HashSet<>(); - Map citMarkers = new HashMap<>(); + Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List cits = cg.getSortedCitations(); final int nCitedEntries = cits.size(); - List pageInfosForCitations = cgs.getPageInfosForCitations(cg); + List pageInfosForCitations = cgs.getPageInfosForCitations(cg); List citationMarkerEntries = new ArrayList<>(nCitedEntries); @@ -379,14 +379,15 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi s = s + String.format("(Unresolved(%s))", cm.getCitationKey()); } } - citMarkers.put(cgid, s); + citMarkers.put(cgid, OOFormattedText.fromString(s)); } else { /* * All entries are resolved. */ - String citMarker = style.getCitationMarker(citationMarkerEntries, - cg.itcType == OOProcess.AUTHORYEAR_PAR, - OOBibStyle.NonUniqueCitationMarker.THROWS); + OOFormattedText citMarker = + style.getCitationMarker(citationMarkerEntries, + cg.itcType == OOProcess.AUTHORYEAR_PAR, + OOBibStyle.NonUniqueCitationMarker.THROWS); citMarkers.put(cgid, citMarker); } } @@ -402,10 +403,10 @@ public static class ProduceCitationMarkersResult { public CitationGroups cgs; /** citation markers */ - public Map citMarkers; + public Map citMarkers; ProduceCitationMarkersResult(CitationGroups cgs, - Map citMarkers) { + Map citMarkers) { this.cgs = cgs; this.citMarkers = citMarkers; if (cgs.getBibliography().isEmpty()) { @@ -447,7 +448,7 @@ public static ProduceCitationMarkersResult produceCitationMarkers(CitationGroups // requires cgs.lookupEntryInDatabases: needs BibEntry data cgs.imposeLocalOrderByComparator(comparatorForMulticite(style)); - Map citMarkers; + Map citMarkers; // fill citMarkers Map uniqueLetters = new HashMap<>(); diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 1846fa66289..8c1f5f2621c 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -13,6 +13,7 @@ import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.Compat; +import org.jabref.logic.oostyle.OOFormattedText; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -113,7 +114,8 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc .map(Citation::new) .collect(Collectors.toList())); - Optional pageInfo = documentConnection.getCustomProperty(refMarkName); + Optional pageInfo = (documentConnection.getCustomProperty(refMarkName) + .map(OOFormattedText::fromString)); Optional sr = (citationStorageManager .getFromDocument(documentConnection, refMarkName)); @@ -180,7 +182,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc */ public CitationGroup createCitationGroup(DocumentConnection documentConnection, List citationKeys, - List pageInfosForCitations, + List pageInfosForCitations, int itcType, XTextCursor position, boolean insertSpaceAfter, @@ -223,9 +225,10 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, switch (dataModel) { case JabRef52: - Optional pageInfo = Compat.getJabRef52PageInfoFromList(pageInfosForCitations); - if (pageInfo.isPresent() && !pageInfo.get().equals("")) { - documentConnection.setCustomProperty(refMarkName, pageInfo.get()); + Optional pageInfo = Compat.getJabRef52PageInfoFromList(pageInfosForCitations); + if (pageInfo.isPresent() && !"".equals(OOFormattedText.toString(pageInfo.get()))) { + documentConnection.setCustomProperty(refMarkName, + OOFormattedText.toString(pageInfo.get())); } else { // do not inherit from trash documentConnection.removeCustomProperty(refMarkName); @@ -244,7 +247,7 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, /** * */ - public List combinePageInfos(List joinableGroup) { + public List combinePageInfos(List joinableGroup) { return Compat.combinePageInfos(this.dataModel, joinableGroup); } @@ -336,7 +339,8 @@ public List getCitationEntries(DocumentConnection documentConnect cursor, 30, 30, true); CitationEntry entry = new CitationEntry(name, context, - cgs.getPageInfo(cgid)); + (cgs.getPageInfo(cgid) + .map(e -> OOFormattedText.toString(e)))); citations.add(entry); } return citations; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index dfabbd407f6..3768e039b08 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -15,6 +15,7 @@ import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.Compat; +import org.jabref.logic.oostyle.OOFormattedText; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -307,7 +308,7 @@ private List getVisuallySortedCitationGroupIDs(DocumentConnecti */ public CitationGroupID createCitationGroup(DocumentConnection documentConnection, List citationKeys, - List pageInfosForCitations, + List pageInfosForCitations, int itcType, XTextCursor position, boolean insertSpaceAfter, diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 658e45e86d4..4cbdec0caa5 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -2,16 +2,11 @@ import java.util.ArrayList; import java.util.List; -import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.logic.layout.Layout; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.Field; -import org.jabref.model.entry.field.UnknownField; +import org.jabref.logic.oostyle.OOFormattedText; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; @@ -54,70 +49,30 @@ public enum Formatting { private static final Pattern HTML_TAG = Pattern.compile(""); - private static final Field UNIQUEFIER_FIELD = new UnknownField("uniq"); - private OOUtil() { // Just to hide the public constructor } - /** - * Format the reference part of a bibliography entry using a Layout. - * - * @param layout The Layout to format the reference with. - * @param entry The entry to insert. - * @param database The database the entry belongs to. - * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. - * - * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation() - * - * TODO: this is not OO-specific, should be in oostyle - */ - public static String formatFullReference(Layout layout, - BibEntry entry, - BibDatabase database, - String uniquefier) { - - // Backup the value of the uniq field, just in case the entry already has it: - Optional oldUniqVal = entry.getField(UNIQUEFIER_FIELD); - - // Set the uniq field with the supplied uniquefier: - if (uniquefier == null) { - entry.clearField(UNIQUEFIER_FIELD); - } else { - entry.setField(UNIQUEFIER_FIELD, uniquefier); - } - - // Do the layout for this entry: - String formattedText = layout.doLayout(entry, database); - - // Afterwards, reset the old value: - if (oldUniqVal.isPresent()) { - entry.setField(UNIQUEFIER_FIELD, oldUniqVal.get()); - } else { - entry.clearField(UNIQUEFIER_FIELD); - } - - return formattedText; - } - /** * Insert a text with formatting indicated by HTML-like tags, into a text at the position given by a cursor. * * @param position The cursor giving the insert location. Not modified. - * @param lText The marked-up text to insert. + * @param ootext The marked-up text to insert. * @throws WrappedTargetException * @throws PropertyVetoException * @throws UnknownPropertyException * @throws IllegalArgumentException */ public static void insertOOFormattedTextAtCurrentLocation(XTextCursor position, - String lText) + OOFormattedText ootext) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException { + String lText = OOFormattedText.toString(ootext); + XText text = position.getText(); XTextCursor cursor = text.createTextCursorByRange(position); diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index b0b2f0c1c0d..908e282062a 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import org.jabref.logic.layout.Layout; import org.jabref.logic.layout.LayoutFormatterPreferences; @@ -80,12 +81,18 @@ void testNumerical() throws IOException { assertTrue(style.isSortByPosition()); } + List asOOFormattedText(List s) { + return (s.stream() + .map(OOFormattedText::fromString) + .collect(Collectors.toList())); + } + @Test void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - List empty = null; + List empty = null; // Unfortunately these two are both "; " in // jabref/src/main/resources/resource/openoffice/default_numerical.jstyle @@ -99,64 +106,68 @@ void testGetNumCitationMarker() throws IOException { assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, - empty)); + empty).asString()); // Identical numeric entries are joined. assertEquals("[1; 2]", style.getNumCitationMarker(Arrays.asList(1,2,1,2), 3, - empty)); + empty).asString()); // ... unless minGroupingCount <= 0 assertEquals("[1; 1; 2; 2]", style.getNumCitationMarker(Arrays.asList(1,2,1,2), 0, - empty)); + empty).asString()); // ... or have different pageInfos assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", style.getNumCitationMarker(Arrays.asList(1,1,2,2,3,3), - 1, - Arrays.asList("p1a","p1b","p2","p2",null,null))); + 1, + asOOFormattedText(Arrays.asList("p1a","p1b","p2","p2", + null, null))).asString()); // Consecutive numbers can become a range ... assertEquals("[1-3]", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, /* minGroupingCount */ - empty)); + empty).asString()); // ... unless minGroupingCount is too high assertEquals("[1; 2; 3]", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 4, /* minGroupingCount */ - empty)); + empty).asString()); // ... or if minGroupingCount <= 0 assertEquals("[1; 2; 3]", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 0, /* minGroupingCount */ - empty)); + empty).asString()); // ... a pageInfo needs to be emitted assertEquals("[1; p1; 2-3]", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, /* minGroupingCount */ - Arrays.asList("p1",null,null))); + asOOFormattedText(Arrays.asList("p1",null,null))) + .asString()); // null and "" pageInfos are taken as equal. // Due to trimming, " " is the same as well. assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ - Arrays.asList("",null," "))); + asOOFormattedText(Arrays.asList("",null," "))) + .asString()); // pageInfos are trimmed assertEquals("[1; p1]", style.getNumCitationMarker(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ - Arrays.asList("p1"," p1","p1 "))); + asOOFormattedText(Arrays.asList("p1"," p1","p1 "))) + .asString()); // The citation numbers come out sorted assertEquals("[3-5; 7; 10-12]", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, - empty)); + empty).asString()); // pageInfos are sorted together with the numbers // (but they inhibit ranges where they are, even if they are identical, @@ -164,42 +175,45 @@ void testGetNumCitationMarker() throws IOException { assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, - Arrays.asList("px", "p7", "p3", "p4", - "px", "px", "p5"))); + asOOFormattedText(Arrays.asList("px", "p7", "p3", "p4", + "px", "px", "p5"))) + .asString()); // pageInfo sorting (for the same number) assertEquals("[1; 1; a; 1; b]", style.getNumCitationMarker(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ - Arrays.asList("","b","a "))); + asOOFormattedText(Arrays.asList("","b","a "))) + .asString()); // pageInfo sorting (for the same number) is not numeric. assertEquals("[1; p100; 1; p20; 1; p9]", style.getNumCitationMarker(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ - Arrays.asList("p20","p9","p100"))); + asOOFormattedText(Arrays.asList("p20","p9","p100"))) + .asString()); assertEquals("[1-3]", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, /* minGroupingCount */ - empty)); + empty).asString()); assertEquals("[1; 2; 3]", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, - empty)); + empty).asString()); assertEquals("[1; 2; 3]", style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, - empty)); + empty).asString()); assertEquals("[1; 3; 12]", style.getNumCitationMarker(Arrays.asList(1, 12, 3), 1, - empty)); + empty).asString()); assertEquals("[3-5; 7; 10-12]", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, - empty)); + empty).asString()); /* * BIBLIOGRAPHY : I think * style.getNumCitationMarkerForBibliography(int num); @@ -208,7 +222,7 @@ void testGetNumCitationMarker() throws IOException { * Nor do we need pageInfo in the bibliography. */ assertEquals("[1] ", - style.getNumCitationMarkerForBibliography(1)); + style.getNumCitationMarkerForBibliography(1).asString()); } @@ -217,30 +231,30 @@ void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - List empty = null; + List empty = null; // unresolved citations look like [??] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", style.getNumCitationMarker(Arrays.asList(0), 1, - empty)); + empty).asString()); // pageInfo is shown for unresolved citations assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; p1]", style.getNumCitationMarker(Arrays.asList(0), 1, - Arrays.asList("p1"))); + asOOFormattedText(Arrays.asList("p1"))).asString()); // unresolved citations sorted to the front assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4]", style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, - empty)); + empty).asString()); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3]", style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, - empty)); + empty).asString()); // multiple unresolved citations are not collapsed assertEquals("[" @@ -249,13 +263,13 @@ void testGetNumCitationMarkerUndefined() throws IOException { + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, - empty)); + empty).asString()); /* * BIBLIOGRAPHY */ assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarkerForBibliography(0)); + style.getNumCitationMarkerForBibliography(0).asString()); } @@ -626,7 +640,7 @@ void testInstitutionAuthorMarker() throws IOException { assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -651,7 +665,7 @@ void testVonAuthorMarker() throws IOException { assertEquals("[von Beta, 2016]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -674,7 +688,7 @@ void testNullAuthorMarker() throws IOException { assertEquals("[, 2016]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -697,7 +711,7 @@ void testNullYearMarker() throws IOException { assertEquals("[von Beta, ]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -718,7 +732,8 @@ void testEmptyEntryMarker() throws IOException { assertEquals("[, ]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS) + .asString()); } @Test @@ -782,12 +797,12 @@ void testGetCitationMarkerUniquefiers() throws IOException { assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", style.getCitationMarker(citationMarkerEntriesA, true, - OOBibStyle.NonUniqueCitationMarker.FORGIVEN)); + OOBibStyle.NonUniqueCitationMarker.FORGIVEN).asString()); assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", style.getCitationMarker(citationMarkerEntriesA, false, - OOBibStyle.NonUniqueCitationMarker.FORGIVEN)); + OOBibStyle.NonUniqueCitationMarker.FORGIVEN).asString()); // With uniquefiers @@ -804,12 +819,12 @@ void testGetCitationMarkerUniquefiers() throws IOException { assertEquals("[Beta, 2000a,b; Epsilon, 2001]", style.getCitationMarker(citationMarkerEntriesB, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); assertEquals("Beta [2000a,b]; Epsilon [2001]", style.getCitationMarker(citationMarkerEntriesB, false, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } @@ -853,12 +868,12 @@ void testGetCitationMarkerUniquefiersThreeSameAuthor() throws IOException { assertEquals("[Beta, 2000a,b,c]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); assertEquals("Beta [2000a,b,c]", style.getCitationMarker(citationMarkerEntries, false, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -921,7 +936,7 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { assertEquals("von Beta, Epsilon, & Tau, 2016", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } @Test From ccf648641cfdd237718948736bdb38ecbf86c7ce Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 26 Apr 2021 22:40:14 +0200 Subject: [PATCH 0642/1068] insertOOFormattedTextAtCurrentLocation can do font,p,locale ,

, --- .../org/jabref/gui/openoffice/OOBibBase.java | 86 +++++++---- .../org/jabref/logic/oostyle/OOFormat.java | 30 +++- .../logic/openoffice/DocumentConnection.java | 17 +++ .../org/jabref/logic/openoffice/OOUtil.java | 143 ++++++++++++++++-- .../jabref/logic/oostyle/OOBibStyleTest.java | 22 +-- 5 files changed, 244 insertions(+), 54 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 166d60c009c..ddd936d7557 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -420,7 +420,8 @@ public void applyCitationEntries(List citationEntries) fr.applyCitationEntries(documentConnection, citationEntries); } - private static void fillCitationMarkInCursor(XTextCursor cursor, + private static void fillCitationMarkInCursor(DocumentConnection documentConnection, + XTextCursor cursor, OOFormattedText citationText, boolean withText, OOBibStyle style) @@ -429,19 +430,27 @@ private static void fillCitationMarkInCursor(XTextCursor cursor, WrappedTargetException, PropertyVetoException, IllegalArgumentException, - UndefinedCharacterFormatException { + UndefinedCharacterFormatException, + NoSuchElementException { Objects.requireNonNull(cursor); Objects.requireNonNull(citationText); Objects.requireNonNull(style); if (withText) { - OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, citationText); + OOFormattedText citationText2 = OOFormat.setLocaleNone(citationText); + if (style.isFormatCitations()) { + String charStyle = style.getCitationCharacterFormat(); + citationText2 = OOFormat.setCharStyle(citationText2, charStyle); + } + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, citationText2); + /* DocumentConnection.setCharLocaleNone(cursor); if (style.isFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); DocumentConnection.setCharStyle(cursor, charStyle); } + */ } else { cursor.setString(""); } @@ -489,7 +498,8 @@ private void createAndFillCitationGroup(OOFrontend fr, UndefinedCharacterFormatException, CreationException, NoDocumentException, - IllegalTypeException { + IllegalTypeException, + NoSuchElementException { CitationGroupID cgid = fr.createCitationGroup(documentConnection, citationKeys, @@ -503,7 +513,8 @@ private void createAndFillCitationGroup(OOFrontend fr, XTextCursor c2 = fr.getFillCursorForCitationGroup(documentConnection, cgid); - fillCitationMarkInCursor(c2, + fillCitationMarkInCursor(documentConnection, + c2, citationText, withText, style); @@ -838,7 +849,8 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, UnknownPropertyException, CreationException, WrappedTargetException, - PropertyVetoException { + PropertyVetoException, + NoSuchElementException { CitationGroups cgs = fr.cgs; final boolean hadBibSection = (documentConnection @@ -875,7 +887,8 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, mustTestCharFormat = false; } - fillCitationMarkInCursor(cursor, + fillCitationMarkInCursor(documentConnection, + cursor, citationText, withText, style); @@ -949,7 +962,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, UnknownPropertyException, PropertyVetoException, WrappedTargetException, - CreationException { + CreationException, + NoSuchElementException { final boolean debugThisFun = false; @@ -972,19 +986,20 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // this is where we create the paragraph. OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - // format the paragraph - try { - if (parStyle != null) { - DocumentConnection.setParagraphStyle(cursor, - parStyle); - } - } catch (UndefinedParagraphFormatException ex) { - // TODO: precheck or remember if we already emitted this message. - String message = - String.format("Could not apply paragraph format '%s' to bibliography entry", - parStyle); - LOGGER.warn(message); // no stack trace + cursor.collapseToEnd(); + // format the paragraph + try { + if (parStyle != null) { + DocumentConnection.setParagraphStyle(cursor, + parStyle); } + } catch (UndefinedParagraphFormatException ex) { + // TODO: precheck or remember if we already emitted this message. + String message = + String.format("Could not apply paragraph format '%s' to bibliography entry", + parStyle); + LOGGER.warn(message); // no stack trace + } // insert marker "[1]" if (style.isNumberEntries()) { @@ -996,7 +1011,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, int number = ck.number.get(); OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); - OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, marker); + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, marker); cursor.collapseToEnd(); } else { // !style.isNumberEntries() : emit no prefix @@ -1007,16 +1022,20 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // Unresolved entry OOFormattedText referenceDetails = OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); - OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, referenceDetails); + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, + cursor, + referenceDetails); cursor.collapseToEnd(); // Try to list citations: if (true) { String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); String suffix = ")"; - OOUtil.insertTextAtCurrentLocation(documentConnection.xText, + OOUtil.insertTextAtCurrentLocation(documentConnection, cursor, prefix, - Collections.emptyList()); + Collections.emptyList(), + Optional.empty(), + Optional.empty()); int last = ck.where.size(); int i = 0; @@ -1025,10 +1044,12 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); if (i > 0) { - OOUtil.insertTextAtCurrentLocation(documentConnection.xText, + OOUtil.insertTextAtCurrentLocation(documentConnection, cursor, String.format(", "), - Collections.emptyList()); + Collections.emptyList(), + Optional.empty(), + Optional.empty()); } documentConnection .insertGetreferenceToPageNumberOfReferenceMark(cg.getMarkName(), cursor); @@ -1036,10 +1057,12 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, } documentConnection.refresh(); - OOUtil.insertTextAtCurrentLocation(documentConnection.xText, + OOUtil.insertTextAtCurrentLocation(documentConnection, cursor, suffix, - Collections.emptyList()); + Collections.emptyList(), + Optional.empty(), + Optional.empty()); } } else { @@ -1056,7 +1079,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, ck.uniqueLetter.orElse(null)); // Insert the formatted text: - OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, formattedText); + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, formattedText); cursor.collapseToEnd(); } } @@ -1078,6 +1101,7 @@ private void createBibTextSection2(DocumentConnection documentConnection) textCursor.gotoEnd(false); OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); + textCursor.collapseToEnd(); documentConnection.insertTextSection(OOBibBase.BIB_SECTION_NAME, textCursor, @@ -1152,7 +1176,9 @@ private void populateBibTextSection(DocumentConnection documentConnection, .createTextCursorByRange(section.getAnchor())); // emit the title of the bibliography - OOUtil.insertOOFormattedTextAtCurrentLocation(cursor, style.getReferenceHeaderText()); + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, + cursor, + style.getReferenceHeaderText()); String parStyle = style.getReferenceHeaderParagraphFormat(); try { if (parStyle != null) { diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index 8eb73f36b93..88d1d0554cd 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -49,4 +49,32 @@ public static OOFormattedText formatFullReference(Layout layout, return formattedText; } -} + + public static OOFormattedText setLocale(OOFormattedText s, String locale) { + return OOFormattedText.fromString(String.format("", locale) + + s.asString() + + ""); + } + + public static OOFormattedText setLocaleNone(OOFormattedText s) { + return OOFormat.setLocale(s, "zxx"); + } + + public static OOFormattedText setCharStyle(OOFormattedText s, String charStyle) { + return OOFormattedText.fromString(String.format("", charStyle) + + s.asString() + + ""); + } + + public static OOFormattedText paragraph(OOFormattedText s, String paraStyle) { + return OOFormattedText.fromString(String.format("

", paraStyle) + + s.asString() + + "

"); + } + + public static OOFormattedText paragraph(OOFormattedText s) { + return OOFormattedText.fromString("

" + + s.asString() + + "

"); + } + } diff --git a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java index a9cdaa2bc73..ba30c10740c 100644 --- a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java @@ -926,6 +926,15 @@ public static void setCharStyle(XTextCursor position, } } + public static String getCharStyle(XTextCursor position) + throws + UnknownPropertyException, + WrappedTargetException { + + XPropertySet xCursorProps = unoQI(XPropertySet.class, position); + return (String) xCursorProps.getPropertyValue(CHAR_STYLE_NAME); + } + public static void setParagraphStyle(XTextCursor cursor, String parStyle) throws @@ -986,6 +995,14 @@ public static void setCharLocaleNone(XTextRange textRange) xcp.setPropertyValue("CharLocale", new Locale("zxx", "", "")); } + public static Locale getCharLocale(XTextRange textRange) + throws + UnknownPropertyException, + WrappedTargetException { + XPropertySet xcp = unoQI(XPropertySet.class, textRange); + return (Locale) xcp.getPropertyValue("CharLocale"); + } + /** * Test if two XTextRange values are comparable (i.e. they share * the same getText()). diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 4cbdec0caa5..1d270d7392c 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -2,6 +2,8 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; +import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -11,6 +13,8 @@ import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertySet; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.ControlCharacter; import com.sun.star.text.XText; @@ -35,6 +39,7 @@ public class OOUtil { private static final String CHAR_WEIGHT = "CharWeight"; private static final String CHAR_ESCAPEMENT_HEIGHT = "CharEscapementHeight"; private static final String CHAR_ESCAPEMENT = "CharEscapement"; + private static final String CHAR_STYLE_NAME = "CharStyleName"; public enum Formatting { BOLD, @@ -47,7 +52,8 @@ public enum Formatting { MONOSPACE } - private static final Pattern HTML_TAG = Pattern.compile(""); + private static final Pattern HTML_TAG = + Pattern.compile("|<(p|font|locale)\\s+(class|value)=\"([^\"]+)\">"); private OOUtil() { // Just to hide the public constructor @@ -63,13 +69,15 @@ private OOUtil() { * @throws UnknownPropertyException * @throws IllegalArgumentException */ - public static void insertOOFormattedTextAtCurrentLocation(XTextCursor position, + public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection documentConnection, + XTextCursor position, OOFormattedText ootext) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, - IllegalArgumentException { + IllegalArgumentException, + NoSuchElementException { String lText = OOFormattedText.toString(ootext); @@ -77,15 +85,28 @@ public static void insertOOFormattedTextAtCurrentLocation(XTextCursor position, XTextCursor cursor = text.createTextCursorByRange(position); List formatting = new ArrayList<>(); + Stack charstyleStack = new Stack<>(); + Stack localeStack = new Stack<>(); + charstyleStack.push(DocumentConnection.getCharStyle(cursor)); + localeStack.push(DocumentConnection.getCharLocale(cursor)); + // We need to extract formatting. Use a simple regexp search iteration: int piv = 0; Matcher m = OOUtil.HTML_TAG.matcher(lText); while (m.find()) { String currentSubstring = lText.substring(piv, m.start()); if (!currentSubstring.isEmpty()) { - OOUtil.insertTextAtCurrentLocation(text, cursor, currentSubstring, formatting); + OOUtil.insertTextAtCurrentLocation(documentConnection, + cursor, + currentSubstring, + formatting, + Optional.of(charstyleStack.peek()), + Optional.of(localeStack.peek())); } String tag = m.group(); + String xtag = m.group(1); + String xvar = m.group(2); + String xval = m.group(3); // Handle tags: if ("".equals(tag)) { formatting.add(Formatting.BOLD); @@ -119,31 +140,102 @@ public static void insertOOFormattedTextAtCurrentLocation(XTextCursor position, formatting.add(Formatting.STRIKEOUT); } else if ("".equals(tag)) { formatting.remove(Formatting.STRIKEOUT); + } else if ("

".equals(tag)) { + // nop + } else if ("p".equals(xtag) || "

".equals(tag)) { + //

+ OOUtil.insertParagraphBreak(text, cursor); + cursor.collapseToEnd(); + if ("class".equals(xvar) && xval != null && !xval.equals("")) { + try { + DocumentConnection.setParagraphStyle(cursor, xval); + } catch (UndefinedParagraphFormatException ex) { + // ignore silently + } + } + } else if ("font".equals(xtag) || "".equals(tag)) { + // + if ("class".equals(xvar) && xval != null && !xval.equals("")) { + charstyleStack.push(xval); + } else { + charstyleStack.push(""); + } + } else if ("".equals(tag)) { + charstyleStack.pop(); + } else if ("locale".equals(xtag)) { + // + // + if ("value".equals(xvar) && xval != null && !xval.equals("")) { + String[] parts = xval.split("-"); + String language = (parts.length > 0) ? parts[0] : ""; + String country = (parts.length > 1) ? parts[1] : ""; + String variant = (parts.length > 2) ? parts[2] : ""; + Locale l = new Locale(language, country, variant); + localeStack.push(l); + } else { + localeStack.push(localeStack.peek()); + } + } else if ("".equals(tag)) { + localeStack.pop(); } piv = m.end(); } if (piv < lText.length()) { - OOUtil.insertTextAtCurrentLocation(text, cursor, lText.substring(piv), formatting); + OOUtil.insertTextAtCurrentLocation(documentConnection, + cursor, + lText.substring(piv), + formatting, + Optional.of(charstyleStack.peek()), + Optional.of(localeStack.peek())); } - } public static void insertParagraphBreak(XText text, XTextCursor cursor) throws IllegalArgumentException { text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); - cursor.collapseToEnd(); } - public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, String string, - List formatting) - throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, - IllegalArgumentException { + public static void insertTextAtCurrentLocation(DocumentConnection documentConnection, + XTextCursor cursor, + String string, + List formatting, + Optional charStyle, + Optional locale) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + XText text = cursor.getText(); text.insertString(cursor, string, true); + formatTextInCursor(documentConnection, + cursor, + formatting, + charStyle, + locale); + + cursor.collapseToEnd(); + } + + public static void formatTextInCursor(DocumentConnection documentConnection, + XTextCursor cursor, + List formatting, + Optional charStyle, + Optional locale) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + // Access the property set of the cursor, and set the currently selected text // (which is the string we just inserted) to be bold XPropertySet xCursorProps = UnoRuntime.queryInterface( XPropertySet.class, cursor); + if (formatting.contains(Formatting.BOLD)) { xCursorProps.setPropertyValue(CHAR_WEIGHT, com.sun.star.awt.FontWeight.BOLD); @@ -178,6 +270,7 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S xCursorProps.setPropertyValue("CharFontPitch", com.sun.star.awt.FontPitch.VARIABLE); } */ + if (formatting.contains(Formatting.SUBSCRIPT)) { xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (short) -10); @@ -206,7 +299,33 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S } else { xCursorProps.setPropertyValue(CHAR_STRIKEOUT, com.sun.star.awt.FontStrikeout.NONE); } - cursor.collapseToEnd(); + + if (locale.isPresent()) { + try { + xCursorProps.setPropertyValue("CharLocale", locale.get()); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + // silently + } + } + + if (charStyle.isPresent() && !charStyle.get().equals("")) { + if (documentConnection + .getInternalNameOfCharacterStyle(charStyle.get()).isPresent()) { + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle.get()); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + // silently + } + } + // otherwise: ignore silently. Assume character style was already tested elsewhere. + } + } /** diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 908e282062a..533a21463aa 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -314,12 +314,12 @@ void testGetCitationMarker() throws IOException { assertEquals("[Boström et al., 2006]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); assertEquals("Boström et al. [2006]", style.getCitationMarker(citationMarkerEntries, false, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); /* * Currently there is no way override for getMaxAuthors(), except @@ -332,7 +332,7 @@ void testGetCitationMarker() throws IOException { assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -409,13 +409,13 @@ void testGetCitationMarkerJoinFirst() throws IOException { +"; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); assertEquals("Boström, Wäyrynen, Bodén, Beznosov & Kruchten [2006a,b]" + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten [2006c]", style.getCitationMarker(citationMarkerEntries, false, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the first is isFirstAppearanceOfSource. @@ -437,7 +437,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { +"; Boström et al., 2006c]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the second is isFirstAppearanceOfSource. @@ -461,7 +461,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström et al., 2006c]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the neither is isFirstAppearanceOfSource. @@ -483,7 +483,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a,b,c]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: different entries with identical non-null pageInfo: not joined. @@ -505,7 +505,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström et al., 2006c; p1]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: same entries with identical non-null pageInfo: collapsed. @@ -526,7 +526,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a; p1]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: same entries with different pageInfo: kept separate. // Empty ("") and null pageInfos considered equal her, collapsed. @@ -550,7 +550,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström et al., 2006a]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); } } From f361b194a8513dac795704a4426bf125c4280eab Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 27 Apr 2021 14:47:20 +0200 Subject: [PATCH 0643/1068] reimplement insertOOFormattedTextAtCurrentLocation Now uses a stack of effects: needed because character style and direct formatting is not orthogonal (order of application matters) insertTextAtCurrentLocation now does not apply any formatting --- .../org/jabref/gui/openoffice/OOBibBase.java | 22 +- .../org/jabref/logic/openoffice/OOUtil.java | 619 +++++++++++++----- 2 files changed, 463 insertions(+), 178 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ddd936d7557..55c8d104c44 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -1030,12 +1029,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, if (true) { String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); String suffix = ")"; - OOUtil.insertTextAtCurrentLocation(documentConnection, - cursor, - prefix, - Collections.emptyList(), - Optional.empty(), - Optional.empty()); + OOUtil.insertTextAtCurrentLocation(cursor, prefix); int last = ck.where.size(); int i = 0; @@ -1044,12 +1038,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); if (i > 0) { - OOUtil.insertTextAtCurrentLocation(documentConnection, - cursor, - String.format(", "), - Collections.emptyList(), - Optional.empty(), - Optional.empty()); + OOUtil.insertTextAtCurrentLocation(cursor, ", "); } documentConnection .insertGetreferenceToPageNumberOfReferenceMark(cg.getMarkName(), cursor); @@ -1057,12 +1046,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, } documentConnection.refresh(); - OOUtil.insertTextAtCurrentLocation(documentConnection, - cursor, - suffix, - Collections.emptyList(), - Optional.empty(), - Optional.empty()); + OOUtil.insertTextAtCurrentLocation(cursor, suffix); } } else { diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 1d270d7392c..8ade726b39a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -1,7 +1,5 @@ package org.jabref.logic.openoffice; -import java.util.ArrayList; -import java.util.List; import java.util.Optional; import java.util.Stack; import java.util.regex.Matcher; @@ -83,12 +81,10 @@ public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection doc XText text = position.getText(); XTextCursor cursor = text.createTextCursorByRange(position); + cursor.collapseToEnd(); - List formatting = new ArrayList<>(); - Stack charstyleStack = new Stack<>(); - Stack localeStack = new Stack<>(); - charstyleStack.push(DocumentConnection.getCharStyle(cursor)); - localeStack.push(DocumentConnection.getCharLocale(cursor)); + Stack formatters = new Stack<>(); + boolean reset = false; // We need to extract formatting. Use a simple regexp search iteration: int piv = 0; @@ -96,50 +92,51 @@ public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection doc while (m.find()) { String currentSubstring = lText.substring(piv, m.start()); if (!currentSubstring.isEmpty()) { - OOUtil.insertTextAtCurrentLocation(documentConnection, - cursor, - currentSubstring, - formatting, - Optional.of(charstyleStack.peek()), - Optional.of(localeStack.peek())); + text.insertString(cursor, currentSubstring, true); + OOUtil.formatTextInCursor2(documentConnection, + cursor, + formatters, + reset); } + cursor.collapseToEnd(); + XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); String tag = m.group(); String xtag = m.group(1); String xvar = m.group(2); String xval = m.group(3); // Handle tags: if ("".equals(tag)) { - formatting.add(Formatting.BOLD); + formatters.push(Bold()); } else if ("".equals(tag)) { - formatting.remove(Formatting.BOLD); + formatters.pop().applyEnd(documentConnection, xCursorProps); } else if ("".equals(tag) || "".equals(tag)) { - formatting.add(Formatting.ITALIC); + formatters.push(Italic()); } else if ("".equals(tag) || "".equals(tag)) { - formatting.remove(Formatting.ITALIC); + formatters.pop().applyEnd(documentConnection, xCursorProps); } else if ("".equals(tag)) { - formatting.add(Formatting.MONOSPACE); + // nop } else if ("".equals(tag)) { - formatting.remove(Formatting.MONOSPACE); + // nop } else if ("".equals(tag)) { - formatting.add(Formatting.SMALLCAPS); + formatters.push(SmallCaps()); } else if ("".equals(tag)) { - formatting.remove(Formatting.SMALLCAPS); + formatters.pop().applyEnd(documentConnection, xCursorProps); } else if ("".equals(tag)) { - formatting.add(Formatting.SUPERSCRIPT); + formatters.push(SuperScript()); } else if ("".equals(tag)) { - formatting.remove(Formatting.SUPERSCRIPT); + formatters.pop().applyEnd(documentConnection, xCursorProps); } else if ("".equals(tag)) { - formatting.add(Formatting.SUBSCRIPT); + formatters.push(SubScript()); } else if ("".equals(tag)) { - formatting.remove(Formatting.SUBSCRIPT); + formatters.pop().applyEnd(documentConnection, xCursorProps); } else if ("".equals(tag)) { - formatting.add(Formatting.UNDERLINE); + formatters.push(Underline()); } else if ("".equals(tag)) { - formatting.remove(Formatting.UNDERLINE); + formatters.pop().applyEnd(documentConnection, xCursorProps); } else if ("".equals(tag)) { - formatting.add(Formatting.STRIKEOUT); + formatters.push(Strikeout()); } else if ("".equals(tag)) { - formatting.remove(Formatting.STRIKEOUT); + formatters.pop().applyEnd(documentConnection, xCursorProps); } else if ("

".equals(tag)) { // nop } else if ("p".equals(xtag) || "

".equals(tag)) { @@ -155,167 +152,337 @@ public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection doc } } else if ("font".equals(xtag) || "".equals(tag)) { // - if ("class".equals(xvar) && xval != null && !xval.equals("")) { - charstyleStack.push(xval); + if ("class".equals(xvar)) { + formatters.push(SetCharStyle(xval)); } else { - charstyleStack.push(""); + formatters.push(SetCharStyle(null)); } } else if ("".equals(tag)) { - charstyleStack.pop(); + formatters.pop().applyEnd(documentConnection, xCursorProps); } else if ("locale".equals(xtag)) { // // - if ("value".equals(xvar) && xval != null && !xval.equals("")) { - String[] parts = xval.split("-"); - String language = (parts.length > 0) ? parts[0] : ""; - String country = (parts.length > 1) ? parts[1] : ""; - String variant = (parts.length > 2) ? parts[2] : ""; - Locale l = new Locale(language, country, variant); - localeStack.push(l); + if ("value".equals(xvar)) { + formatters.push(SetLocale(xval)); } else { - localeStack.push(localeStack.peek()); + formatters.push(SetLocale(null)); } } else if ("".equals(tag)) { - localeStack.pop(); + formatters.pop().applyEnd(documentConnection, xCursorProps); } piv = m.end(); } if (piv < lText.length()) { - OOUtil.insertTextAtCurrentLocation(documentConnection, - cursor, - lText.substring(piv), - formatting, - Optional.of(charstyleStack.peek()), - Optional.of(localeStack.peek())); + text.insertString(cursor, lText.substring(piv), true); + OOUtil.formatTextInCursor2(documentConnection, + cursor, + formatters, + reset); + cursor.collapseToEnd(); } } - public static void insertParagraphBreak(XText text, XTextCursor cursor) throws IllegalArgumentException { - text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); + interface Formatter { + public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException; + + public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException; } - public static void insertTextAtCurrentLocation(DocumentConnection documentConnection, - XTextCursor cursor, - String string, - List formatting, - Optional charStyle, - Optional locale) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - XText text = cursor.getText(); - text.insertString(cursor, string, true); - formatTextInCursor(documentConnection, - cursor, - formatting, - charStyle, - locale); + static class FontWeight implements Formatter { + float oldWeight; + float myWeight; + FontWeight(float weight) { + this.myWeight = weight; + } - cursor.collapseToEnd(); + @Override + public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + oldWeight = (float) xCursorProps.getPropertyValue(CHAR_WEIGHT); + xCursorProps.setPropertyValue(CHAR_WEIGHT, myWeight); + } + + @Override + public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + xCursorProps.setPropertyValue(CHAR_WEIGHT, oldWeight); + } } - public static void formatTextInCursor(DocumentConnection documentConnection, - XTextCursor cursor, - List formatting, - Optional charStyle, - Optional locale) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { + static Formatter Bold() { + return new FontWeight(com.sun.star.awt.FontWeight.BOLD); + } - // Access the property set of the cursor, and set the currently selected text - // (which is the string we just inserted) to be bold - XPropertySet xCursorProps = UnoRuntime.queryInterface( - XPropertySet.class, cursor); - - if (formatting.contains(Formatting.BOLD)) { - xCursorProps.setPropertyValue(CHAR_WEIGHT, - com.sun.star.awt.FontWeight.BOLD); - } else { - xCursorProps.setPropertyValue(CHAR_WEIGHT, - com.sun.star.awt.FontWeight.NORMAL); - } - - if (formatting.contains(Formatting.ITALIC)) { - xCursorProps.setPropertyValue(CHAR_POSTURE, - com.sun.star.awt.FontSlant.ITALIC); - } else { - xCursorProps.setPropertyValue(CHAR_POSTURE, - com.sun.star.awt.FontSlant.NONE); - } - - if (formatting.contains(Formatting.SMALLCAPS)) { - xCursorProps.setPropertyValue(CHAR_CASE_MAP, - com.sun.star.style.CaseMap.SMALLCAPS); - } else { - xCursorProps.setPropertyValue(CHAR_CASE_MAP, - com.sun.star.style.CaseMap.NONE); - } - - // TODO: the tag doesn't work - /* - if (formatting.contains(Formatting.MONOSPACE)) { - xCursorProps.setPropertyValue("CharFontPitch", - com.sun.star.awt.FontPitch.FIXED); - } - else { - xCursorProps.setPropertyValue("CharFontPitch", - com.sun.star.awt.FontPitch.VARIABLE); - } */ - - if (formatting.contains(Formatting.SUBSCRIPT)) { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, - (short) -10); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, - (byte) 58); - } else if (formatting.contains(Formatting.SUPERSCRIPT)) { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, - (short) 33); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, - (byte) 58); - } else { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, - (byte) 0); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, - (byte) 100); - } - - if (formatting.contains(Formatting.UNDERLINE)) { - xCursorProps.setPropertyValue(CHAR_UNDERLINE, com.sun.star.awt.FontUnderline.SINGLE); - } else { - xCursorProps.setPropertyValue(CHAR_UNDERLINE, com.sun.star.awt.FontUnderline.NONE); + static class FontSlant implements Formatter { + com.sun.star.awt.FontSlant oldSlant; + com.sun.star.awt.FontSlant mySlant; + + FontSlant(com.sun.star.awt.FontSlant slant) { + this.mySlant = slant; } - if (formatting.contains(Formatting.STRIKEOUT)) { - xCursorProps.setPropertyValue(CHAR_STRIKEOUT, com.sun.star.awt.FontStrikeout.SINGLE); - } else { - xCursorProps.setPropertyValue(CHAR_STRIKEOUT, com.sun.star.awt.FontStrikeout.NONE); + @Override + public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + oldSlant = (com.sun.star.awt.FontSlant) xCursorProps.getPropertyValue(CHAR_POSTURE); + xCursorProps.setPropertyValue(CHAR_POSTURE, mySlant); } - if (locale.isPresent()) { - try { - xCursorProps.setPropertyValue("CharLocale", locale.get()); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - // silently + @Override + public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + xCursorProps.setPropertyValue(CHAR_POSTURE, oldSlant); + } + } + + static Formatter Italic() { + return new FontSlant(com.sun.star.awt.FontSlant.ITALIC); + } + + /* + * com.sun.star.style.CaseMap + */ + static class CaseMap implements Formatter { + short old; + short my; + + CaseMap(short value) { + this.my = value; + } + + @Override + public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + old = (short) xCursorProps.getPropertyValue(CHAR_CASE_MAP); + xCursorProps.setPropertyValue(CHAR_CASE_MAP, my); + } + + @Override + public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + xCursorProps.setPropertyValue(CHAR_CASE_MAP, old); + } + } + + static Formatter SmallCaps() { + return new CaseMap(com.sun.star.style.CaseMap.SMALLCAPS); + } + + static class CharEscapement implements Formatter { + short oldValue; + byte oldHeight; + + short myValue; + byte myHeight; + + CharEscapement(short value, byte height) { + myValue = value; + myHeight = height; + } + + @Override + public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + oldValue = (short) xCursorProps.getPropertyValue(CHAR_ESCAPEMENT); + oldHeight = (byte) xCursorProps.getPropertyValue(CHAR_ESCAPEMENT_HEIGHT); + + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, myValue); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, myHeight); + } + + @Override + public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, oldValue); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, oldHeight); + } + } + + static Formatter SubScript() { + return new CharEscapement((short) -10, (byte) 58); + } + + static Formatter SuperScript() { + return new CharEscapement((short) 33, (byte) 58); + } + + /* + * com.sun.star.awt.FontUnderline + */ + static class FontUnderline implements Formatter { + short oldValue; + short myValue; + + FontUnderline(short value) { + this.myValue = value; + } + + @Override + public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + oldValue = (short) xCursorProps.getPropertyValue(CHAR_UNDERLINE); + xCursorProps.setPropertyValue(CHAR_UNDERLINE, myValue); + } + + @Override + public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + xCursorProps.setPropertyValue(CHAR_UNDERLINE, oldValue); + } + } + + static Formatter Underline() { + return new FontUnderline(com.sun.star.awt.FontUnderline.SINGLE); + } + + /* + * com.sun.star.awt.FontStrikeout + */ + static class FontStrikeout implements Formatter { + short oldValue; + short myValue; + + FontStrikeout(short value) { + this.myValue = value; + } + + @Override + public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + oldValue = (short) xCursorProps.getPropertyValue(CHAR_STRIKEOUT); + xCursorProps.setPropertyValue(CHAR_STRIKEOUT, myValue); + } + + @Override + public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + xCursorProps.setPropertyValue(CHAR_STRIKEOUT, oldValue); + } + } + + static Formatter Strikeout() { + return new FontStrikeout(com.sun.star.awt.FontStrikeout.SINGLE); + } + + /* + * + */ + static class CharLocale implements Formatter { + private Optional myLocale; + private Optional oldLocale; + + CharLocale(Optional locale) { + this.myLocale = locale; + this.oldLocale = Optional.empty(); + } + + @Override + public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + if (myLocale.isPresent()) { + try { + Locale old = (Locale) xCursorProps.getPropertyValue("CharLocale"); + oldLocale = Optional.of(old); + xCursorProps.setPropertyValue("CharLocale", myLocale.get()); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + // silently + } } } - if (charStyle.isPresent() && !charStyle.get().equals("")) { - if (documentConnection - .getInternalNameOfCharacterStyle(charStyle.get()).isPresent()) { + @Override + public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + if (oldLocale.isPresent()) { try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle.get()); + xCursorProps.setPropertyValue("CharLocale", oldLocale.get()); } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException @@ -323,9 +490,143 @@ public static void formatTextInCursor(DocumentConnection documentConnection, // silently } } - // otherwise: ignore silently. Assume character style was already tested elsewhere. + } + } + + /* + * Locale from string encoding: language, language-country or language-country-variant + */ + static Formatter SetLocale(String value) { + if (value == null || "".equals(value)) { + return new CharLocale(Optional.empty()); + } + + String[] parts = value.split("-"); + String language = (parts.length > 0) ? parts[0] : ""; + String country = (parts.length > 1) ? parts[1] : ""; + String variant = (parts.length > 2) ? parts[2] : ""; + Locale l = new Locale(language, country, variant); + return new CharLocale(Optional.of(l)); + } + + /* + * Set a character style known to OO/LO + */ + static class CharStyleName implements Formatter { + private Optional myCharStyle; + private Optional oldCharStyle; + + public CharStyleName(Optional charStyle) { + this.myCharStyle = charStyle; + this.oldCharStyle = Optional.empty(); } + @Override + public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + if (myCharStyle.isPresent() && !myCharStyle.get().equals("")) { + if (documentConnection + .getInternalNameOfCharacterStyle(myCharStyle.get()).isPresent()) { + try { + String old = (String) xCursorProps.getPropertyValue(CHAR_STYLE_NAME); + oldCharStyle = Optional.of(old); + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, myCharStyle.get()); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + // silently + } + } + // otherwise: ignore silently. Assume character style was already tested elsewhere. + } + } + + @Override + public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + if (oldCharStyle.isPresent() && !oldCharStyle.get().equals("")) { + if (documentConnection + .getInternalNameOfCharacterStyle(oldCharStyle.get()).isPresent()) { + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, oldCharStyle.get()); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + // silently + } + } + // otherwise: ignore silently. Assume character style was already tested elsewhere. + } + } + } + + static Formatter SetCharStyle(String charStyle) { + if (charStyle == null || "".equals(charStyle)) { + return new CharStyleName(Optional.empty()); + } + return new CharStyleName(Optional.of(charStyle)); + } + + /** + * Here: apply only those on the stack, and in that order + */ + public static void formatTextInCursor2(DocumentConnection documentConnection, + XTextCursor cursor, + Stack formatters, + boolean reset) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + + // Access the property set of the cursor, and set the currently selected text + // (which is the string we just inserted) to be bold + XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); + + if (reset) { + // Reset everything. + xCursorProps.setPropertyValue(CHAR_WEIGHT, com.sun.star.awt.FontWeight.NORMAL); + xCursorProps.setPropertyValue(CHAR_POSTURE, com.sun.star.awt.FontSlant.NONE); + xCursorProps.setPropertyValue(CHAR_CASE_MAP, com.sun.star.style.CaseMap.NONE); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (byte) 0); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, (byte) 100); + xCursorProps.setPropertyValue(CHAR_UNDERLINE, com.sun.star.awt.FontUnderline.NONE); + xCursorProps.setPropertyValue(CHAR_STRIKEOUT, com.sun.star.awt.FontStrikeout.NONE); + } + for (Formatter f : formatters) { + f.apply(documentConnection, xCursorProps); + } + } + + public static void insertParagraphBreak(XText text, XTextCursor cursor) throws IllegalArgumentException { + text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); + } + + public static void insertTextAtCurrentLocation(XTextCursor cursor, + String string) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + XText text = cursor.getText(); + text.insertString(cursor, string, true); + cursor.collapseToEnd(); } /** From 223cbbf481b1215638ab985a12972a223aa8f4d8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 27 Apr 2021 21:36:38 +0200 Subject: [PATCH 0644/1068] debuged getFillCursor It does not work when [Edit]/[Track Changes]/[Record] is on in LibreOffice --- .../logic/openoffice/StorageBaseRefMark.java | 104 ++++++++++++++++-- 1 file changed, 97 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index cf7ed4dc6e8..b11a1379982 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -182,7 +182,7 @@ public Optional getMarkRange(DocumentConnection documentConnection) * Cursor for the reference marks as is, not prepared for filling, * but does not need cleanFillCursorForCitationGroup either. * - * @return null if reference mark is missing from the document, + * @return Optional.empty() if reference mark is missing from the document, * otherwise an XTextCursor for getMarkRange * * See: getRawCursorForCitationGroup @@ -259,6 +259,10 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) } if (fullText.length() >= 2) { + if (debugThisFun) { + System.out.printf("getFillCursor: (attempt: %d) fulltext.length() >= 2," + + " break loop%n", i); + } break; } else { // (fullText.length() < 2) @@ -296,6 +300,10 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) throw new RuntimeException("getFillCursor: fullText == null (after loop)"); } + fullText = full.getString(); + if (fullText.length() < 2) { + throw new RuntimeException("getFillCursor: fullText.length() < 2 (after loop)'%n"); + } // we have at least two characters inside XTextCursor alpha = full.getText().createTextCursorByRange(full); alpha.collapseToStart(); @@ -306,18 +314,100 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) beta.collapseToStart(); beta.goRight((short) 1, false); beta.goRight((short) (fullText.length() - 2), true); - beta.setString(left + right); + if (debugThisFun) { + System.out.printf("getFillCursor: beta(1) covers '%s'%n", beta.getString()); + } + // beta now covers everything except first and last character + // Replace its content with brackets + String paddingx = "x"; + String paddingy = "y"; + String paddingz = "z"; + beta.setString(paddingx + left + paddingy + right + paddingz); + if (debugThisFun) { + System.out.printf("getFillCursor: beta(2) covers '%s'%n", beta.getString()); + } + // move beta to before the right bracket beta.collapseToEnd(); - beta.goLeft(rightLength, false); - // drop the initial character - alpha.goRight((short) 1, true); + beta.goLeft((short) (rightLength + 1), false); + // remove middle padding + beta.goLeft((short) 1, true); + if (debugThisFun) { + System.out.printf("getFillCursor: beta(3) covers '%s'%n", beta.getString()); + } + // only drop paddingy later: beta.setString(""); + + // drop the initial character and paddingx + alpha.collapseToStart(); + alpha.goRight((short) (1 + 1), true); + if (debugThisFun) { + System.out.printf("getFillCursor: alpha(4) covers '%s'%n", alpha.getString()); + } alpha.setString(""); - // drop the last character - omega.goLeft((short) 1, true); + // drop the last character and paddingz + omega.collapseToEnd(); + omega.goLeft((short) (1 + 1), true); + if (debugThisFun) { + System.out.printf("getFillCursor: omega(5) covers '%s'%n", omega.getString()); + } omega.setString(""); + + // drop paddingy now + if (debugThisFun) { + System.out.printf("getFillCursor: beta(6) covers '%s'%n", beta.getString()); + } + beta.setString(""); + // should be OK now. + if (debugThisFun) { + alpha.goRight(leftLength, true); + System.out.printf("getFillCursor: alpha(7) covers '%s', should be '%s'%n", + alpha.getString(), left); + omega.goLeft(rightLength, true); + System.out.printf("getFillCursor: omega(8) covers '%s', should be '%s'%n", + omega.getString(), right); + } + + StorageBaseRefMark.checkFillCursor(beta); return beta; } + /* + * Throw RuntimeException if the brackets are not there. + */ + public static void checkFillCursor(XTextCursor cursor) { + final String left = REFERENCE_MARK_LEFT_BRACKET; + final String right = REFERENCE_MARK_RIGHT_BRACKET; + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); + + XTextCursor alpha = cursor.getText().createTextCursorByRange(cursor); + alpha.collapseToStart(); + + XTextCursor omega = cursor.getText().createTextCursorByRange(cursor); + omega.collapseToEnd(); + + if (leftLength > 0) { + alpha.goLeft(leftLength, true); + if (!left.equals(alpha.getString())) { + String msg = String.format("checkFillCursor:" + + " ('%s') is not prefixed with" + + " REFERENCE_MARK_LEFT_BRACKET, has '%s'", + cursor.getString(), alpha.getString()); + throw new RuntimeException(msg); + } + } + + if (rightLength > 0) { + omega.goRight(rightLength, true); + if (!right.equals(omega.getString())) { + String msg = String.format("checkFillCursor:" + + " ('%s') is not followed by" + + " REFERENCE_MARK_RIGHT_BRACKET, has '%s'", + cursor.getString(), omega.getString()); + throw new RuntimeException(msg); + } + } + } + /** * Remove brackets, but if the result would become empty, leave * them; if the result would be a single characer, leave the left bracket. From ee878dc87dc78725e54b42596a43fc5c34582f17 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 27 Apr 2021 21:38:12 +0200 Subject: [PATCH 0645/1068] refuse to edit a document recording changes or containing recorded changes --- .../openoffice/ManageCitationsDialogView.java | 3 +- .../ManageCitationsDialogViewModel.java | 10 +- .../org/jabref/gui/openoffice/OOBibBase.java | 57 ++++- .../gui/openoffice/OpenOfficePanel.java | 32 ++- .../logic/openoffice/DocumentConnection.java | 229 ++++++++++++++++++ src/main/resources/l10n/JabRef_en.properties | 8 + 6 files changed, 334 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index a312a4ef375..8fdd929ce2d 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -15,6 +15,7 @@ import org.jabref.gui.DialogService; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.ValueTableCellFactory; +import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.model.strings.StringUtil; @@ -56,7 +57,7 @@ public ManageCitationsDialogView(OOBibBase ooBase) { } @FXML - private void initialize() throws NoSuchElementException, WrappedTargetException, UnknownPropertyException { + private void initialize() throws NoSuchElementException, WrappedTargetException, UnknownPropertyException, JabRefException { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index d73ed902176..ac7d18198b5 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -8,6 +8,7 @@ import javafx.collections.FXCollections; import org.jabref.gui.DialogService; +import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.CitationEntry; import org.jabref.logic.openoffice.CreationException; @@ -16,6 +17,7 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.IllegalArgumentException; @@ -31,7 +33,12 @@ public class ManageCitationsDialogViewModel { private final OOBibBase ooBase; private final DialogService dialogService; - public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) throws NoSuchElementException, WrappedTargetException, UnknownPropertyException { + public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) + throws + NoSuchElementException, + WrappedTargetException, + UnknownPropertyException, + JabRefException { this.ooBase = ooBase; this.dialogService = dialogService; @@ -44,6 +51,7 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogServ } catch (UnknownPropertyException | WrappedTargetException | NoDocumentException + | PropertyVetoException | CreationException ex) { LOGGER.warn("Problem collecting citations", ex); dialogService.showErrorDialogAndWait(Localization.lang("Problem collecting citations"), ex); diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 55c8d104c44..156daebe952 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -286,7 +286,7 @@ public boolean documentConnectionMissing() { * Either return a valid DocumentConnection or throw * NoDocumentException. */ - private DocumentConnection getDocumentConnectionOrThrow() + public DocumentConnection getDocumentConnectionOrThrow() throws NoDocumentException { if (documentConnectionMissing()) { @@ -372,9 +372,15 @@ public List getCitationEntries() UnknownPropertyException, WrappedTargetException, NoDocumentException, - CreationException { + CreationException, + PropertyVetoException, + JabRefException { DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + + // checkStylesExistInTheDocument(style, documentConnection); + checkRecordChanges(documentConnection); + OOFrontend fr = new OOFrontend(documentConnection); return fr.getCitationEntries(documentConnection); } @@ -683,6 +689,10 @@ public void insertEntry(List entries, final int nEntries = entries.size(); DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + + checkStylesExistInTheDocument(style, documentConnection); + checkRecordChanges(documentConnection); + OOFrontend fr = new OOFrontend(documentConnection); // CitationGroups cgs = new CitationGroups(documentConnection); // TODO: imposeLocalOrder @@ -1228,6 +1238,9 @@ public void combineCiteMarkers(List databases, final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + checkStylesExistInTheDocument(style, documentConnection); + checkRecordChanges(documentConnection); + OOFrontend fr = new OOFrontend(documentConnection); try { @@ -1585,6 +1598,10 @@ public void unCombineCiteMarkers(List databases, final boolean useLockControllers = true; DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + + checkStylesExistInTheDocument(style, documentConnection); + checkRecordChanges(documentConnection); + OOFrontend fr = new OOFrontend(documentConnection); try { @@ -1797,6 +1814,41 @@ private ExportCitedHelperResult generateDatabase(List databases, return new ExportCitedHelperResult(unresolvedKeys, resultDatabase); } + /* + * Throw JabRefException if recording changes or the document contains + * recorded changes. + */ + public void checkRecordChanges(DocumentConnection documentConnection) + throws + UnknownPropertyException, + WrappedTargetException, + PropertyVetoException, + JabRefException { + /* We could do this: documentConnection.setRecordChanges(false); + * but it is more transparent to ask. + */ + boolean recordingChanges = documentConnection.getRecordChanges(); + int nRedlines = documentConnection.countRedlines(); + if (recordingChanges || nRedlines > 0) { + String msg = ""; + if (recordingChanges) { + msg += Localization.lang("Cannot work with [Edit]/[Track Changes]/[Record] turned on."); + } + if (nRedlines > 0) { + if (recordingChanges) { + msg += "\n"; + } + msg += Localization.lang("Changes by JabRef" + + " could result in unexpected interactions with" + + " recorded changes."); + msg += "\n"; + msg += Localization.lang("Use [Edit]/[Track Changes]/[Manage] to resolve them first."); + } + String title = Localization.lang("Recording and/or Recorded changes"); + throw new JabRefException(title, msg); + } + } + void styleIsRequired(OOBibStyle style) throws JabRefException { @@ -1941,6 +1993,7 @@ public List updateDocumentActionHelper(List databases, DocumentConnection documentConnection = getDocumentConnectionOrThrow(); checkStylesExistInTheDocument(style, documentConnection); + checkRecordChanges(documentConnection); try { documentConnection.enterUndoContext("Refresh bibliography"); diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index d735421d896..5bdece8759c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -48,6 +48,7 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.StyleLoader; import org.jabref.logic.openoffice.CreationException; +import org.jabref.logic.openoffice.DocumentConnection; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; @@ -280,9 +281,21 @@ private void initPanel() { settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { - if (ooBase.documentConnectionMissing()) { + try { + DocumentConnection documentConnection = ooBase.getDocumentConnectionOrThrow(); + ooBase.checkRecordChanges(documentConnection); + } catch (JabRefException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("JabRefException"), + ex.getLocalizedMessage()); + return; + } catch (NoDocumentException ex) { showNoDocumentErrorMessage(); return; + } catch (UnknownPropertyException + | PropertyVetoException + | WrappedTargetException ex) { + LOGGER.warn("Problem during checkRecordChanges", ex); } dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); }); @@ -506,6 +519,23 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP return; } + try { + DocumentConnection documentConnection = ooBase.getDocumentConnectionOrThrow(); + ooBase.checkRecordChanges(documentConnection); + } catch (JabRefException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("JabRefException"), + ex.getLocalizedMessage()); + return; + } catch (NoDocumentException ex) { + showNoDocumentErrorMessage(); + return; + } catch (UnknownPropertyException + | PropertyVetoException + | WrappedTargetException ex) { + LOGGER.warn("Problem during checkRecordChanges", ex); + } + Boolean inParenthesis = inParenthesisIn; String pageInfo = null; if (addPageInfo) { diff --git a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java index ba30c10740c..d25e481c7c3 100644 --- a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java @@ -15,10 +15,14 @@ import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XEnumeration; +import com.sun.star.container.XEnumerationAccess; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNameContainer; import com.sun.star.container.XNamed; +import com.sun.star.document.XDocumentProperties; import com.sun.star.document.XDocumentPropertiesSupplier; +import com.sun.star.document.XRedlinesSupplier; import com.sun.star.document.XUndoManager; import com.sun.star.document.XUndoManagerSupplier; import com.sun.star.frame.XController; @@ -52,6 +56,8 @@ import com.sun.star.uno.Any; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.util.DateTime; import com.sun.star.util.InvalidStateException; import com.sun.star.util.XRefreshable; import com.sun.star.view.XSelectionSupplier; @@ -90,6 +96,16 @@ public class DocumentConnection { public XPropertySet propertySet; public DocumentConnection(XTextDocument mxDoc) { + // printServiceInfo(mxDoc); + // *** xserviceinfo + // object is OK + // xserviceinfo is OK + // .getImplementationName: "SwXTextDocument" + // .getSupportedServiceNames: + // "com.sun.star.document.OfficeDocument" + // "com.sun.star.text.GenericTextDocument" + // "com.sun.star.text.TextDocument" + this.mxDoc = mxDoc; this.xCurrentComponent = unoQI(XComponent.class, mxDoc); this.mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); @@ -118,6 +134,219 @@ private static T unoQI(Class zInterface, return UnoRuntime.queryInterface(zInterface, object); } + private XDocumentProperties getXDocumentProperties() { + XDocumentPropertiesSupplier supp = unoQI(XDocumentPropertiesSupplier.class, mxDoc); + return supp.getDocumentProperties(); + } + + private short getRedlineDisplayType() + throws + UnknownPropertyException, + WrappedTargetException { + // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/RedlineDisplayType.html + // Constants (short) + // 0 NONE no changes are displayed. + // 1 INSERTED only inserted parts are displayed and attributed. + // 2 INSERTED_AND_REMOVED only inserted parts are displayed and attributed. + // 3 REMOVED only removed parts are displayed and attributed. + XPropertySet ps = unoQI(XPropertySet.class, mxDoc); + return (short) ps.getPropertyValue("RedlineDisplayType"); + } + + public boolean getRecordChanges() + throws + UnknownPropertyException, + WrappedTargetException { + XPropertySet ps = unoQI(XPropertySet.class, mxDoc); + // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Settings + // "Properties of com.sun.star.text.TextDocument" + if (ps == null) { + throw new RuntimeException("getRecordChanges: ps is null"); + } + return (boolean) ps.getPropertyValue("RecordChanges"); + } + + public void setRecordChanges(boolean value) + throws + UnknownPropertyException, + WrappedTargetException, + PropertyVetoException { + XPropertySet ps = unoQI(XPropertySet.class, mxDoc); + ps.setPropertyValue("RecordChanges", value); + } + + private XRedlinesSupplier getRedlinesSupplier() { + return unoQI(XRedlinesSupplier.class, mxDoc); + } + + public int countRedlines() { + XRedlinesSupplier rs = getRedlinesSupplier(); + XEnumerationAccess ea = rs.getRedlines(); + XEnumeration e = ea.createEnumeration(); // null for empty + if (e == null) { + // System.out.println("countRedLines: no redlines found"); + return 0; + } else { + int count = 0; + for (; e.hasMoreElements(); ) { + try { + Object o = e.nextElement(); + count++; + } catch (NoSuchElementException | WrappedTargetException ex) { + break; + } + } + // System.out.println(String.format("countRedLines: found %d redlines", count)); + return count; + } + } + + private void printRedlines() { + // https://docs.libreoffice.org/sw/html/unoredline_8cxx_source.html#l00290 + // http://www.openoffice.org/api/docs/common/ref/com/sun/star/text/RedlinePortion.html + XRedlinesSupplier rs = getRedlinesSupplier(); + XEnumerationAccess ea = rs.getRedlines(); + XEnumeration e = ea.createEnumeration(); // null for empty + if (e == null) { + System.out.println("printRedLines: no redlines found"); + return; + } else { + int count = 0; + for (; e.hasMoreElements(); ) { + try { + count++; + Object o = e.nextElement(); + XPropertySet ps = unoQI(XPropertySet.class, o); + if (ps == null) { + String msg = String.format("printRedLines: %d XPropertySet is null", count); + System.out.println(msg); + continue; + } + XPropertySetInfo psi = ps.getPropertySetInfo(); + if (psi == null) { + String msg = String.format("printRedLines: %d XPropertySetInfo is null", count); + System.out.println(msg); + } else { + String msg = String.format("printRedLines: %d XPropertySetInfo is OK", count); + System.out.println(msg); + int propertyCount = 0; + for (Property p : psi.getProperties()) { + propertyCount++; + String m = String.format("printRedLines: %d/%d '%s' %d %s", + count, + propertyCount, + p.Name, + p.Handle, + p.Type); + switch (p.Name) { + case "RedlineEnd": + // printRedLines: 1/1 'RedlineEnd' 0 Type[com.sun.star.uno.XInterface] + // UNO_NAME_REDLINE_END "RedlineEnd" + case "RedlineStart": + // printRedLines: 1/12 'RedlineStart' 0 Type[com.sun.star.uno.XInterface] + // UNO_NAME_REDLINE_START "RedlineStart" + XInterface xi = (XInterface) ps.getPropertyValue(p.Name); + // printServiceInfo(xi); + //*** xserviceinfo + // object is OK + // xserviceinfo is OK + // .getImplementationName: "SwXTextRange" + // .getSupportedServiceNames: + // "com.sun.star.text.TextRange" + // "com.sun.star.style.CharacterProperties" + // "com.sun.star.style.CharacterPropertiesAsian" + // "com.sun.star.style.CharacterPropertiesComplex" + // "com.sun.star.style.ParagraphProperties" + // "com.sun.star.style.ParagraphPropertiesAsian" + // "com.sun.star.style.ParagraphPropertiesComplex" + break; + case "RedlineAuthor": + // printRedLines: 1/2 'RedlineAuthor' 0 Type[string] + // UNO_NAME_REDLINE_AUTHOR "RedlineAuthor" + case "RedlineIdentifier": + // printRedLines: 1/3 'RedlineIdentifier' 0 Type[string] + // UNO_NAME_REDLINE_IDENTIFIER "RedlineIdentifier" + case "RedlineDescription": + // printRedLines: 1/5 'RedlineDescription' 0 Type[string] + // UNO_NAME_REDLINE_DESCRIPTION "RedlineDescription" + case "RedlineType": + // printRedLines: 1/7 'RedlineType' 0 Type[string] + // UNO_NAME_REDLINE_TYPE "RedlineType" + case "RedlineComment": + // printRedLines: 1/8 'RedlineComment' 0 Type[string] + // UNO_NAME_REDLINE_COMMENT "RedlineComment" + m += String.format(" '%s'", (String) ps.getPropertyValue(p.Name)); + break; + case "RedlineDateTime": + // printRedLines: 1/4 'RedlineDateTime' 0 Type[com.sun.star.util.DateTime] + // UNO_NAME_REDLINE_DATE_TIME "RedlineDateTime" + // OO http://www.openoffice.org/api/docs/common/ref/com/sun/star/util/DateTime.html + // LO https://api.libreoffice.org/docs/idl/ref/structcom_1_1sun_1_1star_1_1util_1_1DateTime.html + DateTime dt = (DateTime) ps.getPropertyValue(p.Name); + String s1 = String.format("%04d-%02d-%02d %02d:%02d:%02d", + dt.Year, dt.Month, dt.Day, + dt.Hours, dt.Minutes, dt.Seconds + /* OO: dt.HundredthSeconds */ + /* LO: dt.NanoSeconds (but zero anyway) */); + m += String.format(" '%s'", s1); + break; + + case "IsInHeaderFooter": + // printRedLines: 1/9 'IsInHeaderFooter' 0 Type[boolean] + // UNO_NAME_IS_IN_HEADER_FOOTER "IsInHeaderFooter" + case "MergeLastPara": + // printRedLines: 1/11 'MergeLastPara' 0 Type[boolean] + // UNO_NAME_MERGE_LAST_PARA "MergeLastPara" + boolean b = (boolean) ps.getPropertyValue(p.Name); + m += String.format(" '%s'", b); + break; + + case "RedlineText": + // printRedLines: 1/10 'RedlineText' 0 Type[com.sun.star.text.XText] + // UNO_NAME_REDLINE_TEXT "RedlineText" + + // RedlineText: provides access to the text of the + // redline. This interface is only + // provided if the change is not + // visible. The visibility depends on + // the redline display options that + // are set at the documents property + // set (RedlineDisplayType). + + XText t = null; + try { + t = (XText) ps.getPropertyValue(p.Name); + String s2 = t.getString(); + m += String.format(" '%s'", s2); + } catch (java.lang.ClassCastException ex) { + m += " NotAvailable"; + } + break; + // printRedLines: 1/6 'RedlineSuccessorData' 0 Type[[]com.sun.star.beans.PropertyValue] + // UNO_NAME_REDLINE_SUCCESSOR_DATA "RedlineSuccessorData" + + // printRedLines: 1/13 'StartRedline' 22275 Type[[]com.sun.star.beans.PropertyValue] + // UNO_NAME_START_REDLINE "StartRedline" + // "contains the properties of a redline at the start of the document." + + // printRedLines: 1/14 'EndRedline' 22276 Type[[]com.sun.star.beans.PropertyValue] + // UNO_NAME_END_REDLINE "EndRedline" + } + System.out.println(m); + } + } + + } catch (NoSuchElementException + | WrappedTargetException + | UnknownPropertyException ex) { + break; + } + } + System.out.println(String.format("printRedLines: found %d redlines", count)); + return; + } + } + private Optional getStyleFromFamily(String familyName, String styleName) throws NoSuchElementException, diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index e18a911fec5..bc84278239f 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -2339,6 +2339,14 @@ The\ %0\ paragraph\ style\ '%1'\ is\ a\ display\ name\ for\ '%2'.=The %0 paragra The\ %0\ paragraph\ style\ '%1'\ is\ missing\ from\ the\ document=The %0 paragraph style '%1' is missing from the document +Cannot\ work\ with\ [Edit]/[Track\ Changes]/[Record]\ turned\ on.=Cannot work with [Edit]/[Track Changes]/[Record] turned on. + +Changes\ by\ JabRef\ could\ result\ in\ unexpected\ interactions\ with\ recorded\ changes.=Changes by JabRef could result in unexpected interactions with recorded changes. + +Recording\ and/or\ Recorded\ changes=Recording and/or Recorded changes + +Use\ [Edit]/[Track\ Changes]/[Manage]\ to\ resolve\ them\ first.=Use [Edit]/[Track Changes]/[Manage] to resolve them first. + Unable\ to\ find\ valid\ certification\ path\ to\ requested\ target(%0),\ download\ anyway?=Unable to find valid certification path to requested target(%0), download anyway? Download\ operation\ canceled.=Download operation canceled. From a1d681a797fd7b45406d95c8115e17b5d1b0f52d Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 27 Apr 2021 23:36:31 +0200 Subject: [PATCH 0646/1068] insertOOFormattedTextAtCurrentLocation now accepts reset as list of Formatters --- .../org/jabref/gui/openoffice/OOBibBase.java | 19 ++-- .../org/jabref/logic/oostyle/OOBibStyle.java | 12 +++ .../org/jabref/logic/openoffice/OOUtil.java | 89 +++++++++++++------ 3 files changed, 80 insertions(+), 40 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 156daebe952..5fa4726fdd6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -448,14 +448,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti String charStyle = style.getCitationCharacterFormat(); citationText2 = OOFormat.setCharStyle(citationText2, charStyle); } - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, citationText2); - /* - DocumentConnection.setCharLocaleNone(cursor); - if (style.isFormatCitations()) { - String charStyle = style.getCitationCharacterFormat(); - DocumentConnection.setCharStyle(cursor, charStyle); - } - */ + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, citationText2, null); } else { cursor.setString(""); } @@ -1020,7 +1013,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, int number = ck.number.get(); OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, marker); + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, marker, null); cursor.collapseToEnd(); } else { // !style.isNumberEntries() : emit no prefix @@ -1033,7 +1026,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, - referenceDetails); + referenceDetails, + null); cursor.collapseToEnd(); // Try to list citations: if (true) { @@ -1073,7 +1067,10 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, ck.uniqueLetter.orElse(null)); // Insert the formatted text: - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, formattedText); + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, + cursor, + formattedText, + null); cursor.collapseToEnd(); } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index a4d653e5ebc..51e65d49502 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -1227,4 +1227,16 @@ private String nullToEmpty(String s) { return (s == null ? "" : s); } + public OOFormattedText getFormattedBibliographyTitle() { + OOBibStyle style = this; + OOFormattedText title = style.getReferenceHeaderText(); + String parStyle = style.getReferenceHeaderParagraphFormat(); + if (parStyle != null) { + title = OOFormat.paragraph(title, parStyle); + } else { + title = OOFormat.paragraph(title); + } + return title; + } + } diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 8ade726b39a..92e3dea54dc 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -1,5 +1,6 @@ package org.jabref.logic.openoffice; +import java.util.List; import java.util.Optional; import java.util.Stack; import java.util.regex.Matcher; @@ -27,6 +28,17 @@ @AllowedToUseAwt("Requires AWT for changing document properties") public class OOUtil { + /* + * When passed to formatTextInCursor2, RESET supplies default + * values for features not controlled by the OOFormattedText input. + */ + public static final List RESET = List.of(FontWeightDefault(), + FontSlantDefault(), + CaseMapDefault(), + CharEscapementDefault(), + FontUnderlineDefault(), + FontStrikeoutDefault()); + private static final Logger LOGGER = LoggerFactory.getLogger(OOUtil.class); private static final String CHAR_STRIKEOUT = "CharStrikeout"; @@ -39,17 +51,6 @@ public class OOUtil { private static final String CHAR_ESCAPEMENT = "CharEscapement"; private static final String CHAR_STYLE_NAME = "CharStyleName"; - public enum Formatting { - BOLD, - ITALIC, - SMALLCAPS, - SUPERSCRIPT, - SUBSCRIPT, - UNDERLINE, - STRIKEOUT, - MONOSPACE - } - private static final Pattern HTML_TAG = Pattern.compile("|<(p|font|locale)\\s+(class|value)=\"([^\"]+)\">"); @@ -58,10 +59,14 @@ private OOUtil() { } /** - * Insert a text with formatting indicated by HTML-like tags, into a text at the position given by a cursor. + * Insert a text with formatting indicated by HTML-like tags, into + * a text at the position given by a cursor. * + * @param documentConnection * @param position The cursor giving the insert location. Not modified. - * @param ootext The marked-up text to insert. + * @param ootext The marked-up text to insert. + * @param reset Formatters to apply before those given by markup in ootext. + * May be null. * @throws WrappedTargetException * @throws PropertyVetoException * @throws UnknownPropertyException @@ -69,7 +74,8 @@ private OOUtil() { */ public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection documentConnection, XTextCursor position, - OOFormattedText ootext) + OOFormattedText ootext, + List reset) throws UnknownPropertyException, PropertyVetoException, @@ -84,7 +90,6 @@ public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection doc cursor.collapseToEnd(); Stack formatters = new Stack<>(); - boolean reset = false; // We need to extract formatting. Use a simple regexp search iteration: int piv = 0; @@ -237,6 +242,10 @@ static Formatter Bold() { return new FontWeight(com.sun.star.awt.FontWeight.BOLD); } + static Formatter FontWeightDefault() { + return new FontWeight(com.sun.star.awt.FontWeight.NORMAL); + } + static class FontSlant implements Formatter { com.sun.star.awt.FontSlant oldSlant; com.sun.star.awt.FontSlant mySlant; @@ -273,6 +282,10 @@ static Formatter Italic() { return new FontSlant(com.sun.star.awt.FontSlant.ITALIC); } + static Formatter FontSlantDefault() { + return new FontSlant(com.sun.star.awt.FontSlant.NONE); + } + /* * com.sun.star.style.CaseMap */ @@ -312,6 +325,10 @@ static Formatter SmallCaps() { return new CaseMap(com.sun.star.style.CaseMap.SMALLCAPS); } + static Formatter CaseMapDefault() { + return new CaseMap(com.sun.star.style.CaseMap.NONE); + } + static class CharEscapement implements Formatter { short oldValue; byte oldHeight; @@ -360,6 +377,10 @@ static Formatter SuperScript() { return new CharEscapement((short) 33, (byte) 58); } + static Formatter CharEscapementDefault() { + return new CharEscapement((short) 0, (byte) 100); + } + /* * com.sun.star.awt.FontUnderline */ @@ -399,6 +420,10 @@ static Formatter Underline() { return new FontUnderline(com.sun.star.awt.FontUnderline.SINGLE); } + static FontUnderline FontUnderlineDefault() { + return new FontUnderline(com.sun.star.awt.FontUnderline.NONE); + } + /* * com.sun.star.awt.FontStrikeout */ @@ -438,6 +463,10 @@ static Formatter Strikeout() { return new FontStrikeout(com.sun.star.awt.FontStrikeout.SINGLE); } + static Formatter FontStrikeoutDefault() { + return new FontStrikeout(com.sun.star.awt.FontStrikeout.NONE); + } + /* * */ @@ -580,12 +609,17 @@ static Formatter SetCharStyle(String charStyle) { } /** - * Here: apply only those on the stack, and in that order + * Apply Formatters in reset, then those on the stack. + * + * @param documentConnection passed to each Formatter + * @param cursor Marks the text to format + * @param formatters Formatters to apply (normally extracted from OOFormattedText) + * @param reset Formatters to apply before those in formatters. May be null. */ public static void formatTextInCursor2(DocumentConnection documentConnection, XTextCursor cursor, Stack formatters, - boolean reset) + List reset) throws UnknownPropertyException, PropertyVetoException, @@ -593,26 +627,23 @@ public static void formatTextInCursor2(DocumentConnection documentConnection, IllegalArgumentException, NoSuchElementException { - // Access the property set of the cursor, and set the currently selected text - // (which is the string we just inserted) to be bold XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); - if (reset) { - // Reset everything. - xCursorProps.setPropertyValue(CHAR_WEIGHT, com.sun.star.awt.FontWeight.NORMAL); - xCursorProps.setPropertyValue(CHAR_POSTURE, com.sun.star.awt.FontSlant.NONE); - xCursorProps.setPropertyValue(CHAR_CASE_MAP, com.sun.star.style.CaseMap.NONE); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, (byte) 0); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, (byte) 100); - xCursorProps.setPropertyValue(CHAR_UNDERLINE, com.sun.star.awt.FontUnderline.NONE); - xCursorProps.setPropertyValue(CHAR_STRIKEOUT, com.sun.star.awt.FontStrikeout.NONE); + // Set properties we do not want to inherit from the context + // and are not controlled by formatters. + if (reset != null) { + for (Formatter f : reset) { + f.apply(documentConnection, xCursorProps); + } } + for (Formatter f : formatters) { f.apply(documentConnection, xCursorProps); } } - public static void insertParagraphBreak(XText text, XTextCursor cursor) throws IllegalArgumentException { + public static void insertParagraphBreak(XText text, XTextCursor cursor) + throws IllegalArgumentException { text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); } From 481b5f2ab3ada4b79e7d7ab9f9b70f6bfa164bf9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 27 Apr 2021 23:37:59 +0200 Subject: [PATCH 0647/1068] use OOBibStyle.getFormattedBibliographyTitle() --- .../org/jabref/gui/openoffice/OOBibBase.java | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5fa4726fdd6..fd0daa4db34 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1091,7 +1091,7 @@ private void createBibTextSection2(DocumentConnection documentConnection) XTextCursor textCursor = documentConnection.xText.createTextCursor(); textCursor.gotoEnd(false); - OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); + // OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); textCursor.collapseToEnd(); documentConnection.insertTextSection(OOBibBase.BIB_SECTION_NAME, @@ -1169,20 +1169,17 @@ private void populateBibTextSection(DocumentConnection documentConnection, // emit the title of the bibliography OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, - style.getReferenceHeaderText()); - String parStyle = style.getReferenceHeaderParagraphFormat(); - try { - if (parStyle != null) { - DocumentConnection.setParagraphStyle(cursor, parStyle); - } - } catch (UndefinedParagraphFormatException ex) { - String message = - String.format("Could not apply paragraph format '%s' to bibliography header", - parStyle); - LOGGER.warn(message); // No stack trace. - } + style.getFormattedBibliographyTitle(), + null); cursor.collapseToEnd(); + // remove the inital empty paragraph from the section. + XTextCursor initialParagraph = (documentConnection.xText + .createTextCursorByRange(section.getAnchor())); + initialParagraph.collapseToStart(); + initialParagraph.goRight((short) 1, true); + initialParagraph.setString(""); + // emit body insertFullReferenceAtCursor(documentConnection, cursor, From f161808d3f2035ee05e39aa0ea8fbe2a3ba8d225 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 28 Apr 2021 08:39:38 +0200 Subject: [PATCH 0648/1068] renamed formatTextInCursor2 to formatTextInCursor --- .../org/jabref/logic/openoffice/OOUtil.java | 34 +++++++------------ 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 92e3dea54dc..2f1de86b7a0 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -29,7 +29,7 @@ public class OOUtil { /* - * When passed to formatTextInCursor2, RESET supplies default + * When passed to formatTextInCursor, RESET supplies default * values for features not controlled by the OOFormattedText input. */ public static final List RESET = List.of(FontWeightDefault(), @@ -98,10 +98,10 @@ public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection doc String currentSubstring = lText.substring(piv, m.start()); if (!currentSubstring.isEmpty()) { text.insertString(cursor, currentSubstring, true); - OOUtil.formatTextInCursor2(documentConnection, - cursor, - formatters, - reset); + OOUtil.formatTextInCursor(documentConnection, + cursor, + formatters, + reset); } cursor.collapseToEnd(); XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); @@ -181,10 +181,10 @@ public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection doc if (piv < lText.length()) { text.insertString(cursor, lText.substring(piv), true); - OOUtil.formatTextInCursor2(documentConnection, - cursor, - formatters, - reset); + OOUtil.formatTextInCursor(documentConnection, + cursor, + formatters, + reset); cursor.collapseToEnd(); } } @@ -616,10 +616,10 @@ static Formatter SetCharStyle(String charStyle) { * @param formatters Formatters to apply (normally extracted from OOFormattedText) * @param reset Formatters to apply before those in formatters. May be null. */ - public static void formatTextInCursor2(DocumentConnection documentConnection, - XTextCursor cursor, - Stack formatters, - List reset) + public static void formatTextInCursor(DocumentConnection documentConnection, + XTextCursor cursor, + Stack formatters, + List reset) throws UnknownPropertyException, PropertyVetoException, @@ -673,14 +673,6 @@ public static void insertTextAtCurrentLocation(XTextCursor cursor, * @param htmlMarkup If true, the text belonging to the * reference mark is surrounded by bold html tag. * - * TODO: This method could go to OOUtil, except that it refers to - * DocumentConnection, which is in "gui". DocumentConnection - * should go to "logic" as well. As well as many others, ... - * - * TODO: there is also a potential distinction between OO-specific - * parts and those that could participate in for example a Word - * panel. Is the GUI itself dependent on using OO/LO? Hard to - * tell. */ public static String getCursorStringWithContext(DocumentConnection documentConnection, XTextCursor cursor, From ed732d5568f5d41d59294816495406aac7d6ee22 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 29 Apr 2021 10:34:31 +0200 Subject: [PATCH 0649/1068] drop RESET and the reset parameter of insertOOFormattedTextAtCurrentLocation --- .../org/jabref/gui/openoffice/OOBibBase.java | 13 +++---- .../org/jabref/logic/openoffice/OOUtil.java | 38 +++++-------------- 2 files changed, 15 insertions(+), 36 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index fd0daa4db34..7bc6b56f7b6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -448,7 +448,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti String charStyle = style.getCitationCharacterFormat(); citationText2 = OOFormat.setCharStyle(citationText2, charStyle); } - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, citationText2, null); + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, citationText2); } else { cursor.setString(""); } @@ -1013,7 +1013,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, int number = ck.number.get(); OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, marker, null); + OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, marker); cursor.collapseToEnd(); } else { // !style.isNumberEntries() : emit no prefix @@ -1026,8 +1026,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, - referenceDetails, - null); + referenceDetails); cursor.collapseToEnd(); // Try to list citations: if (true) { @@ -1069,8 +1068,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // Insert the formatted text: OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, - formattedText, - null); + formattedText); cursor.collapseToEnd(); } } @@ -1169,8 +1167,7 @@ private void populateBibTextSection(DocumentConnection documentConnection, // emit the title of the bibliography OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, - style.getFormattedBibliographyTitle(), - null); + style.getFormattedBibliographyTitle()); cursor.collapseToEnd(); // remove the inital empty paragraph from the section. diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 2f1de86b7a0..11f0c753577 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -1,6 +1,5 @@ package org.jabref.logic.openoffice; -import java.util.List; import java.util.Optional; import java.util.Stack; import java.util.regex.Matcher; @@ -28,16 +27,6 @@ @AllowedToUseAwt("Requires AWT for changing document properties") public class OOUtil { - /* - * When passed to formatTextInCursor, RESET supplies default - * values for features not controlled by the OOFormattedText input. - */ - public static final List RESET = List.of(FontWeightDefault(), - FontSlantDefault(), - CaseMapDefault(), - CharEscapementDefault(), - FontUnderlineDefault(), - FontStrikeoutDefault()); private static final Logger LOGGER = LoggerFactory.getLogger(OOUtil.class); @@ -65,8 +54,6 @@ private OOUtil() { * @param documentConnection * @param position The cursor giving the insert location. Not modified. * @param ootext The marked-up text to insert. - * @param reset Formatters to apply before those given by markup in ootext. - * May be null. * @throws WrappedTargetException * @throws PropertyVetoException * @throws UnknownPropertyException @@ -74,8 +61,7 @@ private OOUtil() { */ public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection documentConnection, XTextCursor position, - OOFormattedText ootext, - List reset) + OOFormattedText ootext) throws UnknownPropertyException, PropertyVetoException, @@ -98,11 +84,10 @@ public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection doc String currentSubstring = lText.substring(piv, m.start()); if (!currentSubstring.isEmpty()) { text.insertString(cursor, currentSubstring, true); - OOUtil.formatTextInCursor(documentConnection, - cursor, - formatters, - reset); } + OOUtil.formatTextInCursor(documentConnection, + cursor, + formatters); cursor.collapseToEnd(); XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); String tag = m.group(); @@ -181,12 +166,11 @@ public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection doc if (piv < lText.length()) { text.insertString(cursor, lText.substring(piv), true); - OOUtil.formatTextInCursor(documentConnection, - cursor, - formatters, - reset); - cursor.collapseToEnd(); } + OOUtil.formatTextInCursor(documentConnection, + cursor, + formatters); + cursor.collapseToEnd(); } interface Formatter { @@ -609,17 +593,15 @@ static Formatter SetCharStyle(String charStyle) { } /** - * Apply Formatters in reset, then those on the stack. + * Apply Formatters on the stack. * * @param documentConnection passed to each Formatter * @param cursor Marks the text to format * @param formatters Formatters to apply (normally extracted from OOFormattedText) - * @param reset Formatters to apply before those in formatters. May be null. */ public static void formatTextInCursor(DocumentConnection documentConnection, XTextCursor cursor, - Stack formatters, - List reset) + Stack formatters) throws UnknownPropertyException, PropertyVetoException, From ed2e80d2c377cddca61829814de4cd7856bf33e4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 29 Apr 2021 10:35:22 +0200 Subject: [PATCH 0650/1068] drop obsolete comment --- src/main/java/org/jabref/logic/oostyle/OOFormat.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index 88d1d0554cd..8d230e08a38 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -19,8 +19,6 @@ public class OOFormat { * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. * * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation() - * - * TODO: this is not OO-specific, should be in oostyle */ public static OOFormattedText formatFullReference(Layout layout, BibEntry entry, From 3ea4126474179a83585c81b6228da7bcae2d8442 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 30 Apr 2021 19:45:54 +0200 Subject: [PATCH 0651/1068] renamae insertOOFormattedTextAtCurrentLocation to insertOOFormattedTextAtCurrentLocation2 --- .../org/jabref/gui/openoffice/OOBibBase.java | 23 ++++++++++--------- .../org/jabref/logic/oostyle/OOFormat.java | 2 +- .../org/jabref/logic/openoffice/OOUtil.java | 6 ++--- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7bc6b56f7b6..0d67071df16 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -448,7 +448,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti String charStyle = style.getCitationCharacterFormat(); citationText2 = OOFormat.setCharStyle(citationText2, charStyle); } - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, citationText2); + OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, cursor, citationText2); } else { cursor.setString(""); } @@ -1013,7 +1013,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, int number = ck.number.get(); OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, cursor, marker); + OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, cursor, marker); cursor.collapseToEnd(); } else { // !style.isNumberEntries() : emit no prefix @@ -1024,9 +1024,9 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // Unresolved entry OOFormattedText referenceDetails = OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, - cursor, - referenceDetails); + OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, + cursor, + referenceDetails); cursor.collapseToEnd(); // Try to list citations: if (true) { @@ -1066,9 +1066,9 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, ck.uniqueLetter.orElse(null)); // Insert the formatted text: - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, - cursor, - formattedText); + OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, + cursor, + formattedText); cursor.collapseToEnd(); } } @@ -1165,9 +1165,10 @@ private void populateBibTextSection(DocumentConnection documentConnection, .createTextCursorByRange(section.getAnchor())); // emit the title of the bibliography - OOUtil.insertOOFormattedTextAtCurrentLocation(documentConnection, - cursor, - style.getFormattedBibliographyTitle()); + OOUtil.removeDirectFormatting(documentConnection, cursor); + OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, + cursor, + style.getFormattedBibliographyTitle()); cursor.collapseToEnd(); // remove the inital empty paragraph from the section. diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index 8d230e08a38..b154d359478 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -18,7 +18,7 @@ public class OOFormat { * @param database The database the entry belongs to. * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. * - * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation() + * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation2() */ public static OOFormattedText formatFullReference(Layout layout, BibEntry entry, diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 11f0c753577..f9a2b52349a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -59,9 +59,9 @@ private OOUtil() { * @throws UnknownPropertyException * @throws IllegalArgumentException */ - public static void insertOOFormattedTextAtCurrentLocation(DocumentConnection documentConnection, - XTextCursor position, - OOFormattedText ootext) + public static void insertOOFormattedTextAtCurrentLocation2(DocumentConnection documentConnection, + XTextCursor position, + OOFormattedText ootext) throws UnknownPropertyException, PropertyVetoException, From 515a450e962dd3a8bb7c2b1b8201e310b88b2835 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 30 Apr 2021 19:47:18 +0200 Subject: [PATCH 0652/1068] document OOFormat methods --- .../org/jabref/logic/oostyle/OOFormat.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index b154d359478..815f17045fc 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -48,28 +48,61 @@ public static OOFormattedText formatFullReference(Layout layout, return formattedText; } + /** + * Mark {@code s} as using a character locale known to OO. + * + * @param locale language[-country[-territory]] + * + * https://www.openoffice.org/api/docs/common/ref/com/sun/star/lang/Locale.html + * + * The country part is optional. + * + * The territory part is not only optional, the allowed "codes are + * vendor and browser-specific", so probably best to avoid them if possible. + * + */ public static OOFormattedText setLocale(OOFormattedText s, String locale) { return OOFormattedText.fromString(String.format("", locale) + s.asString() + ""); } + /** + * Mark {@code s} as using the character locale "zxx", which means + * "no language", "no linguistic content". + * + * Used around citation marks, probably to turn off spellchecking. + * + */ public static OOFormattedText setLocaleNone(OOFormattedText s) { return OOFormat.setLocale(s, "zxx"); } + /** + * Mark {@code s} using a character style {@code charStyle} + * + * @param charStyle Name of a character style known to OO. May be + * empty for "Standard", which in turn means do not override any properties. + * + */ public static OOFormattedText setCharStyle(OOFormattedText s, String charStyle) { return OOFormattedText.fromString(String.format("", charStyle) + s.asString() + ""); } + /** + * Mark {@code s} as part of a paragraph with style {@code paraStyle} + */ public static OOFormattedText paragraph(OOFormattedText s, String paraStyle) { return OOFormattedText.fromString(String.format("

", paraStyle) + s.asString() + "

"); } + /** + * Mark {@code s} as part of a paragraph. + */ public static OOFormattedText paragraph(OOFormattedText s) { return OOFormattedText.fromString("

" + s.asString() From ee024dfb083c4714276aba7400ee6ff731820c48 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 30 Apr 2021 19:49:27 +0200 Subject: [PATCH 0653/1068] insertOOFormattedTextAtCurrentLocation2 : closing tags now properly restore insertOOFormattedTextAtCurrentLocation2 : closing tags now properly restore the state of the property changes at the start tag --- .../org/jabref/logic/openoffice/OOUtil.java | 555 ++++++++++++------ 1 file changed, 372 insertions(+), 183 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index f9a2b52349a..ce12f38dac2 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -1,5 +1,8 @@ package org.jabref.logic.openoffice; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Stack; import java.util.regex.Matcher; @@ -8,9 +11,12 @@ import org.jabref.architecture.AllowedToUseAwt; import org.jabref.logic.oostyle.OOFormattedText; +import com.sun.star.beans.PropertyState; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.beans.XMultiPropertyStates; import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.XPropertyState; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; @@ -39,14 +45,38 @@ public class OOUtil { private static final String CHAR_ESCAPEMENT_HEIGHT = "CharEscapementHeight"; private static final String CHAR_ESCAPEMENT = "CharEscapement"; private static final String CHAR_STYLE_NAME = "CharStyleName"; + private static final String CHAR_LOCALE = "CharLocale"; + private static final String TAG_NAME_REGEXP = "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|font|locale)"; + private static final String ATTRIBUTE_NAME_REGEXP = "(?:class|value)"; + private static final String ATTRIBUTE_VALUE_REGEXP = "\"([^\"]*)\""; private static final Pattern HTML_TAG = - Pattern.compile("|<(p|font|locale)\\s+(class|value)=\"([^\"]+)\">"); + Pattern.compile("<(/" + TAG_NAME_REGEXP + ")>" + + "|" + + "<(" + TAG_NAME_REGEXP + ")" + + "((?:\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP + ")*)" + + ">"); + private static final Pattern ATTRIBUTE_PATTERN = + Pattern.compile("\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP); private OOUtil() { // Just to hide the public constructor } + private static Map parseAttributes(String s) { + Map res = new HashMap<>(); + if (s == null) { + return res; + } + Matcher m = OOUtil.ATTRIBUTE_PATTERN.matcher(s); + while (m.find()) { + String key = m.group(1); + String value = m.group(2); + res.put(key, value); + } + return res; + } + /** * Insert a text with formatting indicated by HTML-like tags, into * a text at the position given by a cursor. @@ -76,6 +106,7 @@ public static void insertOOFormattedTextAtCurrentLocation2(DocumentConnection do cursor.collapseToEnd(); Stack formatters = new Stack<>(); + Stack expectEnd = new Stack<>(); // We need to extract formatting. Use a simple regexp search iteration: int piv = 0; @@ -89,76 +120,98 @@ public static void insertOOFormattedTextAtCurrentLocation2(DocumentConnection do cursor, formatters); cursor.collapseToEnd(); - XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); - String tag = m.group(); - String xtag = m.group(1); - String xvar = m.group(2); - String xval = m.group(3); + + // XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); + + String fullTag = m.group(); + String endTagName = m.group(1); + String startTagName = m.group(2); + String attributeListPart = m.group(3); + boolean isStartTag = (endTagName == null) || "".equals(endTagName); + String tagName = isStartTag ? startTagName : endTagName; + Objects.requireNonNull(tagName); + + Map attributes = parseAttributes(attributeListPart); + // Handle tags: - if ("".equals(tag)) { + switch (tagName) { + case "b": formatters.push(Bold()); - } else if ("".equals(tag)) { - formatters.pop().applyEnd(documentConnection, xCursorProps); - } else if ("".equals(tag) || "".equals(tag)) { + expectEnd.push("/" + tagName); + break; + case "i": + case "em": formatters.push(Italic()); - } else if ("".equals(tag) || "".equals(tag)) { - formatters.pop().applyEnd(documentConnection, xCursorProps); - } else if ("".equals(tag)) { - // nop - } else if ("".equals(tag)) { - // nop - } else if ("".equals(tag)) { + expectEnd.push("/" + tagName); + break; + case "smallcaps": formatters.push(SmallCaps()); - } else if ("".equals(tag)) { - formatters.pop().applyEnd(documentConnection, xCursorProps); - } else if ("".equals(tag)) { + expectEnd.push("/" + tagName); + break; + case "sup": formatters.push(SuperScript()); - } else if ("".equals(tag)) { - formatters.pop().applyEnd(documentConnection, xCursorProps); - } else if ("".equals(tag)) { + expectEnd.push("/" + tagName); + break; + case "sub": formatters.push(SubScript()); - } else if ("".equals(tag)) { - formatters.pop().applyEnd(documentConnection, xCursorProps); - } else if ("".equals(tag)) { + expectEnd.push("/" + tagName); + break; + case "u": formatters.push(Underline()); - } else if ("".equals(tag)) { - formatters.pop().applyEnd(documentConnection, xCursorProps); - } else if ("".equals(tag)) { + expectEnd.push("/" + tagName); + break; + case "s": formatters.push(Strikeout()); - } else if ("".equals(tag)) { - formatters.pop().applyEnd(documentConnection, xCursorProps); - } else if ("

".equals(tag)) { + expectEnd.push("/" + tagName); + break; + case "/p": // nop - } else if ("p".equals(xtag) || "

".equals(tag)) { + break; + case "p": + String cls = attributes.get("class"); //

OOUtil.insertParagraphBreak(text, cursor); cursor.collapseToEnd(); - if ("class".equals(xvar) && xval != null && !xval.equals("")) { + if (cls != null && !cls.equals("")) { try { - DocumentConnection.setParagraphStyle(cursor, xval); + DocumentConnection.setParagraphStyle(cursor, cls); } catch (UndefinedParagraphFormatException ex) { // ignore silently } } - } else if ("font".equals(xtag) || "".equals(tag)) { - // - if ("class".equals(xvar)) { - formatters.push(SetCharStyle(xval)); - } else { - formatters.push(SetCharStyle(null)); - } - } else if ("".equals(tag)) { - formatters.pop().applyEnd(documentConnection, xCursorProps); - } else if ("locale".equals(xtag)) { + break; + case "font": + formatters.push(SetCharStyle(attributes.get("class"))); + expectEnd.push("/" + tagName); + break; + case "tt": + // Note: "Example" names a character style in LibreOffice. + formatters.push(SetCharStyle("Example")); + expectEnd.push("/" + tagName); + break; + case "locale": // // - if ("value".equals(xvar)) { - formatters.push(SetLocale(xval)); - } else { - formatters.push(SetLocale(null)); + formatters.push(SetLocale(attributes.get("value"))); + expectEnd.push("/" + tagName); + break; + case "/b": + case "/i": + case "/em": + case "/tt": + case "/smallcaps": + case "/sup": + case "/sub": + case "/u": + case "/s": + case "/font": + case "/locale": + formatters.pop().applyEnd(documentConnection, cursor); + String expected = expectEnd.pop(); + if (!tagName.equals(expected)) { + LOGGER.warn(String.format("expected '<%s>', found '<%s>'", expected, tagName)); } - } else if ("".equals(tag)) { - formatters.pop().applyEnd(documentConnection, xCursorProps); + break; } piv = m.end(); @@ -173,8 +226,25 @@ public static void insertOOFormattedTextAtCurrentLocation2(DocumentConnection do cursor.collapseToEnd(); } + /** + * Problem: in some cases we do not want to inherit direct + * formatting from the context. + * + * In particular, when filling the bibliography title. + */ + public static void removeDirectFormatting(DocumentConnection documentConnection, XTextCursor cursor) { + // Probably this is the official solution. + // (Throws no exceptions) + XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); + mpss.setAllPropertiesToDefault(); + } + interface Formatter { - public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + /* + * Note: apply may be called multiple times, but should pick up old value + * at its first call. + */ + public void apply(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, @@ -182,7 +252,7 @@ public void apply(DocumentConnection documentConnection, XPropertySet xCursorPro IllegalArgumentException, NoSuchElementException; - public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, @@ -191,264 +261,389 @@ public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursor NoSuchElementException; } + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if available, + * otherwise null + */ + private static T unoQI(Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + + /** + * Remove direct formatting of propertyName from propertySet. + * + * Observation: while + * XPropertyState.setPropertyToDefault(propertyName) does reset + * the property, it also has a side effect (probably bug in LO + * 6.4.6.2) that it also resets other properties. + * + * Wrokaround: + * (https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=105117) + * + * Use setPropertyValue with either result from + * getPropertyValue to restore the earlier state or with + * result from getPropertyDefault. In this case the property + * "CharStyleName" has to be handled specially, by mapping the + * received value "" to "Standard". Hopefully other + * properties will not need special handling. + * + */ + private static void setPropertyToDefault(XTextCursor cursor, String propertyName) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + // setPropertyToDefault("CharWeight") also removes "CharColor" + + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + if ("CharStyleName".equals(propertyName)) { + String value = "Standard"; + propertySet.setPropertyValue(propertyName, value); + } else { + Object value = propertyState.getPropertyDefault(propertyName); + propertySet.setPropertyValue(propertyName, value); + } + } + + /** + * We rely on property values being ether DIRECT_VALUE or + * DEFAULT_VALUE (not AMBIGUOUS_VALUE). If the cursor covers a homogeneous region, + * or is collapsed, then this is true. + */ + private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) + throws + UnknownPropertyException { + XPropertyState propState = unoQI(XPropertyState.class, cursor); + PropertyState pst = propState.getPropertyState(propertyName); + if (pst == PropertyState.AMBIGUOUS_VALUE) { + throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE" + + " (expected properties for a homogeneous cursor)"); + } + return pst == PropertyState.DEFAULT_VALUE; + } + + private static Optional getPropertyValue(XTextCursor cursor, String propertyName) + throws + UnknownPropertyException, + WrappedTargetException { + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + if (isPropertyDefault(cursor, propertyName)) { + return Optional.empty(); + } else { + return Optional.of(propertySet.getPropertyValue(propertyName)); + } + } + + private static void setPropertyValue(XTextCursor cursor, String propertyName, Optional value) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + if (value.isPresent()) { + propertySet.setPropertyValue(propertyName, value.get()); + } else { + setPropertyToDefault(cursor, propertyName); + } + } + static class FontWeight implements Formatter { - float oldWeight; - float myWeight; - FontWeight(float weight) { + Optional myWeight; + Optional oldWeight; + boolean started; + FontWeight(Optional weight) { this.myWeight = weight; + this.started = false; } @Override - public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void apply(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - oldWeight = (float) xCursorProps.getPropertyValue(CHAR_WEIGHT); - xCursorProps.setPropertyValue(CHAR_WEIGHT, myWeight); + if (!started) { + oldWeight = getPropertyValue(cursor, CHAR_WEIGHT).map(e -> (float) e); + started = true; + } + + setPropertyValue(cursor, CHAR_WEIGHT, myWeight); } @Override - public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - xCursorProps.setPropertyValue(CHAR_WEIGHT, oldWeight); + setPropertyValue(cursor, CHAR_WEIGHT, oldWeight); } } static Formatter Bold() { - return new FontWeight(com.sun.star.awt.FontWeight.BOLD); + return new FontWeight(Optional.of(com.sun.star.awt.FontWeight.BOLD)); } static Formatter FontWeightDefault() { - return new FontWeight(com.sun.star.awt.FontWeight.NORMAL); + return new FontWeight(Optional.of(com.sun.star.awt.FontWeight.NORMAL)); } static class FontSlant implements Formatter { - com.sun.star.awt.FontSlant oldSlant; - com.sun.star.awt.FontSlant mySlant; + Optional mySlant; + Optional oldSlant; + boolean started; - FontSlant(com.sun.star.awt.FontSlant slant) { + FontSlant(Optional slant) { this.mySlant = slant; + this.oldSlant = Optional.empty(); + this.started = false; } @Override - public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void apply(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - oldSlant = (com.sun.star.awt.FontSlant) xCursorProps.getPropertyValue(CHAR_POSTURE); - xCursorProps.setPropertyValue(CHAR_POSTURE, mySlant); + if (!started) { + oldSlant = getPropertyValue(cursor, CHAR_POSTURE).map(e -> (com.sun.star.awt.FontSlant) e); + started = true; + } + setPropertyValue(cursor, CHAR_POSTURE, mySlant); } @Override - public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - xCursorProps.setPropertyValue(CHAR_POSTURE, oldSlant); + setPropertyValue(cursor, CHAR_POSTURE, oldSlant); } } static Formatter Italic() { - return new FontSlant(com.sun.star.awt.FontSlant.ITALIC); + return new FontSlant(Optional.of(com.sun.star.awt.FontSlant.ITALIC)); } static Formatter FontSlantDefault() { - return new FontSlant(com.sun.star.awt.FontSlant.NONE); + return new FontSlant(Optional.of(com.sun.star.awt.FontSlant.NONE)); } /* * com.sun.star.style.CaseMap */ static class CaseMap implements Formatter { - short old; - short my; + Optional my; + Optional old; + boolean started; - CaseMap(short value) { + CaseMap(Optional value) { this.my = value; + this.started = false; } @Override - public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void apply(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - old = (short) xCursorProps.getPropertyValue(CHAR_CASE_MAP); - xCursorProps.setPropertyValue(CHAR_CASE_MAP, my); + if (!started) { + old = getPropertyValue(cursor, CHAR_CASE_MAP).map(e -> (short) e); + started = true; + } + setPropertyValue(cursor, CHAR_CASE_MAP, my); } @Override - public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - xCursorProps.setPropertyValue(CHAR_CASE_MAP, old); + setPropertyValue(cursor, CHAR_CASE_MAP, old); } } static Formatter SmallCaps() { - return new CaseMap(com.sun.star.style.CaseMap.SMALLCAPS); + return new CaseMap(Optional.of(com.sun.star.style.CaseMap.SMALLCAPS)); } static Formatter CaseMapDefault() { - return new CaseMap(com.sun.star.style.CaseMap.NONE); + return new CaseMap(Optional.of(com.sun.star.style.CaseMap.NONE)); } static class CharEscapement implements Formatter { - short oldValue; - byte oldHeight; + Optional myValue; + Optional myHeight; - short myValue; - byte myHeight; + Optional oldValue; + Optional oldHeight; + boolean started; - CharEscapement(short value, byte height) { + CharEscapement(Optional value, Optional height) { myValue = value; myHeight = height; + oldValue = Optional.empty(); + oldHeight = Optional.empty(); + started = false; } @Override - public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void apply(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - oldValue = (short) xCursorProps.getPropertyValue(CHAR_ESCAPEMENT); - oldHeight = (byte) xCursorProps.getPropertyValue(CHAR_ESCAPEMENT_HEIGHT); - - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, myValue); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, myHeight); + if (!started) { + oldValue = getPropertyValue(cursor, CHAR_ESCAPEMENT).map(e -> (short) e); + oldHeight = getPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT).map(e -> (byte) e); + started = true; + } + setPropertyValue(cursor, CHAR_ESCAPEMENT, myValue); + setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, myHeight); } @Override - public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, oldValue); - xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, oldHeight); + setPropertyValue(cursor, CHAR_ESCAPEMENT, oldValue); + setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, oldHeight); } } static Formatter SubScript() { - return new CharEscapement((short) -10, (byte) 58); + return new CharEscapement(Optional.of((short) -10), Optional.of((byte) 58)); } static Formatter SuperScript() { - return new CharEscapement((short) 33, (byte) 58); + return new CharEscapement(Optional.of((short) 33), Optional.of((byte) 58)); } static Formatter CharEscapementDefault() { - return new CharEscapement((short) 0, (byte) 100); + return new CharEscapement(Optional.of((short) 0), Optional.of((byte) 100)); } /* * com.sun.star.awt.FontUnderline */ static class FontUnderline implements Formatter { - short oldValue; - short myValue; + Optional myValue; + Optional oldValue; + boolean started; - FontUnderline(short value) { + FontUnderline(Optional value) { this.myValue = value; + this.oldValue = Optional.empty(); + this.started = false; } @Override - public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void apply(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - oldValue = (short) xCursorProps.getPropertyValue(CHAR_UNDERLINE); - xCursorProps.setPropertyValue(CHAR_UNDERLINE, myValue); + if (!started) { + oldValue = getPropertyValue(cursor, CHAR_UNDERLINE).map(e -> (short) e); + started = true; + } + setPropertyValue(cursor, CHAR_UNDERLINE, myValue); } @Override - public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - xCursorProps.setPropertyValue(CHAR_UNDERLINE, oldValue); + setPropertyValue(cursor, CHAR_UNDERLINE, oldValue); } } static Formatter Underline() { - return new FontUnderline(com.sun.star.awt.FontUnderline.SINGLE); + return new FontUnderline(Optional.of(com.sun.star.awt.FontUnderline.SINGLE)); } static FontUnderline FontUnderlineDefault() { - return new FontUnderline(com.sun.star.awt.FontUnderline.NONE); + return new FontUnderline(Optional.of(com.sun.star.awt.FontUnderline.NONE)); } /* * com.sun.star.awt.FontStrikeout */ static class FontStrikeout implements Formatter { - short oldValue; - short myValue; + Optional myValue; + Optional oldValue; + boolean started; - FontStrikeout(short value) { + FontStrikeout(Optional value) { this.myValue = value; + this.oldValue = Optional.empty(); + this.started = false; } @Override - public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void apply(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - oldValue = (short) xCursorProps.getPropertyValue(CHAR_STRIKEOUT); - xCursorProps.setPropertyValue(CHAR_STRIKEOUT, myValue); + if (!started) { + oldValue = getPropertyValue(cursor, CHAR_STRIKEOUT).map(e -> (short) e); + started = true; + } + setPropertyValue(cursor, CHAR_STRIKEOUT, myValue); } @Override - public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - xCursorProps.setPropertyValue(CHAR_STRIKEOUT, oldValue); + setPropertyValue(cursor, CHAR_STRIKEOUT, oldValue); } } static Formatter Strikeout() { - return new FontStrikeout(com.sun.star.awt.FontStrikeout.SINGLE); + return new FontStrikeout(Optional.of(com.sun.star.awt.FontStrikeout.SINGLE)); } static Formatter FontStrikeoutDefault() { - return new FontStrikeout(com.sun.star.awt.FontStrikeout.NONE); + return new FontStrikeout(Optional.of(com.sun.star.awt.FontStrikeout.NONE)); } /* @@ -457,57 +652,59 @@ static Formatter FontStrikeoutDefault() { static class CharLocale implements Formatter { private Optional myLocale; private Optional oldLocale; + private boolean started; CharLocale(Optional locale) { this.myLocale = locale; this.oldLocale = Optional.empty(); + this.started = false; } @Override - public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void apply(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - if (myLocale.isPresent()) { - try { - Locale old = (Locale) xCursorProps.getPropertyValue("CharLocale"); - oldLocale = Optional.of(old); - xCursorProps.setPropertyValue("CharLocale", myLocale.get()); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - // silently + try { + if (!started) { + oldLocale = getPropertyValue(cursor, CHAR_LOCALE).map(e -> (Locale) e); + started = true; } + setPropertyValue(cursor, CHAR_LOCALE, myLocale); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + LOGGER.warn("CharLocale.apply caught", ex); } } @Override - public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - if (oldLocale.isPresent()) { - try { - xCursorProps.setPropertyValue("CharLocale", oldLocale.get()); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - // silently - } + try { + setPropertyValue(cursor, CHAR_LOCALE, oldLocale); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + LOGGER.warn("CharLocale.applyEnd caught", ex); } } } - /* + /** * Locale from string encoding: language, language-country or language-country-variant + * + * @param value Empty or null encodes "remove direct formatting" */ static Formatter SetLocale(String value) { if (value == null || "".equals(value)) { @@ -522,69 +719,71 @@ static Formatter SetLocale(String value) { return new CharLocale(Optional.of(l)); } - /* + /** * Set a character style known to OO/LO + * + * Optional.empty() encodes (remove direct formatting) both in + * myCharStyle and in oldCharStyle. + * */ static class CharStyleName implements Formatter { private Optional myCharStyle; private Optional oldCharStyle; + private boolean started; public CharStyleName(Optional charStyle) { this.myCharStyle = charStyle; this.oldCharStyle = Optional.empty(); + this.started = false; } @Override - public void apply(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void apply(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - if (myCharStyle.isPresent() && !myCharStyle.get().equals("")) { - if (documentConnection - .getInternalNameOfCharacterStyle(myCharStyle.get()).isPresent()) { - try { - String old = (String) xCursorProps.getPropertyValue(CHAR_STYLE_NAME); - oldCharStyle = Optional.of(old); - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, myCharStyle.get()); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - // silently - } + try { + if (!started) { + oldCharStyle = getPropertyValue(cursor, CHAR_STYLE_NAME).map(e -> (String) e); + started = true; } - // otherwise: ignore silently. Assume character style was already tested elsewhere. + setPropertyValue(cursor, CHAR_STYLE_NAME, myCharStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + LOGGER.warn("CharStyleName.apply caught", ex); } } @Override - public void applyEnd(DocumentConnection documentConnection, XPropertySet xCursorProps) + public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, NoSuchElementException { - if (oldCharStyle.isPresent() && !oldCharStyle.get().equals("")) { - if (documentConnection - .getInternalNameOfCharacterStyle(oldCharStyle.get()).isPresent()) { - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, oldCharStyle.get()); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - // silently - } - } - // otherwise: ignore silently. Assume character style was already tested elsewhere. + + try { + setPropertyValue(cursor, CHAR_STYLE_NAME, oldCharStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + LOGGER.warn("CharStyleName.applyEnd caught", ex); } } + } + /** + * @param charStyle null or "" encodes "remove direct formatting", + * not "do nothing". + */ static Formatter SetCharStyle(String charStyle) { if (charStyle == null || "".equals(charStyle)) { return new CharStyleName(Optional.empty()); @@ -609,18 +808,8 @@ public static void formatTextInCursor(DocumentConnection documentConnection, IllegalArgumentException, NoSuchElementException { - XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); - - // Set properties we do not want to inherit from the context - // and are not controlled by formatters. - if (reset != null) { - for (Formatter f : reset) { - f.apply(documentConnection, xCursorProps); - } - } - for (Formatter f : formatters) { - f.apply(documentConnection, xCursorProps); + f.apply(documentConnection, cursor); } } From 5684dac69349de0f228adcb09ce4f684f5d11afc Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 30 Apr 2021 22:38:52 +0200 Subject: [PATCH 0654/1068] inject ZERO_WIDTH_SPACE into citation marker, to hold the initial character format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0d67071df16..cc37f94b3c7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -448,6 +448,9 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti String charStyle = style.getCitationCharacterFormat(); citationText2 = OOFormat.setCharStyle(citationText2, charStyle); } + // inject a ZERO_WIDTH_SPACE to hold the initial character format + final String ZERO_WIDTH_SPACE = "\u200b"; + citationText2 = OOFormattedText.fromString(ZERO_WIDTH_SPACE + citationText2.asString()); OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, cursor, citationText2); } else { cursor.setString(""); From 60e54ebc0b26df11e5463bd0c053385e601dcb38 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 30 Apr 2021 22:43:28 +0200 Subject: [PATCH 0655/1068] insertFullReferenceAtCursor formats each entry before inserting --- .../org/jabref/gui/openoffice/OOBibBase.java | 44 +++++++------------ 1 file changed, 15 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index cc37f94b3c7..d2e7bac7e8d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -989,23 +989,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, : String.format("%02d", ck.number.get()))); } - // this is where we create the paragraph. - OOUtil.insertParagraphBreak(documentConnection.xText, cursor); - cursor.collapseToEnd(); - // format the paragraph - try { - if (parStyle != null) { - DocumentConnection.setParagraphStyle(cursor, - parStyle); - } - } catch (UndefinedParagraphFormatException ex) { - // TODO: precheck or remember if we already emitted this message. - String message = - String.format("Could not apply paragraph format '%s' to bibliography entry", - parStyle); - LOGGER.warn(message); // no stack trace - } - + StringBuilder sb = new StringBuilder(); // insert marker "[1]" if (style.isNumberEntries()) { @@ -1016,8 +1000,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, int number = ck.number.get(); OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); - OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, cursor, marker); - cursor.collapseToEnd(); + sb.append(marker.asString()); } else { // !style.isNumberEntries() : emit no prefix // TODO: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); @@ -1027,12 +1010,12 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // Unresolved entry OOFormattedText referenceDetails = OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); - OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, - cursor, - referenceDetails); - cursor.collapseToEnd(); + sb.append(referenceDetails.asString()); // Try to list citations: - if (true) { + if (false) { + // + // TODO: not implemented in insertOOFormattedTextAtCurrentLocation2 + // String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); String suffix = ")"; OOUtil.insertTextAtCurrentLocation(cursor, prefix); @@ -1069,12 +1052,15 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, ck.uniqueLetter.orElse(null)); // Insert the formatted text: - OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, - cursor, - formattedText); - cursor.collapseToEnd(); + sb.append(formattedText.asString()); } - } + + OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); + OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, + cursor, + OOFormat.paragraph(entryText, parStyle)); + cursor.collapseToEnd(); + } // for CitedKey } /** From f6790edc5fb62408eabf8c494264daa859a23c99 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 3 May 2021 23:02:45 +0200 Subject: [PATCH 0656/1068] insertOOFormattedTextAtCurrentLocation2 seems to work now --- .../org/jabref/gui/openoffice/OOBibBase.java | 3 +- .../org/jabref/logic/openoffice/OOUtil.java | 276 +++++++++++++++++- 2 files changed, 262 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d2e7bac7e8d..ce0ac3b8587 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1055,6 +1055,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, sb.append(formattedText.asString()); } + // Emit a bibliography entry OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, cursor, @@ -1154,7 +1155,7 @@ private void populateBibTextSection(DocumentConnection documentConnection, .createTextCursorByRange(section.getAnchor())); // emit the title of the bibliography - OOUtil.removeDirectFormatting(documentConnection, cursor); + OOUtil.removeDirectFormatting(cursor); OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, cursor, style.getFormattedBibliographyTitle()); diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index ce12f38dac2..fd9ddaf7038 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -1,9 +1,11 @@ package org.jabref.logic.openoffice; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -11,11 +13,14 @@ import org.jabref.architecture.AllowedToUseAwt; import org.jabref.logic.oostyle.OOFormattedText; +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyAttribute; import com.sun.star.beans.PropertyState; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XMultiPropertyStates; import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.XPropertySetInfo; import com.sun.star.beans.XPropertyState; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.Locale; @@ -47,6 +52,15 @@ public class OOUtil { private static final String CHAR_STYLE_NAME = "CharStyleName"; private static final String CHAR_LOCALE = "CharLocale"; + /* + * SUPERSCRIPT_VALUE and SUPERSCRIPT_HEIGHT are percents of the normal character height + */ + private static final short SUPERSCRIPT_VALUE = (short) 33; + private static final short SUBSCRIPT_VALUE = (short) -10; + private static final byte SUPERSCRIPT_HEIGHT = (byte) 58; + private static final byte SUBSCRIPT_HEIGHT = (byte) 58; + + private static final String TAG_NAME_REGEXP = "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|font|locale)"; private static final String ATTRIBUTE_NAME_REGEXP = "(?:class|value)"; private static final String ATTRIBUTE_VALUE_REGEXP = "\"([^\"]*)\""; @@ -81,6 +95,38 @@ private static Map parseAttributes(String s) { * Insert a text with formatting indicated by HTML-like tags, into * a text at the position given by a cursor. * + * Limitation: understands no entitites. It does not receive any either, unless + * the user provides it. + * + * To limit the damage (and for a bit of self-documenting) + * {@code TAG_NAME_REGEXP} and {@code ATTRIBUTE_NAME_REGEXP} explicitly lists the + * values we care about. + * + * + * Notable changes w.r.t insertOOFormattedTextAtCurrentLocation: + * + * - new tags: + * - <locale value=""> + * - earlier was applied from code + * - <font class=""> + * - earlier was applied from code, for "CitationCharacterFormat" + * - <tt> + * - earlier: known, but ignored (no effect) + * - now: equivalent to <font class="Example"> + * + * - closing tags try to properly restore state instead of dictating + * an "off" state. + * + * - The practical consequence: the user can now format the + * citation mark (it is enough to format its start) and the + * properties not dictated by the style markup are preserved. + * + * A comparable example: a style with + * ReferenceParagraphFormat="JR_bibentry" + * JR_bibentry in LibreOffice, paragraph style prescribes "bold" font. + * LAYOUT only mentions bold around year. + * Which parts of the bibliography entries should come out as bold? + * * @param documentConnection * @param position The cursor giving the insert location. Not modified. * @param ootext The marked-up text to insert. @@ -99,6 +145,11 @@ public static void insertOOFormattedTextAtCurrentLocation2(DocumentConnection do IllegalArgumentException, NoSuchElementException { + final boolean debugThisFun = false; + if (debugThisFun) { + System.out.println(ootext.asString()); + } + String lText = OOFormattedText.toString(ootext); XText text = position.getText(); @@ -112,6 +163,7 @@ public static void insertOOFormattedTextAtCurrentLocation2(DocumentConnection do int piv = 0; Matcher m = OOUtil.HTML_TAG.matcher(lText); while (m.find()) { + String currentSubstring = lText.substring(piv, m.start()); if (!currentSubstring.isEmpty()) { text.insertString(cursor, currentSubstring, true); @@ -121,7 +173,6 @@ public static void insertOOFormattedTextAtCurrentLocation2(DocumentConnection do formatters); cursor.collapseToEnd(); - // XPropertySet xCursorProps = unoQI(XPropertySet.class, cursor); String fullTag = m.group(); String endTagName = m.group(1); @@ -224,19 +275,90 @@ public static void insertOOFormattedTextAtCurrentLocation2(DocumentConnection do cursor, formatters); cursor.collapseToEnd(); + + if (!expectEnd.empty()) { + String rest = ""; + for (String s : expectEnd) { + rest = String.format("<%s>", s) + rest; + } + LOGGER.warn(String.format("insertOOFormattedTextAtCurrentLocation2:" + + " expectEnd stack is not empty at the end: %s%n", + rest)); + } } /** - * Problem: in some cases we do not want to inherit direct + * Purpose: in some cases we do not want to inherit direct * formatting from the context. * - * In particular, when filling the bibliography title. + * In particular, when filling the bibliography title and body. */ - public static void removeDirectFormatting(DocumentConnection documentConnection, XTextCursor cursor) { + public static void removeDirectFormatting(XTextCursor cursor) { // Probably this is the official solution. // (Throws no exceptions) XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); mpss.setAllPropertiesToDefault(); + // Some are not reset by setAllPropertiesToDefault() + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + + try { + // Special handling + propertySet.setPropertyValue(CHAR_STYLE_NAME, "Standard"); + propertyState.setPropertyToDefault(CHAR_STRIKEOUT); + } catch (UnknownPropertyException | + PropertyVetoException | + IllegalArgumentException | + WrappedTargetException ex) { + LOGGER.warn("exception caught", ex); + } + + // Only report those we do not yet know about: + final Set knownToFail = Set.of( + /* + "CharStrikeout", + "CharEscapement", + "CharEscapementHeight", + "CharUnderline", + "CharCrossedOut", + */ + + "ListAutoFormat", + "ListId", + "NumberingIsNumber", + "NumberingLevel", + "NumberingRules", + "NumberingStartValue", + "ParaChapterNumberingLevel", + "ParaIsNumberingRestart", + "ParaStyleName"); + + // query again, just in case it matters + propertySet = unoQI(XPropertySet.class, cursor); + XPropertySetInfo psi = propertySet.getPropertySetInfo(); + + // check the result + for (Property p : psi.getProperties()) { + if ((p.Attributes & PropertyAttribute.READONLY) != 0) { + continue; + } + try { + if (isPropertyDefault(cursor, p.Name)) { + continue; + } + } catch (UnknownPropertyException ex) { + // impossible + } + /* + * If something turns up here, then it needs to be added to + * removeDirectFormatting() + */ + if (knownToFail.contains(p.Name)) { + continue; + } + LOGGER.warn(String.format("OOUtil.removeDirectFormatting failed on '%s'", + p.Name)); + } } interface Formatter { @@ -300,12 +422,83 @@ private static void setPropertyToDefault(XTextCursor cursor, String propertyName XPropertySet propertySet = unoQI(XPropertySet.class, cursor); XPropertyState propertyState = unoQI(XPropertyState.class, cursor); - if ("CharStyleName".equals(propertyName)) { - String value = "Standard"; - propertySet.setPropertyValue(propertyName, value); + + // CharStrikeout and CharCrossedOut interact: if we deafult one, + // we default the other as well. + Set charStrikeOutSet = Set.of(CHAR_STRIKEOUT, "CharCrossedOut"); + Set charEscapementSet = Set.of("CharAutoEscapement", + CHAR_ESCAPEMENT, + CHAR_ESCAPEMENT_HEIGHT); + Set charUnderlineSet = Set.of(CHAR_UNDERLINE, + "CharUnderlineColor", + "CharUnderlineHasColor"); + + Set namesToDefault = new HashSet<>(); + if (charStrikeOutSet.contains(propertyName)) { + namesToDefault = charStrikeOutSet; + } else if (charEscapementSet.contains(propertyName)) { + namesToDefault = charEscapementSet; + } else if (charUnderlineSet.contains(propertyName)) { + namesToDefault = charUnderlineSet; } else { + namesToDefault.add(propertyName); + } + + if (false) { + // This is what should simply work. + // However it loses e.g. font color when propertyName is "CharWeight". + propertyState.setPropertyToDefault(propertyName); + } else if (false) { + // Despite the name getPropertyDefault, storing + // its result by setPropertyValue is NOT equivalent + // to setPropertyToDefault(). + // + // setPropertyToDefault() should remove direct ("hard") formatting, + // setPropertyValue(getPropertyDefault()) can only do that + // if getPropertyDefault provides a value with the meaning + // "use whatever comes from the level above". + // Object value = propertyState.getPropertyDefault(propertyName); propertySet.setPropertyValue(propertyName, value); + } else { + // Try to remove all, then add all directly formatted again, + // except the one we are removing. + XPropertySetInfo psi = propertySet.getPropertySetInfo(); + + Map ds = new HashMap<>(); + for (Property p : psi.getProperties()) { + boolean noRestore = (namesToDefault.contains(p.Name) + || ((p.Attributes & PropertyAttribute.READONLY) != 0) + || (isPropertyDefault(cursor, p.Name))); + if (noRestore) { + continue; + } + ds.put(p.Name, propertySet.getPropertyValue(p.Name)); + } + + OOUtil.removeDirectFormatting(cursor); + if (!isPropertyDefault(cursor, propertyName)) { + LOGGER.warn(String.format("OOUtil.setPropertyToDefault failed (1) on '%s'", + propertyName)); + } + + // restore those saved + for (Map.Entry e : ds.entrySet()) { + propertySet.setPropertyValue(e.getKey(), e.getValue()); + if (!isPropertyDefault(cursor, propertyName)) { + LOGGER.warn(String.format("OOUtil.setPropertyToDefault failed (2) on '%s' after '%s'", + propertyName, e.getKey())); + } + } + if (!isPropertyDefault(cursor, propertyName)) { + /* + * If something turns up here, then it needs to be added to + * removeDirectFormatting() + */ + LOGGER.warn(String.format("OOUtil.setPropertyToDefault failed (3) on '%s'", + propertyName)); + } + } } @@ -317,8 +510,8 @@ private static void setPropertyToDefault(XTextCursor cursor, String propertyName private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) throws UnknownPropertyException { - XPropertyState propState = unoQI(XPropertyState.class, cursor); - PropertyState pst = propState.getPropertyState(propertyName); + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + PropertyState pst = propertyState.getPropertyState(propertyName); if (pst == PropertyState.AMBIGUOUS_VALUE) { throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE" + " (expected properties for a homogeneous cursor)"); @@ -332,6 +525,14 @@ private static Optional getPropertyValue(XTextCursor cursor, String prop WrappedTargetException { XPropertySet propertySet = unoQI(XPropertySet.class, cursor); if (isPropertyDefault(cursor, propertyName)) { + final boolean debugThisFun = false; + if (debugThisFun) { + if (CHAR_STRIKEOUT.equals(propertyName)) { + System.out.printf("OOUtil.getPropertyValue default: '%s' = '%s'%n", + propertyName, + propertySet.getPropertyValue(propertyName)); + } + } return Optional.empty(); } else { return Optional.of(propertySet.getPropertyValue(propertyName)); @@ -352,6 +553,7 @@ private static void setPropertyValue(XTextCursor cursor, String propertyName } static class FontWeight implements Formatter { + final String propertyName = CHAR_WEIGHT; Optional myWeight; Optional oldWeight; boolean started; @@ -368,11 +570,20 @@ public void apply(DocumentConnection documentConnection, XTextCursor cursor) WrappedTargetException, IllegalArgumentException, NoSuchElementException { + final boolean debugThisFun = false; if (!started) { - oldWeight = getPropertyValue(cursor, CHAR_WEIGHT).map(e -> (float) e); + oldWeight = getPropertyValue(cursor, CHAR_WEIGHT).map(e -> (Float) e); + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + if (debugThisFun) { + // float defaultValue = (float) propertyState.getPropertyDefault(propertyName); + System.out.printf("FontWeight.start %s%n", oldWeight); + } started = true; } + if (debugThisFun) { + System.out.printf("FontWeight.apply %s%n", myWeight); + } setPropertyValue(cursor, CHAR_WEIGHT, myWeight); } @@ -384,6 +595,10 @@ public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) WrappedTargetException, IllegalArgumentException, NoSuchElementException { + final boolean debugThisFun = false; + if (debugThisFun) { + System.out.printf("FontWeight.applyEnd %s%n", oldWeight); + } setPropertyValue(cursor, CHAR_WEIGHT, oldWeight); } } @@ -493,14 +708,26 @@ static Formatter CaseMapDefault() { static class CharEscapement implements Formatter { Optional myValue; Optional myHeight; + boolean relative; Optional oldValue; Optional oldHeight; boolean started; - CharEscapement(Optional value, Optional height) { + /** + * Probably either both value and height should be present, or + * neither, because charEscapementSet (or rather, the + * corresponding mechanics in LibreOffice) links them + * together. + * + * @param relative Make value and height relative to oldHeight and oldValue. + * Needed for e^{x_i} e^{x^2} (i.e. sup or sub within sup or sup) + * + */ + CharEscapement(Optional value, Optional height, boolean relative) { myValue = value; myHeight = height; + this.relative = relative; oldValue = Optional.empty(); oldHeight = Optional.empty(); started = false; @@ -519,8 +746,17 @@ public void apply(DocumentConnection documentConnection, XTextCursor cursor) oldHeight = getPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT).map(e -> (byte) e); started = true; } - setPropertyValue(cursor, CHAR_ESCAPEMENT, myValue); - setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, myHeight); + if (relative && myValue.isPresent() && myHeight.isPresent()) { + double oh = oldHeight.orElse((byte) 100) * 0.01; + double xHeight = myHeight.orElse((byte) 100) * oh; + double ov = oldValue.orElse((short) 0); + double xValue = myValue.orElse((short) 0) * oh + ov; + setPropertyValue(cursor, CHAR_ESCAPEMENT, Optional.of((short) Math.round(xValue))); + setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, Optional.of((byte) Math.round(xHeight))); + } else { + setPropertyValue(cursor, CHAR_ESCAPEMENT, myValue); + setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, myHeight); + } } @Override @@ -537,15 +773,15 @@ public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) } static Formatter SubScript() { - return new CharEscapement(Optional.of((short) -10), Optional.of((byte) 58)); + return new CharEscapement(Optional.of(SUBSCRIPT_VALUE), Optional.of(SUBSCRIPT_HEIGHT), true); } static Formatter SuperScript() { - return new CharEscapement(Optional.of((short) 33), Optional.of((byte) 58)); + return new CharEscapement(Optional.of(SUPERSCRIPT_VALUE), Optional.of(SUPERSCRIPT_HEIGHT), true); } static Formatter CharEscapementDefault() { - return new CharEscapement(Optional.of((short) 0), Optional.of((byte) 100)); + return new CharEscapement(Optional.of((short) 0), Optional.of((byte) 100), false); } /* @@ -622,6 +858,10 @@ public void apply(DocumentConnection documentConnection, XTextCursor cursor) if (!started) { oldValue = getPropertyValue(cursor, CHAR_STRIKEOUT).map(e -> (short) e); started = true; + final boolean debugThisFun = false; + if (debugThisFun) { + System.out.printf("FontStrikeout.apply.start %s%n", oldValue); + } } setPropertyValue(cursor, CHAR_STRIKEOUT, myValue); } @@ -634,6 +874,10 @@ public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) WrappedTargetException, IllegalArgumentException, NoSuchElementException { + final boolean debugThisFun = false; + if (debugThisFun) { + System.out.printf("FontStrikeout.applyEnd %s%n", oldValue); + } setPropertyValue(cursor, CHAR_STRIKEOUT, oldValue); } } From ba8db01a01fc23470cbacfa4fdda74013f8a4471 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 5 May 2021 10:07:05 +0200 Subject: [PATCH 0657/1068] refactor: OOFormattedTextIntoOO.java Interpreting OOFormattedText has grown out "util" status, now it has its own class --- .../org/jabref/gui/openoffice/OOBibBase.java | 17 +- .../openoffice/OOFormattedTextIntoOO.java | 788 +++++++++++++ .../org/jabref/logic/openoffice/OOUtil.java | 1037 +---------------- 3 files changed, 798 insertions(+), 1044 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ce0ac3b8587..a19205fa539 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -35,6 +35,7 @@ import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.DocumentConnection; import org.jabref.logic.openoffice.NoDocumentException; +import org.jabref.logic.openoffice.OOFormattedTextIntoOO; import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.OOUtil; import org.jabref.logic.openoffice.UndefinedCharacterFormatException; @@ -451,7 +452,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti // inject a ZERO_WIDTH_SPACE to hold the initial character format final String ZERO_WIDTH_SPACE = "\u200b"; citationText2 = OOFormattedText.fromString(ZERO_WIDTH_SPACE + citationText2.asString()); - OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, cursor, citationText2); + OOFormattedTextIntoOO.write(cursor, citationText2); } else { cursor.setString(""); } @@ -1014,7 +1015,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // Try to list citations: if (false) { // - // TODO: not implemented in insertOOFormattedTextAtCurrentLocation2 + // TODO: not implemented in OOFormattedTextIntoOO.write // String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); String suffix = ")"; @@ -1057,9 +1058,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // Emit a bibliography entry OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); - OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, - cursor, - OOFormat.paragraph(entryText, parStyle)); + entryText = OOFormat.paragraph(entryText, parStyle); + OOFormattedTextIntoOO.write(cursor, entryText); cursor.collapseToEnd(); } // for CitedKey } @@ -1155,10 +1155,9 @@ private void populateBibTextSection(DocumentConnection documentConnection, .createTextCursorByRange(section.getAnchor())); // emit the title of the bibliography - OOUtil.removeDirectFormatting(cursor); - OOUtil.insertOOFormattedTextAtCurrentLocation2(documentConnection, - cursor, - style.getFormattedBibliographyTitle()); + OOFormattedTextIntoOO.removeDirectFormatting(cursor); + OOFormattedText title = style.getFormattedBibliographyTitle(); + OOFormattedTextIntoOO.write(cursor, title); cursor.collapseToEnd(); // remove the inital empty paragraph from the section. diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java new file mode 100644 index 00000000000..1542a37ab0d --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -0,0 +1,788 @@ +package org.jabref.logic.openoffice; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.Stack; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jabref.architecture.AllowedToUseAwt; +import org.jabref.logic.oostyle.OOFormattedText; + +import com.sun.star.awt.FontSlant; +import com.sun.star.awt.FontStrikeout; +import com.sun.star.awt.FontUnderline; +import com.sun.star.awt.FontWeight; +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyAttribute; +import com.sun.star.beans.PropertyState; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.beans.XMultiPropertyStates; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.XPropertySetInfo; +import com.sun.star.beans.XPropertyState; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.Locale; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.style.CaseMap; +import com.sun.star.text.XText; +import com.sun.star.text.XTextCursor; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Interpret OOFormattedText into an OpenOffice or LibreOffice writer + * document. + * + * + */ +@AllowedToUseAwt("Requires AWT for changing document properties") +public class OOFormattedTextIntoOO { + + private static final Logger LOGGER = LoggerFactory.getLogger(OOFormattedTextIntoOO.class); + + /* + * Character property names used in multiple locations below. + */ + private static final String CHAR_ESCAPEMENT_HEIGHT = "CharEscapementHeight"; + private static final String CHAR_ESCAPEMENT = "CharEscapement"; + private static final String CHAR_STYLE_NAME = "CharStyleName"; + private static final String CHAR_UNDERLINE = "CharUnderline"; + private static final String CHAR_STRIKEOUT = "CharStrikeout"; + + /* + * SUPERSCRIPT_VALUE and SUPERSCRIPT_HEIGHT are percents of the normal character height + */ + private static final short CHAR_ESCAPEMENT_VALUE_DEFAULT = (short) 0; + private static final short SUPERSCRIPT_VALUE = (short) 33; + private static final short SUBSCRIPT_VALUE = (short) -10; + private static final byte CHAR_ESCAPEMENT_HEIGHT_DEFAULT = (byte) 100; + private static final byte SUPERSCRIPT_HEIGHT = (byte) 58; + private static final byte SUBSCRIPT_HEIGHT = (byte) 58; + + private static final String TAG_NAME_REGEXP = "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|font|locale)"; + private static final String ATTRIBUTE_NAME_REGEXP = "(?:class|value)"; + private static final String ATTRIBUTE_VALUE_REGEXP = "\"([^\"]*)\""; + private static final Pattern HTML_TAG = + Pattern.compile("<(/" + TAG_NAME_REGEXP + ")>" + + "|" + + "<(" + TAG_NAME_REGEXP + ")" + + "((?:\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP + ")*)" + + ">"); + private static final Pattern ATTRIBUTE_PATTERN = + Pattern.compile("\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP); + + private OOFormattedTextIntoOO() { + // Just to hide the public constructor + } + + /** + * Insert a text with formatting indicated by HTML-like tags, into + * a text at the position given by a cursor. + * + * Limitation: understands no entities. It does not receive any either, unless + * the user provides it. + * + * To limit the damage {@code TAG_NAME_REGEXP} and {@code ATTRIBUTE_NAME_REGEXP} + * explicitly lists the values we care about. + * + * Notable changes w.r.t insertOOFormattedTextAtCurrentLocation: + * + * - new tags: + * - <locale value="zxx"> + * - earlier was applied from code + * - <font class="CharStylename"> + * - earlier was applied from code, for "CitationCharacterFormat" + * - <p> start new paragraph + * - earlier was applied from code + * - <p class="ParStyleName"> : start new paragraph and apply ParStyleName + * - earlier was applied from code + * - <tt> + * - earlier: known, but ignored + * - now: equivalent to <font class="Example"> + * + * - closing tags try to properly restore state instead of dictating + * an "off" state. + * + * - The practical consequence: the user can format + * citation marks (it is enough to format its start) and the + * properties not dictated by the style are preserved. + * + * A comparable example: a style with + * ReferenceParagraphFormat="JR_bibentry" + * JR_bibentry in LibreOffice, paragraph style prescribes "bold" font. + * LAYOUT only mentions bold around year. + * Which parts of the bibliography entries should come out as bold? + * + * @param position The cursor giving the insert location. Not modified. + * @param ootext The marked-up text to insert. + */ + public static void write(XTextCursor position, + OOFormattedText ootext) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + + String lText = OOFormattedText.toString(ootext); + + XText text = position.getText(); + XTextCursor cursor = text.createTextCursorByRange(position); + cursor.collapseToEnd(); + + Stack formatters = new Stack<>(); + Stack expectEnd = new Stack<>(); + + // We need to extract formatting. Use a simple regexp search iteration: + int piv = 0; + Matcher m = HTML_TAG.matcher(lText); + while (m.find()) { + + String currentSubstring = lText.substring(piv, m.start()); + if (!currentSubstring.isEmpty()) { + text.insertString(cursor, currentSubstring, true); + } + formatTextInCursor(cursor, formatters); + cursor.collapseToEnd(); + + String fullTag = m.group(); + String endTagName = m.group(1); + String startTagName = m.group(2); + String attributeListPart = m.group(3); + boolean isStartTag = (endTagName == null) || "".equals(endTagName); + String tagName = isStartTag ? startTagName : endTagName; + Objects.requireNonNull(tagName); + + LinkedHashMap attributes = parseAttributes(attributeListPart); + + // Handle tags: + switch (tagName) { + case "b": + formatters.push(setCharWeight(FontWeight.BOLD)); + expectEnd.push("/" + tagName); + break; + case "i": + case "em": + formatters.push(setCharPosture(FontSlant.ITALIC)); + expectEnd.push("/" + tagName); + break; + case "smallcaps": + formatters.push(setCharCaseMap(CaseMap.SMALLCAPS)); + expectEnd.push("/" + tagName); + break; + case "sup": + formatters.push(SuperScript()); + expectEnd.push("/" + tagName); + break; + case "sub": + formatters.push(SubScript()); + expectEnd.push("/" + tagName); + break; + case "u": + formatters.push(setCharUnderline(FontUnderline.SINGLE)); + expectEnd.push("/" + tagName); + break; + case "s": + formatters.push(setCharStrikeout(FontStrikeout.SINGLE)); + expectEnd.push("/" + tagName); + break; + case "/p": + // nop + break; + case "p": + String cls = attributes.get("class"); + //

+ OOUtil.insertParagraphBreak(text, cursor); + cursor.collapseToEnd(); + if (cls != null && !cls.equals("")) { + try { + DocumentConnection.setParagraphStyle(cursor, cls); + } catch (UndefinedParagraphFormatException ex) { + // ignore silently + } + } + break; + case "tt": + // Note: "Example" names a character style in LibreOffice. + formatters.push(setCharStyleName("Example")); + expectEnd.push("/" + tagName); + break; + case "font": + formatters.push(setCharStyleName(attributes.get("class"))); + expectEnd.push("/" + tagName); + break; + case "locale": + // + // + formatters.push(setCharLocale(attributes.get("value"))); + expectEnd.push("/" + tagName); + break; + case "/b": + case "/i": + case "/em": + case "/tt": + case "/smallcaps": + case "/sup": + case "/sub": + case "/u": + case "/s": + case "/font": + case "/locale": + formatters.pop().applyEnd(cursor); + String expected = expectEnd.pop(); + if (!tagName.equals(expected)) { + LOGGER.warn(String.format("expected '<%s>', found '<%s>'", expected, tagName)); + } + break; + } + + piv = m.end(); + } + + if (piv < lText.length()) { + text.insertString(cursor, lText.substring(piv), true); + } + formatTextInCursor(cursor, formatters); + cursor.collapseToEnd(); + + if (!expectEnd.empty()) { + String rest = ""; + for (String s : expectEnd) { + rest = String.format("<%s>", s) + rest; + } + LOGGER.warn(String.format("insertOOFormattedTextAtCurrentLocation2:" + + " expectEnd stack is not empty at the end: %s%n", + rest)); + } + } + + /** + * Purpose: in some cases we do not want to inherit direct + * formatting from the context. + * + * In particular, when filling the bibliography title and body. + */ + public static void removeDirectFormatting(XTextCursor cursor) { + + XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); + mpss.setAllPropertiesToDefault(); + + /* + * Now that we have setAllPropertiesToDefault, check which properties + * are not set to default and try to correct what we can and seem necessary. + * + * Note: tested with LibreOffice : 6.4.6.2 + */ + + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + + try { + // Special handling + propertySet.setPropertyValue(CHAR_STYLE_NAME, "Standard"); + } catch (UnknownPropertyException | + PropertyVetoException | + IllegalArgumentException | + WrappedTargetException ex) { + LOGGER.warn("exception caught", ex); + } + + // Only report those we do not yet know about + final Set knownToFail = Set.of("ListAutoFormat", + "ListId", + "NumberingIsNumber", + "NumberingLevel", + "NumberingRules", + "NumberingStartValue", + "ParaChapterNumberingLevel", + "ParaIsNumberingRestart", + "ParaStyleName"); + + // query again, just in case it matters + propertySet = unoQI(XPropertySet.class, cursor); + XPropertySetInfo psi = propertySet.getPropertySetInfo(); + + // check the result + for (Property p : psi.getProperties()) { + if ((p.Attributes & PropertyAttribute.READONLY) != 0) { + continue; + } + try { + if (isPropertyDefault(cursor, p.Name)) { + continue; + } + } catch (UnknownPropertyException ex) { + throw new RuntimeException("Unexpected UnknownPropertyException"); + } + if (knownToFail.contains(p.Name)) { + continue; + } + LOGGER.warn(String.format("OOFormattedTextIntoOO.removeDirectFormatting failed on '%s'", + p.Name)); + } + } + + private static LinkedHashMap parseAttributes(String s) { + LinkedHashMap res = new LinkedHashMap<>(); + if (s == null) { + return res; + } + Matcher m = ATTRIBUTE_PATTERN.matcher(s); + while (m.find()) { + String key = m.group(1); + String value = m.group(2); + res.put(key, value); + } + return res; + } + + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if available, + * otherwise null + */ + private static T unoQI(Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + + /** + * Remove direct formatting of propertyName from propertySet. + * + * Observation: while + * XPropertyState.setPropertyToDefault(propertyName) does reset + * the property, it also has a side effect (probably bug in LO + * 6.4.6.2) that it also resets other properties. + * + * For example setPropertyToDefault("CharWeight") also removes "CharColor" + * + * Workaround: + * (https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=105117) + * + * Use setPropertyValue with either result from + * getPropertyValue to restore the earlier state or with + * result from getPropertyDefault. + * + * In either case the property "CharStyleName" has to be handled + * specially, by mapping the received value "" to "Standard". + * Hopefully other properties will not need special handling. + * + * Well, they do. Some properties interact: setting one to + * non-default also sets the other to non-default. Fortunately + * these interactions appear meaningful. For example setting + * "CharCrossedOut" to non-default also modifies "CharStrikeout". + * For the strategy applied here (remove all, then restore all + * except the one we wanted to default) it means we have to avoid + * restoring those that would, as a side-effect set to non-default + * what we promised to set to default. I did not investigate + * potential asymmetries of these interactions, the code below implements + * symmetric behaviour. This means that for example for + * propertyName == "CharCrossedOut" we do not restore + * "CharStrikeout", although the problematic behaviour observed was + * that restoring "CharCrossedOut" changes "CharStrikeout" from its default. + * + */ + private static void setPropertyToDefault(XTextCursor cursor, String propertyName) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + + if (false) { + // This is what should "simply work". + // However it loses e.g. font color when propertyName is "CharWeight". + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + propertyState.setPropertyToDefault(propertyName); + } else if (false) { + + // Despite the name getPropertyDefault, storing + // its result by setPropertyValue is NOT (always) equivalent + // to setPropertyToDefault(). + // + // setPropertyToDefault() should remove direct ("hard") + // formatting. + // + // setPropertyValue(getPropertyDefault()) can only do that + // if getPropertyDefault provides a value with the meaning + // "use whatever comes from the level above". + // + // If the value from getPropertyDefault dictates any + // concrete value for the property and "whatever comes + // from the level above" happens to be a different value, + // then the two behaviours yield different results. + + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + Object value = propertyState.getPropertyDefault(propertyName); + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + propertySet.setPropertyValue(propertyName, value); + } else { + + // Try to remove all, then add all directly formatted again, + // except the one we are removing. And those that would override + // what we try to achieve. + + /* https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Formatting + * at the bottom lists interdependent sets: + * + * Those marked [-] we probably will not touch, [X] handled, [?] maybe will touch. + * + * - [-] ParaRightMargin, ParaLeftMargin, ParaFirstLineIndent, ParaIsAutoFirstLineIndent + * - [-] ParaTopMargin, ParaBottomMargin + * - [-] ParaGraphicURL/Filter/Location, ParaBackColor, ParaBackTransparent + * - [-] ParaIsHyphenation, ParaHyphenationMaxLeadingChars/MaxTrailingChars/MaxHyphens + * - [-] Left/Right/Top/BottomBorder, Left/Right/Top/BottomBorderDistance, BorderDistance + * - [-] DropCapFormat, DropCapWholeWord, DropCapCharStyleName + * - [-] PageDescName, PageNumberOffset, PageStyleName + * + * - [-] CharCombineIsOn, CharCombinePrefix, CharCombineSuffix + * - [-] RubyText, RubyAdjust, RubyCharStyleName, RubyIsAbove + * + * - [X] CharStrikeOut, CharCrossedOut + * - [X] CharEscapement, CharAutoEscapement, CharEscapementHeight + * - [X] CharUnderline, CharUnderlineColor, CharUnderlineHasColor + * + * - [?] CharFontName, CharFontStyleName, CharFontFamily, CharFontPitch + * - [?] HyperLinkURL/Name/Target, UnvisitedCharStyleName, VisitedCharStyleName + * + */ + + // CharStrikeout and CharCrossedOut interact: if we default one, + // we default the other as well. + Set charStrikeOutSet = Set.of(CHAR_STRIKEOUT, + "CharCrossedOut"); + Set charEscapementSet = Set.of("CharAutoEscapement", + CHAR_ESCAPEMENT, + CHAR_ESCAPEMENT_HEIGHT); + Set charUnderlineSet = Set.of(CHAR_UNDERLINE, + "CharUnderlineColor", + "CharUnderlineHasColor"); + + Set namesToDefault = new HashSet<>(); + if (charStrikeOutSet.contains(propertyName)) { + namesToDefault = charStrikeOutSet; + } else if (charEscapementSet.contains(propertyName)) { + namesToDefault = charEscapementSet; + } else if (charUnderlineSet.contains(propertyName)) { + namesToDefault = charUnderlineSet; + } else { + namesToDefault.add(propertyName); + } + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertySetInfo psi = propertySet.getPropertySetInfo(); + + // Remember those we shall we restore later + Map ds = new HashMap<>(); + for (Property p : psi.getProperties()) { + boolean noRestore = (namesToDefault.contains(p.Name) + || ((p.Attributes & PropertyAttribute.READONLY) != 0) + || (isPropertyDefault(cursor, p.Name))); + if (noRestore) { + continue; + } + ds.put(p.Name, propertySet.getPropertyValue(p.Name)); + } + + // Remove all + removeDirectFormatting(cursor); + + boolean failed = false; + if (!isPropertyDefault(cursor, propertyName)) { + LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault:" + + " removeDirectFormatting failed to reset '%s'", + propertyName)); + failed = true; + } + + // Restore those saved + for (Map.Entry e : ds.entrySet()) { + propertySet.setPropertyValue(e.getKey(), e.getValue()); + if (!failed && !isPropertyDefault(cursor, propertyName)) { + LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault('%s')" + + " setPropertyValue('%s') caused loss of default state", + propertyName, e.getKey())); + failed = true; + } + } + + if (!failed && !isPropertyDefault(cursor, propertyName)) { + LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault('%s') failed", + propertyName)); + } + + } + } + + /** + * We rely on property values being either DIRECT_VALUE or + * DEFAULT_VALUE (not AMBIGUOUS_VALUE). If the cursor covers a homogeneous region, + * or is collapsed, then this is true. + */ + private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) + throws + UnknownPropertyException { + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + PropertyState pst = propertyState.getPropertyState(propertyName); + if (pst == PropertyState.AMBIGUOUS_VALUE) { + throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE" + + " (expected properties for a homogeneous cursor)"); + } + return pst == PropertyState.DEFAULT_VALUE; + } + + /** + * @return Optional.empty() if the property is not directly formatted. + */ + private static Optional getPropertyValue(XTextCursor cursor, String propertyName) + throws + UnknownPropertyException, + WrappedTargetException { + if (isPropertyDefault(cursor, propertyName)) { + return Optional.empty(); + } else { + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + return Optional.of(propertySet.getPropertyValue(propertyName)); + } + } + + /** + * @param value Optional.empty() means instruction to remove direct formatting. + */ + private static void setPropertyValue(XTextCursor cursor, String propertyName, Optional value) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + if (value.isPresent()) { + propertySet.setPropertyValue(propertyName, value.get()); + } else { + setPropertyToDefault(cursor, propertyName); + } + } + + /** + * At each tag we adjust the current stack of formatters-to-apply + * stack, then run it. + */ + private interface Formatter { + /** + * Note: apply may be called multiple times, but should pick up old value only + * at its first call. + */ + public void apply(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException; + + /** + * Closing tags call applyEnd directly, so applyEnd is only called once. + * + * It should restore the state to that seen by the first call to apply. + * + */ + public void applyEnd(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException; + } + + /** + * Apply Formatters on the stack. + * + * @param cursor Marks the text to format + * @param formatters Formatters to apply (normally extracted from OOFormattedText) + */ + private static void formatTextInCursor(XTextCursor cursor, + Stack formatters) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + + for (Formatter f : formatters) { + f.apply(cursor); + } + } + + private static class SimpleFormatter implements Formatter { + final String propertyName; + Optional myValue; + Optional oldValue; + boolean started; + + SimpleFormatter(String propertyName, Optional value) { + this.propertyName = propertyName; + this.myValue = value; + this.oldValue = Optional.empty(); + this.started = false; + } + + @Override + public void apply(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + + if (!started) { + oldValue = getPropertyValue(cursor, propertyName).map(e -> (T) e); + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + started = true; + } + + setPropertyValue(cursor, propertyName, myValue); + } + + @Override + public void applyEnd(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + setPropertyValue(cursor, propertyName, oldValue); + } + } + + private static Formatter setCharWeight(float value) { + return new SimpleFormatter("CharWeight", Optional.of(value)); + } + + private static Formatter setCharPosture(FontSlant value) { + return new SimpleFormatter("CharPosture", Optional.of(value)); + } + + private static Formatter setCharCaseMap(short value) { + return new SimpleFormatter("CharCaseMap", Optional.of(value)); + } + + // com.sun.star.awt.FontUnderline + private static Formatter setCharUnderline(short value) { + return new SimpleFormatter(CHAR_UNDERLINE, Optional.of(value)); + } + + // com.sun.star.awt.FontStrikeout + private static Formatter setCharStrikeout(short value) { + return new SimpleFormatter(CHAR_STRIKEOUT, Optional.of(value)); + } + + // CharStyleName + private static Formatter setCharStyleName(String value) { + return new SimpleFormatter(CHAR_STYLE_NAME, Optional.ofNullable(value)); + } + + // Locale + private static Formatter setCharLocale(Locale value) { + return new SimpleFormatter("CharLocale", Optional.of(value)); + } + + /** + * Locale from string encoding: language, language-country or language-country-variant + */ + private static Formatter setCharLocale(String value) { + if (value == null || "".equals(value)) { + throw new RuntimeException("setCharLocale \"\" or null"); + } + String[] parts = value.split("-"); + String language = (parts.length > 0) ? parts[0] : ""; + String country = (parts.length > 1) ? parts[1] : ""; + String variant = (parts.length > 2) ? parts[2] : ""; + Locale l = new Locale(language, country, variant); + return setCharLocale(l); + } + + /* + * SuperScript and SubScript + */ + private static class CharEscapement implements Formatter { + Optional myValue; + Optional myHeight; + boolean relative; + + Optional oldValue; + Optional oldHeight; + boolean started; + + /** + * @param relative Make value and height relative to oldHeight and oldValue. + * Needed for e^{x_i} e^{x^2} (i.e. sup or sub within sup or sup) + * + */ + CharEscapement(Optional value, Optional height, boolean relative) { + this.myValue = value; + this.myHeight = height; + this.relative = relative; + this.oldValue = Optional.empty(); + this.oldHeight = Optional.empty(); + this.started = false; + } + + @Override + public void apply(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + if (!started) { + oldValue = getPropertyValue(cursor, CHAR_ESCAPEMENT).map(e -> (short) e); + oldHeight = getPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT).map(e -> (byte) e); + started = true; + } + if (relative && (myValue.isPresent() || myHeight.isPresent())) { + double oh = oldHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * 0.01; + double xHeight = myHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * oh; + double ov = oldValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT); + double xValue = myValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT) * oh + ov; + setPropertyValue(cursor, CHAR_ESCAPEMENT, Optional.of((short) Math.round(xValue))); + setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, Optional.of((byte) Math.round(xHeight))); + } else { + setPropertyValue(cursor, CHAR_ESCAPEMENT, myValue); + setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, myHeight); + } + } + + @Override + public void applyEnd(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + setPropertyValue(cursor, CHAR_ESCAPEMENT, oldValue); + setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, oldHeight); + } + } + + private static Formatter SubScript() { + return new CharEscapement(Optional.of(SUBSCRIPT_VALUE), Optional.of(SUBSCRIPT_HEIGHT), true); + } + + private static Formatter SuperScript() { + return new CharEscapement(Optional.of(SUPERSCRIPT_VALUE), Optional.of(SUPERSCRIPT_HEIGHT), true); + } + +} diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index fd9ddaf7038..08d83590c6d 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -1,1062 +1,29 @@ package org.jabref.logic.openoffice; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.Stack; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +// import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.logic.oostyle.OOFormattedText; - -import com.sun.star.beans.Property; -import com.sun.star.beans.PropertyAttribute; -import com.sun.star.beans.PropertyState; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.beans.XMultiPropertyStates; -import com.sun.star.beans.XPropertySet; -import com.sun.star.beans.XPropertySetInfo; -import com.sun.star.beans.XPropertyState; import com.sun.star.container.NoSuchElementException; -import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.ControlCharacter; import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; -import com.sun.star.uno.UnoRuntime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utility methods for processing OO Writer documents. */ -@AllowedToUseAwt("Requires AWT for changing document properties") +// @AllowedToUseAwt("Requires AWT for changing document properties") public class OOUtil { - private static final Logger LOGGER = LoggerFactory.getLogger(OOUtil.class); - private static final String CHAR_STRIKEOUT = "CharStrikeout"; - private static final String CHAR_UNDERLINE = "CharUnderline"; - private static final String PARA_STYLE_NAME = "ParaStyleName"; - private static final String CHAR_CASE_MAP = "CharCaseMap"; - private static final String CHAR_POSTURE = "CharPosture"; - private static final String CHAR_WEIGHT = "CharWeight"; - private static final String CHAR_ESCAPEMENT_HEIGHT = "CharEscapementHeight"; - private static final String CHAR_ESCAPEMENT = "CharEscapement"; - private static final String CHAR_STYLE_NAME = "CharStyleName"; - private static final String CHAR_LOCALE = "CharLocale"; - - /* - * SUPERSCRIPT_VALUE and SUPERSCRIPT_HEIGHT are percents of the normal character height - */ - private static final short SUPERSCRIPT_VALUE = (short) 33; - private static final short SUBSCRIPT_VALUE = (short) -10; - private static final byte SUPERSCRIPT_HEIGHT = (byte) 58; - private static final byte SUBSCRIPT_HEIGHT = (byte) 58; - - - private static final String TAG_NAME_REGEXP = "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|font|locale)"; - private static final String ATTRIBUTE_NAME_REGEXP = "(?:class|value)"; - private static final String ATTRIBUTE_VALUE_REGEXP = "\"([^\"]*)\""; - private static final Pattern HTML_TAG = - Pattern.compile("<(/" + TAG_NAME_REGEXP + ")>" - + "|" - + "<(" + TAG_NAME_REGEXP + ")" - + "((?:\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP + ")*)" - + ">"); - private static final Pattern ATTRIBUTE_PATTERN = - Pattern.compile("\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP); - private OOUtil() { // Just to hide the public constructor } - private static Map parseAttributes(String s) { - Map res = new HashMap<>(); - if (s == null) { - return res; - } - Matcher m = OOUtil.ATTRIBUTE_PATTERN.matcher(s); - while (m.find()) { - String key = m.group(1); - String value = m.group(2); - res.put(key, value); - } - return res; - } - - /** - * Insert a text with formatting indicated by HTML-like tags, into - * a text at the position given by a cursor. - * - * Limitation: understands no entitites. It does not receive any either, unless - * the user provides it. - * - * To limit the damage (and for a bit of self-documenting) - * {@code TAG_NAME_REGEXP} and {@code ATTRIBUTE_NAME_REGEXP} explicitly lists the - * values we care about. - * - * - * Notable changes w.r.t insertOOFormattedTextAtCurrentLocation: - * - * - new tags: - * - <locale value=""> - * - earlier was applied from code - * - <font class=""> - * - earlier was applied from code, for "CitationCharacterFormat" - * - <tt> - * - earlier: known, but ignored (no effect) - * - now: equivalent to <font class="Example"> - * - * - closing tags try to properly restore state instead of dictating - * an "off" state. - * - * - The practical consequence: the user can now format the - * citation mark (it is enough to format its start) and the - * properties not dictated by the style markup are preserved. - * - * A comparable example: a style with - * ReferenceParagraphFormat="JR_bibentry" - * JR_bibentry in LibreOffice, paragraph style prescribes "bold" font. - * LAYOUT only mentions bold around year. - * Which parts of the bibliography entries should come out as bold? - * - * @param documentConnection - * @param position The cursor giving the insert location. Not modified. - * @param ootext The marked-up text to insert. - * @throws WrappedTargetException - * @throws PropertyVetoException - * @throws UnknownPropertyException - * @throws IllegalArgumentException - */ - public static void insertOOFormattedTextAtCurrentLocation2(DocumentConnection documentConnection, - XTextCursor position, - OOFormattedText ootext) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - - final boolean debugThisFun = false; - if (debugThisFun) { - System.out.println(ootext.asString()); - } - - String lText = OOFormattedText.toString(ootext); - - XText text = position.getText(); - XTextCursor cursor = text.createTextCursorByRange(position); - cursor.collapseToEnd(); - - Stack formatters = new Stack<>(); - Stack expectEnd = new Stack<>(); - - // We need to extract formatting. Use a simple regexp search iteration: - int piv = 0; - Matcher m = OOUtil.HTML_TAG.matcher(lText); - while (m.find()) { - - String currentSubstring = lText.substring(piv, m.start()); - if (!currentSubstring.isEmpty()) { - text.insertString(cursor, currentSubstring, true); - } - OOUtil.formatTextInCursor(documentConnection, - cursor, - formatters); - cursor.collapseToEnd(); - - - String fullTag = m.group(); - String endTagName = m.group(1); - String startTagName = m.group(2); - String attributeListPart = m.group(3); - boolean isStartTag = (endTagName == null) || "".equals(endTagName); - String tagName = isStartTag ? startTagName : endTagName; - Objects.requireNonNull(tagName); - - Map attributes = parseAttributes(attributeListPart); - - // Handle tags: - switch (tagName) { - case "b": - formatters.push(Bold()); - expectEnd.push("/" + tagName); - break; - case "i": - case "em": - formatters.push(Italic()); - expectEnd.push("/" + tagName); - break; - case "smallcaps": - formatters.push(SmallCaps()); - expectEnd.push("/" + tagName); - break; - case "sup": - formatters.push(SuperScript()); - expectEnd.push("/" + tagName); - break; - case "sub": - formatters.push(SubScript()); - expectEnd.push("/" + tagName); - break; - case "u": - formatters.push(Underline()); - expectEnd.push("/" + tagName); - break; - case "s": - formatters.push(Strikeout()); - expectEnd.push("/" + tagName); - break; - case "/p": - // nop - break; - case "p": - String cls = attributes.get("class"); - //

- OOUtil.insertParagraphBreak(text, cursor); - cursor.collapseToEnd(); - if (cls != null && !cls.equals("")) { - try { - DocumentConnection.setParagraphStyle(cursor, cls); - } catch (UndefinedParagraphFormatException ex) { - // ignore silently - } - } - break; - case "font": - formatters.push(SetCharStyle(attributes.get("class"))); - expectEnd.push("/" + tagName); - break; - case "tt": - // Note: "Example" names a character style in LibreOffice. - formatters.push(SetCharStyle("Example")); - expectEnd.push("/" + tagName); - break; - case "locale": - // - // - formatters.push(SetLocale(attributes.get("value"))); - expectEnd.push("/" + tagName); - break; - case "/b": - case "/i": - case "/em": - case "/tt": - case "/smallcaps": - case "/sup": - case "/sub": - case "/u": - case "/s": - case "/font": - case "/locale": - formatters.pop().applyEnd(documentConnection, cursor); - String expected = expectEnd.pop(); - if (!tagName.equals(expected)) { - LOGGER.warn(String.format("expected '<%s>', found '<%s>'", expected, tagName)); - } - break; - } - - piv = m.end(); - } - - if (piv < lText.length()) { - text.insertString(cursor, lText.substring(piv), true); - } - OOUtil.formatTextInCursor(documentConnection, - cursor, - formatters); - cursor.collapseToEnd(); - - if (!expectEnd.empty()) { - String rest = ""; - for (String s : expectEnd) { - rest = String.format("<%s>", s) + rest; - } - LOGGER.warn(String.format("insertOOFormattedTextAtCurrentLocation2:" - + " expectEnd stack is not empty at the end: %s%n", - rest)); - } - } - - /** - * Purpose: in some cases we do not want to inherit direct - * formatting from the context. - * - * In particular, when filling the bibliography title and body. - */ - public static void removeDirectFormatting(XTextCursor cursor) { - // Probably this is the official solution. - // (Throws no exceptions) - XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); - mpss.setAllPropertiesToDefault(); - // Some are not reset by setAllPropertiesToDefault() - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); - - try { - // Special handling - propertySet.setPropertyValue(CHAR_STYLE_NAME, "Standard"); - propertyState.setPropertyToDefault(CHAR_STRIKEOUT); - } catch (UnknownPropertyException | - PropertyVetoException | - IllegalArgumentException | - WrappedTargetException ex) { - LOGGER.warn("exception caught", ex); - } - - // Only report those we do not yet know about: - final Set knownToFail = Set.of( - /* - "CharStrikeout", - "CharEscapement", - "CharEscapementHeight", - "CharUnderline", - "CharCrossedOut", - */ - - "ListAutoFormat", - "ListId", - "NumberingIsNumber", - "NumberingLevel", - "NumberingRules", - "NumberingStartValue", - "ParaChapterNumberingLevel", - "ParaIsNumberingRestart", - "ParaStyleName"); - - // query again, just in case it matters - propertySet = unoQI(XPropertySet.class, cursor); - XPropertySetInfo psi = propertySet.getPropertySetInfo(); - - // check the result - for (Property p : psi.getProperties()) { - if ((p.Attributes & PropertyAttribute.READONLY) != 0) { - continue; - } - try { - if (isPropertyDefault(cursor, p.Name)) { - continue; - } - } catch (UnknownPropertyException ex) { - // impossible - } - /* - * If something turns up here, then it needs to be added to - * removeDirectFormatting() - */ - if (knownToFail.contains(p.Name)) { - continue; - } - LOGGER.warn(String.format("OOUtil.removeDirectFormatting failed on '%s'", - p.Name)); - } - } - - interface Formatter { - /* - * Note: apply may be called multiple times, but should pick up old value - * at its first call. - */ - public void apply(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException; - - public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException; - } - - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if available, - * otherwise null - */ - private static T unoQI(Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - - /** - * Remove direct formatting of propertyName from propertySet. - * - * Observation: while - * XPropertyState.setPropertyToDefault(propertyName) does reset - * the property, it also has a side effect (probably bug in LO - * 6.4.6.2) that it also resets other properties. - * - * Wrokaround: - * (https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=105117) - * - * Use setPropertyValue with either result from - * getPropertyValue to restore the earlier state or with - * result from getPropertyDefault. In this case the property - * "CharStyleName" has to be handled specially, by mapping the - * received value "" to "Standard". Hopefully other - * properties will not need special handling. - * - */ - private static void setPropertyToDefault(XTextCursor cursor, String propertyName) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - // setPropertyToDefault("CharWeight") also removes "CharColor" - - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); - - // CharStrikeout and CharCrossedOut interact: if we deafult one, - // we default the other as well. - Set charStrikeOutSet = Set.of(CHAR_STRIKEOUT, "CharCrossedOut"); - Set charEscapementSet = Set.of("CharAutoEscapement", - CHAR_ESCAPEMENT, - CHAR_ESCAPEMENT_HEIGHT); - Set charUnderlineSet = Set.of(CHAR_UNDERLINE, - "CharUnderlineColor", - "CharUnderlineHasColor"); - - Set namesToDefault = new HashSet<>(); - if (charStrikeOutSet.contains(propertyName)) { - namesToDefault = charStrikeOutSet; - } else if (charEscapementSet.contains(propertyName)) { - namesToDefault = charEscapementSet; - } else if (charUnderlineSet.contains(propertyName)) { - namesToDefault = charUnderlineSet; - } else { - namesToDefault.add(propertyName); - } - - if (false) { - // This is what should simply work. - // However it loses e.g. font color when propertyName is "CharWeight". - propertyState.setPropertyToDefault(propertyName); - } else if (false) { - // Despite the name getPropertyDefault, storing - // its result by setPropertyValue is NOT equivalent - // to setPropertyToDefault(). - // - // setPropertyToDefault() should remove direct ("hard") formatting, - // setPropertyValue(getPropertyDefault()) can only do that - // if getPropertyDefault provides a value with the meaning - // "use whatever comes from the level above". - // - Object value = propertyState.getPropertyDefault(propertyName); - propertySet.setPropertyValue(propertyName, value); - } else { - // Try to remove all, then add all directly formatted again, - // except the one we are removing. - XPropertySetInfo psi = propertySet.getPropertySetInfo(); - - Map ds = new HashMap<>(); - for (Property p : psi.getProperties()) { - boolean noRestore = (namesToDefault.contains(p.Name) - || ((p.Attributes & PropertyAttribute.READONLY) != 0) - || (isPropertyDefault(cursor, p.Name))); - if (noRestore) { - continue; - } - ds.put(p.Name, propertySet.getPropertyValue(p.Name)); - } - - OOUtil.removeDirectFormatting(cursor); - if (!isPropertyDefault(cursor, propertyName)) { - LOGGER.warn(String.format("OOUtil.setPropertyToDefault failed (1) on '%s'", - propertyName)); - } - - // restore those saved - for (Map.Entry e : ds.entrySet()) { - propertySet.setPropertyValue(e.getKey(), e.getValue()); - if (!isPropertyDefault(cursor, propertyName)) { - LOGGER.warn(String.format("OOUtil.setPropertyToDefault failed (2) on '%s' after '%s'", - propertyName, e.getKey())); - } - } - if (!isPropertyDefault(cursor, propertyName)) { - /* - * If something turns up here, then it needs to be added to - * removeDirectFormatting() - */ - LOGGER.warn(String.format("OOUtil.setPropertyToDefault failed (3) on '%s'", - propertyName)); - } - - } - } - - /** - * We rely on property values being ether DIRECT_VALUE or - * DEFAULT_VALUE (not AMBIGUOUS_VALUE). If the cursor covers a homogeneous region, - * or is collapsed, then this is true. - */ - private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) - throws - UnknownPropertyException { - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); - PropertyState pst = propertyState.getPropertyState(propertyName); - if (pst == PropertyState.AMBIGUOUS_VALUE) { - throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE" - + " (expected properties for a homogeneous cursor)"); - } - return pst == PropertyState.DEFAULT_VALUE; - } - - private static Optional getPropertyValue(XTextCursor cursor, String propertyName) - throws - UnknownPropertyException, - WrappedTargetException { - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); - if (isPropertyDefault(cursor, propertyName)) { - final boolean debugThisFun = false; - if (debugThisFun) { - if (CHAR_STRIKEOUT.equals(propertyName)) { - System.out.printf("OOUtil.getPropertyValue default: '%s' = '%s'%n", - propertyName, - propertySet.getPropertyValue(propertyName)); - } - } - return Optional.empty(); - } else { - return Optional.of(propertySet.getPropertyValue(propertyName)); - } - } - - private static void setPropertyValue(XTextCursor cursor, String propertyName, Optional value) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); - if (value.isPresent()) { - propertySet.setPropertyValue(propertyName, value.get()); - } else { - setPropertyToDefault(cursor, propertyName); - } - } - - static class FontWeight implements Formatter { - final String propertyName = CHAR_WEIGHT; - Optional myWeight; - Optional oldWeight; - boolean started; - FontWeight(Optional weight) { - this.myWeight = weight; - this.started = false; - } - - @Override - public void apply(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - final boolean debugThisFun = false; - if (!started) { - oldWeight = getPropertyValue(cursor, CHAR_WEIGHT).map(e -> (Float) e); - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); - if (debugThisFun) { - // float defaultValue = (float) propertyState.getPropertyDefault(propertyName); - System.out.printf("FontWeight.start %s%n", oldWeight); - } - started = true; - } - - if (debugThisFun) { - System.out.printf("FontWeight.apply %s%n", myWeight); - } - setPropertyValue(cursor, CHAR_WEIGHT, myWeight); - } - - @Override - public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - final boolean debugThisFun = false; - if (debugThisFun) { - System.out.printf("FontWeight.applyEnd %s%n", oldWeight); - } - setPropertyValue(cursor, CHAR_WEIGHT, oldWeight); - } - } - - static Formatter Bold() { - return new FontWeight(Optional.of(com.sun.star.awt.FontWeight.BOLD)); - } - - static Formatter FontWeightDefault() { - return new FontWeight(Optional.of(com.sun.star.awt.FontWeight.NORMAL)); - } - - static class FontSlant implements Formatter { - Optional mySlant; - Optional oldSlant; - boolean started; - - FontSlant(Optional slant) { - this.mySlant = slant; - this.oldSlant = Optional.empty(); - this.started = false; - } - - @Override - public void apply(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - if (!started) { - oldSlant = getPropertyValue(cursor, CHAR_POSTURE).map(e -> (com.sun.star.awt.FontSlant) e); - started = true; - } - setPropertyValue(cursor, CHAR_POSTURE, mySlant); - } - - @Override - public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - setPropertyValue(cursor, CHAR_POSTURE, oldSlant); - } - } - - static Formatter Italic() { - return new FontSlant(Optional.of(com.sun.star.awt.FontSlant.ITALIC)); - } - - static Formatter FontSlantDefault() { - return new FontSlant(Optional.of(com.sun.star.awt.FontSlant.NONE)); - } - - /* - * com.sun.star.style.CaseMap - */ - static class CaseMap implements Formatter { - Optional my; - Optional old; - boolean started; - - CaseMap(Optional value) { - this.my = value; - this.started = false; - } - - @Override - public void apply(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - if (!started) { - old = getPropertyValue(cursor, CHAR_CASE_MAP).map(e -> (short) e); - started = true; - } - setPropertyValue(cursor, CHAR_CASE_MAP, my); - } - - @Override - public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - setPropertyValue(cursor, CHAR_CASE_MAP, old); - } - } - - static Formatter SmallCaps() { - return new CaseMap(Optional.of(com.sun.star.style.CaseMap.SMALLCAPS)); - } - - static Formatter CaseMapDefault() { - return new CaseMap(Optional.of(com.sun.star.style.CaseMap.NONE)); - } - - static class CharEscapement implements Formatter { - Optional myValue; - Optional myHeight; - boolean relative; - - Optional oldValue; - Optional oldHeight; - boolean started; - - /** - * Probably either both value and height should be present, or - * neither, because charEscapementSet (or rather, the - * corresponding mechanics in LibreOffice) links them - * together. - * - * @param relative Make value and height relative to oldHeight and oldValue. - * Needed for e^{x_i} e^{x^2} (i.e. sup or sub within sup or sup) - * - */ - CharEscapement(Optional value, Optional height, boolean relative) { - myValue = value; - myHeight = height; - this.relative = relative; - oldValue = Optional.empty(); - oldHeight = Optional.empty(); - started = false; - } - - @Override - public void apply(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - if (!started) { - oldValue = getPropertyValue(cursor, CHAR_ESCAPEMENT).map(e -> (short) e); - oldHeight = getPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT).map(e -> (byte) e); - started = true; - } - if (relative && myValue.isPresent() && myHeight.isPresent()) { - double oh = oldHeight.orElse((byte) 100) * 0.01; - double xHeight = myHeight.orElse((byte) 100) * oh; - double ov = oldValue.orElse((short) 0); - double xValue = myValue.orElse((short) 0) * oh + ov; - setPropertyValue(cursor, CHAR_ESCAPEMENT, Optional.of((short) Math.round(xValue))); - setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, Optional.of((byte) Math.round(xHeight))); - } else { - setPropertyValue(cursor, CHAR_ESCAPEMENT, myValue); - setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, myHeight); - } - } - - @Override - public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - setPropertyValue(cursor, CHAR_ESCAPEMENT, oldValue); - setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, oldHeight); - } - } - - static Formatter SubScript() { - return new CharEscapement(Optional.of(SUBSCRIPT_VALUE), Optional.of(SUBSCRIPT_HEIGHT), true); - } - - static Formatter SuperScript() { - return new CharEscapement(Optional.of(SUPERSCRIPT_VALUE), Optional.of(SUPERSCRIPT_HEIGHT), true); - } - - static Formatter CharEscapementDefault() { - return new CharEscapement(Optional.of((short) 0), Optional.of((byte) 100), false); - } - - /* - * com.sun.star.awt.FontUnderline - */ - static class FontUnderline implements Formatter { - Optional myValue; - Optional oldValue; - boolean started; - - FontUnderline(Optional value) { - this.myValue = value; - this.oldValue = Optional.empty(); - this.started = false; - } - - @Override - public void apply(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - if (!started) { - oldValue = getPropertyValue(cursor, CHAR_UNDERLINE).map(e -> (short) e); - started = true; - } - setPropertyValue(cursor, CHAR_UNDERLINE, myValue); - } - - @Override - public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - setPropertyValue(cursor, CHAR_UNDERLINE, oldValue); - } - } - - static Formatter Underline() { - return new FontUnderline(Optional.of(com.sun.star.awt.FontUnderline.SINGLE)); - } - - static FontUnderline FontUnderlineDefault() { - return new FontUnderline(Optional.of(com.sun.star.awt.FontUnderline.NONE)); - } - - /* - * com.sun.star.awt.FontStrikeout - */ - static class FontStrikeout implements Formatter { - Optional myValue; - Optional oldValue; - boolean started; - - FontStrikeout(Optional value) { - this.myValue = value; - this.oldValue = Optional.empty(); - this.started = false; - } - - @Override - public void apply(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - if (!started) { - oldValue = getPropertyValue(cursor, CHAR_STRIKEOUT).map(e -> (short) e); - started = true; - final boolean debugThisFun = false; - if (debugThisFun) { - System.out.printf("FontStrikeout.apply.start %s%n", oldValue); - } - } - setPropertyValue(cursor, CHAR_STRIKEOUT, myValue); - } - - @Override - public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - final boolean debugThisFun = false; - if (debugThisFun) { - System.out.printf("FontStrikeout.applyEnd %s%n", oldValue); - } - setPropertyValue(cursor, CHAR_STRIKEOUT, oldValue); - } - } - - static Formatter Strikeout() { - return new FontStrikeout(Optional.of(com.sun.star.awt.FontStrikeout.SINGLE)); - } - - static Formatter FontStrikeoutDefault() { - return new FontStrikeout(Optional.of(com.sun.star.awt.FontStrikeout.NONE)); - } - - /* - * - */ - static class CharLocale implements Formatter { - private Optional myLocale; - private Optional oldLocale; - private boolean started; - - CharLocale(Optional locale) { - this.myLocale = locale; - this.oldLocale = Optional.empty(); - this.started = false; - } - - @Override - public void apply(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - try { - if (!started) { - oldLocale = getPropertyValue(cursor, CHAR_LOCALE).map(e -> (Locale) e); - started = true; - } - setPropertyValue(cursor, CHAR_LOCALE, myLocale); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - LOGGER.warn("CharLocale.apply caught", ex); - } - } - - @Override - public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - try { - setPropertyValue(cursor, CHAR_LOCALE, oldLocale); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - LOGGER.warn("CharLocale.applyEnd caught", ex); - } - } - } - - /** - * Locale from string encoding: language, language-country or language-country-variant - * - * @param value Empty or null encodes "remove direct formatting" - */ - static Formatter SetLocale(String value) { - if (value == null || "".equals(value)) { - return new CharLocale(Optional.empty()); - } - - String[] parts = value.split("-"); - String language = (parts.length > 0) ? parts[0] : ""; - String country = (parts.length > 1) ? parts[1] : ""; - String variant = (parts.length > 2) ? parts[2] : ""; - Locale l = new Locale(language, country, variant); - return new CharLocale(Optional.of(l)); - } - - /** - * Set a character style known to OO/LO - * - * Optional.empty() encodes (remove direct formatting) both in - * myCharStyle and in oldCharStyle. - * - */ - static class CharStyleName implements Formatter { - private Optional myCharStyle; - private Optional oldCharStyle; - private boolean started; - - public CharStyleName(Optional charStyle) { - this.myCharStyle = charStyle; - this.oldCharStyle = Optional.empty(); - this.started = false; - } - - @Override - public void apply(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - try { - if (!started) { - oldCharStyle = getPropertyValue(cursor, CHAR_STYLE_NAME).map(e -> (String) e); - started = true; - } - setPropertyValue(cursor, CHAR_STYLE_NAME, myCharStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - LOGGER.warn("CharStyleName.apply caught", ex); - } - } - - @Override - public void applyEnd(DocumentConnection documentConnection, XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - - try { - setPropertyValue(cursor, CHAR_STYLE_NAME, oldCharStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - LOGGER.warn("CharStyleName.applyEnd caught", ex); - } - } - - } - - /** - * @param charStyle null or "" encodes "remove direct formatting", - * not "do nothing". - */ - static Formatter SetCharStyle(String charStyle) { - if (charStyle == null || "".equals(charStyle)) { - return new CharStyleName(Optional.empty()); - } - return new CharStyleName(Optional.of(charStyle)); - } - - /** - * Apply Formatters on the stack. - * - * @param documentConnection passed to each Formatter - * @param cursor Marks the text to format - * @param formatters Formatters to apply (normally extracted from OOFormattedText) - */ - public static void formatTextInCursor(DocumentConnection documentConnection, - XTextCursor cursor, - Stack formatters) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - - for (Formatter f : formatters) { - f.apply(documentConnection, cursor); - } - } - public static void insertParagraphBreak(XText text, XTextCursor cursor) throws IllegalArgumentException { text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); From 7f622b5a227ccb863914fea097aef2f8240ecc51 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 08:24:35 +0200 Subject: [PATCH 0658/1068] use and oo: attibute prefix instead of --- .../org/jabref/logic/oostyle/OOFormat.java | 10 +- .../openoffice/OOFormattedTextIntoOO.java | 147 ++++++++++++++---- 2 files changed, 126 insertions(+), 31 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index 815f17045fc..90a93dba951 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -62,9 +62,9 @@ public static OOFormattedText formatFullReference(Layout layout, * */ public static OOFormattedText setLocale(OOFormattedText s, String locale) { - return OOFormattedText.fromString(String.format("", locale) + return OOFormattedText.fromString(String.format("", locale) + s.asString() - + ""); + + ""); } /** @@ -86,16 +86,16 @@ public static OOFormattedText setLocaleNone(OOFormattedText s) { * */ public static OOFormattedText setCharStyle(OOFormattedText s, String charStyle) { - return OOFormattedText.fromString(String.format("", charStyle) + return OOFormattedText.fromString(String.format("", charStyle) + s.asString() - + ""); + + ""); } /** * Mark {@code s} as part of a paragraph with style {@code paraStyle} */ public static OOFormattedText paragraph(OOFormattedText s, String paraStyle) { - return OOFormattedText.fromString(String.format("

", paraStyle) + return OOFormattedText.fromString(String.format("

", paraStyle) + s.asString() + "

"); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index 1542a37ab0d..f2b7977d405 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -1,8 +1,9 @@ package org.jabref.logic.openoffice; +import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -41,7 +42,10 @@ * Interpret OOFormattedText into an OpenOffice or LibreOffice writer * document. * - * + * On the question of what should it understand: apart from what + * it can do now, probably whatever a CSL style with HTML output + * emits. + * */ @AllowedToUseAwt("Requires AWT for changing document properties") public class OOFormattedTextIntoOO { @@ -67,8 +71,8 @@ public class OOFormattedTextIntoOO { private static final byte SUPERSCRIPT_HEIGHT = (byte) 58; private static final byte SUBSCRIPT_HEIGHT = (byte) 58; - private static final String TAG_NAME_REGEXP = "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|font|locale)"; - private static final String ATTRIBUTE_NAME_REGEXP = "(?:class|value)"; + private static final String TAG_NAME_REGEXP = "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|span)"; + private static final String ATTRIBUTE_NAME_REGEXP = "(?:oo:ParaStyleName|oo:CharStyleName|lang|style)"; private static final String ATTRIBUTE_VALUE_REGEXP = "\"([^\"]*)\""; private static final Pattern HTML_TAG = Pattern.compile("<(/" + TAG_NAME_REGEXP + ")>" @@ -135,6 +139,8 @@ public static void write(XTextCursor position, String lText = OOFormattedText.toString(ootext); + System.out.println(lText); + XText text = position.getText(); XTextCursor cursor = text.createTextCursorByRange(position); cursor.collapseToEnd(); @@ -162,7 +168,7 @@ public static void write(XTextCursor position, String tagName = isStartTag ? startTagName : endTagName; Objects.requireNonNull(tagName); - LinkedHashMap attributes = parseAttributes(attributeListPart); + List> attributes = parseAttributes(attributeListPart); // Handle tags: switch (tagName) { @@ -199,15 +205,25 @@ public static void write(XTextCursor position, // nop break; case "p": - String cls = attributes.get("class"); - //

OOUtil.insertParagraphBreak(text, cursor); cursor.collapseToEnd(); - if (cls != null && !cls.equals("")) { - try { - DocumentConnection.setParagraphStyle(cursor, cls); - } catch (UndefinedParagraphFormatException ex) { - // ignore silently + for (Pair kv : attributes) { + String key = kv.getKey(); + String value = kv.getValue(); + switch (key) { + case "oo:ParaStyleName": + //

+ if (value != null && !value.equals("")) { + try { + DocumentConnection.setParagraphStyle(cursor, value); + } catch (UndefinedParagraphFormatException ex) { + // ignore silently + } + } + break; + default: + LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); + break; } } break; @@ -216,14 +232,36 @@ public static void write(XTextCursor position, formatters.push(setCharStyleName("Example")); expectEnd.push("/" + tagName); break; - case "font": - formatters.push(setCharStyleName(attributes.get("class"))); - expectEnd.push("/" + tagName); - break; - case "locale": - // - // - formatters.push(setCharLocale(attributes.get("value"))); + case "span": + Formatters fs = new Formatters(); + for (Pair kv : attributes) { + String key = kv.getKey(); + String value = kv.getValue(); + switch (key) { + case "oo:CharStylename": + // + fs.add(setCharStyleName(value)); + break; + case "lang": + // + // + fs.add(setCharLocale(value)); + break; + case "style": + // In general we may need to parse value + if (value.equals("font-variant: small-caps")) { + fs.add(setCharCaseMap(CaseMap.SMALLCAPS)); + break; + } + LOGGER.warn(String.format("Unexpected value %s for attribute '%s' for <%s>", + value, key, tagName)); + break; + default: + LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); + break; + } + } + formatters.push(fs); expectEnd.push("/" + tagName); break; case "/b": @@ -235,8 +273,7 @@ public static void write(XTextCursor position, case "/sub": case "/u": case "/s": - case "/font": - case "/locale": + case "/span": formatters.pop().applyEnd(cursor); String expected = expectEnd.pop(); if (!tagName.equals(expected)) { @@ -274,7 +311,6 @@ public static void write(XTextCursor position, public static void removeDirectFormatting(XTextCursor cursor) { XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); - mpss.setAllPropertiesToDefault(); /* * Now that we have setAllPropertiesToDefault, check which properties @@ -289,6 +325,8 @@ public static void removeDirectFormatting(XTextCursor cursor) { try { // Special handling propertySet.setPropertyValue(CHAR_STYLE_NAME, "Standard"); + // propertySet.setPropertyValue("CharCaseMap", CaseMap.NONE); + propertyState.setPropertyToDefault("CharCaseMap"); } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | @@ -296,6 +334,8 @@ public static void removeDirectFormatting(XTextCursor cursor) { LOGGER.warn("exception caught", ex); } + mpss.setAllPropertiesToDefault(); + // Only report those we do not yet know about final Set knownToFail = Set.of("ListAutoFormat", "ListId", @@ -331,8 +371,25 @@ public static void removeDirectFormatting(XTextCursor cursor) { } } - private static LinkedHashMap parseAttributes(String s) { - LinkedHashMap res = new LinkedHashMap<>(); + private static class Pair { + K key; + V value; + public Pair(K k, V v) { + key = k; + value = v; + } + + K getKey() { + return key; + } + + V getValue() { + return value; + } + } + + private static List> parseAttributes(String s) { + List> res = new ArrayList<>(); if (s == null) { return res; } @@ -340,7 +397,7 @@ private static LinkedHashMap parseAttributes(String s) { while (m.find()) { String key = m.group(1); String value = m.group(2); - res.put(key, value); + res.add(new Pair(key, value)); } return res; } @@ -622,6 +679,44 @@ private static void formatTextInCursor(XTextCursor cursor, } } + private static class Formatters implements Formatter { + List parts; + public Formatters() { + parts = new ArrayList<>(); + } + + public void add(Formatter f) { + parts.add(f); + } + + @Override + public void apply(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + for (Formatter f : parts) { + f.apply(cursor); + } + } + + @Override + public void applyEnd(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + for (int i = parts.size() - 1; i >= 0; i--) { + Formatter f = parts.get(i); + f.applyEnd(cursor); + } + } + } + private static class SimpleFormatter implements Formatter { final String propertyName; Optional myValue; From dc5abdda2f08c1edbfbbdb0a59f3f9ecd66f152d Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 11:31:37 +0200 Subject: [PATCH 0659/1068] extract OOBibBaseConnect --- .../org/jabref/gui/openoffice/OOBibBase.java | 183 +----------- .../gui/openoffice/OOBibBaseConnect.java | 271 ++++++++++++++++++ 2 files changed, 281 insertions(+), 173 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a19205fa539..458858393bc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -51,22 +51,14 @@ import com.sun.star.beans.UnknownPropertyException; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XEnumeration; -import com.sun.star.container.XEnumerationAccess; import com.sun.star.container.XNameAccess; -import com.sun.star.frame.XComponentLoader; -import com.sun.star.frame.XDesktop; import com.sun.star.lang.DisposedException; import com.sun.star.lang.WrappedTargetException; -import com.sun.star.lang.XComponent; -import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextSection; import com.sun.star.uno.Any; import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -87,14 +79,15 @@ class OOBibBase { /* variables */ private final DialogService dialogService; - private final XDesktop xDesktop; /** * Created when connected to a document. * * Cleared (to null) when we discover we lost the connection. */ - private DocumentConnection xDocumentConnection; + // private DocumentConnection xDocumentConnection; + + private OOBibBaseConnect connection; /* * Constructor @@ -106,156 +99,15 @@ public OOBibBase(Path loPath, CreationException { this.dialogService = dialogService; - this.xDesktop = simpleBootstrap(loPath); - } - - /* ***************************** - * - * Establish connection - * - * *****************************/ - - private XDesktop simpleBootstrap(Path loPath) - throws - CreationException, - BootstrapException { - - // Get the office component context: - XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); - XMultiComponentFactory sem = context.getServiceManager(); - - // Create the desktop, which is the root frame of the - // hierarchy of frames that contain viewable components: - Object desktop; - try { - desktop = sem.createInstanceWithContext("com.sun.star.frame.Desktop", context); - } catch (Exception e) { - throw new CreationException(e.getMessage()); - } - XDesktop result = unoQI(XDesktop.class, desktop); - - unoQI(XComponentLoader.class, desktop); - - return result; - } - - private static List getTextDocuments(XDesktop desktop) - throws - NoSuchElementException, - WrappedTargetException { - - List result = new ArrayList<>(); - - XEnumerationAccess enumAccess = desktop.getComponents(); - XEnumeration compEnum = enumAccess.createEnumeration(); - - while (compEnum.hasMoreElements()) { - Object next = compEnum.nextElement(); - XComponent comp = unoQI(XComponent.class, next); - XTextDocument doc = unoQI(XTextDocument.class, comp); - if (doc != null) { - result.add(doc); - } - } - return result; + this.connection = new OOBibBaseConnect(loPath, dialogService); } - /** - * Run a dialog allowing the user to choose among the documents in `list`. - * - * @return Null if no document was selected. Otherwise the - * document selected. - * - */ - private static XTextDocument selectDocumentDialog(List list, - DialogService dialogService) { - - class DocumentTitleViewModel { - - private final XTextDocument xTextDocument; - private final String description; - - public DocumentTitleViewModel(XTextDocument xTextDocument) { - this.xTextDocument = xTextDocument; - this.description = DocumentConnection.getDocumentTitle(xTextDocument).orElse(""); - } - - public XTextDocument getXtextDocument() { - return xTextDocument; - } - - @Override - public String toString() { - return description; - } - } - - List viewModel = (list.stream() - .map(DocumentTitleViewModel::new) - .collect(Collectors.toList())); - - // This whole method is part of a background task when - // auto-detecting instances, so we need to show dialog in FX - // thread - Optional selectedDocument = - (dialogService - .showChoiceDialogAndWait(Localization.lang("Select document"), - Localization.lang("Found documents:"), - Localization.lang("Use selected document"), - viewModel)); - - return (selectedDocument - .map(DocumentTitleViewModel::getXtextDocument) - .orElse(null)); - } - - /** - * Choose a document to work with. - * - * Assumes we have already connected to LibreOffice or OpenOffice. - * - * If there is a single document to choose from, selects that. - * If there are more than one, shows selection dialog. - * If there are none, throws NoDocumentException - * - * After successful selection connects to the selected document - * and extracts some frequently used parts (starting points for - * managing its content). - * - * Finally initializes this.xDocumentConnection with the selected - * document and parts extracted. - * - */ public void selectDocument() throws NoDocumentException, NoSuchElementException, WrappedTargetException { - - XTextDocument selected; - List textDocumentList = getTextDocuments(this.xDesktop); - if (textDocumentList.isEmpty()) { - throw new NoDocumentException("No Writer documents found"); - } else if (textDocumentList.size() == 1) { - selected = textDocumentList.get(0); // Get the only one - } else { // Bring up a dialog - selected = OOBibBase.selectDocumentDialog(textDocumentList, - this.dialogService); - } - - if (selected == null) { - return; - } - - this.xDocumentConnection = new DocumentConnection(selected); - } - - /** - * Mark the current document as missing. - * - */ - private void forgetDocument() { - this.xDocumentConnection = null; + this.connection.selectDocument(); } /** @@ -266,21 +118,14 @@ private void forgetDocument() { * */ public boolean isConnectedToDocument() { - return this.xDocumentConnection != null; + return this.connection.isConnectedToDocument(); } /** * @return true if we are connected to a document */ public boolean documentConnectionMissing() { - if (this.xDocumentConnection == null) { - return true; - } - boolean res = this.xDocumentConnection.documentConnectionMissing(); - if (res) { - forgetDocument(); - } - return res; + return this.connection.documentConnectionMissing(); } /** @@ -290,21 +135,14 @@ public boolean documentConnectionMissing() { public DocumentConnection getDocumentConnectionOrThrow() throws NoDocumentException { - if (documentConnectionMissing()) { - throw new NoDocumentException("Not connected to document"); - } - return this.xDocumentConnection; + return this.connection.getDocumentConnectionOrThrow(); } /** * The title of the current document, or Optional.empty() */ public Optional getCurrentDocumentTitle() { - if (documentConnectionMissing()) { - return Optional.empty(); - } else { - return this.xDocumentConnection.getDocumentTitle(); - } + return this.connection.getCurrentDocumentTitle(); } /* **************************** @@ -479,7 +317,6 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti * reference mark. */ private void createAndFillCitationGroup(OOFrontend fr, - // CitationGroups cgs, DocumentConnection documentConnection, List citationKeys, List pageInfosForCitations, @@ -1985,7 +1822,7 @@ public List updateDocumentActionHelper(List databases, // Check Range overlaps int maxReportedOverlaps = 10; - fr.checkRangeOverlaps(this.xDocumentConnection, + fr.checkRangeOverlaps(documentConnection, requireSeparation, maxReportedOverlaps); diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java new file mode 100644 index 00000000000..b80f2aeb264 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -0,0 +1,271 @@ +package org.jabref.gui.openoffice; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.jabref.gui.DialogService; +import org.jabref.logic.l10n.Localization; +import org.jabref.logic.openoffice.CreationException; +import org.jabref.logic.openoffice.DocumentConnection; +import org.jabref.logic.openoffice.NoDocumentException; + +import com.sun.star.comp.helper.BootstrapException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XEnumeration; +import com.sun.star.container.XEnumerationAccess; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XDesktop; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.text.XTextDocument; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class for manipulating the Bibliography of the currently started + * document in OpenOffice. + */ +class OOBibBaseConnect { + + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBaseConnect.class); + + /* variables */ + private final DialogService dialogService; + private final XDesktop xDesktop; + + /** + * Created when connected to a document. + * + * Cleared (to null) when we discover we lost the connection. + */ + private DocumentConnection xDocumentConnection; + + /* + * Constructor + */ + public OOBibBaseConnect(Path loPath, + DialogService dialogService) + throws + BootstrapException, + CreationException { + + this.dialogService = dialogService; + this.xDesktop = simpleBootstrap(loPath); + } + + /* ***************************** + * + * Establish connection + * + * *****************************/ + + private XDesktop simpleBootstrap(Path loPath) + throws + CreationException, + BootstrapException { + + // Get the office component context: + XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); + XMultiComponentFactory sem = context.getServiceManager(); + + // Create the desktop, which is the root frame of the + // hierarchy of frames that contain viewable components: + Object desktop; + try { + desktop = sem.createInstanceWithContext("com.sun.star.frame.Desktop", context); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + XDesktop result = unoQI(XDesktop.class, desktop); + + unoQI(XComponentLoader.class, desktop); + + return result; + } + + private static List getTextDocuments(XDesktop desktop) + throws + NoSuchElementException, + WrappedTargetException { + + List result = new ArrayList<>(); + + XEnumerationAccess enumAccess = desktop.getComponents(); + XEnumeration compEnum = enumAccess.createEnumeration(); + + while (compEnum.hasMoreElements()) { + Object next = compEnum.nextElement(); + XComponent comp = unoQI(XComponent.class, next); + XTextDocument doc = unoQI(XTextDocument.class, comp); + if (doc != null) { + result.add(doc); + } + } + return result; + } + + /** + * Run a dialog allowing the user to choose among the documents in `list`. + * + * @return Null if no document was selected. Otherwise the + * document selected. + * + */ + private static XTextDocument selectDocumentDialog(List list, + DialogService dialogService) { + + class DocumentTitleViewModel { + + private final XTextDocument xTextDocument; + private final String description; + + public DocumentTitleViewModel(XTextDocument xTextDocument) { + this.xTextDocument = xTextDocument; + this.description = DocumentConnection.getDocumentTitle(xTextDocument).orElse(""); + } + + public XTextDocument getXtextDocument() { + return xTextDocument; + } + + @Override + public String toString() { + return description; + } + } + + List viewModel = (list.stream() + .map(DocumentTitleViewModel::new) + .collect(Collectors.toList())); + + // This whole method is part of a background task when + // auto-detecting instances, so we need to show dialog in FX + // thread + Optional selectedDocument = + (dialogService + .showChoiceDialogAndWait(Localization.lang("Select document"), + Localization.lang("Found documents:"), + Localization.lang("Use selected document"), + viewModel)); + + return (selectedDocument + .map(DocumentTitleViewModel::getXtextDocument) + .orElse(null)); + } + + /** + * Choose a document to work with. + * + * Assumes we have already connected to LibreOffice or OpenOffice. + * + * If there is a single document to choose from, selects that. + * If there are more than one, shows selection dialog. + * If there are none, throws NoDocumentException + * + * After successful selection connects to the selected document + * and extracts some frequently used parts (starting points for + * managing its content). + * + * Finally initializes this.xDocumentConnection with the selected + * document and parts extracted. + * + */ + public void selectDocument() + throws + NoDocumentException, + NoSuchElementException, + WrappedTargetException { + + XTextDocument selected; + List textDocumentList = getTextDocuments(this.xDesktop); + if (textDocumentList.isEmpty()) { + throw new NoDocumentException("No Writer documents found"); + } else if (textDocumentList.size() == 1) { + selected = textDocumentList.get(0); // Get the only one + } else { // Bring up a dialog + selected = OOBibBaseConnect.selectDocumentDialog(textDocumentList, + this.dialogService); + } + + if (selected == null) { + return; + } + + this.xDocumentConnection = new DocumentConnection(selected); + } + + /** + * Mark the current document as missing. + * + */ + private void forgetDocument() { + this.xDocumentConnection = null; + } + + /** + * A simple test for document availability. + * + * See also `documentConnectionMissing` for a test + * actually attempting to use teh connection. + * + */ + public boolean isConnectedToDocument() { + return this.xDocumentConnection != null; + } + + /** + * @return true if we are connected to a document + */ + public boolean documentConnectionMissing() { + if (this.xDocumentConnection == null) { + return true; + } + boolean res = this.xDocumentConnection.documentConnectionMissing(); + if (res) { + forgetDocument(); + } + return res; + } + + /** + * Either return a valid DocumentConnection or throw + * NoDocumentException. + */ + public DocumentConnection getDocumentConnectionOrThrow() + throws + NoDocumentException { + if (documentConnectionMissing()) { + throw new NoDocumentException("Not connected to document"); + } + return this.xDocumentConnection; + } + + /** + * The title of the current document, or Optional.empty() + */ + public Optional getCurrentDocumentTitle() { + if (documentConnectionMissing()) { + return Optional.empty(); + } else { + return this.xDocumentConnection.getDocumentTitle(); + } + } + + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if + * available, otherwise null. + */ + private static T unoQI(Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + +} // end of OOBibBaseConnect From 46401bbe80b0f5b7d5eb84ca9d2ca3741748e1bf Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 13:14:52 +0200 Subject: [PATCH 0660/1068] add InTextCitationType --- .../org/jabref/gui/openoffice/OOBibBase.java | 69 ++++--------------- .../jabref/logic/oostyle/CitationGroup.java | 4 +- .../jabref/logic/oostyle/CitationGroups.java | 2 +- .../logic/oostyle/InTextCitationType.java | 12 ++++ .../org/jabref/logic/oostyle/OOProcess.java | 18 ++--- .../jabref/logic/openoffice/Backend52.java | 3 +- .../org/jabref/logic/openoffice/Codec52.java | 50 +++++++++++--- .../jabref/logic/openoffice/OOFrontend.java | 3 +- 8 files changed, 80 insertions(+), 81 deletions(-) create mode 100644 src/main/java/org/jabref/logic/oostyle/InTextCitationType.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 458858393bc..b2e3bf8d9e2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -27,6 +27,7 @@ import org.jabref.logic.oostyle.CitedKey; import org.jabref.logic.oostyle.CitedKeys; import org.jabref.logic.oostyle.Compat; +import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOFormat; import org.jabref.logic.oostyle.OOFormattedText; @@ -162,50 +163,6 @@ private static T unoQI(Class zInterface, return UnoRuntime.queryInterface(zInterface, object); } - /* *************************************** - * - * Storage/retrieve of citations - * - * - * We store some information in the document about - * - * Citation groups: - * - * - citations belonging to the group. - * - Range of text owned (where the citation marks go). - * - pageInfo - * - * Citations : citation key - * Each belongs to exactly one group. - * - * From these, the databases and the style we create and update - * the presentation (citation marks) - * - * How: - * database lookup - * - * Local order - * presentation order within groups from (style,BibEntry) - * - * Global order: - * visualPosition (for first appearance order) - * bibliography-order - * - * Make them unique - * numbering - * uniqueLetters from (Set, firstAppearanceOrder, style) - * - * - * Bibliography uses parts of the information above: - * citation keys, - * location of citation groups (if ordered and/or numbered by first appearance) - * - * and - * the range of text controlled (storage) - * - * And fills the bibliography (presentation) - * - * **************************************/ public List getCitationEntries() throws UnknownPropertyException, @@ -320,7 +277,7 @@ private void createAndFillCitationGroup(OOFrontend fr, DocumentConnection documentConnection, List citationKeys, List pageInfosForCitations, - int itcType, + InTextCitationType itcType, OOFormattedText citationText, XTextCursor position, boolean withText, @@ -565,7 +522,7 @@ public void insertEntry(List entries, .map(OOBibBase::insertEntryGetCitationKey) .collect(Collectors.toList()); - int itcType = OOProcess.citationTypeFromOptions(withText, inParenthesis); + InTextCitationType itcType = OOProcess.citationTypeFromOptions(withText, inParenthesis); assertCitationCharacterFormatIsOK(cursor, style); @@ -718,7 +675,7 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - boolean withText = (cg.itcType != OOProcess.INVISIBLE_CIT); + boolean withText = (cg.itcType != InTextCitationType.INVISIBLE_CIT); if (withText) { @@ -1091,7 +1048,7 @@ public void combineCiteMarkers(List databases, // can get itcType from the first element of each // joinableGroup. // - // List itcTypes = new ArrayList<>(); + // List itcTypes = new ArrayList<>(); if (referenceMarkNames.size() > 0) { // current group of CitationGroup values @@ -1114,9 +1071,9 @@ public void combineCiteMarkers(List databases, */ // Only combine (Author 2000) type citations - if (cg.itcType != OOProcess.AUTHORYEAR_PAR + if (cg.itcType != InTextCitationType.AUTHORYEAR_PAR // allow "Author (2000)" - // && itcTypes[i] != OOBibBase.AUTHORYEAR_INTEXT + // && itcTypes[i] != InTextCitationType.AUTHORYEAR_INTEXT ) { addToGroup = false; } @@ -1208,7 +1165,7 @@ public void combineCiteMarkers(List databases, * * Can it start a new group? */ - boolean canStartGroup = (cg.itcType == OOProcess.AUTHORYEAR_PAR); + boolean canStartGroup = (cg.itcType == InTextCitationType.AUTHORYEAR_PAR); if (!addToGroup) { // close currentGroup @@ -1313,7 +1270,7 @@ public void combineCiteMarkers(List databases, newGroupCitations.addAll(rk.citations); } - int itcType = joinableGroup.get(0).itcType; + InTextCitationType itcType = joinableGroup.get(0).itcType; // cgPageInfos belong to the CitationGroup (DataModel JabRef52), // but it is not clear how should we handle them here. @@ -1344,7 +1301,7 @@ public void combineCiteMarkers(List databases, documentConnection, citationKeys, pageInfosForCitations, - itcType, // OOBibBase.AUTHORYEAR_PAR + itcType, // InTextCitationType.AUTHORYEAR_PAR OOFormattedText.fromString("tmp"), textCursor, true, // withText @@ -1480,15 +1437,15 @@ public void unCombineCiteMarkers(List databases, // We just reread below. boolean insertSpaceAfter = (i != last); + boolean withText = cg.itcType != InTextCitationType.INVISIBLE_CIT; // true createAndFillCitationGroup(fr, documentConnection, keys.subList(i, i + 1), // citationKeys, pageInfosForCitations.subList(i, i + 1), // pageInfos, - OOProcess.AUTHORYEAR_PAR, // itcType, + InTextCitationType.AUTHORYEAR_PAR, // itcType, OOFormattedText.fromString("tmp"), textCursor, - true, /* withText. - * Should be itcType != OOBibBase.INVISIBLE_CIT */ + withText, style, insertSpaceAfter); textCursor.collapseToEnd(); diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index 0a6e230adc6..b7df7f18216 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -13,7 +13,7 @@ public class CitationGroup { public CitationGroupID cgid; public StorageBase.NamedRange cgRangeStorage; // knows referenceMarkName - public int itcType; + public InTextCitationType itcType; public List citations; public List localOrder; @@ -22,7 +22,7 @@ public class CitationGroup { public CitationGroup(CitationGroupID cgid, StorageBase.NamedRange cgRangeStorage, - int itcType, + InTextCitationType itcType, List citations, Optional pageInfo) { this.cgid = cgid; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index d891479e308..5f9c7347e12 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -253,7 +253,7 @@ public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { return e; } - private Optional getItcType(CitationGroupID cgid) { + private Optional getItcType(CitationGroupID cgid) { return getCitationGroup(cgid).map(cg -> cg.itcType); } diff --git a/src/main/java/org/jabref/logic/oostyle/InTextCitationType.java b/src/main/java/org/jabref/logic/oostyle/InTextCitationType.java new file mode 100644 index 00000000000..d8135ca41aa --- /dev/null +++ b/src/main/java/org/jabref/logic/oostyle/InTextCitationType.java @@ -0,0 +1,12 @@ +package org.jabref.logic.oostyle; + +/* + * Types of in-text citation. (itcType) + */ +public enum InTextCitationType { + AUTHORYEAR_PAR, + AUTHORYEAR_INTEXT, + INVISIBLE_CIT; +} + + diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 33f17f2e028..a065d568365 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -20,12 +20,6 @@ import org.slf4j.LoggerFactory; public class OOProcess { - /* Types of in-text citation. (itcType) - * Their numeric values are used in reference mark names. - */ - public static final int AUTHORYEAR_PAR = 1; - public static final int AUTHORYEAR_INTEXT = 2; - public static final int INVISIBLE_CIT = 3; private static final Comparator AUTHOR_YEAR_TITLE_COMPARATOR = makeAuthorYearTitleComparator(); @@ -192,13 +186,13 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, * @param inParenthesis True means "(Au and Thor 2000)". * False means "Au and Thor (2000)". */ - public static int citationTypeFromOptions(boolean withText, boolean inParenthesis) { + public static InTextCitationType citationTypeFromOptions(boolean withText, boolean inParenthesis) { if (!withText) { - return OOProcess.INVISIBLE_CIT; + return InTextCitationType.INVISIBLE_CIT; } return (inParenthesis - ? OOProcess.AUTHORYEAR_PAR - : OOProcess.AUTHORYEAR_INTEXT); + ? InTextCitationType.AUTHORYEAR_PAR + : InTextCitationType.AUTHORYEAR_INTEXT); } /** @@ -373,7 +367,7 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi if (cm.getBibEntry().isPresent()) { s = (s + style.getCitationMarker(citationMarkerEntries.subList(j, j + 1), - cg.itcType == OOProcess.AUTHORYEAR_PAR, + cg.itcType == InTextCitationType.AUTHORYEAR_PAR, OOBibStyle.NonUniqueCitationMarker.THROWS)); } else { s = s + String.format("(Unresolved(%s))", cm.getCitationKey()); @@ -386,7 +380,7 @@ public static int citationTypeFromOptions(boolean withText, boolean inParenthesi */ OOFormattedText citMarker = style.getCitationMarker(citationMarkerEntries, - cg.itcType == OOProcess.AUTHORYEAR_PAR, + cg.itcType == InTextCitationType.AUTHORYEAR_PAR, OOBibStyle.NonUniqueCitationMarker.THROWS); citMarkers.put(cgid, citMarker); } diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 8c1f5f2621c..34aacb71eb5 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -13,6 +13,7 @@ import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.Compat; +import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; import com.sun.star.beans.IllegalTypeException; @@ -183,7 +184,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc public CitationGroup createCitationGroup(DocumentConnection documentConnection, List citationKeys, List pageInfosForCitations, - int itcType, + InTextCitationType itcType, XTextCursor position, boolean insertSpaceAfter, boolean withoutBrackets) diff --git a/src/main/java/org/jabref/logic/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/Codec52.java index 2f03ddc2cd2..d0d3b56571c 100644 --- a/src/main/java/org/jabref/logic/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/Codec52.java @@ -9,6 +9,8 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; +import org.jabref.logic.oostyle.InTextCitationType; + /** * How and what is encoded in a mark names. * @@ -19,8 +21,8 @@ class Codec52 { private static final String BIB_CITATION = "JR_cite"; private static final Pattern CITE_PATTERN = // Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); - // itcType is always "0" "1" or "2" - Pattern.compile(BIB_CITATION + "(\\d*)_([012])_(.*)"); + // itcType is always "1" "2" or "3" + Pattern.compile(BIB_CITATION + "(\\d*)_([123])_(.*)"); /** * This is what we get back from parsing a refMarkName. @@ -30,11 +32,11 @@ public static class ParsedMarkName { /** "", "0", "1" ... */ public final String i; /** in-text-citation type */ - public final int itcType; + public final InTextCitationType itcType; /** Citation keys embedded in the reference mark. */ public final List citationKeys; - ParsedMarkName(String i, int itcType, List citationKeys) { + ParsedMarkName(String i, InTextCitationType itcType, List citationKeys) { Objects.requireNonNull(i); Objects.requireNonNull(citationKeys); this.i = i; @@ -43,6 +45,36 @@ public static class ParsedMarkName { } } + /* + * Integer representation was written into the document in + * JabRef52, must keep it for compatibility. + */ + public static InTextCitationType InTextCitationTypeFromInt(int i) { + switch (i) { + case 1: + return InTextCitationType.AUTHORYEAR_PAR; + case 2: + return InTextCitationType.AUTHORYEAR_INTEXT; + case 3: + return InTextCitationType.INVISIBLE_CIT; + default: + throw new RuntimeException("Invalid InTextCitationType code"); + } + } + + public static int InTextCitationTypeToInt(InTextCitationType i) { + switch (i) { + case AUTHORYEAR_PAR: + return 1; + case AUTHORYEAR_INTEXT: + return 2; + case INVISIBLE_CIT: + return 3; + default: + throw new RuntimeException("Invalid InTextCitationType"); + } + } + /** * Produce a reference mark name for JabRef for the given citation * key and itcType that does not yet appear among the reference @@ -59,14 +91,15 @@ public static class ParsedMarkName { */ public static String getUniqueMarkName(Set usedNames, String bibtexKey, - int itcType) + InTextCitationType itcType) throws NoDocumentException { // XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); int i = 0; - String name = BIB_CITATION + '_' + itcType + '_' + bibtexKey; + int j = InTextCitationTypeToInt(itcType); + String name = BIB_CITATION + '_' + j + '_' + bibtexKey; while (usedNames.contains(name)) { - name = BIB_CITATION + i + '_' + itcType + '_' + bibtexKey; + name = BIB_CITATION + i + '_' + j + '_' + bibtexKey; i++; } return name; @@ -87,7 +120,8 @@ public static Optional parseMarkName(String refMarkName) { List keys = Arrays.asList(citeMatcher.group(3).split(",")); String i = citeMatcher.group(1); - int itcType = Integer.parseInt(citeMatcher.group(2)); + int j = Integer.parseInt(citeMatcher.group(2)); + InTextCitationType itcType = InTextCitationTypeFromInt(j); return (Optional.of(new Codec52.ParsedMarkName(i, itcType, keys))); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 3768e039b08..817720684be 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -15,6 +15,7 @@ import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.Compat; +import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; import com.sun.star.beans.IllegalTypeException; @@ -309,7 +310,7 @@ private List getVisuallySortedCitationGroupIDs(DocumentConnecti public CitationGroupID createCitationGroup(DocumentConnection documentConnection, List citationKeys, List pageInfosForCitations, - int itcType, + InTextCitationType itcType, XTextCursor position, boolean insertSpaceAfter, boolean withoutBrackets) From 2c92c0f591540fb1215c1c7a07f02971b68fbdb1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 13:50:52 +0200 Subject: [PATCH 0661/1068] moved CitationEntry to its suggested location model/openoffice --- .../java/org/jabref/gui/openoffice/CitationEntryViewModel.java | 2 +- .../jabref/gui/openoffice/ManageCitationsDialogViewModel.java | 2 +- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/logic/openoffice/Backend52.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 2 +- .../{logic/oostyle => model/openoffice}/CitationEntry.java | 2 +- .../{logic/oostyle => model/openoffice}/CitationEntryTest.java | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) rename src/main/java/org/jabref/{logic/oostyle => model/openoffice}/CitationEntry.java (97%) rename src/test/java/org/jabref/{logic/oostyle => model/openoffice}/CitationEntryTest.java (98%) diff --git a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java index cd64684fc13..c29f24c8424 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java @@ -3,7 +3,7 @@ import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; -import org.jabref.logic.oostyle.CitationEntry; +import org.jabref.model.openoffice.CitationEntry; public class CitationEntryViewModel { diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index ac7d18198b5..37efb1b16ea 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -10,9 +10,9 @@ import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.oostyle.CitationEntry; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.NoDocumentException; +import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b2e3bf8d9e2..a5e55e440d1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -17,7 +17,6 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; import org.jabref.logic.oostyle.Citation; -import org.jabref.logic.oostyle.CitationEntry; import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; @@ -44,6 +43,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; +import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 34aacb71eb5..b08d2a26f30 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -8,13 +8,13 @@ import java.util.stream.Collectors; import org.jabref.logic.oostyle.Citation; -import org.jabref.logic.oostyle.CitationEntry; import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.Compat; import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; +import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 817720684be..2fc52611d45 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -10,13 +10,13 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.oostyle.CitationEntry; import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.Compat; import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; +import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationEntry.java b/src/main/java/org/jabref/model/openoffice/CitationEntry.java similarity index 97% rename from src/main/java/org/jabref/logic/oostyle/CitationEntry.java rename to src/main/java/org/jabref/model/openoffice/CitationEntry.java index c643a7089f2..219e71eb0d1 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationEntry.java +++ b/src/main/java/org/jabref/model/openoffice/CitationEntry.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.openoffice; import java.util.Objects; import java.util.Optional; diff --git a/src/test/java/org/jabref/logic/oostyle/CitationEntryTest.java b/src/test/java/org/jabref/model/openoffice/CitationEntryTest.java similarity index 98% rename from src/test/java/org/jabref/logic/oostyle/CitationEntryTest.java rename to src/test/java/org/jabref/model/openoffice/CitationEntryTest.java index f702bc64ece..fd7ec48b9b3 100644 --- a/src/test/java/org/jabref/logic/oostyle/CitationEntryTest.java +++ b/src/test/java/org/jabref/model/openoffice/CitationEntryTest.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.openoffice; import java.util.Optional; From 314e36f11b60a7a673f246c3e4b9e1cc793b923b Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 14:35:00 +0200 Subject: [PATCH 0662/1068] CitationSort : also consider pageInfo for unresolved citations --- .../jabref/logic/oostyle/CitationSort.java | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/CitationSort.java b/src/main/java/org/jabref/logic/oostyle/CitationSort.java index b2d58e36197..c614c770adc 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationSort.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationSort.java @@ -8,6 +8,7 @@ class CitationSort { interface ComparableCitation { + public String getCitationKey(); public Optional getBibEntry(); @@ -29,25 +30,23 @@ static class CitationComparator implements Comparator { public int compare(ComparableCitation a, ComparableCitation b) { Optional abe = a.getBibEntry(); Optional bbe = b.getBibEntry(); + final int mul = unresolvedComesFirst ? (+1) : (-1); + int res = 0; if (abe.isEmpty() && bbe.isEmpty()) { // Both are unresolved: compare them by citation key. String ack = a.getCitationKey(); String bck = b.getCitationKey(); - return ack.compareTo(bck); - } - // Comparing unresolved and real entry - - final int mul = unresolvedComesFirst ? (+1) : (-1); - if (abe.isEmpty()) { + res = ack.compareTo(bck); + } else if (abe.isEmpty()) { return -mul; - } - if (bbe.isEmpty()) { + } else if (bbe.isEmpty()) { return mul; - } - // Proper comparison of entries - int res = entryComparator.compare(abe.get(), + } else { + // Proper comparison of entries + res = entryComparator.compare(abe.get(), bbe.get()); + } // Also consider pageInfo if (res == 0) { OOBibStyle.comparePageInfo(a.getPageInfo().orElse(null), From ca03f64f48340a3d6a69728e89e80e7d570ece76 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 14:36:53 +0200 Subject: [PATCH 0663/1068] extract OOStyleDataModelVersion --- .../org/jabref/logic/oostyle/Citation.java | 2 -- .../jabref/logic/oostyle/CitationGroups.java | 4 +-- .../java/org/jabref/logic/oostyle/Compat.java | 34 ++----------------- .../oostyle/OOStyleDataModelVersion.java | 31 +++++++++++++++++ .../jabref/logic/openoffice/Backend52.java | 5 +-- .../jabref/logic/openoffice/OOFrontend.java | 4 +-- 6 files changed, 40 insertions(+), 40 deletions(-) create mode 100644 src/main/java/org/jabref/logic/oostyle/OOStyleDataModelVersion.java diff --git a/src/main/java/org/jabref/logic/oostyle/Citation.java b/src/main/java/org/jabref/logic/oostyle/Citation.java index 5084a827f74..e36f37b8d8c 100644 --- a/src/main/java/org/jabref/logic/oostyle/Citation.java +++ b/src/main/java/org/jabref/logic/oostyle/Citation.java @@ -25,8 +25,6 @@ public class Citation implements CitationSort.ComparableCitation { * citations. */ - // TODO: Citation constructor needs dataModel, to check - // if usage of pageInfo confirms to expectations. public Citation(String citationKey) { this.citationKey = citationKey; this.db = Optional.empty(); diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 5f9c7347e12..d8682a99106 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -23,7 +23,7 @@ public class CitationGroups { private static final Logger LOGGER = LoggerFactory.getLogger(CitationGroups.class); - private final Compat.DataModel dataModel; + private final OOStyleDataModelVersion dataModel; /** * Original CitationGroups Data @@ -51,7 +51,7 @@ public class CitationGroups { /** * Constructor */ - public CitationGroups(Compat.DataModel dataModel, + public CitationGroups(OOStyleDataModelVersion dataModel, Map citationGroups) { this.dataModel = dataModel; diff --git a/src/main/java/org/jabref/logic/oostyle/Compat.java b/src/main/java/org/jabref/logic/oostyle/Compat.java index 9be42d2f360..b31ac6ab4a3 100644 --- a/src/main/java/org/jabref/logic/oostyle/Compat.java +++ b/src/main/java/org/jabref/logic/oostyle/Compat.java @@ -7,36 +7,6 @@ public class Compat { - /** What is the data stored? */ - public enum DataModel { - /** - * JabRef52: - * pageInfo belongs to CitationGroup, not Citation. - * - * Note: pageInfo stored in [File]/[Properties]/[Custom Properties] - * - * under the same name as the reference mark for the - * CitationGroup. - * - * JabRef "Merge" leaves pageInfo values of the parts joined - * around. Separate, or a new citation may pick these up. - * - * In-text citep format: "[ ... ; pageInfo]", injected just before the - * closing parenthesis (here "]"), with "; " as a separator. - * - * citet format: the same, (injected to parens around - * year of last citation of the group) - */ - JabRef52, - - /** - * JabRef53: - * pageInfo belongs to Citation. - * Need: formatting citation needs to know about these, inject after each year part - */ - JabRef53 - } - /** * Return the last pageInfo from the list, if there is one. */ @@ -82,7 +52,7 @@ public static List fakePageInfosForCitations(String pageInfo, * * TODO: we may want class DataModel52, DataModel53 and split this. */ - public static List getPageInfosForCitations(Compat.DataModel dataModel, + public static List getPageInfosForCitations(OOStyleDataModelVersion dataModel, CitationGroup cg) { switch (dataModel) { case JabRef52: @@ -121,7 +91,7 @@ public static List getPageInfosForCitations(Compat.DataModel da * TODO: JabRef52 combinePageInfos is not reversible. Should warn * user to check the result. Or ask what to do. */ - public static List combinePageInfos(Compat.DataModel dataModel, + public static List combinePageInfos(OOStyleDataModelVersion dataModel, List joinableGroup) { switch (dataModel) { case JabRef52: diff --git a/src/main/java/org/jabref/logic/oostyle/OOStyleDataModelVersion.java b/src/main/java/org/jabref/logic/oostyle/OOStyleDataModelVersion.java new file mode 100644 index 00000000000..c03e6db3494 --- /dev/null +++ b/src/main/java/org/jabref/logic/oostyle/OOStyleDataModelVersion.java @@ -0,0 +1,31 @@ +package org.jabref.logic.oostyle; + +/** What is the data stored? */ +public enum OOStyleDataModelVersion { + /** + * JabRef52: + * pageInfo belongs to CitationGroup, not Citation. + * + * Note: pageInfo stored in [File]/[Properties]/[Custom Properties] + * + * under the same name as the reference mark for the + * CitationGroup. + * + * JabRef "Merge" leaves pageInfo values of the parts joined + * around. Separate, or a new citation may pick these up. + * + * In-text citep format: "[ ... ; pageInfo]", injected just before the + * closing parenthesis (here "]"), with "; " as a separator. + * + * citet format: the same, (injected to parens around + * year of last citation of the group) + */ + JabRef52, + + /** + * JabRef53: + * pageInfo belongs to Citation. + * Need: formatting citation needs to know about these, inject after each year part + */ + JabRef53 +} diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index b08d2a26f30..c3835679171 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -14,6 +14,7 @@ import org.jabref.logic.oostyle.Compat; import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; +import org.jabref.logic.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; @@ -26,11 +27,11 @@ import com.sun.star.text.XTextRange; public class Backend52 { - public final Compat.DataModel dataModel; + public final OOStyleDataModelVersion dataModel; public final StorageBase.NamedRangeManager citationStorageManager; // uses: Codec52 public Backend52() { - this.dataModel = Compat.DataModel.JabRef52; + this.dataModel = OOStyleDataModelVersion.JabRef52; this.citationStorageManager = new StorageBaseRefMark.Manager(); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 2fc52611d45..9560de2ca1e 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -13,9 +13,9 @@ import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; -import org.jabref.logic.oostyle.Compat; import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; +import org.jabref.logic.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; @@ -54,7 +54,7 @@ public OOFrontend(DocumentConnection documentConnection) this.cgs = new CitationGroups(backend.dataModel, citationGroups); } - public Compat.DataModel getDataModel() { + public OOStyleDataModelVersion getDataModel() { return backend.dataModel; } From 969524bd2d2b60f48ed2fa9be3709743325b214b Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 14:44:28 +0200 Subject: [PATCH 0664/1068] move OOStyleDataModelVersion to model --- src/main/java/org/jabref/logic/oostyle/CitationGroups.java | 1 + src/main/java/org/jabref/logic/oostyle/Compat.java | 2 ++ src/main/java/org/jabref/logic/openoffice/Backend52.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 2 +- .../{logic => model}/oostyle/OOStyleDataModelVersion.java | 2 +- 5 files changed, 6 insertions(+), 3 deletions(-) rename src/main/java/org/jabref/{logic => model}/oostyle/OOStyleDataModelVersion.java (96%) diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index d8682a99106..fe8fe383768 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -10,6 +10,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/logic/oostyle/Compat.java b/src/main/java/org/jabref/logic/oostyle/Compat.java index b31ac6ab4a3..b28171a7e39 100644 --- a/src/main/java/org/jabref/logic/oostyle/Compat.java +++ b/src/main/java/org/jabref/logic/oostyle/Compat.java @@ -5,6 +5,8 @@ import java.util.Optional; import java.util.stream.Collectors; +import org.jabref.model.oostyle.OOStyleDataModelVersion; + public class Compat { /** diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index c3835679171..4c1239d1844 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -14,7 +14,7 @@ import org.jabref.logic.oostyle.Compat; import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; -import org.jabref.logic.oostyle.OOStyleDataModelVersion; +import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 9560de2ca1e..3a180f172ab 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -15,7 +15,7 @@ import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; -import org.jabref.logic.oostyle.OOStyleDataModelVersion; +import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/logic/oostyle/OOStyleDataModelVersion.java b/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java similarity index 96% rename from src/main/java/org/jabref/logic/oostyle/OOStyleDataModelVersion.java rename to src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java index c03e6db3494..6af28ac09ea 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOStyleDataModelVersion.java +++ b/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; /** What is the data stored? */ public enum OOStyleDataModelVersion { From 93315528b23d35d99b26d1ae25895b118bf4840b Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 15:04:44 +0200 Subject: [PATCH 0665/1068] moved CitationGroupID.java to model --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/logic/oostyle/CitationGroup.java | 1 + src/main/java/org/jabref/logic/oostyle/CitationGroups.java | 1 + src/main/java/org/jabref/logic/oostyle/CitationPath.java | 2 ++ src/main/java/org/jabref/logic/oostyle/OOProcess.java | 1 + src/main/java/org/jabref/logic/openoffice/Backend52.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 2 +- .../org/jabref/{logic => model}/oostyle/CitationGroupID.java | 2 +- 8 files changed, 9 insertions(+), 4 deletions(-) rename src/main/java/org/jabref/{logic => model}/oostyle/CitationGroupID.java (90%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index a5e55e440d1..7c5eecafc46 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -18,7 +18,6 @@ import org.jabref.logic.layout.Layout; import org.jabref.logic.oostyle.Citation; import org.jabref.logic.oostyle.CitationGroup; -import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.CitationMarkerEntry; import org.jabref.logic.oostyle.CitationMarkerEntryImpl; @@ -43,6 +42,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; +import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index b7df7f18216..3caa726f628 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -9,6 +9,7 @@ import org.jabref.logic.openoffice.StorageBase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.CitationGroupID; public class CitationGroup { public CitationGroupID cgid; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index fe8fe383768..901b7a8c970 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -10,6 +10,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.slf4j.Logger; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationPath.java b/src/main/java/org/jabref/logic/oostyle/CitationPath.java index bf655ef97e4..8bc1360447c 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationPath.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationPath.java @@ -1,5 +1,7 @@ package org.jabref.logic.oostyle; +import org.jabref.model.oostyle.CitationGroupID; + /** * Identifies a citation with the citation group containing it and * its storage index within. diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index a065d568365..164db9b9aa3 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -15,6 +15,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; +import org.jabref.model.oostyle.CitationGroupID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 4c1239d1844..0ceb2b504cf 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -9,11 +9,11 @@ import org.jabref.logic.oostyle.Citation; import org.jabref.logic.oostyle.CitationGroup; -import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.Compat; import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; +import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 3a180f172ab..d92977fa822 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -11,10 +11,10 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.CitationGroup; -import org.jabref.logic.oostyle.CitationGroupID; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; +import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroupID.java b/src/main/java/org/jabref/model/oostyle/CitationGroupID.java similarity index 90% rename from src/main/java/org/jabref/logic/oostyle/CitationGroupID.java rename to src/main/java/org/jabref/model/oostyle/CitationGroupID.java index baed10bd647..569fb0bd8ba 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroupID.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroupID.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; /** * Identifies a citation group in a document. From e2971c0faa11a107f93723f8ff163b039fb6c1fc Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 15:27:42 +0200 Subject: [PATCH 0666/1068] move InTextCitationType to model --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/logic/oostyle/CitationGroup.java | 1 + src/main/java/org/jabref/logic/oostyle/CitationGroups.java | 1 + src/main/java/org/jabref/logic/oostyle/OOProcess.java | 1 + src/main/java/org/jabref/logic/openoffice/Backend52.java | 2 +- src/main/java/org/jabref/logic/openoffice/Codec52.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 2 +- .../org/jabref/{logic => model}/oostyle/InTextCitationType.java | 2 +- 8 files changed, 8 insertions(+), 5 deletions(-) rename src/main/java/org/jabref/{logic => model}/oostyle/InTextCitationType.java (81%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7c5eecafc46..c8947adf317 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -25,7 +25,6 @@ import org.jabref.logic.oostyle.CitedKey; import org.jabref.logic.oostyle.CitedKeys; import org.jabref.logic.oostyle.Compat; -import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOFormat; import org.jabref.logic.oostyle.OOFormattedText; @@ -43,6 +42,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index 3caa726f628..e3079093c75 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -10,6 +10,7 @@ import org.jabref.logic.openoffice.StorageBase; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.InTextCitationType; public class CitationGroup { public CitationGroupID cgid; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 901b7a8c970..dd863cb8a2c 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -11,6 +11,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.slf4j.Logger; diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 164db9b9aa3..da15cabc382 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -16,6 +16,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.InTextCitationType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 0ceb2b504cf..bd146af5ace 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -11,9 +11,9 @@ import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.Compat; -import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; diff --git a/src/main/java/org/jabref/logic/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/Codec52.java index d0d3b56571c..b0df03e6f80 100644 --- a/src/main/java/org/jabref/logic/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/Codec52.java @@ -9,7 +9,7 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; -import org.jabref.logic.oostyle.InTextCitationType; +import org.jabref.model.oostyle.InTextCitationType; /** * How and what is encoded in a mark names. diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index d92977fa822..ebc015f03eb 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -12,9 +12,9 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitationGroups; -import org.jabref.logic.oostyle.InTextCitationType; import org.jabref.logic.oostyle.OOFormattedText; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; diff --git a/src/main/java/org/jabref/logic/oostyle/InTextCitationType.java b/src/main/java/org/jabref/model/oostyle/InTextCitationType.java similarity index 81% rename from src/main/java/org/jabref/logic/oostyle/InTextCitationType.java rename to src/main/java/org/jabref/model/oostyle/InTextCitationType.java index d8135ca41aa..d3a16956c28 100644 --- a/src/main/java/org/jabref/logic/oostyle/InTextCitationType.java +++ b/src/main/java/org/jabref/model/oostyle/InTextCitationType.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; /* * Types of in-text citation. (itcType) From 14d768de124459a90c4b9036e21c5d0af6a88651 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 17:46:14 +0200 Subject: [PATCH 0667/1068] move OOFormattedText, remove Compat --- .../org/jabref/gui/openoffice/OOBibBase.java | 6 +- .../org/jabref/logic/oostyle/Citation.java | 1 + .../jabref/logic/oostyle/CitationGroup.java | 12 +- .../jabref/logic/oostyle/CitationGroups.java | 62 +++++++-- .../logic/oostyle/CitationMarkerEntry.java | 1 + .../oostyle/CitationMarkerEntryImpl.java | 1 + .../jabref/logic/oostyle/CitationSort.java | 1 + .../org/jabref/logic/oostyle/CitedKey.java | 1 + .../java/org/jabref/logic/oostyle/Compat.java | 128 ------------------ .../org/jabref/logic/oostyle/OOBibStyle.java | 1 + .../oostyle/OOBibStyleGetCitationMarker.java | 1 + .../OOBibStyleGetNumCitationMarker.java | 2 + .../org/jabref/logic/oostyle/OOFormat.java | 1 + .../org/jabref/logic/oostyle/OOProcess.java | 5 +- .../jabref/logic/openoffice/Backend52.java | 123 +++++++++++++++-- .../openoffice/OOFormattedTextIntoOO.java | 2 +- .../jabref/logic/openoffice/OOFrontend.java | 2 +- .../oostyle/OOFormattedText.java | 2 +- .../oostyle/OOStyleDataModelVersion.java | 22 ++- .../jabref/logic/oostyle/OOBibStyleTest.java | 1 + 20 files changed, 211 insertions(+), 164 deletions(-) delete mode 100644 src/main/java/org/jabref/logic/oostyle/Compat.java rename src/main/java/org/jabref/{logic => model}/oostyle/OOFormattedText.java (93%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c8947adf317..9c722d9e980 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -24,10 +24,8 @@ import org.jabref.logic.oostyle.CitationPath; import org.jabref.logic.oostyle.CitedKey; import org.jabref.logic.oostyle.CitedKeys; -import org.jabref.logic.oostyle.Compat; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOFormat; -import org.jabref.logic.oostyle.OOFormattedText; import org.jabref.logic.oostyle.OOPreFormatter; import org.jabref.logic.oostyle.OOProcess; import org.jabref.logic.openoffice.CreationException; @@ -43,6 +41,8 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; @@ -528,7 +528,7 @@ public void insertEntry(List entries, // JabRef53 style pageInfo list List pageInfosForCitations = - Compat.fakePageInfosForCitations(pageInfo, nEntries); + OOStyleDataModelVersion.fakePageInfosForCitations(pageInfo, nEntries); List citationMarkerEntries = new ArrayList<>(entries.size()); for (int i = 0; i < nEntries; i++) { diff --git a/src/main/java/org/jabref/logic/oostyle/Citation.java b/src/main/java/org/jabref/logic/oostyle/Citation.java index e36f37b8d8c..215e282c9f9 100644 --- a/src/main/java/org/jabref/logic/oostyle/Citation.java +++ b/src/main/java/org/jabref/logic/oostyle/Citation.java @@ -3,6 +3,7 @@ import java.util.Optional; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.OOFormattedText; public class Citation implements CitationSort.ComparableCitation { diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index e3079093c75..25b18c533f0 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -11,6 +11,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OOFormattedText; public class CitationGroup { public CitationGroupID cgid; @@ -19,19 +20,14 @@ public class CitationGroup { public List citations; public List localOrder; - /** For Compat.DataModel.JabRef52 pageInfo belongs to the group */ - public Optional pageInfo; - public CitationGroup(CitationGroupID cgid, StorageBase.NamedRange cgRangeStorage, InTextCitationType itcType, - List citations, - Optional pageInfo) { + List citations) { this.cgid = cgid; this.cgRangeStorage = cgRangeStorage; this.itcType = itcType; this.citations = citations; - this.pageInfo = pageInfo; this.localOrder = makeIndices(citations.size()); } @@ -44,7 +40,7 @@ static List makeIndices(int n) { return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); } - public List getSortedCitations() { + public List getCitationsInLocalOrder() { List res = new ArrayList<>(citations.size()); for (int i : localOrder) { res.add(citations.get(i)); @@ -53,7 +49,7 @@ public List getSortedCitations() { } public List getSortedNumbers() { - List cits = getSortedCitations(); + List cits = getCitationsInLocalOrder(); return (cits.stream() .map(cit -> cit.number.orElseThrow(RuntimeException::new)) .collect(Collectors.toList())); diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index dd863cb8a2c..18d7a4dbdb2 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -1,5 +1,6 @@ package org.jabref.logic.oostyle; +import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; @@ -7,11 +8,13 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.slf4j.Logger; @@ -264,14 +267,57 @@ public int numberOfCitationGroups() { return citationGroups.size(); } - public Optional getPageInfo(CitationGroupID cgid) { - return (getCitationGroup(cgid) - .map(cg -> cg.pageInfo) - .flatMap(x -> x)); + /** + * @return List of nullable pageInfo values, one for each citation, + * instrage order. + * + * Result contains null for missing pageInfo values. + * The list itself is not null. + * + * For JabRef52 compatibility the last citation in + * localOrder gets the single pageInfo from the last in + * storage order, to make sure it is presented after the citations. + * This can only be done after localOrder is set. + * + * The result is passed to OOBibStyle.getCitationMarker or + * OOBibStyle.getNumCitationMarker + * + * TODO: we may want class DataModel52, DataModel53 and split this. + */ + private static List getPageInfosForCitations(OOStyleDataModelVersion dataModel, + CitationGroup cg) { + switch (dataModel) { + case JabRef52: + // check conformance to dataModel + for (int i = 0; i < cg.citations.size() - 1; i++) { + if (cg.citations.get(i).pageInfo.isPresent()) { + throw new RuntimeException("getPageInfosForCitations:" + + " found Citation.pageInfo" + + " outside last citation under JabRef52 dataModel"); + } + } + // A list of null values, except the last that comes from this.pageInfo + List result = new ArrayList<>(cg.citations.size()); + for (int i = 0; i < cg.citations.size() - 1; i++) { + int j = cg.localOrder.get(i); + OOFormattedText value = cg.citations.get(j).pageInfo.orElse(null); + result.add(value); + } + return result; + case JabRef53: + // pageInfo values from citations, empty mapped to null. + return (cg.citations.stream() + .map(cit -> cit.pageInfo.orElse(null)) + .collect(Collectors.toList())); + + default: + throw new RuntimeException("getPageInfosForCitations:" + + "unhandled dataModel"); + } } public List getPageInfosForCitations(CitationGroup cg) { - return Compat.getPageInfosForCitations(this.dataModel, cg); + return getPageInfosForCitations(this.dataModel, cg); } public List getPageInfosForCitations(CitationGroupID cgid) { @@ -283,12 +329,12 @@ public Optional> getCitations(CitationGroupID cgid) { return getCitationGroup(cgid).map(cg -> cg.citations); } - public List getSortedCitations(CitationGroupID cgid) { + public List getCitationsInLocalOrder(CitationGroupID cgid) { Optional cg = getCitationGroup(cgid); if (cg.isEmpty()) { - throw new RuntimeException("getSortedCitations: invalid cgid"); + throw new RuntimeException("getCitationsInLocalOrder: invalid cgid"); } - return cg.get().getSortedCitations(); + return cg.get().getCitationsInLocalOrder(); } public void afterCreateCitationGroup(CitationGroup cg) { diff --git a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java index 5dc96fc889b..3b52eaf9b94 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java @@ -4,6 +4,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.OOFormattedText; /** * This is what we need for getCitationMarker to produce author-year diff --git a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java index 530aca912fb..cb5537c01b1 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java @@ -5,6 +5,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.OOFormattedText; /** * Implement CitationMarkerEntry by containing the data needed. diff --git a/src/main/java/org/jabref/logic/oostyle/CitationSort.java b/src/main/java/org/jabref/logic/oostyle/CitationSort.java index c614c770adc..5d0a06858bd 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationSort.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationSort.java @@ -4,6 +4,7 @@ import java.util.Optional; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.OOFormattedText; class CitationSort { diff --git a/src/main/java/org/jabref/logic/oostyle/CitedKey.java b/src/main/java/org/jabref/logic/oostyle/CitedKey.java index fca035f02ce..2ef8e60525d 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/logic/oostyle/CitedKey.java @@ -6,6 +6,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.OOFormattedText; public class CitedKey implements CitationSort.ComparableCitation { public String citationKey; diff --git a/src/main/java/org/jabref/logic/oostyle/Compat.java b/src/main/java/org/jabref/logic/oostyle/Compat.java deleted file mode 100644 index b28171a7e39..00000000000 --- a/src/main/java/org/jabref/logic/oostyle/Compat.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.jabref.logic.oostyle; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.jabref.model.oostyle.OOStyleDataModelVersion; - -public class Compat { - - /** - * Return the last pageInfo from the list, if there is one. - */ - public static Optional - getJabRef52PageInfoFromList(List pageInfosForCitations) { - if (pageInfosForCitations == null) { - return Optional.empty(); - } - int n = pageInfosForCitations.size(); - if (n == 0) { - return Optional.empty(); - } - return Optional.ofNullable(pageInfosForCitations.get(n - 1)); - } - - /** - * @param pageInfo Nullable. - * @return JabRef53 style pageInfo list - */ - public static List fakePageInfosForCitations(String pageInfo, - int nCitations) { - List pageInfosForCitations = new ArrayList<>(nCitations); - for (int i = 0; i < nCitations; i++) { - if (i == nCitations - 1) { - pageInfosForCitations.add(OOFormattedText.fromString(pageInfo)); - } else { - pageInfosForCitations.add(null); - } - } - return pageInfosForCitations; - } - - /** - * @return List of nullable pageInfo values, one for each citation. - * Result contains null for missing pageInfo values. - * The list itself is not null. - * - * For Compat.DataModel.JabRef52 the last citation gets - * the CitationGroup.pageInfo - * - * The result is passed to OOBibStyle.getCitationMarker or - * OOBibStyle.getNumCitationMarker - * - * TODO: we may want class DataModel52, DataModel53 and split this. - */ - public static List getPageInfosForCitations(OOStyleDataModelVersion dataModel, - CitationGroup cg) { - switch (dataModel) { - case JabRef52: - // check conformance to dataModel - for (int i = 0; i < cg.citations.size(); i++) { - if (cg.citations.get(i).pageInfo.isPresent()) { - throw new RuntimeException("getPageInfosForCitations:" - + " found Citation.pageInfo under JabRef52 dataModel"); - } - } - // A list of null values, except the last that comes from this.pageInfo - OOFormattedText pi = cg.pageInfo.orElse(null); - return Compat.fakePageInfosForCitations(OOFormattedText.toString(pi), - cg.citations.size()); - case JabRef53: - // check conformance to dataModel - if (cg.pageInfo.isPresent()) { - throw new RuntimeException("getPageInfosForCitations:" - + " found CitationGroup.pageInfo under JabRef53 dataModel"); - } - // pageInfo values from citations, empty mapped to null. - return (cg.citations.stream() - .map(cit -> cit.pageInfo.orElse(null)) - .collect(Collectors.toList())); - - default: - throw new RuntimeException("getPageInfosForCitations:" - + "unhandled dataModel"); - } - } - - /** - * @return A list with one nullable pageInfo entry for each citation in - * joinableGroups. - * - * TODO: JabRef52 combinePageInfos is not reversible. Should warn - * user to check the result. Or ask what to do. - */ - public static List combinePageInfos(OOStyleDataModelVersion dataModel, - List joinableGroup) { - switch (dataModel) { - case JabRef52: - // collect to cgPageInfos - List> cgPageInfos = (joinableGroup.stream() - .map(cg -> cg.pageInfo) - .collect(Collectors.toList())); - - // Try to do something of the cgPageInfos. - String cgPageInfo = (cgPageInfos.stream() - .filter(pi -> pi.isPresent()) - .map(pi -> OOFormattedText.toString(pi.get())) - .distinct() - .collect(Collectors.joining("; "))); - - int nCitations = (joinableGroup.stream() - .map(cg -> cg.citations.size()) - .mapToInt(Integer::intValue).sum()); - - return Compat.fakePageInfosForCitations(cgPageInfo, nCitations); - - case JabRef53: - return (joinableGroup.stream() - .flatMap(cg -> (cg.citations.stream() - .map(cit -> cit.pageInfo.orElse(null)))) - .collect(Collectors.toList())); - default: - throw new RuntimeException("unhandled dataModel here"); - } - } - -} diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 51e65d49502..47589fed991 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -30,6 +30,7 @@ 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.oostyle.OOFormattedText; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index c173873d399..2e9f4a43ded 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -12,6 +12,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; +import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.strings.StringUtil; class OOBibStyleGetCitationMarker { diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index 120a1653a0a..c3966847ea1 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -5,6 +5,8 @@ import java.util.List; import java.util.function.ToIntFunction; +import org.jabref.model.oostyle.OOFormattedText; + class OOBibStyleGetNumCitationMarker { /* diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index 90a93dba951..a60d6eae411 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -7,6 +7,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.UnknownField; +import org.jabref.model.oostyle.OOFormattedText; public class OOFormat { private static final Field UNIQUEFIER_FIELD = new UnknownField("uniq"); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index da15cabc382..7f0072cf693 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -17,6 +17,7 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OOFormattedText; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -212,7 +213,7 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole Map citMarkers = new HashMap<>(); for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - List cits = cgs.getSortedCitations(cgid); + List cits = cgs.getCitationsInLocalOrder(cgid); String citMarker = style.getCitationGroupMarkupBefore() + (cits.stream() @@ -321,7 +322,7 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - List cits = cg.getSortedCitations(); + List cits = cg.getCitationsInLocalOrder(); final int nCitedEntries = cits.size(); List pageInfosForCitations = cgs.getPageInfosForCitations(cg); diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index bd146af5ace..c7f780e96c4 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -10,10 +10,9 @@ import org.jabref.logic.oostyle.Citation; import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitationGroups; -import org.jabref.logic.oostyle.Compat; -import org.jabref.logic.oostyle.OOFormattedText; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; @@ -25,10 +24,14 @@ import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextRange; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class Backend52 { + private static final Logger LOGGER = LoggerFactory.getLogger(Backend52.class); public final OOStyleDataModelVersion dataModel; public final StorageBase.NamedRangeManager citationStorageManager; + // uses: Codec52 public Backend52() { this.dataModel = OOStyleDataModelVersion.JabRef52; @@ -95,6 +98,21 @@ public Optional healthReport(DocumentConnection documentConnection) return Optional.of(msg); } + private static void setPageInfoInData(List citations, Optional pageInfo) { + // attribute to last citation (in storage order) + if (citations.size() > 0) { + citations.get(citations.size() - 1).pageInfo = pageInfo; + } + } + + private static Optional getPageInfoFromData(List citations) { + if (citations.size() > 0) { + return citations.get(citations.size() - 1).pageInfo; + } else { + return Optional.empty(); + } + } + /** * We have circular dependency here: backend uses * class from ... @@ -119,6 +137,8 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc Optional pageInfo = (documentConnection.getCustomProperty(refMarkName) .map(OOFormattedText::fromString)); + setPageInfoInData(citations, pageInfo); + Optional sr = (citationStorageManager .getFromDocument(documentConnection, refMarkName)); @@ -130,11 +150,35 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc CitationGroup cg = new CitationGroup(id, sr.get(), ov.itcType, - citations, - pageInfo); + citations); return cg; } + static Optional normalizePageInfoToOptional(OOFormattedText o) { + String s; + if (o == null || "".equals(OOFormattedText.toString(o))) { + s = null; + } else { + s = OOFormattedText.toString(o); + } + return Optional.ofNullable(OOFormattedText.fromString(s)); + } + + /** + * Return the last pageInfo from the list, if there is one. + */ + private static Optional + getJabRef52PageInfoFromList(List pageInfosForCitations) { + if (pageInfosForCitations == null) { + return Optional.empty(); + } + int n = pageInfosForCitations.size(); + if (n == 0) { + return Optional.empty(); + } + return normalizePageInfoToOptional(pageInfosForCitations.get(n - 1)); + } + /** * Create a reference mark with the given name, at the * end of position. @@ -213,7 +257,21 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, for (int i = 0; i < citationKeys.size(); i++) { Citation cit = new Citation(citationKeys.get(i)); citations.add(cit); - // cit.setPageInfo(getJabRef53PageInfo(pageInfosForCitations, i)); + + Optional pageInfo = normalizePageInfoToOptional(pageInfosForCitations.get(i)); + switch (dataModel) { + case JabRef52: + if (i == citationKeys.size() - 1) { + cit.pageInfo = pageInfo; + } else { + if (pageInfo.isPresent()) { + LOGGER.warn("dataModel JabRef52" + + " only supports pageInfo for the last citation of a group"); + } + } + case JabRef53: + cit.pageInfo = pageInfo; + } } /* @@ -227,7 +285,7 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, switch (dataModel) { case JabRef52: - Optional pageInfo = Compat.getJabRef52PageInfoFromList(pageInfosForCitations); + Optional pageInfo = getJabRef52PageInfoFromList(pageInfosForCitations); if (pageInfo.isPresent() && !"".equals(OOFormattedText.toString(pageInfo.get()))) { documentConnection.setCustomProperty(refMarkName, OOFormattedText.toString(pageInfo.get())); @@ -238,19 +296,57 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, CitationGroup cg = new CitationGroup(cgid, sr, itcType, - citations, - pageInfo); + citations); return cg; default: throw new RuntimeException("Backend52 requires JabRef52 dataModel"); } } + /** + * @return A list with one nullable pageInfo entry for each citation in + * joinableGroups. + * + * TODO: JabRef52 combinePageInfos is not reversible. Should warn + * user to check the result. Or ask what to do. + */ + public static List combinePageInfosCommon(OOStyleDataModelVersion dataModel, + List joinableGroup) { + switch (dataModel) { + case JabRef52: + // collect to cgPageInfos + List> cgPageInfos = (joinableGroup.stream() + .map(cg -> getPageInfoFromData(cg.citations)) + .collect(Collectors.toList())); + + // Try to do something of the cgPageInfos. + String cgPageInfo = (cgPageInfos.stream() + .filter(pi -> pi.isPresent()) + .map(pi -> OOFormattedText.toString(pi.get())) + .distinct() + .collect(Collectors.joining("; "))); + + int nCitations = (joinableGroup.stream() + .map(cg -> cg.citations.size()) + .mapToInt(Integer::intValue).sum()); + + return OOStyleDataModelVersion.fakePageInfosForCitations(cgPageInfo, nCitations); + + case JabRef53: + return (joinableGroup.stream() + .flatMap(cg -> (cg.citations.stream() + .map(cit -> cit.pageInfo.orElse(null)))) + .collect(Collectors.toList())); + default: + throw new RuntimeException("unhandled dataModel here"); + } + } + /** * */ public List combinePageInfos(List joinableGroup) { - return Compat.combinePageInfos(this.dataModel, joinableGroup); + return combinePageInfosCommon(this.dataModel, joinableGroup); } public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) @@ -339,10 +435,15 @@ public List getCitationEntries(DocumentConnection documentConnect .orElseThrow(RuntimeException::new)); String context = OOUtil.getCursorStringWithContext(documentConnection, cursor, 30, 30, true); + Optional pageInfo = (cg.citations.size() > 0 + ? (cg.citations + .get(cg.citations.size() - 1) + .getPageInfo() + .map(e -> OOFormattedText.toString(e))) + : Optional.empty()); CitationEntry entry = new CitationEntry(name, context, - (cgs.getPageInfo(cgid) - .map(e -> OOFormattedText.toString(e)))); + pageInfo); citations.add(entry); } return citations; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index f2b7977d405..90af3ffb62e 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -13,7 +13,7 @@ import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.logic.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOFormattedText; import com.sun.star.awt.FontSlant; import com.sun.star.awt.FontStrikeout; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index ebc015f03eb..19d11a4e3e1 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -12,9 +12,9 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitationGroups; -import org.jabref.logic.oostyle.OOFormattedText; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormattedText.java b/src/main/java/org/jabref/model/oostyle/OOFormattedText.java similarity index 93% rename from src/main/java/org/jabref/logic/oostyle/OOFormattedText.java rename to src/main/java/org/jabref/model/oostyle/OOFormattedText.java index 84f9075f478..b514edc6cce 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormattedText.java +++ b/src/main/java/org/jabref/model/oostyle/OOFormattedText.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; public class OOFormattedText { diff --git a/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java b/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java index 6af28ac09ea..2f6f35142d3 100644 --- a/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java +++ b/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java @@ -1,5 +1,8 @@ package org.jabref.model.oostyle; +import java.util.ArrayList; +import java.util.List; + /** What is the data stored? */ public enum OOStyleDataModelVersion { /** @@ -27,5 +30,22 @@ public enum OOStyleDataModelVersion { * pageInfo belongs to Citation. * Need: formatting citation needs to know about these, inject after each year part */ - JabRef53 + JabRef53; + + /** + * @param pageInfo Nullable. + * @return JabRef53 style pageInfo list + */ + public static List fakePageInfosForCitations(String pageInfo, + int nCitations) { + List pageInfosForCitations = new ArrayList<>(nCitations); + for (int i = 0; i < nCitations; i++) { + if (i == nCitations - 1) { + pageInfosForCitations.add(OOFormattedText.fromString(pageInfo)); + } else { + pageInfosForCitations.add(null); + } + } + return pageInfosForCitations; + } } diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 533a21463aa..29b87185ffe 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -21,6 +21,7 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; +import org.jabref.model.oostyle.OOFormattedText; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; From 43e3a6ef82ac67575f49c5a66ae5c65fcdfe073d Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 17:51:56 +0200 Subject: [PATCH 0668/1068] move CitationDatabaseLookup.java --- src/main/java/org/jabref/logic/oostyle/Citation.java | 1 + src/main/java/org/jabref/logic/oostyle/CitationGroups.java | 1 + src/main/java/org/jabref/logic/oostyle/CitedKey.java | 1 + .../{logic => model}/oostyle/CitationDatabaseLookup.java | 4 +++- 4 files changed, 6 insertions(+), 1 deletion(-) rename src/main/java/org/jabref/{logic => model}/oostyle/CitationDatabaseLookup.java (90%) diff --git a/src/main/java/org/jabref/logic/oostyle/Citation.java b/src/main/java/org/jabref/logic/oostyle/Citation.java index 215e282c9f9..5badb760c4f 100644 --- a/src/main/java/org/jabref/logic/oostyle/Citation.java +++ b/src/main/java/org/jabref/logic/oostyle/Citation.java @@ -3,6 +3,7 @@ import java.util.Optional; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.OOFormattedText; public class Citation implements CitationSort.ComparableCitation { diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 18d7a4dbdb2..ba49094ac1c 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -12,6 +12,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; diff --git a/src/main/java/org/jabref/logic/oostyle/CitedKey.java b/src/main/java/org/jabref/logic/oostyle/CitedKey.java index 2ef8e60525d..09abf8af4a6 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/logic/oostyle/CitedKey.java @@ -6,6 +6,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.OOFormattedText; public class CitedKey implements CitationSort.ComparableCitation { diff --git a/src/main/java/org/jabref/logic/oostyle/CitationDatabaseLookup.java b/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java similarity index 90% rename from src/main/java/org/jabref/logic/oostyle/CitationDatabaseLookup.java rename to src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java index ef5bda5dd3b..635dbd500c0 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationDatabaseLookup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java @@ -1,4 +1,6 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; + +// import org.jabref.model.oostyle.CitationDatabaseLookup; import java.util.List; import java.util.Optional; From 4bf6ed08b0322a5e9c5305f010277da64b60daaf Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 18:35:27 +0200 Subject: [PATCH 0669/1068] correct off by one error --- src/main/java/org/jabref/logic/oostyle/CitationGroups.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index ba49094ac1c..811d94f7dca 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -290,7 +290,8 @@ private static List getPageInfosForCitations(OOStyleDataModelVe switch (dataModel) { case JabRef52: // check conformance to dataModel - for (int i = 0; i < cg.citations.size() - 1; i++) { + final int nCitations = cg.citations.size(); + for (int i = 0; i < nCitations - 1; i++) { if (cg.citations.get(i).pageInfo.isPresent()) { throw new RuntimeException("getPageInfosForCitations:" + " found Citation.pageInfo" @@ -299,7 +300,7 @@ private static List getPageInfosForCitations(OOStyleDataModelVe } // A list of null values, except the last that comes from this.pageInfo List result = new ArrayList<>(cg.citations.size()); - for (int i = 0; i < cg.citations.size() - 1; i++) { + for (int i = 0; i < nCitations; i++) { int j = cg.localOrder.get(i); OOFormattedText value = cg.citations.get(j).pageInfo.orElse(null); result.add(value); From c6fdab90ded3ebaa80c19572e36593a5445ec584 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 19:26:18 +0200 Subject: [PATCH 0670/1068] add formatReferenceToPageNumberOfReferenceMark --- .../org/jabref/gui/openoffice/OOBibBase.java | 34 +++++++++++-------- .../org/jabref/logic/oostyle/OOFormat.java | 6 ++++ .../logic/openoffice/DocumentConnection.java | 7 ++-- .../openoffice/OOFormattedTextIntoOO.java | 27 ++++++++++++--- 4 files changed, 51 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9c722d9e980..de4ef0ca294 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -33,7 +33,6 @@ import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.OOFormattedTextIntoOO; import org.jabref.logic.openoffice.OOFrontend; -import org.jabref.logic.openoffice.OOUtil; import org.jabref.logic.openoffice.UndefinedCharacterFormatException; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; import org.jabref.model.database.BibDatabase; @@ -232,7 +231,8 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti PropertyVetoException, IllegalArgumentException, UndefinedCharacterFormatException, - NoSuchElementException { + NoSuchElementException, + CreationException { Objects.requireNonNull(cursor); Objects.requireNonNull(citationText); @@ -247,7 +247,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti // inject a ZERO_WIDTH_SPACE to hold the initial character format final String ZERO_WIDTH_SPACE = "\u200b"; citationText2 = OOFormattedText.fromString(ZERO_WIDTH_SPACE + citationText2.asString()); - OOFormattedTextIntoOO.write(cursor, citationText2); + OOFormattedTextIntoOO.write(documentConnection, cursor, citationText2); } else { cursor.setString(""); } @@ -806,14 +806,21 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, OOFormattedText referenceDetails = OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); sb.append(referenceDetails.asString()); - // Try to list citations: - if (false) { + if (true) { + // Try to list citations: // // TODO: not implemented in OOFormattedTextIntoOO.write // + // Problems: + // + // - With Reference + // - we do not control the text shown + // - using page numbers: useful in print + // - we would want it sorted by page number: why is it not? + // String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); String suffix = ")"; - OOUtil.insertTextAtCurrentLocation(cursor, prefix); + sb.append(prefix); int last = ck.where.size(); int i = 0; @@ -822,15 +829,14 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); if (i > 0) { - OOUtil.insertTextAtCurrentLocation(cursor, ", "); + sb.append(", "); } - documentConnection - .insertGetreferenceToPageNumberOfReferenceMark(cg.getMarkName(), cursor); + OOFormattedText xref = + OOFormat.formatReferenceToPageNumberOfReferenceMark(cg.getMarkName()); + sb.append(xref.asString()); i++; } - documentConnection.refresh(); - - OOUtil.insertTextAtCurrentLocation(cursor, suffix); + sb.append(suffix); } } else { @@ -853,7 +859,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, // Emit a bibliography entry OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); entryText = OOFormat.paragraph(entryText, parStyle); - OOFormattedTextIntoOO.write(cursor, entryText); + OOFormattedTextIntoOO.write(documentConnection, cursor, entryText); cursor.collapseToEnd(); } // for CitedKey } @@ -951,7 +957,7 @@ private void populateBibTextSection(DocumentConnection documentConnection, // emit the title of the bibliography OOFormattedTextIntoOO.removeDirectFormatting(cursor); OOFormattedText title = style.getFormattedBibliographyTitle(); - OOFormattedTextIntoOO.write(cursor, title); + OOFormattedTextIntoOO.write(documentConnection, cursor, title); cursor.collapseToEnd(); // remove the inital empty paragraph from the section. diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index a60d6eae411..25b528a52a1 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -109,4 +109,10 @@ public static OOFormattedText paragraph(OOFormattedText s) { + s.asString() + "

"); } + + public static OOFormattedText formatReferenceToPageNumberOfReferenceMark(String referencMarkName) { + String s = String.format("", + referencMarkName); + return OOFormattedText.fromString(s); + } } diff --git a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java index d25e481c7c3..85860eb0710 100644 --- a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java @@ -1017,8 +1017,8 @@ public XNamed insertBookmark(String name, * May need a documentConnection.refresh() after, to update * the text shown. */ - public void insertGetreferenceToPageNumberOfReferenceMark(String referenceMarkName, - XTextRange cursor) + public void insertReferenceToPageNumberOfReferenceMark(String referenceMarkName, + XTextRange cursor) throws CreationException, UnknownPropertyException, @@ -1054,9 +1054,6 @@ public void insertGetreferenceToPageNumberOfReferenceMark(String referenceMarkNa // Get the XTextContent interface of the GetReference text field XTextContent xRefContent = (XTextContent) unoQI(XTextContent.class, xFieldProps); - // Make some text to precede the reference - // this.xText.insertString(cursor.getEnd(), "Page ", false); - // Insert the text field this.xText.insertTextContent(cursor.getEnd(), xRefContent, false); diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index 90af3ffb62e..89f4607c26d 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -71,8 +71,10 @@ public class OOFormattedTextIntoOO { private static final byte SUPERSCRIPT_HEIGHT = (byte) 58; private static final byte SUBSCRIPT_HEIGHT = (byte) 58; - private static final String TAG_NAME_REGEXP = "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|span)"; - private static final String ATTRIBUTE_NAME_REGEXP = "(?:oo:ParaStyleName|oo:CharStyleName|lang|style)"; + private static final String TAG_NAME_REGEXP = + "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|span|oo:referenceToPageNumberOfReferenceMark)"; + private static final String ATTRIBUTE_NAME_REGEXP = + "(?:oo:ParaStyleName|oo:CharStyleName|lang|style|target)"; private static final String ATTRIBUTE_VALUE_REGEXP = "\"([^\"]*)\""; private static final Pattern HTML_TAG = Pattern.compile("<(/" + TAG_NAME_REGEXP + ")>" @@ -128,14 +130,16 @@ private OOFormattedTextIntoOO() { * @param position The cursor giving the insert location. Not modified. * @param ootext The marked-up text to insert. */ - public static void write(XTextCursor position, + public static void write(DocumentConnection documentConnection, + XTextCursor position, OOFormattedText ootext) throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, IllegalArgumentException, - NoSuchElementException { + NoSuchElementException, + CreationException { String lText = OOFormattedText.toString(ootext); @@ -227,6 +231,21 @@ public static void write(XTextCursor position, } } break; + case "oo:referenceToPageNumberOfReferenceMark": + for (Pair kv : attributes) { + String key = kv.getKey(); + String value = kv.getValue(); + switch (key) { + case "target": + documentConnection + .insertReferenceToPageNumberOfReferenceMark(value, cursor); + break; + default: + LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); + break; + } + } + break; case "tt": // Note: "Example" names a character style in LibreOffice. formatters.push(setCharStyleName("Example")); From 24a17f410df826127aa933055bed3fbfd4679124 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 21:20:13 +0200 Subject: [PATCH 0671/1068] add formatBibliographyBody --- .../org/jabref/gui/openoffice/OOBibBase.java | 138 +++------------- .../jabref/logic/oostyle/CitationGroup.java | 29 +++- .../jabref/logic/oostyle/CitationGroups.java | 17 ++ .../org/jabref/logic/oostyle/OOFormat.java | 151 +++++++++++++++++- .../jabref/logic/openoffice/Backend52.java | 6 +- 5 files changed, 215 insertions(+), 126 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index de4ef0ca294..82866f9a9c7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -15,18 +15,15 @@ import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.layout.Layout; import org.jabref.logic.oostyle.Citation; import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.CitationMarkerEntry; import org.jabref.logic.oostyle.CitationMarkerEntryImpl; -import org.jabref.logic.oostyle.CitationPath; import org.jabref.logic.oostyle.CitedKey; import org.jabref.logic.oostyle.CitedKeys; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOFormat; -import org.jabref.logic.oostyle.OOPreFormatter; import org.jabref.logic.oostyle.OOProcess; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.DocumentConnection; @@ -69,7 +66,6 @@ */ @AllowedToUseAwt("Requires AWT for italics and bold") class OOBibBase { - private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); private static final String BIB_SECTION_NAME = "JR_bib"; private static final String BIB_SECTION_END_NAME = "JR_bib_end"; @@ -79,6 +75,7 @@ class OOBibBase { /* variables */ private final DialogService dialogService; + private final boolean alwaysAddCitedOnPages; /** * Created when connected to a document. @@ -100,6 +97,7 @@ public OOBibBase(Path loPath, this.dialogService = dialogService; this.connection = new OOBibBaseConnect(loPath, dialogService); + this.alwaysAddCitedOnPages = true; } public void selectDocument() @@ -588,7 +586,8 @@ public void insertEntry(List entries, rebuildBibTextSection(documentConnection, style, fr2, - x.getBibliography()); + x.getBibliography(), + this.alwaysAddCitedOnPages); } finally { documentConnection.unlockControllers(); } @@ -723,7 +722,8 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, private void rebuildBibTextSection(DocumentConnection documentConnection, OOBibStyle style, OOFrontend fr, - CitedKeys bibliography) + CitedKeys bibliography, + boolean alwaysAddCitedOnPages) throws NoSuchElementException, WrappedTargetException, @@ -738,17 +738,11 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, populateBibTextSection(documentConnection, fr, bibliography, - style); + style, + alwaysAddCitedOnPages); } - /** - * Insert body of bibliography at `cursor`. - * - * @param documentConnection Connection. - * @param cursor Where to - * @param cgs - * @param bibliography - * @param style Style. + /* * * Only called from populateBibTextSection (and that from rebuildBibTextSection) */ @@ -756,7 +750,8 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, XTextCursor cursor, CitationGroups cgs, CitedKeys bibliography, - OOBibStyle style) + OOBibStyle style, + boolean alwaysAddCitedOnPages) throws IllegalArgumentException, UnknownPropertyException, @@ -764,104 +759,10 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, WrappedTargetException, CreationException, NoSuchElementException { - - final boolean debugThisFun = false; - - if (debugThisFun) { - System.out.printf("Ref IsSortByPosition %s\n", style.isSortByPosition()); - System.out.printf("Ref IsNumberEntries %s\n", style.isNumberEntries()); - } - - String parStyle = style.getReferenceParagraphFormat(); - - for (CitedKey ck : bibliography.values()) { - - if (debugThisFun) { - System.out.printf("Ref cit %-20s ck.number %7s%n", - String.format("'%s'", ck.citationKey), - (ck.number.isEmpty() - ? "(empty)" - : String.format("%02d", ck.number.get()))); - } - - StringBuilder sb = new StringBuilder(); - // insert marker "[1]" - if (style.isNumberEntries()) { - - if (ck.number.isEmpty()) { - throw new RuntimeException("insertFullReferenceAtCursor:" - + " numbered style, but found unnumbered entry"); - } - - int number = ck.number.get(); - OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); - sb.append(marker.asString()); - } else { - // !style.isNumberEntries() : emit no prefix - // TODO: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); - } - - if (ck.db.isEmpty()) { - // Unresolved entry - OOFormattedText referenceDetails = - OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); - sb.append(referenceDetails.asString()); - if (true) { - // Try to list citations: - // - // TODO: not implemented in OOFormattedTextIntoOO.write - // - // Problems: - // - // - With Reference - // - we do not control the text shown - // - using page numbers: useful in print - // - we would want it sorted by page number: why is it not? - // - String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); - String suffix = ")"; - sb.append(prefix); - - int last = ck.where.size(); - int i = 0; - for (CitationPath p : ck.where) { - CitationGroupID cgid = p.group; - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - - if (i > 0) { - sb.append(", "); - } - OOFormattedText xref = - OOFormat.formatReferenceToPageNumberOfReferenceMark(cg.getMarkName()); - sb.append(xref.asString()); - i++; - } - sb.append(suffix); - } - - } else { - // Resolved entry - BibEntry bibentry = ck.db.get().entry; - - // insert the actual details. - Layout layout = style.getReferenceFormat(bibentry.getType()); - layout.setPostFormatter(POSTFORMATTER); - - OOFormattedText formattedText = OOFormat.formatFullReference(layout, - bibentry, - ck.db.get().database, - ck.uniqueLetter.orElse(null)); - - // Insert the formatted text: - sb.append(formattedText.asString()); - } - - // Emit a bibliography entry - OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); - entryText = OOFormat.paragraph(entryText, parStyle); - OOFormattedTextIntoOO.write(documentConnection, cursor, entryText); - cursor.collapseToEnd(); - } // for CitedKey + OOFormattedText text = + OOFormat.formatBibliographyBody(cgs, bibliography, style, alwaysAddCitedOnPages); + OOFormattedTextIntoOO.write(documentConnection, cursor, text); + cursor.collapseToEnd(); } /** @@ -937,7 +838,8 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) private void populateBibTextSection(DocumentConnection documentConnection, OOFrontend fr, CitedKeys bibliography, - OOBibStyle style) + OOBibStyle style, + boolean alwaysAddCitedOnPages) throws NoSuchElementException, WrappedTargetException, @@ -972,7 +874,8 @@ private void populateBibTextSection(DocumentConnection documentConnection, cursor, fr.cgs, bibliography, - style); + style, + alwaysAddCitedOnPages); documentConnection.insertBookmark(OOBibBase.BIB_SECTION_END_NAME, cursor, @@ -1806,7 +1709,8 @@ public List updateDocumentActionHelper(List databases, rebuildBibTextSection(documentConnection, style, fr, - x.getBibliography()); + x.getBibliography(), + this.alwaysAddCitedOnPages); return x.getUnresolvedKeys(); } finally { if (useLockControllers && documentConnection.hasControllersLocked()) { diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index 25b18c533f0..b5281dc4b6f 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -18,21 +18,44 @@ public class CitationGroup { public StorageBase.NamedRange cgRangeStorage; // knows referenceMarkName public InTextCitationType itcType; public List citations; + public List localOrder; + /* + * A name of a reference mark to link to by formatCitedOnPages. + * May be empty, if Backend does not use reference marks. + */ + private Optional referenceMarkNameForLinking; + private Optional indexInGlobalOrder; + public CitationGroup(CitationGroupID cgid, StorageBase.NamedRange cgRangeStorage, InTextCitationType itcType, - List citations) { + List citations, + Optional referenceMarkNameForLinking) { this.cgid = cgid; this.cgRangeStorage = cgRangeStorage; this.itcType = itcType; this.citations = citations; this.localOrder = makeIndices(citations.size()); + this.referenceMarkNameForLinking = referenceMarkNameForLinking; + this.indexInGlobalOrder = Optional.empty(); + } + + public void setIndexInGlobalOrder(Optional i) { + this.indexInGlobalOrder = i; + } + + public Optional getIndexInGlobalOrder() { + return this.indexInGlobalOrder; + } + + public Optional getReferenceMarkNameForLinking() { + return referenceMarkNameForLinking; } - public String getMarkName() { - return cgRangeStorage.getName(); + public void setReferenceMarkNameForLinking(Optional referenceMarkNameForLinking) { + this.referenceMarkNameForLinking = referenceMarkNameForLinking; } /** Integers 0..(n-1) */ diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 811d94f7dca..41382014700 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -241,6 +241,11 @@ public void setGlobalOrder(List globalOrder) { + " globalOrder.size() != citationGroups.size()"); } this.globalOrder = Optional.of(globalOrder); + int i = 0; + for (CitationGroupID cgid : globalOrder) { + citationGroups.get(cgid).setIndexInGlobalOrder(Optional.of(i)); + i++; + } } public Optional getCitationGroup(CitationGroupID cgid) { @@ -339,6 +344,18 @@ public List getCitationsInLocalOrder(CitationGroupID cgid) { return cg.get().getCitationsInLocalOrder(); } + /* + * @return true if all citation groups have referenceMarkNameForLinking + */ + public boolean citationGroupsProvideReferenceMarkNameForLinking() { + for (CitationGroup cg : citationGroups.values()) { + if (cg.getReferenceMarkNameForLinking().isEmpty()) { + return false; + } + } + return true; + } + public void afterCreateCitationGroup(CitationGroup cg) { // add to our data diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index 25b528a52a1..eb8911414ba 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -1,16 +1,22 @@ package org.jabref.logic.oostyle; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; +import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.UnknownField; +import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.OOFormattedText; public class OOFormat { + private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); private static final Field UNIQUEFIER_FIELD = new UnknownField("uniq"); + /** * Format the reference part of a bibliography entry using a Layout. * @@ -21,10 +27,10 @@ public class OOFormat { * * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation2() */ - public static OOFormattedText formatFullReference(Layout layout, - BibEntry entry, - BibDatabase database, - String uniquefier) { + private static OOFormattedText formatFullReferenceOfBibEbtry(Layout layout, + BibEntry entry, + BibDatabase database, + String uniquefier) { // Backup the value of the uniq field, just in case the entry already has it: Optional oldUniqVal = entry.getField(UNIQUEFIER_FIELD); @@ -49,6 +55,143 @@ public static OOFormattedText formatFullReference(Layout layout, return formattedText; } + private static OOFormattedText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { + if (!cgs.citationGroupsProvideReferenceMarkNameForLinking()) { + return OOFormattedText.fromString(""); + } + + // Format links to citations. + // + // Requires reference marks for citation groups. + // + // - With Reference + // - we do not control the text shown + // - using page numbers: useful in print + // + StringBuilder sb = new StringBuilder(); + + String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); + String suffix = ")"; + sb.append(prefix); + + List citationGroups = new ArrayList(); + for (CitationPath p : ck.where) { + CitationGroupID cgid = p.group; + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + citationGroups.add(cg); + } + + // sort the citationGroups according to their indexInGlobalOrder + citationGroups.sort((a, b) -> { + return (a + .getIndexInGlobalOrder() + .orElseThrow(RuntimeException::new) + .compareTo(b + .getIndexInGlobalOrder() + .orElseThrow(RuntimeException::new))); }); + + int i = 0; + for (CitationGroup cg : citationGroups) { + if (i > 0) { + sb.append(", "); + } + String referenceMarkName = (cg.getReferenceMarkNameForLinking() + .orElseThrow(RuntimeException::new)); + OOFormattedText xref = + OOFormat.formatReferenceToPageNumberOfReferenceMark(referenceMarkName); + sb.append(xref.asString()); + i++; + } + sb.append(suffix); + return OOFormattedText.fromString(sb.toString()); + } + + /** + * Format body of bibliography. + */ + public static OOFormattedText formatBibliographyBody(CitationGroups cgs, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { + + final boolean debugThisFun = false; + + if (debugThisFun) { + System.out.printf("Ref IsSortByPosition %s\n", style.isSortByPosition()); + System.out.printf("Ref IsNumberEntries %s\n", style.isNumberEntries()); + } + + String parStyle = style.getReferenceParagraphFormat(); + + StringBuilder stringBuilder = new StringBuilder(); + + for (CitedKey ck : bibliography.values()) { + StringBuilder sb = new StringBuilder(); + + if (debugThisFun) { + System.out.printf("Ref cit %-20s ck.number %7s%n", + String.format("'%s'", ck.citationKey), + (ck.number.isEmpty() + ? "(empty)" + : String.format("%02d", ck.number.get()))); + } + + // insert marker "[1]" + if (style.isNumberEntries()) { + + if (ck.number.isEmpty()) { + throw new RuntimeException("formatFullReference:" + + " numbered style, but found unnumbered entry"); + } + + int number = ck.number.get(); + OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); + sb.append(marker.asString()); + } else { + // !style.isNumberEntries() : emit no prefix + // TODO: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); + } + + if (ck.db.isEmpty()) { + // Unresolved entry + OOFormattedText referenceDetails = + OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); + sb.append(referenceDetails.asString()); + if (true) { + sb.append(formatCitedOnPages(cgs, ck).asString()); + } + + } else { + // Resolved entry + BibEntry bibentry = ck.db.get().entry; + + // insert the actual details. + Layout layout = style.getReferenceFormat(bibentry.getType()); + layout.setPostFormatter(POSTFORMATTER); + + OOFormattedText formattedText = + OOFormat.formatFullReferenceOfBibEbtry(layout, + bibentry, + ck.db.get().database, + ck.uniqueLetter.orElse(null)); + + // Insert the formatted text: + sb.append(formattedText.asString()); + if (alwaysAddCitedOnPages) { + sb.append(formatCitedOnPages(cgs, ck).asString()); + } + } + + // Emit a bibliography entry + OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); + entryText = OOFormat.paragraph(entryText, parStyle); + stringBuilder.append(entryText.asString()); + } // for CitedKey + + OOFormattedText full = OOFormattedText.fromString(stringBuilder.toString()); + return full; + } + /** * Mark {@code s} as using a character locale known to OO. * diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index c7f780e96c4..77bd8c4be62 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -150,7 +150,8 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc CitationGroup cg = new CitationGroup(id, sr.get(), ov.itcType, - citations); + citations, + Optional.of(refMarkName)); return cg; } @@ -296,7 +297,8 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, CitationGroup cg = new CitationGroup(cgid, sr, itcType, - citations); + citations, + Optional.of(refMarkName)); return cg; default: throw new RuntimeException("Backend52 requires JabRef52 dataModel"); From bb56baba40d93781644e782241198238aee6adc9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 21:28:09 +0200 Subject: [PATCH 0672/1068] separate OOFormatBibliography.java --- .../org/jabref/gui/openoffice/OOBibBase.java | 3 +- .../org/jabref/logic/oostyle/OOFormat.java | 188 ----------------- .../logic/oostyle/OOFormatBibliography.java | 194 ++++++++++++++++++ 3 files changed, 196 insertions(+), 189 deletions(-) create mode 100644 src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 82866f9a9c7..18b02eb348b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -24,6 +24,7 @@ import org.jabref.logic.oostyle.CitedKeys; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOFormat; +import org.jabref.logic.oostyle.OOFormatBibliography; import org.jabref.logic.oostyle.OOProcess; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.DocumentConnection; @@ -760,7 +761,7 @@ private void insertFullReferenceAtCursor(DocumentConnection documentConnection, CreationException, NoSuchElementException { OOFormattedText text = - OOFormat.formatBibliographyBody(cgs, bibliography, style, alwaysAddCitedOnPages); + OOFormatBibliography.formatBibliographyBody(cgs, bibliography, style, alwaysAddCitedOnPages); OOFormattedTextIntoOO.write(documentConnection, cursor, text); cursor.collapseToEnd(); } diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index eb8911414ba..9a361171da2 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -1,196 +1,8 @@ package org.jabref.logic.oostyle; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import org.jabref.logic.l10n.Localization; -import org.jabref.logic.layout.Layout; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.Field; -import org.jabref.model.entry.field.UnknownField; -import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.OOFormattedText; public class OOFormat { - private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); - private static final Field UNIQUEFIER_FIELD = new UnknownField("uniq"); - - /** - * Format the reference part of a bibliography entry using a Layout. - * - * @param layout The Layout to format the reference with. - * @param entry The entry to insert. - * @param database The database the entry belongs to. - * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. - * - * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation2() - */ - private static OOFormattedText formatFullReferenceOfBibEbtry(Layout layout, - BibEntry entry, - BibDatabase database, - String uniquefier) { - - // Backup the value of the uniq field, just in case the entry already has it: - Optional oldUniqVal = entry.getField(UNIQUEFIER_FIELD); - - // Set the uniq field with the supplied uniquefier: - if (uniquefier == null) { - entry.clearField(UNIQUEFIER_FIELD); - } else { - entry.setField(UNIQUEFIER_FIELD, uniquefier); - } - - // Do the layout for this entry: - OOFormattedText formattedText = OOFormattedText.fromString(layout.doLayout(entry, database)); - - // Afterwards, reset the old value: - if (oldUniqVal.isPresent()) { - entry.setField(UNIQUEFIER_FIELD, oldUniqVal.get()); - } else { - entry.clearField(UNIQUEFIER_FIELD); - } - - return formattedText; - } - - private static OOFormattedText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { - if (!cgs.citationGroupsProvideReferenceMarkNameForLinking()) { - return OOFormattedText.fromString(""); - } - - // Format links to citations. - // - // Requires reference marks for citation groups. - // - // - With Reference - // - we do not control the text shown - // - using page numbers: useful in print - // - StringBuilder sb = new StringBuilder(); - - String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); - String suffix = ")"; - sb.append(prefix); - - List citationGroups = new ArrayList(); - for (CitationPath p : ck.where) { - CitationGroupID cgid = p.group; - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - citationGroups.add(cg); - } - - // sort the citationGroups according to their indexInGlobalOrder - citationGroups.sort((a, b) -> { - return (a - .getIndexInGlobalOrder() - .orElseThrow(RuntimeException::new) - .compareTo(b - .getIndexInGlobalOrder() - .orElseThrow(RuntimeException::new))); }); - - int i = 0; - for (CitationGroup cg : citationGroups) { - if (i > 0) { - sb.append(", "); - } - String referenceMarkName = (cg.getReferenceMarkNameForLinking() - .orElseThrow(RuntimeException::new)); - OOFormattedText xref = - OOFormat.formatReferenceToPageNumberOfReferenceMark(referenceMarkName); - sb.append(xref.asString()); - i++; - } - sb.append(suffix); - return OOFormattedText.fromString(sb.toString()); - } - - /** - * Format body of bibliography. - */ - public static OOFormattedText formatBibliographyBody(CitationGroups cgs, - CitedKeys bibliography, - OOBibStyle style, - boolean alwaysAddCitedOnPages) { - - final boolean debugThisFun = false; - - if (debugThisFun) { - System.out.printf("Ref IsSortByPosition %s\n", style.isSortByPosition()); - System.out.printf("Ref IsNumberEntries %s\n", style.isNumberEntries()); - } - - String parStyle = style.getReferenceParagraphFormat(); - - StringBuilder stringBuilder = new StringBuilder(); - - for (CitedKey ck : bibliography.values()) { - StringBuilder sb = new StringBuilder(); - - if (debugThisFun) { - System.out.printf("Ref cit %-20s ck.number %7s%n", - String.format("'%s'", ck.citationKey), - (ck.number.isEmpty() - ? "(empty)" - : String.format("%02d", ck.number.get()))); - } - - // insert marker "[1]" - if (style.isNumberEntries()) { - - if (ck.number.isEmpty()) { - throw new RuntimeException("formatFullReference:" - + " numbered style, but found unnumbered entry"); - } - - int number = ck.number.get(); - OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); - sb.append(marker.asString()); - } else { - // !style.isNumberEntries() : emit no prefix - // TODO: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); - } - - if (ck.db.isEmpty()) { - // Unresolved entry - OOFormattedText referenceDetails = - OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); - sb.append(referenceDetails.asString()); - if (true) { - sb.append(formatCitedOnPages(cgs, ck).asString()); - } - - } else { - // Resolved entry - BibEntry bibentry = ck.db.get().entry; - - // insert the actual details. - Layout layout = style.getReferenceFormat(bibentry.getType()); - layout.setPostFormatter(POSTFORMATTER); - - OOFormattedText formattedText = - OOFormat.formatFullReferenceOfBibEbtry(layout, - bibentry, - ck.db.get().database, - ck.uniqueLetter.orElse(null)); - - // Insert the formatted text: - sb.append(formattedText.asString()); - if (alwaysAddCitedOnPages) { - sb.append(formatCitedOnPages(cgs, ck).asString()); - } - } - - // Emit a bibliography entry - OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); - entryText = OOFormat.paragraph(entryText, parStyle); - stringBuilder.append(entryText.asString()); - } // for CitedKey - - OOFormattedText full = OOFormattedText.fromString(stringBuilder.toString()); - return full; - } /** * Mark {@code s} as using a character locale known to OO. diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java new file mode 100644 index 00000000000..5a32016e36e --- /dev/null +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -0,0 +1,194 @@ +package org.jabref.logic.oostyle; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.jabref.logic.l10n.Localization; +import org.jabref.logic.layout.Layout; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; +import org.jabref.model.entry.field.UnknownField; +import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.OOFormattedText; + +public class OOFormatBibliography { + private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); + private static final Field UNIQUEFIER_FIELD = new UnknownField("uniq"); + + /** + * Format the reference part of a bibliography entry using a Layout. + * + * @param layout The Layout to format the reference with. + * @param entry The entry to insert. + * @param database The database the entry belongs to. + * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. + * + * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation2() + */ + private static OOFormattedText formatFullReferenceOfBibEbtry(Layout layout, + BibEntry entry, + BibDatabase database, + String uniquefier) { + + // Backup the value of the uniq field, just in case the entry already has it: + Optional oldUniqVal = entry.getField(UNIQUEFIER_FIELD); + + // Set the uniq field with the supplied uniquefier: + if (uniquefier == null) { + entry.clearField(UNIQUEFIER_FIELD); + } else { + entry.setField(UNIQUEFIER_FIELD, uniquefier); + } + + // Do the layout for this entry: + OOFormattedText formattedText = OOFormattedText.fromString(layout.doLayout(entry, database)); + + // Afterwards, reset the old value: + if (oldUniqVal.isPresent()) { + entry.setField(UNIQUEFIER_FIELD, oldUniqVal.get()); + } else { + entry.clearField(UNIQUEFIER_FIELD); + } + + return formattedText; + } + + private static OOFormattedText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { + if (!cgs.citationGroupsProvideReferenceMarkNameForLinking()) { + return OOFormattedText.fromString(""); + } + + // Format links to citations. + // + // Requires reference marks for citation groups. + // + // - With Reference + // - we do not control the text shown + // - using page numbers: useful in print + // + StringBuilder sb = new StringBuilder(); + + String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); + String suffix = ")"; + sb.append(prefix); + + List citationGroups = new ArrayList(); + for (CitationPath p : ck.where) { + CitationGroupID cgid = p.group; + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + citationGroups.add(cg); + } + + // sort the citationGroups according to their indexInGlobalOrder + citationGroups.sort((a, b) -> { + return (a + .getIndexInGlobalOrder() + .orElseThrow(RuntimeException::new) + .compareTo(b + .getIndexInGlobalOrder() + .orElseThrow(RuntimeException::new))); }); + + int i = 0; + for (CitationGroup cg : citationGroups) { + if (i > 0) { + sb.append(", "); + } + String referenceMarkName = (cg.getReferenceMarkNameForLinking() + .orElseThrow(RuntimeException::new)); + OOFormattedText xref = + OOFormat.formatReferenceToPageNumberOfReferenceMark(referenceMarkName); + sb.append(xref.asString()); + i++; + } + sb.append(suffix); + return OOFormattedText.fromString(sb.toString()); + } + + /** + * Format body of bibliography. + */ + public static OOFormattedText formatBibliographyBody(CitationGroups cgs, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { + + final boolean debugThisFun = false; + + if (debugThisFun) { + System.out.printf("Ref IsSortByPosition %s\n", style.isSortByPosition()); + System.out.printf("Ref IsNumberEntries %s\n", style.isNumberEntries()); + } + + String parStyle = style.getReferenceParagraphFormat(); + + StringBuilder stringBuilder = new StringBuilder(); + + for (CitedKey ck : bibliography.values()) { + StringBuilder sb = new StringBuilder(); + + if (debugThisFun) { + System.out.printf("Ref cit %-20s ck.number %7s%n", + String.format("'%s'", ck.citationKey), + (ck.number.isEmpty() + ? "(empty)" + : String.format("%02d", ck.number.get()))); + } + + // insert marker "[1]" + if (style.isNumberEntries()) { + + if (ck.number.isEmpty()) { + throw new RuntimeException("formatFullReference:" + + " numbered style, but found unnumbered entry"); + } + + int number = ck.number.get(); + OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); + sb.append(marker.asString()); + } else { + // !style.isNumberEntries() : emit no prefix + // TODO: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); + } + + if (ck.db.isEmpty()) { + // Unresolved entry + OOFormattedText referenceDetails = + OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); + sb.append(referenceDetails.asString()); + if (true) { + sb.append(formatCitedOnPages(cgs, ck).asString()); + } + + } else { + // Resolved entry + BibEntry bibentry = ck.db.get().entry; + + // insert the actual details. + Layout layout = style.getReferenceFormat(bibentry.getType()); + layout.setPostFormatter(POSTFORMATTER); + + OOFormattedText formattedText = + formatFullReferenceOfBibEbtry(layout, + bibentry, + ck.db.get().database, + ck.uniqueLetter.orElse(null)); + + // Insert the formatted text: + sb.append(formattedText.asString()); + if (alwaysAddCitedOnPages) { + sb.append(formatCitedOnPages(cgs, ck).asString()); + } + } + + // Emit a bibliography entry + OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); + entryText = OOFormat.paragraph(entryText, parStyle); + stringBuilder.append(entryText.asString()); + } // for CitedKey + + OOFormattedText full = OOFormattedText.fromString(stringBuilder.toString()); + return full; + } +} From 0805667c7fb88067c9356d6783a462827147a007 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 22:00:00 +0200 Subject: [PATCH 0673/1068] add formatBibliographyEntryBody, formatBibliographyEntry Potentially useful parts. --- .../org/jabref/logic/oostyle/OOFormat.java | 3 + .../logic/oostyle/OOFormatBibliography.java | 193 ++++++++++-------- 2 files changed, 111 insertions(+), 85 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index 9a361171da2..fb77c13d4ae 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -51,6 +51,9 @@ public static OOFormattedText setCharStyle(OOFormattedText s, String charStyle) * Mark {@code s} as part of a paragraph with style {@code paraStyle} */ public static OOFormattedText paragraph(OOFormattedText s, String paraStyle) { + if (paraStyle == null || "".equals(paraStyle)) { + return paragraph(s); + } return OOFormattedText.fromString(String.format("

", paraStyle) + s.asString() + "

"); diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index 5a32016e36e..77feaba9966 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -17,6 +17,114 @@ public class OOFormatBibliography { private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); private static final Field UNIQUEFIER_FIELD = new UnknownField("uniq"); + private OOFormatBibliography() { + } + + /* + * @return just the body. No label, "Cited on pages" or paragraph. + */ + public static OOFormattedText formatBibliographyEntryBody(CitedKey ck, + OOBibStyle style) { + if (ck.db.isEmpty()) { + // Unresolved entry + return OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); + } else { + // Resolved entry, use the layout engine + BibEntry bibentry = ck.db.get().entry; + Layout layout = style.getReferenceFormat(bibentry.getType()); + layout.setPostFormatter(POSTFORMATTER); + + return formatFullReferenceOfBibEbtry(layout, + bibentry, + ck.db.get().database, + ck.uniqueLetter.orElse(null)); + } + } + + /* + * @return a paragraph. Includes label and "Cited on pages". + */ + public static OOFormattedText formatBibliographyEntry(CitationGroups cgs, + CitedKey ck, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { + StringBuilder sb = new StringBuilder(); + + // insert marker "[1]" + if (style.isNumberEntries()) { + + if (ck.number.isEmpty()) { + throw new RuntimeException("formatBibliographyEntry:" + + " numbered style, but found unnumbered entry"); + } + + int number = ck.number.get(); + OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); + sb.append(marker.asString()); + } else { + // !style.isNumberEntries() : emit no prefix + // Note: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); + } + + // Add entry body + OOFormattedText formattedText = formatBibliographyEntryBody(ck, style); + sb.append(formattedText.asString()); + + // Add "Cited on pages" + if (ck.db.isEmpty()) { + // Unresolved entry: add links to citations + sb.append(formatCitedOnPages(cgs, ck).asString()); + } else { + // Resolved entry + if (alwaysAddCitedOnPages) { + sb.append(formatCitedOnPages(cgs, ck).asString()); + } + } + + // Add paragraph + OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); + String parStyle = style.getReferenceParagraphFormat(); + return OOFormat.paragraph(entryText, parStyle); + } + + /** + * Format body of bibliography. + */ + public static OOFormattedText formatBibliographyBody(CitationGroups cgs, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { + + final boolean debugThisFun = false; + + if (debugThisFun) { + System.out.printf("Ref IsSortByPosition %s\n", style.isSortByPosition()); + System.out.printf("Ref IsNumberEntries %s\n", style.isNumberEntries()); + } + + StringBuilder stringBuilder = new StringBuilder(); + + for (CitedKey ck : bibliography.values()) { + StringBuilder sb = new StringBuilder(); + + if (debugThisFun) { + System.out.printf("Ref cit %-20s ck.number %7s%n", + String.format("'%s'", ck.citationKey), + (ck.number.isEmpty() + ? "(empty)" + : String.format("%02d", ck.number.get()))); + } + + OOFormattedText entryText = formatBibliographyEntry(cgs, ck, style, alwaysAddCitedOnPages); + + // Add full entry to bibliography. + stringBuilder.append(entryText.asString()); + } // for CitedKey + + OOFormattedText full = OOFormattedText.fromString(stringBuilder.toString()); + return full; + } + /** * Format the reference part of a bibliography entry using a Layout. * @@ -106,89 +214,4 @@ private static OOFormattedText formatCitedOnPages(CitationGroups cgs, CitedKey c return OOFormattedText.fromString(sb.toString()); } - /** - * Format body of bibliography. - */ - public static OOFormattedText formatBibliographyBody(CitationGroups cgs, - CitedKeys bibliography, - OOBibStyle style, - boolean alwaysAddCitedOnPages) { - - final boolean debugThisFun = false; - - if (debugThisFun) { - System.out.printf("Ref IsSortByPosition %s\n", style.isSortByPosition()); - System.out.printf("Ref IsNumberEntries %s\n", style.isNumberEntries()); - } - - String parStyle = style.getReferenceParagraphFormat(); - - StringBuilder stringBuilder = new StringBuilder(); - - for (CitedKey ck : bibliography.values()) { - StringBuilder sb = new StringBuilder(); - - if (debugThisFun) { - System.out.printf("Ref cit %-20s ck.number %7s%n", - String.format("'%s'", ck.citationKey), - (ck.number.isEmpty() - ? "(empty)" - : String.format("%02d", ck.number.get()))); - } - - // insert marker "[1]" - if (style.isNumberEntries()) { - - if (ck.number.isEmpty()) { - throw new RuntimeException("formatFullReference:" - + " numbered style, but found unnumbered entry"); - } - - int number = ck.number.get(); - OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); - sb.append(marker.asString()); - } else { - // !style.isNumberEntries() : emit no prefix - // TODO: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); - } - - if (ck.db.isEmpty()) { - // Unresolved entry - OOFormattedText referenceDetails = - OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); - sb.append(referenceDetails.asString()); - if (true) { - sb.append(formatCitedOnPages(cgs, ck).asString()); - } - - } else { - // Resolved entry - BibEntry bibentry = ck.db.get().entry; - - // insert the actual details. - Layout layout = style.getReferenceFormat(bibentry.getType()); - layout.setPostFormatter(POSTFORMATTER); - - OOFormattedText formattedText = - formatFullReferenceOfBibEbtry(layout, - bibentry, - ck.db.get().database, - ck.uniqueLetter.orElse(null)); - - // Insert the formatted text: - sb.append(formattedText.asString()); - if (alwaysAddCitedOnPages) { - sb.append(formatCitedOnPages(cgs, ck).asString()); - } - } - - // Emit a bibliography entry - OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); - entryText = OOFormat.paragraph(entryText, parStyle); - stringBuilder.append(entryText.asString()); - } // for CitedKey - - OOFormattedText full = OOFormattedText.fromString(stringBuilder.toString()); - return full; - } } From 9da2fcf0c848bf969371f74e323779c38158740d Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 22:23:05 +0200 Subject: [PATCH 0674/1068] rename checkRecordChanges to checkIfOpenOfficeIsRecordingChanges --- .../org/jabref/gui/openoffice/OOBibBase.java | 25 +++++-------------- .../gui/openoffice/OpenOfficePanel.java | 8 +++--- 2 files changed, 10 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 18b02eb348b..6be79696c4c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -56,7 +56,6 @@ import com.sun.star.text.XTextRange; import com.sun.star.text.XTextSection; import com.sun.star.uno.Any; -import com.sun.star.uno.UnoRuntime; import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -150,17 +149,6 @@ public Optional getCurrentDocumentTitle() { * * ****************************/ - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if - * available, otherwise null. - */ - private static T unoQI(Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - public List getCitationEntries() throws UnknownPropertyException, @@ -172,8 +160,7 @@ public List getCitationEntries() DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - // checkStylesExistInTheDocument(style, documentConnection); - checkRecordChanges(documentConnection); + checkIfOpenOfficeIsRecordingChanges(documentConnection); OOFrontend fr = new OOFrontend(documentConnection); return fr.getCitationEntries(documentConnection); @@ -481,7 +468,7 @@ public void insertEntry(List entries, DocumentConnection documentConnection = getDocumentConnectionOrThrow(); checkStylesExistInTheDocument(style, documentConnection); - checkRecordChanges(documentConnection); + checkIfOpenOfficeIsRecordingChanges(documentConnection); OOFrontend fr = new OOFrontend(documentConnection); // CitationGroups cgs = new CitationGroups(documentConnection); @@ -924,7 +911,7 @@ public void combineCiteMarkers(List databases, final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); checkStylesExistInTheDocument(style, documentConnection); - checkRecordChanges(documentConnection); + checkIfOpenOfficeIsRecordingChanges(documentConnection); OOFrontend fr = new OOFrontend(documentConnection); @@ -1285,7 +1272,7 @@ public void unCombineCiteMarkers(List databases, DocumentConnection documentConnection = getDocumentConnectionOrThrow(); checkStylesExistInTheDocument(style, documentConnection); - checkRecordChanges(documentConnection); + checkIfOpenOfficeIsRecordingChanges(documentConnection); OOFrontend fr = new OOFrontend(documentConnection); @@ -1503,7 +1490,7 @@ private ExportCitedHelperResult generateDatabase(List databases, * Throw JabRefException if recording changes or the document contains * recorded changes. */ - public void checkRecordChanges(DocumentConnection documentConnection) + public void checkIfOpenOfficeIsRecordingChanges(DocumentConnection documentConnection) throws UnknownPropertyException, WrappedTargetException, @@ -1678,7 +1665,7 @@ public List updateDocumentActionHelper(List databases, DocumentConnection documentConnection = getDocumentConnectionOrThrow(); checkStylesExistInTheDocument(style, documentConnection); - checkRecordChanges(documentConnection); + checkIfOpenOfficeIsRecordingChanges(documentConnection); try { documentConnection.enterUndoContext("Refresh bibliography"); diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 5bdece8759c..948c295f850 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -283,7 +283,7 @@ private void initPanel() { manageCitations.setOnAction(e -> { try { DocumentConnection documentConnection = ooBase.getDocumentConnectionOrThrow(); - ooBase.checkRecordChanges(documentConnection); + ooBase.checkIfOpenOfficeIsRecordingChanges(documentConnection); } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( Localization.lang("JabRefException"), @@ -295,7 +295,7 @@ private void initPanel() { } catch (UnknownPropertyException | PropertyVetoException | WrappedTargetException ex) { - LOGGER.warn("Problem during checkRecordChanges", ex); + LOGGER.warn("Problem during checkIfOpenOfficeIsRecordingChanges", ex); } dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); }); @@ -521,7 +521,7 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP try { DocumentConnection documentConnection = ooBase.getDocumentConnectionOrThrow(); - ooBase.checkRecordChanges(documentConnection); + ooBase.checkIfOpenOfficeIsRecordingChanges(documentConnection); } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( Localization.lang("JabRefException"), @@ -533,7 +533,7 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP } catch (UnknownPropertyException | PropertyVetoException | WrappedTargetException ex) { - LOGGER.warn("Problem during checkRecordChanges", ex); + LOGGER.warn("Problem during checkIfOpenOfficeIsRecordingChanges", ex); } Boolean inParenthesis = inParenthesisIn; From 31b3b38c5847455c7f5ed479fe5cd53c056eb4df Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 22:44:57 +0200 Subject: [PATCH 0675/1068] add formatBibliography --- .../org/jabref/gui/openoffice/OOBibBase.java | 38 +++---------------- .../logic/oostyle/OOFormatBibliography.java | 13 +++++++ 2 files changed, 18 insertions(+), 33 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6be79696c4c..bf8f1071a8d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -730,29 +730,6 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, alwaysAddCitedOnPages); } - /* - * - * Only called from populateBibTextSection (and that from rebuildBibTextSection) - */ - private void insertFullReferenceAtCursor(DocumentConnection documentConnection, - XTextCursor cursor, - CitationGroups cgs, - CitedKeys bibliography, - OOBibStyle style, - boolean alwaysAddCitedOnPages) - throws - IllegalArgumentException, - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - CreationException, - NoSuchElementException { - OOFormattedText text = - OOFormatBibliography.formatBibliographyBody(cgs, bibliography, style, alwaysAddCitedOnPages); - OOFormattedTextIntoOO.write(documentConnection, cursor, text); - cursor.collapseToEnd(); - } - /** * Insert a paragraph break and create a text section for the bibliography. * @@ -846,8 +823,11 @@ private void populateBibTextSection(DocumentConnection documentConnection, // emit the title of the bibliography OOFormattedTextIntoOO.removeDirectFormatting(cursor); - OOFormattedText title = style.getFormattedBibliographyTitle(); - OOFormattedTextIntoOO.write(documentConnection, cursor, title); + OOFormattedText bibliographyText = OOFormatBibliography.formatBibliography(fr.cgs, + bibliography, + style, + alwaysAddCitedOnPages); + OOFormattedTextIntoOO.write(documentConnection, cursor, bibliographyText); cursor.collapseToEnd(); // remove the inital empty paragraph from the section. @@ -857,14 +837,6 @@ private void populateBibTextSection(DocumentConnection documentConnection, initialParagraph.goRight((short) 1, true); initialParagraph.setString(""); - // emit body - insertFullReferenceAtCursor(documentConnection, - cursor, - fr.cgs, - bibliography, - style, - alwaysAddCitedOnPages); - documentConnection.insertBookmark(OOBibBase.BIB_SECTION_END_NAME, cursor, true); diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index 77feaba9966..267999327b8 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -125,6 +125,19 @@ public static OOFormattedText formatBibliographyBody(CitationGroups cgs, return full; } + public static OOFormattedText formatBibliography(CitationGroups cgs, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { + + OOFormattedText title = style.getFormattedBibliographyTitle(); + OOFormattedText body = OOFormatBibliography.formatBibliography(cgs, + bibliography, + style, + alwaysAddCitedOnPages); + return OOFormattedText.fromString(title.asString() + body.asString()); + } + /** * Format the reference part of a bibliography entry using a Layout. * From 83f17a5577cbf0a8c464189a6c6c0dcba65fb048 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 6 May 2021 22:44:57 +0200 Subject: [PATCH 0676/1068] add formatBibliography --- .../org/jabref/gui/openoffice/OOBibBase.java | 38 +++---------------- .../logic/oostyle/OOFormatBibliography.java | 13 +++++++ 2 files changed, 18 insertions(+), 33 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6be79696c4c..bf8f1071a8d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -730,29 +730,6 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, alwaysAddCitedOnPages); } - /* - * - * Only called from populateBibTextSection (and that from rebuildBibTextSection) - */ - private void insertFullReferenceAtCursor(DocumentConnection documentConnection, - XTextCursor cursor, - CitationGroups cgs, - CitedKeys bibliography, - OOBibStyle style, - boolean alwaysAddCitedOnPages) - throws - IllegalArgumentException, - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - CreationException, - NoSuchElementException { - OOFormattedText text = - OOFormatBibliography.formatBibliographyBody(cgs, bibliography, style, alwaysAddCitedOnPages); - OOFormattedTextIntoOO.write(documentConnection, cursor, text); - cursor.collapseToEnd(); - } - /** * Insert a paragraph break and create a text section for the bibliography. * @@ -846,8 +823,11 @@ private void populateBibTextSection(DocumentConnection documentConnection, // emit the title of the bibliography OOFormattedTextIntoOO.removeDirectFormatting(cursor); - OOFormattedText title = style.getFormattedBibliographyTitle(); - OOFormattedTextIntoOO.write(documentConnection, cursor, title); + OOFormattedText bibliographyText = OOFormatBibliography.formatBibliography(fr.cgs, + bibliography, + style, + alwaysAddCitedOnPages); + OOFormattedTextIntoOO.write(documentConnection, cursor, bibliographyText); cursor.collapseToEnd(); // remove the inital empty paragraph from the section. @@ -857,14 +837,6 @@ private void populateBibTextSection(DocumentConnection documentConnection, initialParagraph.goRight((short) 1, true); initialParagraph.setString(""); - // emit body - insertFullReferenceAtCursor(documentConnection, - cursor, - fr.cgs, - bibliography, - style, - alwaysAddCitedOnPages); - documentConnection.insertBookmark(OOBibBase.BIB_SECTION_END_NAME, cursor, true); diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index 77feaba9966..267999327b8 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -125,6 +125,19 @@ public static OOFormattedText formatBibliographyBody(CitationGroups cgs, return full; } + public static OOFormattedText formatBibliography(CitationGroups cgs, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { + + OOFormattedText title = style.getFormattedBibliographyTitle(); + OOFormattedText body = OOFormatBibliography.formatBibliography(cgs, + bibliography, + style, + alwaysAddCitedOnPages); + return OOFormattedText.fromString(title.asString() + body.asString()); + } + /** * Format the reference part of a bibliography entry using a Layout. * From d1d92bb6310eac2e5fa20c9819d009a5e03a7474 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 7 May 2021 07:53:28 +0200 Subject: [PATCH 0677/1068] combineCiteMarkers, unCombineCiteMarkers : fix which frontend is used --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index bf8f1071a8d..9f2e5b27bd6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1190,7 +1190,7 @@ public void combineCiteMarkers(List databases, OOFrontend fr2 = new OOFrontend(documentConnection); fr2.imposeGlobalOrder(documentConnection); OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr.cgs, + OOProcess.produceCitationMarkers(fr2.cgs, databases, style); try { @@ -1198,7 +1198,7 @@ public void combineCiteMarkers(List databases, documentConnection.lockControllers(); } applyNewCitationMarkers(documentConnection, - fr, + fr2, x.citMarkers, style); } finally { @@ -1333,7 +1333,7 @@ public void unCombineCiteMarkers(List databases, OOFrontend fr2 = new OOFrontend(documentConnection); fr2.imposeGlobalOrder(documentConnection); OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr.cgs, databases, style); + OOProcess.produceCitationMarkers(fr2.cgs, databases, style); try { if (useLockControllers) { documentConnection.lockControllers(); From cebd63c88875af89a575efd2f39a7b131312cdd0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 7 May 2021 08:06:12 +0200 Subject: [PATCH 0678/1068] move call to documentConnection.refresh to outside lockControllers --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 ++ .../java/org/jabref/logic/openoffice/DocumentConnection.java | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 9f2e5b27bd6..2b176c9b034 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1210,6 +1210,7 @@ public void combineCiteMarkers(List databases, } finally { documentConnection.leaveUndoContext(); } + documentConnection.refresh(); } // combineCiteMarkers /** @@ -1348,6 +1349,7 @@ public void unCombineCiteMarkers(List databases, } finally { documentConnection.leaveUndoContext(); } + documentConnection.refresh(); } static class ExportCitedHelperResult { diff --git a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java index 85860eb0710..46bb802e785 100644 --- a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java @@ -1056,8 +1056,6 @@ public void insertReferenceToPageNumberOfReferenceMark(String referenceMarkName, // Insert the text field this.xText.insertTextContent(cursor.getEnd(), xRefContent, false); - - this.refresh(); } /** From 09e2d05fd4f59ff221673098203e6a416d7e6213 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 7 May 2021 08:10:03 +0200 Subject: [PATCH 0679/1068] need documentConnection.refresh(); before reread --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 2b176c9b034..629a49c020e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1187,6 +1187,7 @@ public void combineCiteMarkers(List databases, } if (madeModifications) { + documentConnection.refresh(); OOFrontend fr2 = new OOFrontend(documentConnection); fr2.imposeGlobalOrder(documentConnection); OOProcess.ProduceCitationMarkersResult x = @@ -1331,6 +1332,7 @@ public void unCombineCiteMarkers(List databases, } if (madeModifications) { + documentConnection.refresh(); OOFrontend fr2 = new OOFrontend(documentConnection); fr2.imposeGlobalOrder(documentConnection); OOProcess.ProduceCitationMarkersResult x = From 3a4ac482c0e093e826355dd9e5d0b7f05873b730 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 7 May 2021 08:12:35 +0200 Subject: [PATCH 0680/1068] fix case in oo:CharStyleName --- .../org/jabref/logic/openoffice/OOFormattedTextIntoOO.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index 89f4607c26d..b18f53da98f 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -257,8 +257,8 @@ public static void write(DocumentConnection documentConnection, String key = kv.getKey(); String value = kv.getValue(); switch (key) { - case "oo:CharStylename": - // + case "oo:CharStyleName": + // fs.add(setCharStyleName(value)); break; case "lang": From 5f25287b12143b955ddd55e92583c925367d3dfa Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 8 May 2021 16:11:59 +0200 Subject: [PATCH 0681/1068] OOFormattedTextIntoOO.write was slow. Rewritten. Old version kept around in OOFormattedTextIntoOOV1.java, just in case. Can be removed if the new variant is OK. --- .../org/jabref/gui/openoffice/OOBibBase.java | 6 +- .../openoffice/OOFormattedTextIntoOO.java | 928 ++++++++++-------- .../openoffice/OOFormattedTextIntoOOV1.java | 917 +++++++++++++++++ 3 files changed, 1414 insertions(+), 437 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 629a49c020e..f3056101f14 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1202,6 +1202,7 @@ public void combineCiteMarkers(List databases, fr2, x.citMarkers, style); + // bibliography is not refreshed } finally { if (useLockControllers) { documentConnection.unlockControllers(); @@ -1211,7 +1212,7 @@ public void combineCiteMarkers(List databases, } finally { documentConnection.leaveUndoContext(); } - documentConnection.refresh(); + // documentConnection.refresh(); } // combineCiteMarkers /** @@ -1342,6 +1343,7 @@ public void unCombineCiteMarkers(List databases, documentConnection.lockControllers(); } applyNewCitationMarkers(documentConnection, fr2, x.citMarkers, style); + // bibliography is not refreshed } finally { if (useLockControllers) { documentConnection.unlockControllers(); @@ -1351,7 +1353,7 @@ public void unCombineCiteMarkers(List databases, } finally { documentConnection.leaveUndoContext(); } - documentConnection.refresh(); + // documentConnection.refresh(); } static class ExportCitedHelperResult { diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index b18f53da98f..b3383f0ab5a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -1,8 +1,8 @@ package org.jabref.logic.openoffice; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -24,6 +24,7 @@ import com.sun.star.beans.PropertyState; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.beans.XMultiPropertySet; import com.sun.star.beans.XMultiPropertyStates; import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; @@ -44,7 +45,16 @@ * * On the question of what should it understand: apart from what * it can do now, probably whatever a CSL style with HTML output - * emits. + * emits. + * + * Seems slow with approx 40 citations. + * + * Idea: + * + * - Use setString, not insertString. This removes character formats, + * probably no need for workaround about setPropertyToDefault. + * - Calculate current set of character properties in java. + * - Use interface allowing to set multiple properties in a single call. * */ @AllowedToUseAwt("Requires AWT for changing document properties") @@ -89,6 +99,359 @@ private OOFormattedTextIntoOO() { // Just to hide the public constructor } + static class MyPropertyStack { + + // Only try to control these. In particular, leave paragraph + // properties alone. + static final Set CONTROLLED_PROPERTIES = Set.of( + + /* Used for SuperScript, SubScript. + * + * These three are interdependent: changing one may change others. + */ + "CharEscapement", "CharEscapementHeight", "CharAutoEscapement", + + /* used for Bold */ + "CharWeight", + + /* Used for Italic */ + "CharPosture", + + /* CharWordMode : If this property is TRUE, the underline + * and strike-through properties are not applied to white + * spaces. + */ + // "CharWordMode", + + /* Used for strikeout. These two are interdependent. */ + "CharStrikeout", "CharCrossedOut", + + /* Used for underline */ + "CharUnderline", // "CharUnderlineColor", "CharUnderlineHasColor", + + // "CharOverline", "CharOverlineColor", "CharOverlineHasColor", + + /* Used for lang="zxx" to shut spellchecker. */ + "CharLocale", + + /* Used for CitationCharacterFormat */ + "CharStyleName", // "CharStyleNames", "CharAutoStyleName", + + /* Used for and */ + "CharCaseMap" + + /* HyperLink */ + // "HyperLinkName", /* ??? */ + // "HyperLinkURL", /* empty for thisDocument */ + // "HyperLinkTarget", + /* HyperLinkTarget : What comes after '#' (location in doc). + * Can be a bookmark name. + */ + /* character style names for unvisited and visited links */ + // "UnvisitedCharStyleName", "VisitedCharStyleName", + // "HyperLinkEvents", + + // "CharColor", + // "CharHighlight", + // "CharBackColor", "CharBackTransparent", + + // "CharScaleWidth", /* Allows to reduce font width */ + + // "CharKerning", "CharAutoKerning", + + // "CharFontCharSet", + // "CharFontFamily", + // "CharFontName", + // "CharFontPitch", + // "CharFontStyleName", + // "CharHeight", + + // "CharHidden", + + /* + * CharInteropGrabBag : **Since LibreOffice 4.3** + * + * Grab bag of character properties, used as a string-any + * map for interim interop purposes. + * + * This property is intentionally not handled by the ODF + * filter. Any member that should be handled there should + * be first moved out from this grab bag to a separate + * property. + */ + // "CharInteropGrabBag", + + // "CharNoHyphenation", + + // "CharContoured", "CharFlash", "CharRelief", + + // "CharRotation", "CharRotationIsFitToLine", + + // "CharShadingValue", "CharShadowFormat", "CharShadowed", + + /* CharBorder */ + // "CharBorderDistance", + // "CharBottomBorder", "CharBottomBorderDistance", + // "CharTopBorder", "CharTopBorderDistance", + // "CharRightBorder", "CharRightBorderDistance", + // "CharLeftBorder", "CharLeftBorderDistance", + + // "IsSkipHiddenText", + // "IsSkipProtectedText", + + /* TextUserDefinedAttributes: Saved into doc, but lost on Load. + * + * They might be usable within a session to invisibly attach info + * available elsewhere, but costly to get to. + * + */ + // "TextUserDefinedAttributes", + + // "WritingMode" + + // "CharCombineIsOn", "CharCombinePrefix", "CharCombineSuffix", + + /* Ruby */ + // "RubyAdjust", "RubyCharStyleName", "RubyIsAbove", "RubyPosition", "RubyText", + + // "CharEmphasis", /* emphasis mark in asian texts */ + + /* Asian */ + // "CharWeightAsian", + // "CharPostureAsian", + // "CharLocaleAsian", + // "CharFontCharSetAsian", + // "CharFontFamilyAsian", + // "CharFontNameAsian", + // "CharFontPitchAsian", + // "CharFontStyleNameAsian", + // "CharHeightAsian", + + /* Complex */ + // "CharWeightComplex", + // "CharPostureComplex", + // "CharLocaleComplex", + // "CharFontCharSetComplex", + // "CharFontFamilyComplex", + // "CharFontNameComplex", + // "CharFontPitchComplex", + // "CharFontStyleNameComplex", + // "CharHeightComplex", + + /* + * Non-character properties + */ + // "SnapToGrid", + // "BreakType" + // + // "BorderDistance" + // "BottomBorder" "BottomBorderDistance" + // "LeftBorder" "LeftBorderDistance" + // "RightBorder" "RightBorderDistance" + // "TopBorder" "TopBorderDistance" + // + // "ParaBottomMargin" + // "ParaLeftMargin" + // "ParaTopMargin" + // "ParaRightMargin" + // "ParaContextMargin" + // + // "DropCapCharStyleName" + // "DropCapFormat" + // "DropCapWholeWord" + // + // "ListAutoFormat" "ListId" + // + // "NumberingIsNumber" + // "NumberingLevel" + // "NumberingRules" + // "NumberingStartValue" + // "NumberingStyleName" + // "OutlineLevel" + // "ParaChapterNumberingLevel" + // + // "PageDescName" "PageNumberOffset" + // + // "Rsid" "ParRsid" + // + // "ParaAdjust" "ParaAutoStyleName" + // + // "ParaBackColor" + // "ParaBackGraphic" + // "ParaBackGraphicFilter" + // "ParaBackGraphicLocation" + // "ParaBackGraphicURL" + // "ParaBackTransparent" + // + // "ParaExpandSingleWord" + // "ParaFirstLineIndent" + // + // "ParaIsHyphenation" + // "ParaHyphenationMaxHyphens" + // "ParaHyphenationMaxLeadingChars" + // "ParaHyphenationMaxTrailingChars" + // "ParaHyphenationNoCaps" + // + // "ParaInteropGrabBag" + // "ParaIsAutoFirstLineIndent" + // "ParaIsCharacterDistance" + // "ParaIsConnectBorder" + // "ParaIsForbiddenRules" + // "ParaIsHangingPunctuation" + // "ParaIsNumberingRestart" + // "ParaKeepTogether" + // "ParaLastLineAdjust" + // "ParaLineNumberCount" "ParaLineNumberStartValue" + // "ParaLineSpacing" "ParaOrphans" "ParaRegisterModeActive" + // "ParaShadowFormat" "ParaSplit" + // "ParaStyleName" "ParaTabStops" + // "ParaUserDefinedAttributes" "ParaVertAlignment" + // "ParaWidows" + + /**/); + final int goodSize; + final Map goodNameToIndex; + final String[] goodNames; + final Stack>> layers; + + MyPropertyStack(XTextCursor cursor) + throws UnknownPropertyException { + + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertySetInfo psi = propertySet.getPropertySetInfo(); + + this.goodNameToIndex = new HashMap<>(); + int nextIndex = 0; + for (Property p : psi.getProperties()) { + if ((p.Attributes & PropertyAttribute.READONLY) != 0) { + continue; + } + if (!CONTROLLED_PROPERTIES.contains(p.Name)) { + continue; + } + this.goodNameToIndex.put(p.Name, nextIndex); + nextIndex++; + } + + this.goodSize = nextIndex; + + this.goodNames = new String[goodSize]; + for (Map.Entry kv : goodNameToIndex.entrySet()) { + goodNames[ kv.getValue() ] = kv.getKey(); + } + + // XMultiPropertySet.setPropertyValues() + // requires alphabetically sorted property names. + Arrays.sort(goodNames); + for (int i = 0; i < goodSize; i++) { + this.goodNameToIndex.put(goodNames[i], i); + } + + /* + for (int i = 0; i < goodSize; i++) { + System.out.printf(" '%s'", goodNames[i]); + } + System.out.printf("%n"); + */ + + // This throws: + // XPropertyAccess xPropertyAccess = unoQI(XPropertyAccess.class, cursor); + // if (xPropertyAccess == null) { + // throw new RuntimeException("MyPropertyStack: xPropertyAccess is null"); + // } + + // we could use: + // import com.sun.star.beans.XMultiPropertyStates; + XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); + PropertyState[] propertyStates = mpss.getPropertyStates(goodNames); + + XMultiPropertySet mps = unoQI(XMultiPropertySet.class, cursor); + Object[] initialValues = mps.getPropertyValues(goodNames); + + ArrayList> initialValuesOpt = new ArrayList<>(goodSize); + + for (int i = 0; i < goodSize; i++) { + if (propertyStates[i] == PropertyState.DIRECT_VALUE) { + initialValuesOpt.add(Optional.of(initialValues[i])); + } else { + initialValuesOpt.add(Optional.empty()); + } + } + + this.layers = new Stack<>(); + this.layers.push(initialValuesOpt); + } + + void pushLayer(List> settings) { + ArrayList> oldLayer = layers.peek(); + ArrayList> newLayer = new ArrayList<>(oldLayer); + for (Pair kv : settings) { + String name = kv.getKey(); + Integer i = goodNameToIndex.get(name); + if (i == null) { + LOGGER.warn(String.format("pushLayer: '%s' is not in goodNameToIndex", name)); + continue; + } + Object newValue = kv.getValue(); + newLayer.set(i, Optional.ofNullable(newValue)); + } + layers.push(newLayer); + } + + void popLayer() { + if (layers.size() <= 1) { + LOGGER.warn("popLayer: underflow"); + return; + } + layers.pop(); + } + + void apply(XTextCursor cursor) { + // removeDirectFormatting(cursor); + XMultiPropertySet mps = unoQI(XMultiPropertySet.class, cursor); + XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); + ArrayList> topLayer = layers.peek(); + try { + // select values to be set + ArrayList names = new ArrayList<>(goodSize); + ArrayList values = new ArrayList<>(goodSize); + ArrayList delNames = new ArrayList<>(goodSize); + for (int i = 0; i < goodSize; i++) { + if (topLayer.get(i).isPresent()) { + names.add(goodNames[i]); + values.add(topLayer.get(i).get()); + } else { + delNames.add(goodNames[i]); + } + } + // namesArray must be alphabetically sorted. + String[] namesArray = names.toArray(new String[names.size()]); + String[] delNamesArray = delNames.toArray(new String[names.size()]); + mpss.setPropertiesToDefault(delNamesArray); + mps.setPropertyValues(namesArray, values.toArray()); + } catch (UnknownPropertyException ex) { + LOGGER.warn("UnknownPropertyException in MyPropertyStack.apply"); + } catch (PropertyVetoException ex) { + LOGGER.warn("PropertyVetoException in MyPropertyStack.apply"); + } catch (IllegalArgumentException ex) { + LOGGER.warn("IllegalArgumentException in MyPropertyStack.apply"); + } catch (WrappedTargetException ex) { + LOGGER.warn("WrappedTargetException in MyPropertyStack.apply"); + } + } + + // Relative CharEscapement needs to know current values. + Optional getPropertyValue(String name) { + if (goodNameToIndex.containsKey(name)) { + int i = goodNameToIndex.get(name); + ArrayList> topLayer = layers.peek(); + Optional value = topLayer.get(i); + return value; + } + return Optional.empty(); + } + } + /** * Insert a text with formatting indicated by HTML-like tags, into * a text at the position given by a cursor. @@ -102,17 +465,23 @@ private OOFormattedTextIntoOO() { * Notable changes w.r.t insertOOFormattedTextAtCurrentLocation: * * - new tags: - * - <locale value="zxx"> + * + * - <span lang="zxx"> * - earlier was applied from code - * - <font class="CharStylename"> + * + * - <span oo:CharStyleName="CharStylename"> * - earlier was applied from code, for "CitationCharacterFormat" + * * - <p> start new paragraph * - earlier was applied from code - * - <p class="ParStyleName"> : start new paragraph and apply ParStyleName + * + * - <p oo:ParaStyleName="ParStyleName"> : start new paragraph and apply ParStyleName * - earlier was applied from code + * * - <tt> * - earlier: known, but ignored - * - now: equivalent to <font class="Example"> + * - now: equivalent to <span oo:CharStyleName="Example"> + * - <oo:referenceToPageNumberOfReferenceMark> (self-closing) * * - closing tags try to properly restore state instead of dictating * an "off" state. @@ -141,15 +510,20 @@ public static void write(DocumentConnection documentConnection, NoSuchElementException, CreationException { + final boolean useSetString = true; + String lText = OOFormattedText.toString(ootext); - System.out.println(lText); + // System.out.println(lText); XText text = position.getText(); XTextCursor cursor = text.createTextCursorByRange(position); cursor.collapseToEnd(); - Stack formatters = new Stack<>(); + MyPropertyStack formatStack = new MyPropertyStack(cursor); + + // Stack formatters = new Stack<>(); + Stack expectEnd = new Stack<>(); // We need to extract formatting. Use a simple regexp search iteration: @@ -159,9 +533,13 @@ public static void write(DocumentConnection documentConnection, String currentSubstring = lText.substring(piv, m.start()); if (!currentSubstring.isEmpty()) { - text.insertString(cursor, currentSubstring, true); + if (useSetString) { + cursor.setString(currentSubstring); + } else { + text.insertString(cursor, currentSubstring, true); + } } - formatTextInCursor(cursor, formatters); + formatStack.apply(cursor); cursor.collapseToEnd(); String fullTag = m.group(); @@ -177,32 +555,32 @@ public static void write(DocumentConnection documentConnection, // Handle tags: switch (tagName) { case "b": - formatters.push(setCharWeight(FontWeight.BOLD)); + formatStack.pushLayer(setCharWeight(FontWeight.BOLD)); expectEnd.push("/" + tagName); break; case "i": case "em": - formatters.push(setCharPosture(FontSlant.ITALIC)); + formatStack.pushLayer(setCharPosture(FontSlant.ITALIC)); expectEnd.push("/" + tagName); break; case "smallcaps": - formatters.push(setCharCaseMap(CaseMap.SMALLCAPS)); + formatStack.pushLayer(setCharCaseMap(CaseMap.SMALLCAPS)); expectEnd.push("/" + tagName); break; case "sup": - formatters.push(SuperScript()); + formatStack.pushLayer(SuperScript(formatStack)); expectEnd.push("/" + tagName); break; case "sub": - formatters.push(SubScript()); + formatStack.pushLayer(SubScript(formatStack)); expectEnd.push("/" + tagName); break; case "u": - formatters.push(setCharUnderline(FontUnderline.SINGLE)); + formatStack.pushLayer(setCharUnderline(FontUnderline.SINGLE)); expectEnd.push("/" + tagName); break; case "s": - formatters.push(setCharStrikeout(FontStrikeout.SINGLE)); + formatStack.pushLayer(setCharStrikeout(FontStrikeout.SINGLE)); expectEnd.push("/" + tagName); break; case "/p": @@ -218,11 +596,15 @@ public static void write(DocumentConnection documentConnection, case "oo:ParaStyleName": //

if (value != null && !value.equals("")) { + // LOGGER.warn(String.format("oo:ParaStyleName=\"%s\" found", value)); try { DocumentConnection.setParagraphStyle(cursor, value); } catch (UndefinedParagraphFormatException ex) { - // ignore silently + LOGGER.warn(String.format("oo:ParaStyleName=\"%s\" failed with" + + " UndefinedParagraphFormatException", value)); } + } else { + LOGGER.warn(String.format("oo:ParaStyleName inherited")); } break; default: @@ -248,28 +630,28 @@ public static void write(DocumentConnection documentConnection, break; case "tt": // Note: "Example" names a character style in LibreOffice. - formatters.push(setCharStyleName("Example")); + formatStack.pushLayer(setCharStyleName("Example")); expectEnd.push("/" + tagName); break; case "span": - Formatters fs = new Formatters(); + List> settings = new ArrayList<>(); for (Pair kv : attributes) { String key = kv.getKey(); String value = kv.getValue(); switch (key) { case "oo:CharStyleName": // - fs.add(setCharStyleName(value)); + settings.addAll(setCharStyleName(value)); break; case "lang": // // - fs.add(setCharLocale(value)); + settings.addAll(setCharLocale(value)); break; case "style": // In general we may need to parse value if (value.equals("font-variant: small-caps")) { - fs.add(setCharCaseMap(CaseMap.SMALLCAPS)); + settings.addAll(setCharCaseMap(CaseMap.SMALLCAPS)); break; } LOGGER.warn(String.format("Unexpected value %s for attribute '%s' for <%s>", @@ -280,7 +662,7 @@ public static void write(DocumentConnection documentConnection, break; } } - formatters.push(fs); + formatStack.pushLayer(settings); expectEnd.push("/" + tagName); break; case "/b": @@ -293,10 +675,13 @@ public static void write(DocumentConnection documentConnection, case "/u": case "/s": case "/span": - formatters.pop().applyEnd(cursor); + formatStack.popLayer(); String expected = expectEnd.pop(); if (!tagName.equals(expected)) { - LOGGER.warn(String.format("expected '<%s>', found '<%s>'", expected, tagName)); + LOGGER.warn(String.format("expected '<%s>', found '<%s>' after '%s'", + expected, + tagName, + currentSubstring)); } break; } @@ -305,9 +690,13 @@ public static void write(DocumentConnection documentConnection, } if (piv < lText.length()) { - text.insertString(cursor, lText.substring(piv), true); + if (useSetString) { + cursor.setString(lText.substring(piv)); + } else { + text.insertString(cursor, lText.substring(piv), true); + } } - formatTextInCursor(cursor, formatters); + formatStack.apply(cursor); cursor.collapseToEnd(); if (!expectEnd.empty()) { @@ -432,173 +821,7 @@ private static T unoQI(Class zInterface, return UnoRuntime.queryInterface(zInterface, object); } - /** - * Remove direct formatting of propertyName from propertySet. - * - * Observation: while - * XPropertyState.setPropertyToDefault(propertyName) does reset - * the property, it also has a side effect (probably bug in LO - * 6.4.6.2) that it also resets other properties. - * - * For example setPropertyToDefault("CharWeight") also removes "CharColor" - * - * Workaround: - * (https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=105117) - * - * Use setPropertyValue with either result from - * getPropertyValue to restore the earlier state or with - * result from getPropertyDefault. - * - * In either case the property "CharStyleName" has to be handled - * specially, by mapping the received value "" to "Standard". - * Hopefully other properties will not need special handling. - * - * Well, they do. Some properties interact: setting one to - * non-default also sets the other to non-default. Fortunately - * these interactions appear meaningful. For example setting - * "CharCrossedOut" to non-default also modifies "CharStrikeout". - * For the strategy applied here (remove all, then restore all - * except the one we wanted to default) it means we have to avoid - * restoring those that would, as a side-effect set to non-default - * what we promised to set to default. I did not investigate - * potential asymmetries of these interactions, the code below implements - * symmetric behaviour. This means that for example for - * propertyName == "CharCrossedOut" we do not restore - * "CharStrikeout", although the problematic behaviour observed was - * that restoring "CharCrossedOut" changes "CharStrikeout" from its default. - * - */ - private static void setPropertyToDefault(XTextCursor cursor, String propertyName) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - - if (false) { - // This is what should "simply work". - // However it loses e.g. font color when propertyName is "CharWeight". - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); - propertyState.setPropertyToDefault(propertyName); - } else if (false) { - - // Despite the name getPropertyDefault, storing - // its result by setPropertyValue is NOT (always) equivalent - // to setPropertyToDefault(). - // - // setPropertyToDefault() should remove direct ("hard") - // formatting. - // - // setPropertyValue(getPropertyDefault()) can only do that - // if getPropertyDefault provides a value with the meaning - // "use whatever comes from the level above". - // - // If the value from getPropertyDefault dictates any - // concrete value for the property and "whatever comes - // from the level above" happens to be a different value, - // then the two behaviours yield different results. - - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); - Object value = propertyState.getPropertyDefault(propertyName); - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); - propertySet.setPropertyValue(propertyName, value); - } else { - - // Try to remove all, then add all directly formatted again, - // except the one we are removing. And those that would override - // what we try to achieve. - - /* https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Formatting - * at the bottom lists interdependent sets: - * - * Those marked [-] we probably will not touch, [X] handled, [?] maybe will touch. - * - * - [-] ParaRightMargin, ParaLeftMargin, ParaFirstLineIndent, ParaIsAutoFirstLineIndent - * - [-] ParaTopMargin, ParaBottomMargin - * - [-] ParaGraphicURL/Filter/Location, ParaBackColor, ParaBackTransparent - * - [-] ParaIsHyphenation, ParaHyphenationMaxLeadingChars/MaxTrailingChars/MaxHyphens - * - [-] Left/Right/Top/BottomBorder, Left/Right/Top/BottomBorderDistance, BorderDistance - * - [-] DropCapFormat, DropCapWholeWord, DropCapCharStyleName - * - [-] PageDescName, PageNumberOffset, PageStyleName - * - * - [-] CharCombineIsOn, CharCombinePrefix, CharCombineSuffix - * - [-] RubyText, RubyAdjust, RubyCharStyleName, RubyIsAbove - * - * - [X] CharStrikeOut, CharCrossedOut - * - [X] CharEscapement, CharAutoEscapement, CharEscapementHeight - * - [X] CharUnderline, CharUnderlineColor, CharUnderlineHasColor - * - * - [?] CharFontName, CharFontStyleName, CharFontFamily, CharFontPitch - * - [?] HyperLinkURL/Name/Target, UnvisitedCharStyleName, VisitedCharStyleName - * - */ - - // CharStrikeout and CharCrossedOut interact: if we default one, - // we default the other as well. - Set charStrikeOutSet = Set.of(CHAR_STRIKEOUT, - "CharCrossedOut"); - Set charEscapementSet = Set.of("CharAutoEscapement", - CHAR_ESCAPEMENT, - CHAR_ESCAPEMENT_HEIGHT); - Set charUnderlineSet = Set.of(CHAR_UNDERLINE, - "CharUnderlineColor", - "CharUnderlineHasColor"); - - Set namesToDefault = new HashSet<>(); - if (charStrikeOutSet.contains(propertyName)) { - namesToDefault = charStrikeOutSet; - } else if (charEscapementSet.contains(propertyName)) { - namesToDefault = charEscapementSet; - } else if (charUnderlineSet.contains(propertyName)) { - namesToDefault = charUnderlineSet; - } else { - namesToDefault.add(propertyName); - } - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); - XPropertySetInfo psi = propertySet.getPropertySetInfo(); - - // Remember those we shall we restore later - Map ds = new HashMap<>(); - for (Property p : psi.getProperties()) { - boolean noRestore = (namesToDefault.contains(p.Name) - || ((p.Attributes & PropertyAttribute.READONLY) != 0) - || (isPropertyDefault(cursor, p.Name))); - if (noRestore) { - continue; - } - ds.put(p.Name, propertySet.getPropertyValue(p.Name)); - } - - // Remove all - removeDirectFormatting(cursor); - - boolean failed = false; - if (!isPropertyDefault(cursor, propertyName)) { - LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault:" - + " removeDirectFormatting failed to reset '%s'", - propertyName)); - failed = true; - } - - // Restore those saved - for (Map.Entry e : ds.entrySet()) { - propertySet.setPropertyValue(e.getKey(), e.getValue()); - if (!failed && !isPropertyDefault(cursor, propertyName)) { - LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault('%s')" - + " setPropertyValue('%s') caused loss of default state", - propertyName, e.getKey())); - failed = true; - } - } - - if (!failed && !isPropertyDefault(cursor, propertyName)) { - LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault('%s') failed", - propertyName)); - } - - } - } - - /** + /* * We rely on property values being either DIRECT_VALUE or * DEFAULT_VALUE (not AMBIGUOUS_VALUE). If the cursor covers a homogeneous region, * or is collapsed, then this is true. @@ -615,206 +838,60 @@ private static boolean isPropertyDefault(XTextCursor cursor, String propertyName return pst == PropertyState.DEFAULT_VALUE; } - /** - * @return Optional.empty() if the property is not directly formatted. - */ - private static Optional getPropertyValue(XTextCursor cursor, String propertyName) - throws - UnknownPropertyException, - WrappedTargetException { - if (isPropertyDefault(cursor, propertyName)) { - return Optional.empty(); - } else { - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); - return Optional.of(propertySet.getPropertyValue(propertyName)); - } + private static List> setCharWeight(float value) { + List> settings = new ArrayList<>(); + settings.add(new Pair("CharWeight", (Float) value)); + return settings; } - /** - * @param value Optional.empty() means instruction to remove direct formatting. - */ - private static void setPropertyValue(XTextCursor cursor, String propertyName, Optional value) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); - if (value.isPresent()) { - propertySet.setPropertyValue(propertyName, value.get()); - } else { - setPropertyToDefault(cursor, propertyName); - } + private static List> setCharPosture(FontSlant value) { + List> settings = new ArrayList<>(); + settings.add(new Pair("CharPosture", (Object) value)); + return settings; } - /** - * At each tag we adjust the current stack of formatters-to-apply - * stack, then run it. - */ - private interface Formatter { - /** - * Note: apply may be called multiple times, but should pick up old value only - * at its first call. - */ - public void apply(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException; - - /** - * Closing tags call applyEnd directly, so applyEnd is only called once. - * - * It should restore the state to that seen by the first call to apply. - * - */ - public void applyEnd(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException; - } - - /** - * Apply Formatters on the stack. - * - * @param cursor Marks the text to format - * @param formatters Formatters to apply (normally extracted from OOFormattedText) - */ - private static void formatTextInCursor(XTextCursor cursor, - Stack formatters) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - - for (Formatter f : formatters) { - f.apply(cursor); - } - } - - private static class Formatters implements Formatter { - List parts; - public Formatters() { - parts = new ArrayList<>(); - } - - public void add(Formatter f) { - parts.add(f); - } - - @Override - public void apply(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - for (Formatter f : parts) { - f.apply(cursor); - } - } - - @Override - public void applyEnd(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - for (int i = parts.size() - 1; i >= 0; i--) { - Formatter f = parts.get(i); - f.applyEnd(cursor); - } - } - } - - private static class SimpleFormatter implements Formatter { - final String propertyName; - Optional myValue; - Optional oldValue; - boolean started; - - SimpleFormatter(String propertyName, Optional value) { - this.propertyName = propertyName; - this.myValue = value; - this.oldValue = Optional.empty(); - this.started = false; - } - - @Override - public void apply(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - - if (!started) { - oldValue = getPropertyValue(cursor, propertyName).map(e -> (T) e); - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); - started = true; - } - - setPropertyValue(cursor, propertyName, myValue); - } - - @Override - public void applyEnd(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - setPropertyValue(cursor, propertyName, oldValue); - } - } - - private static Formatter setCharWeight(float value) { - return new SimpleFormatter("CharWeight", Optional.of(value)); - } - - private static Formatter setCharPosture(FontSlant value) { - return new SimpleFormatter("CharPosture", Optional.of(value)); - } - - private static Formatter setCharCaseMap(short value) { - return new SimpleFormatter("CharCaseMap", Optional.of(value)); + private static List> setCharCaseMap(short value) { + List> settings = new ArrayList<>(); + settings.add(new Pair("CharCaseMap", (Short) value)); + return settings; } // com.sun.star.awt.FontUnderline - private static Formatter setCharUnderline(short value) { - return new SimpleFormatter(CHAR_UNDERLINE, Optional.of(value)); + private static List> setCharUnderline(short value) { + List> settings = new ArrayList<>(); + settings.add(new Pair(CHAR_UNDERLINE, (Short) value)); + return settings; } // com.sun.star.awt.FontStrikeout - private static Formatter setCharStrikeout(short value) { - return new SimpleFormatter(CHAR_STRIKEOUT, Optional.of(value)); + private static List> setCharStrikeout(short value) { + List> settings = new ArrayList<>(); + settings.add(new Pair(CHAR_STRIKEOUT, (Short) value)); + return settings; } // CharStyleName - private static Formatter setCharStyleName(String value) { - return new SimpleFormatter(CHAR_STYLE_NAME, Optional.ofNullable(value)); + private static List> setCharStyleName(String value) { + List> settings = new ArrayList<>(); + if (value != null && value != "") { + settings.add(new Pair(CHAR_STYLE_NAME, value)); + } else { + LOGGER.warn("setCharStyleName: received null or empty value"); + } + return settings; } // Locale - private static Formatter setCharLocale(Locale value) { - return new SimpleFormatter("CharLocale", Optional.of(value)); + private static List> setCharLocale(Locale value) { + List> settings = new ArrayList<>(); + settings.add(new Pair("CharLocale", (Object) value)); + return settings; } /** * Locale from string encoding: language, language-country or language-country-variant */ - private static Formatter setCharLocale(String value) { + private static List> setCharLocale(String value) { if (value == null || "".equals(value)) { throw new RuntimeException("setCharLocale \"\" or null"); } @@ -829,74 +906,55 @@ private static Formatter setCharLocale(String value) { /* * SuperScript and SubScript */ - private static class CharEscapement implements Formatter { - Optional myValue; - Optional myHeight; - boolean relative; - - Optional oldValue; - Optional oldHeight; - boolean started; - - /** - * @param relative Make value and height relative to oldHeight and oldValue. - * Needed for e^{x_i} e^{x^2} (i.e. sup or sub within sup or sup) - * - */ - CharEscapement(Optional value, Optional height, boolean relative) { - this.myValue = value; - this.myHeight = height; - this.relative = relative; - this.oldValue = Optional.empty(); - this.oldHeight = Optional.empty(); - this.started = false; - } - - @Override - public void apply(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - if (!started) { - oldValue = getPropertyValue(cursor, CHAR_ESCAPEMENT).map(e -> (short) e); - oldHeight = getPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT).map(e -> (byte) e); - started = true; + private static List> CharEscapement(Optional value, + Optional height, + boolean relative, + MyPropertyStack formatStack) { + List> settings = new ArrayList<>(); + Optional oldValue = (formatStack + .getPropertyValue(CHAR_ESCAPEMENT) + .map(e -> (short) e)); + + Optional oldHeight = (formatStack + .getPropertyValue(CHAR_ESCAPEMENT_HEIGHT) + .map(e -> (byte) e)); + + if (relative && (value.isPresent() || height.isPresent())) { + double oh = oldHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * 0.01; + double xHeight = height.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * oh; + double ov = oldValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT); + double xValue = value.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT) * oh + ov; + short newValue = (short) Math.round(xValue); + byte newHeight = (byte) Math.round(xHeight); + if (value.isPresent()) { + settings.add(new Pair(CHAR_ESCAPEMENT, (Short) newValue)); } - if (relative && (myValue.isPresent() || myHeight.isPresent())) { - double oh = oldHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * 0.01; - double xHeight = myHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * oh; - double ov = oldValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT); - double xValue = myValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT) * oh + ov; - setPropertyValue(cursor, CHAR_ESCAPEMENT, Optional.of((short) Math.round(xValue))); - setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, Optional.of((byte) Math.round(xHeight))); - } else { - setPropertyValue(cursor, CHAR_ESCAPEMENT, myValue); - setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, myHeight); + if (height.isPresent()) { + settings.add(new Pair(CHAR_ESCAPEMENT_HEIGHT, (Byte) newHeight)); + } + } else { + if (value.isPresent()) { + settings.add(new Pair(CHAR_ESCAPEMENT, (Short) value.get())); + } + if (height.isPresent()) { + settings.add(new Pair(CHAR_ESCAPEMENT_HEIGHT, (Byte) height.get())); } } - - @Override - public void applyEnd(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - setPropertyValue(cursor, CHAR_ESCAPEMENT, oldValue); - setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, oldHeight); - } + return settings; } - private static Formatter SubScript() { - return new CharEscapement(Optional.of(SUBSCRIPT_VALUE), Optional.of(SUBSCRIPT_HEIGHT), true); + private static List> SubScript(MyPropertyStack formatStack) { + return CharEscapement(Optional.of(SUBSCRIPT_VALUE), + Optional.of(SUBSCRIPT_HEIGHT), + true, + formatStack); } - private static Formatter SuperScript() { - return new CharEscapement(Optional.of(SUPERSCRIPT_VALUE), Optional.of(SUPERSCRIPT_HEIGHT), true); + private static List> SuperScript(MyPropertyStack formatStack) { + return CharEscapement(Optional.of(SUPERSCRIPT_VALUE), + Optional.of(SUPERSCRIPT_HEIGHT), + true, + formatStack); } } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java new file mode 100644 index 00000000000..c0e5f18ac6a --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java @@ -0,0 +1,917 @@ +package org.jabref.logic.openoffice; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.Stack; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jabref.architecture.AllowedToUseAwt; +import org.jabref.model.oostyle.OOFormattedText; + +import com.sun.star.awt.FontSlant; +import com.sun.star.awt.FontStrikeout; +import com.sun.star.awt.FontUnderline; +import com.sun.star.awt.FontWeight; +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyAttribute; +import com.sun.star.beans.PropertyState; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.beans.XMultiPropertyStates; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.XPropertySetInfo; +import com.sun.star.beans.XPropertyState; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.Locale; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.style.CaseMap; +import com.sun.star.text.XText; +import com.sun.star.text.XTextCursor; +import com.sun.star.uno.UnoRuntime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Interpret OOFormattedText into an OpenOffice or LibreOffice writer + * document. + * + * On the question of what should it understand: apart from what + * it can do now, probably whatever a CSL style with HTML output + * emits. + * + * Seems slow with approx 40 citations. + * + * Idea: + * + * - Use setString, not insertString. This removes character formats, + * probably no need for workaround about setPropertyToDefault. + * - Calculate current set of character properties in java. + * - Use interface allowing to set multiple properties in a single call. + * + */ +@AllowedToUseAwt("Requires AWT for changing document properties") +public class OOFormattedTextIntoOOV1 { + + private static final Logger LOGGER = LoggerFactory.getLogger(OOFormattedTextIntoOO.class); + + /* + * Character property names used in multiple locations below. + */ + private static final String CHAR_ESCAPEMENT_HEIGHT = "CharEscapementHeight"; + private static final String CHAR_ESCAPEMENT = "CharEscapement"; + private static final String CHAR_STYLE_NAME = "CharStyleName"; + private static final String CHAR_UNDERLINE = "CharUnderline"; + private static final String CHAR_STRIKEOUT = "CharStrikeout"; + + /* + * SUPERSCRIPT_VALUE and SUPERSCRIPT_HEIGHT are percents of the normal character height + */ + private static final short CHAR_ESCAPEMENT_VALUE_DEFAULT = (short) 0; + private static final short SUPERSCRIPT_VALUE = (short) 33; + private static final short SUBSCRIPT_VALUE = (short) -10; + private static final byte CHAR_ESCAPEMENT_HEIGHT_DEFAULT = (byte) 100; + private static final byte SUPERSCRIPT_HEIGHT = (byte) 58; + private static final byte SUBSCRIPT_HEIGHT = (byte) 58; + + private static final String TAG_NAME_REGEXP = + "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|span|oo:referenceToPageNumberOfReferenceMark)"; + private static final String ATTRIBUTE_NAME_REGEXP = + "(?:oo:ParaStyleName|oo:CharStyleName|lang|style|target)"; + private static final String ATTRIBUTE_VALUE_REGEXP = "\"([^\"]*)\""; + private static final Pattern HTML_TAG = + Pattern.compile("<(/" + TAG_NAME_REGEXP + ")>" + + "|" + + "<(" + TAG_NAME_REGEXP + ")" + + "((?:\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP + ")*)" + + ">"); + private static final Pattern ATTRIBUTE_PATTERN = + Pattern.compile("\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP); + + private OOFormattedTextIntoOOV1() { + // Just to hide the public constructor + } + + /** + * Insert a text with formatting indicated by HTML-like tags, into + * a text at the position given by a cursor. + * + * Limitation: understands no entities. It does not receive any either, unless + * the user provides it. + * + * To limit the damage {@code TAG_NAME_REGEXP} and {@code ATTRIBUTE_NAME_REGEXP} + * explicitly lists the values we care about. + * + * Notable changes w.r.t insertOOFormattedTextAtCurrentLocation: + * + * - new tags: + * + * - <span lang="zxx"> + * - earlier was applied from code + * + * - <span oo:CharStyleName="CharStylename"> + * - earlier was applied from code, for "CitationCharacterFormat" + * + * - <p> start new paragraph + * - earlier was applied from code + * + * - <p oo:ParaStyleName="ParStyleName"> : start new paragraph and apply ParStyleName + * - earlier was applied from code + * + * - <tt> + * - earlier: known, but ignored + * - now: equivalent to <span oo:CharStyleName="Example"> + * - <oo:referenceToPageNumberOfReferenceMark> (self-closing) + * + * - closing tags try to properly restore state instead of dictating + * an "off" state. + * + * - The practical consequence: the user can format + * citation marks (it is enough to format its start) and the + * properties not dictated by the style are preserved. + * + * A comparable example: a style with + * ReferenceParagraphFormat="JR_bibentry" + * JR_bibentry in LibreOffice, paragraph style prescribes "bold" font. + * LAYOUT only mentions bold around year. + * Which parts of the bibliography entries should come out as bold? + * + * @param position The cursor giving the insert location. Not modified. + * @param ootext The marked-up text to insert. + */ + public static void write(DocumentConnection documentConnection, + XTextCursor position, + OOFormattedText ootext) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException, + CreationException { + + String lText = OOFormattedText.toString(ootext); + + System.out.println(lText); + + XText text = position.getText(); + XTextCursor cursor = text.createTextCursorByRange(position); + cursor.collapseToEnd(); + + Stack formatters = new Stack<>(); + Stack expectEnd = new Stack<>(); + + // We need to extract formatting. Use a simple regexp search iteration: + int piv = 0; + Matcher m = HTML_TAG.matcher(lText); + while (m.find()) { + + String currentSubstring = lText.substring(piv, m.start()); + if (!currentSubstring.isEmpty()) { + text.insertString(cursor, currentSubstring, true); + } + formatTextInCursor(cursor, formatters); + cursor.collapseToEnd(); + + String fullTag = m.group(); + String endTagName = m.group(1); + String startTagName = m.group(2); + String attributeListPart = m.group(3); + boolean isStartTag = (endTagName == null) || "".equals(endTagName); + String tagName = isStartTag ? startTagName : endTagName; + Objects.requireNonNull(tagName); + + List> attributes = parseAttributes(attributeListPart); + + // Handle tags: + switch (tagName) { + case "b": + formatters.push(setCharWeight(FontWeight.BOLD)); + expectEnd.push("/" + tagName); + break; + case "i": + case "em": + formatters.push(setCharPosture(FontSlant.ITALIC)); + expectEnd.push("/" + tagName); + break; + case "smallcaps": + formatters.push(setCharCaseMap(CaseMap.SMALLCAPS)); + expectEnd.push("/" + tagName); + break; + case "sup": + formatters.push(SuperScript()); + expectEnd.push("/" + tagName); + break; + case "sub": + formatters.push(SubScript()); + expectEnd.push("/" + tagName); + break; + case "u": + formatters.push(setCharUnderline(FontUnderline.SINGLE)); + expectEnd.push("/" + tagName); + break; + case "s": + formatters.push(setCharStrikeout(FontStrikeout.SINGLE)); + expectEnd.push("/" + tagName); + break; + case "/p": + // nop + break; + case "p": + OOUtil.insertParagraphBreak(text, cursor); + cursor.collapseToEnd(); + for (Pair kv : attributes) { + String key = kv.getKey(); + String value = kv.getValue(); + switch (key) { + case "oo:ParaStyleName": + //

+ if (value != null && !value.equals("")) { + try { + DocumentConnection.setParagraphStyle(cursor, value); + } catch (UndefinedParagraphFormatException ex) { + // ignore silently + } + } + break; + default: + LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); + break; + } + } + break; + case "oo:referenceToPageNumberOfReferenceMark": + for (Pair kv : attributes) { + String key = kv.getKey(); + String value = kv.getValue(); + switch (key) { + case "target": + documentConnection + .insertReferenceToPageNumberOfReferenceMark(value, cursor); + break; + default: + LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); + break; + } + } + break; + case "tt": + // Note: "Example" names a character style in LibreOffice. + formatters.push(setCharStyleName("Example")); + expectEnd.push("/" + tagName); + break; + case "span": + Formatters fs = new Formatters(); + for (Pair kv : attributes) { + String key = kv.getKey(); + String value = kv.getValue(); + switch (key) { + case "oo:CharStyleName": + // + fs.add(setCharStyleName(value)); + break; + case "lang": + // + // + fs.add(setCharLocale(value)); + break; + case "style": + // In general we may need to parse value + if (value.equals("font-variant: small-caps")) { + fs.add(setCharCaseMap(CaseMap.SMALLCAPS)); + break; + } + LOGGER.warn(String.format("Unexpected value %s for attribute '%s' for <%s>", + value, key, tagName)); + break; + default: + LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); + break; + } + } + formatters.push(fs); + expectEnd.push("/" + tagName); + break; + case "/b": + case "/i": + case "/em": + case "/tt": + case "/smallcaps": + case "/sup": + case "/sub": + case "/u": + case "/s": + case "/span": + formatters.pop().applyEnd(cursor); + String expected = expectEnd.pop(); + if (!tagName.equals(expected)) { + LOGGER.warn(String.format("expected '<%s>', found '<%s>'", expected, tagName)); + } + break; + } + + piv = m.end(); + } + + if (piv < lText.length()) { + text.insertString(cursor, lText.substring(piv), true); + } + formatTextInCursor(cursor, formatters); + cursor.collapseToEnd(); + + if (!expectEnd.empty()) { + String rest = ""; + for (String s : expectEnd) { + rest = String.format("<%s>", s) + rest; + } + LOGGER.warn(String.format("insertOOFormattedTextAtCurrentLocation2:" + + " expectEnd stack is not empty at the end: %s%n", + rest)); + } + } + + /** + * Purpose: in some cases we do not want to inherit direct + * formatting from the context. + * + * In particular, when filling the bibliography title and body. + */ + public static void removeDirectFormatting(XTextCursor cursor) { + + XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); + + /* + * Now that we have setAllPropertiesToDefault, check which properties + * are not set to default and try to correct what we can and seem necessary. + * + * Note: tested with LibreOffice : 6.4.6.2 + */ + + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + + try { + // Special handling + propertySet.setPropertyValue(CHAR_STYLE_NAME, "Standard"); + // propertySet.setPropertyValue("CharCaseMap", CaseMap.NONE); + propertyState.setPropertyToDefault("CharCaseMap"); + } catch (UnknownPropertyException | + PropertyVetoException | + IllegalArgumentException | + WrappedTargetException ex) { + LOGGER.warn("exception caught", ex); + } + + mpss.setAllPropertiesToDefault(); + + // Only report those we do not yet know about + final Set knownToFail = Set.of("ListAutoFormat", + "ListId", + "NumberingIsNumber", + "NumberingLevel", + "NumberingRules", + "NumberingStartValue", + "ParaChapterNumberingLevel", + "ParaIsNumberingRestart", + "ParaStyleName"); + + // query again, just in case it matters + propertySet = unoQI(XPropertySet.class, cursor); + XPropertySetInfo psi = propertySet.getPropertySetInfo(); + + // check the result + for (Property p : psi.getProperties()) { + if ((p.Attributes & PropertyAttribute.READONLY) != 0) { + continue; + } + try { + if (isPropertyDefault(cursor, p.Name)) { + continue; + } + } catch (UnknownPropertyException ex) { + throw new RuntimeException("Unexpected UnknownPropertyException"); + } + if (knownToFail.contains(p.Name)) { + continue; + } + LOGGER.warn(String.format("OOFormattedTextIntoOO.removeDirectFormatting failed on '%s'", + p.Name)); + } + } + + private static class Pair { + K key; + V value; + public Pair(K k, V v) { + key = k; + value = v; + } + + K getKey() { + return key; + } + + V getValue() { + return value; + } + } + + private static List> parseAttributes(String s) { + List> res = new ArrayList<>(); + if (s == null) { + return res; + } + Matcher m = ATTRIBUTE_PATTERN.matcher(s); + while (m.find()) { + String key = m.group(1); + String value = m.group(2); + res.add(new Pair(key, value)); + } + return res; + } + + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if available, + * otherwise null + */ + private static T unoQI(Class zInterface, + Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + + /** + * Remove direct formatting of propertyName from propertySet. + * + * Observation: while + * XPropertyState.setPropertyToDefault(propertyName) does reset + * the property, it also has a side effect (probably bug in LO + * 6.4.6.2) that it also resets other properties. + * + * For example setPropertyToDefault("CharWeight") also removes "CharColor" + * + * Workaround: + * (https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=105117) + * + * Use setPropertyValue with either result from + * getPropertyValue to restore the earlier state or with + * result from getPropertyDefault. + * + * In either case the property "CharStyleName" has to be handled + * specially, by mapping the received value "" to "Standard". + * Hopefully other properties will not need special handling. + * + * Well, they do. Some properties interact: setting one to + * non-default also sets the other to non-default. Fortunately + * these interactions appear meaningful. For example setting + * "CharCrossedOut" to non-default also modifies "CharStrikeout". + * For the strategy applied here (remove all, then restore all + * except the one we wanted to default) it means we have to avoid + * restoring those that would, as a side-effect set to non-default + * what we promised to set to default. I did not investigate + * potential asymmetries of these interactions, the code below implements + * symmetric behaviour. This means that for example for + * propertyName == "CharCrossedOut" we do not restore + * "CharStrikeout", although the problematic behaviour observed was + * that restoring "CharCrossedOut" changes "CharStrikeout" from its default. + * + */ + private static void setPropertyToDefault(XTextCursor cursor, String propertyName) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + + if (false) { + // This is what should "simply work". + // However it loses e.g. font color when propertyName is "CharWeight". + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + propertyState.setPropertyToDefault(propertyName); + } else if (false) { + + // Despite the name getPropertyDefault, storing + // its result by setPropertyValue is NOT (always) equivalent + // to setPropertyToDefault(). + // + // setPropertyToDefault() should remove direct ("hard") + // formatting. + // + // setPropertyValue(getPropertyDefault()) can only do that + // if getPropertyDefault provides a value with the meaning + // "use whatever comes from the level above". + // + // If the value from getPropertyDefault dictates any + // concrete value for the property and "whatever comes + // from the level above" happens to be a different value, + // then the two behaviours yield different results. + + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + Object value = propertyState.getPropertyDefault(propertyName); + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + propertySet.setPropertyValue(propertyName, value); + } else { + + // Try to remove all, then add all directly formatted again, + // except the one we are removing. And those that would override + // what we try to achieve. + + /* https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Formatting + * at the bottom lists interdependent sets: + * + * Those marked [-] we probably will not touch, [X] handled, [?] maybe will touch. + * + * - [-] ParaRightMargin, ParaLeftMargin, ParaFirstLineIndent, ParaIsAutoFirstLineIndent + * - [-] ParaTopMargin, ParaBottomMargin + * - [-] ParaGraphicURL/Filter/Location, ParaBackColor, ParaBackTransparent + * - [-] ParaIsHyphenation, ParaHyphenationMaxLeadingChars/MaxTrailingChars/MaxHyphens + * - [-] Left/Right/Top/BottomBorder, Left/Right/Top/BottomBorderDistance, BorderDistance + * - [-] DropCapFormat, DropCapWholeWord, DropCapCharStyleName + * - [-] PageDescName, PageNumberOffset, PageStyleName + * + * - [-] CharCombineIsOn, CharCombinePrefix, CharCombineSuffix + * - [-] RubyText, RubyAdjust, RubyCharStyleName, RubyIsAbove + * + * - [X] CharStrikeOut, CharCrossedOut + * - [X] CharEscapement, CharAutoEscapement, CharEscapementHeight + * - [X] CharUnderline, CharUnderlineColor, CharUnderlineHasColor + * + * - [?] CharFontName, CharFontStyleName, CharFontFamily, CharFontPitch + * - [?] HyperLinkURL/Name/Target, UnvisitedCharStyleName, VisitedCharStyleName + * + */ + + // CharStrikeout and CharCrossedOut interact: if we default one, + // we default the other as well. + Set charStrikeOutSet = Set.of(CHAR_STRIKEOUT, + "CharCrossedOut"); + Set charEscapementSet = Set.of("CharAutoEscapement", + CHAR_ESCAPEMENT, + CHAR_ESCAPEMENT_HEIGHT); + Set charUnderlineSet = Set.of(CHAR_UNDERLINE, + "CharUnderlineColor", + "CharUnderlineHasColor"); + + Set namesToDefault = new HashSet<>(); + if (charStrikeOutSet.contains(propertyName)) { + namesToDefault = charStrikeOutSet; + } else if (charEscapementSet.contains(propertyName)) { + namesToDefault = charEscapementSet; + } else if (charUnderlineSet.contains(propertyName)) { + namesToDefault = charUnderlineSet; + } else { + namesToDefault.add(propertyName); + } + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertySetInfo psi = propertySet.getPropertySetInfo(); + + // Remember those we shall we restore later + Map ds = new HashMap<>(); + for (Property p : psi.getProperties()) { + boolean noRestore = (namesToDefault.contains(p.Name) + || ((p.Attributes & PropertyAttribute.READONLY) != 0) + || (isPropertyDefault(cursor, p.Name))); + if (noRestore) { + continue; + } + ds.put(p.Name, propertySet.getPropertyValue(p.Name)); + } + + // Remove all + removeDirectFormatting(cursor); + + boolean failed = false; + if (!isPropertyDefault(cursor, propertyName)) { + LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault:" + + " removeDirectFormatting failed to reset '%s'", + propertyName)); + failed = true; + } + + // Restore those saved + for (Map.Entry e : ds.entrySet()) { + propertySet.setPropertyValue(e.getKey(), e.getValue()); + if (!failed && !isPropertyDefault(cursor, propertyName)) { + LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault('%s')" + + " setPropertyValue('%s') caused loss of default state", + propertyName, e.getKey())); + failed = true; + } + } + + if (!failed && !isPropertyDefault(cursor, propertyName)) { + LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault('%s') failed", + propertyName)); + } + + } + } + + /** + * We rely on property values being either DIRECT_VALUE or + * DEFAULT_VALUE (not AMBIGUOUS_VALUE). If the cursor covers a homogeneous region, + * or is collapsed, then this is true. + */ + private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) + throws + UnknownPropertyException { + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + PropertyState pst = propertyState.getPropertyState(propertyName); + if (pst == PropertyState.AMBIGUOUS_VALUE) { + throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE" + + " (expected properties for a homogeneous cursor)"); + } + return pst == PropertyState.DEFAULT_VALUE; + } + + /** + * @return Optional.empty() if the property is not directly formatted. + */ + private static Optional getPropertyValue(XTextCursor cursor, String propertyName) + throws + UnknownPropertyException, + WrappedTargetException { + if (isPropertyDefault(cursor, propertyName)) { + return Optional.empty(); + } else { + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + return Optional.of(propertySet.getPropertyValue(propertyName)); + } + } + + /** + * @param value Optional.empty() means instruction to remove direct formatting. + */ + private static void setPropertyValue(XTextCursor cursor, String propertyName, Optional value) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + if (value.isPresent()) { + propertySet.setPropertyValue(propertyName, value.get()); + } else { + setPropertyToDefault(cursor, propertyName); + } + } + + /** + * At each tag we adjust the current stack of formatters-to-apply + * stack, then run it. + */ + private interface Formatter { + /** + * Note: apply may be called multiple times, but should pick up old value only + * at its first call. + */ + public void apply(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException; + + /** + * Closing tags call applyEnd directly, so applyEnd is only called once. + * + * It should restore the state to that seen by the first call to apply. + * + */ + public void applyEnd(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException; + } + + /** + * Apply Formatters on the stack. + * + * @param cursor Marks the text to format + * @param formatters Formatters to apply (normally extracted from OOFormattedText) + */ + private static void formatTextInCursor(XTextCursor cursor, + Stack formatters) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + + for (Formatter f : formatters) { + f.apply(cursor); + } + } + + private static class Formatters implements Formatter { + List parts; + public Formatters() { + parts = new ArrayList<>(); + } + + public void add(Formatter f) { + parts.add(f); + } + + @Override + public void apply(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + for (Formatter f : parts) { + f.apply(cursor); + } + } + + @Override + public void applyEnd(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + for (int i = parts.size() - 1; i >= 0; i--) { + Formatter f = parts.get(i); + f.applyEnd(cursor); + } + } + } + + private static class SimpleFormatter implements Formatter { + final String propertyName; + Optional myValue; + Optional oldValue; + boolean started; + + SimpleFormatter(String propertyName, Optional value) { + this.propertyName = propertyName; + this.myValue = value; + this.oldValue = Optional.empty(); + this.started = false; + } + + @Override + public void apply(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + + if (!started) { + oldValue = getPropertyValue(cursor, propertyName).map(e -> (T) e); + XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + started = true; + } + + setPropertyValue(cursor, propertyName, myValue); + } + + @Override + public void applyEnd(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + setPropertyValue(cursor, propertyName, oldValue); + } + } + + private static Formatter setCharWeight(float value) { + return new SimpleFormatter("CharWeight", Optional.of(value)); + } + + private static Formatter setCharPosture(FontSlant value) { + return new SimpleFormatter("CharPosture", Optional.of(value)); + } + + private static Formatter setCharCaseMap(short value) { + return new SimpleFormatter("CharCaseMap", Optional.of(value)); + } + + // com.sun.star.awt.FontUnderline + private static Formatter setCharUnderline(short value) { + return new SimpleFormatter(CHAR_UNDERLINE, Optional.of(value)); + } + + // com.sun.star.awt.FontStrikeout + private static Formatter setCharStrikeout(short value) { + return new SimpleFormatter(CHAR_STRIKEOUT, Optional.of(value)); + } + + // CharStyleName + private static Formatter setCharStyleName(String value) { + return new SimpleFormatter(CHAR_STYLE_NAME, Optional.ofNullable(value)); + } + + // Locale + private static Formatter setCharLocale(Locale value) { + return new SimpleFormatter("CharLocale", Optional.of(value)); + } + + /** + * Locale from string encoding: language, language-country or language-country-variant + */ + private static Formatter setCharLocale(String value) { + if (value == null || "".equals(value)) { + throw new RuntimeException("setCharLocale \"\" or null"); + } + String[] parts = value.split("-"); + String language = (parts.length > 0) ? parts[0] : ""; + String country = (parts.length > 1) ? parts[1] : ""; + String variant = (parts.length > 2) ? parts[2] : ""; + Locale l = new Locale(language, country, variant); + return setCharLocale(l); + } + + /* + * SuperScript and SubScript + */ + private static class CharEscapement implements Formatter { + Optional myValue; + Optional myHeight; + boolean relative; + + Optional oldValue; + Optional oldHeight; + boolean started; + + /** + * @param relative Make value and height relative to oldHeight and oldValue. + * Needed for e^{x_i} e^{x^2} (i.e. sup or sub within sup or sup) + * + */ + CharEscapement(Optional value, Optional height, boolean relative) { + this.myValue = value; + this.myHeight = height; + this.relative = relative; + this.oldValue = Optional.empty(); + this.oldHeight = Optional.empty(); + this.started = false; + } + + @Override + public void apply(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + if (!started) { + oldValue = getPropertyValue(cursor, CHAR_ESCAPEMENT).map(e -> (short) e); + oldHeight = getPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT).map(e -> (byte) e); + started = true; + } + if (relative && (myValue.isPresent() || myHeight.isPresent())) { + double oh = oldHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * 0.01; + double xHeight = myHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * oh; + double ov = oldValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT); + double xValue = myValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT) * oh + ov; + setPropertyValue(cursor, CHAR_ESCAPEMENT, Optional.of((short) Math.round(xValue))); + setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, Optional.of((byte) Math.round(xHeight))); + } else { + setPropertyValue(cursor, CHAR_ESCAPEMENT, myValue); + setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, myHeight); + } + } + + @Override + public void applyEnd(XTextCursor cursor) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + IllegalArgumentException, + NoSuchElementException { + setPropertyValue(cursor, CHAR_ESCAPEMENT, oldValue); + setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, oldHeight); + } + } + + private static Formatter SubScript() { + return new CharEscapement(Optional.of(SUBSCRIPT_VALUE), Optional.of(SUBSCRIPT_HEIGHT), true); + } + + private static Formatter SuperScript() { + return new CharEscapement(Optional.of(SUPERSCRIPT_VALUE), Optional.of(SUPERSCRIPT_HEIGHT), true); + } + +} From 88d5b4c12d6d1164fb01b7d16ba6585651a724ba Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 8 May 2021 16:43:22 +0200 Subject: [PATCH 0682/1068] ManageCitationsDialogViewModel does not throw now --- .../gui/openoffice/ManageCitationsDialogViewModel.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 37efb1b16ea..f852ddd2162 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -19,7 +19,6 @@ import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.WrappedTargetException; import org.slf4j.Logger; @@ -33,12 +32,7 @@ public class ManageCitationsDialogViewModel { private final OOBibBase ooBase; private final DialogService dialogService; - public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) - throws - NoSuchElementException, - WrappedTargetException, - UnknownPropertyException, - JabRefException { + public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) { this.ooBase = ooBase; this.dialogService = dialogService; @@ -52,6 +46,7 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogServ | WrappedTargetException | NoDocumentException | PropertyVetoException + | JabRefException | CreationException ex) { LOGGER.warn("Problem collecting citations", ex); dialogService.showErrorDialogAndWait(Localization.lang("Problem collecting citations"), ex); From 6b1d175b9618487899758d36a882fe358d6efae3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 8 May 2021 16:52:57 +0200 Subject: [PATCH 0683/1068] changed for (;e.hasMoreElements();) to while (e.hasMoreElements()) --- .../org/jabref/logic/openoffice/DocumentConnection.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java index 46bb802e785..f7ce8516d8f 100644 --- a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java @@ -188,9 +188,9 @@ public int countRedlines() { return 0; } else { int count = 0; - for (; e.hasMoreElements(); ) { + while (e.hasMoreElements()) { try { - Object o = e.nextElement(); + e.nextElement(); count++; } catch (NoSuchElementException | WrappedTargetException ex) { break; @@ -212,7 +212,7 @@ private void printRedlines() { return; } else { int count = 0; - for (; e.hasMoreElements(); ) { + while (e.hasMoreElements()) { try { count++; Object o = e.nextElement(); From 2b19719c52c8d64e115faa61b5235bf7cb84db28 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 8 May 2021 17:05:57 +0200 Subject: [PATCH 0684/1068] update description of OOBibBaseConnect --- .../java/org/jabref/gui/openoffice/OOBibBaseConnect.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index b80f2aeb264..68302d293a7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -28,8 +28,7 @@ import org.slf4j.LoggerFactory; /** - * Class for manipulating the Bibliography of the currently started - * document in OpenOffice. + * Establish connection to a document opened in OpenOffice or LibreOffice. */ class OOBibBaseConnect { @@ -59,12 +58,6 @@ public OOBibBaseConnect(Path loPath, this.xDesktop = simpleBootstrap(loPath); } - /* ***************************** - * - * Establish connection - * - * *****************************/ - private XDesktop simpleBootstrap(Path loPath) throws CreationException, From be65ddf8b9e3dae1cb7d2ccad69eb94ccb1415a2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 8 May 2021 17:14:47 +0200 Subject: [PATCH 0685/1068] removed call with no effect: unoQI(XComponentLoader.class, desktop); Also: drop import of XComponentLoader --- .../java/org/jabref/gui/openoffice/OOBibBaseConnect.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 68302d293a7..afd507f5aaa 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -16,7 +16,6 @@ import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XEnumeration; import com.sun.star.container.XEnumerationAccess; -import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XDesktop; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XComponent; @@ -75,11 +74,7 @@ private XDesktop simpleBootstrap(Path loPath) } catch (Exception e) { throw new CreationException(e.getMessage()); } - XDesktop result = unoQI(XDesktop.class, desktop); - - unoQI(XComponentLoader.class, desktop); - - return result; + return unoQI(XDesktop.class, desktop); } private static List getTextDocuments(XDesktop desktop) From 57a1a973ad1dc38863431764a1019e0351461107 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 8 May 2021 17:40:39 +0200 Subject: [PATCH 0686/1068] drop " + " (twice) --- src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 948c295f850..0b8bffd44f4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -682,12 +682,12 @@ private boolean checkThatEntriesHaveKeys(List entries) { private void showConnectionLostErrorMessage() { dialogService.showErrorDialogAndWait(Localization.lang("Connection lost"), - Localization.lang("Connection to OpenOffice/LibreOffice has been lost. " + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); + Localization.lang("Connection to OpenOffice/LibreOffice has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); } private void showNoDocumentErrorMessage() { dialogService.showErrorDialogAndWait(Localization.lang("Connection to document lost"), - Localization.lang("Connection to OpenOffice/LibreOffice document has been lost. " + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); + Localization.lang("Connection to OpenOffice/LibreOffice document has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); } private void reportUndefinedParagraphFormat(UndefinedParagraphFormatException ex) { From 6d04095b34ea9aa627e17c6aa4ab07c09ab924bb Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 8 May 2021 19:04:23 +0200 Subject: [PATCH 0687/1068] rework DocumentConnection --- .../org/jabref/gui/openoffice/OOBibBase.java | 11 +- .../logic/openoffice/DocumentConnection.java | 136 ++++++++---------- .../logic/openoffice/RangeSortVisual.java | 2 +- 3 files changed, 65 insertions(+), 84 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f3056101f14..f977b2c1076 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -740,9 +740,9 @@ private void createBibTextSection2(DocumentConnection documentConnection) IllegalArgumentException, CreationException { - // Always creating at the end of documentConnection.xText + // Always creating at the end of documentConnection.getText() // Alternatively, we could receive a cursor. - XTextCursor textCursor = documentConnection.xText.createTextCursor(); + XTextCursor textCursor = documentConnection.getText().createTextCursor(); textCursor.gotoEnd(false); // OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); @@ -777,7 +777,8 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) XTextSection section = (XTextSection) a.getObject(); // Clear it: - XTextCursor cursor = documentConnection.xText.createTextCursorByRange(section.getAnchor()); + XTextCursor cursor = (documentConnection.getText() + .createTextCursorByRange(section.getAnchor())); cursor.gotoRange(section.getAnchor(), false); cursor.setString(""); @@ -818,7 +819,7 @@ private void populateBibTextSection(DocumentConnection documentConnection, .getTextSectionByName(OOBibBase.BIB_SECTION_NAME) .orElseThrow(RuntimeException::new)); - XTextCursor cursor = (documentConnection.xText + XTextCursor cursor = (documentConnection.getText() .createTextCursorByRange(section.getAnchor())); // emit the title of the bibliography @@ -831,7 +832,7 @@ private void populateBibTextSection(DocumentConnection documentConnection, cursor.collapseToEnd(); // remove the inital empty paragraph from the section. - XTextCursor initialParagraph = (documentConnection.xText + XTextCursor initialParagraph = (documentConnection.getText() .createTextCursorByRange(section.getAnchor())); initialParagraph.collapseToStart(); initialParagraph.goRight((short) 1, true); diff --git a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java index f7ce8516d8f..da93400393f 100644 --- a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java @@ -77,23 +77,7 @@ public class DocumentConnection { private static final Logger LOGGER = LoggerFactory.getLogger(DocumentConnection.class); - public XTextDocument mxDoc; - - // unoQI(XComponent.class, mxDoc); - public XComponent xCurrentComponent; - - // unoQI(XMultiServiceFactory.class, mxDoc); - public XMultiServiceFactory mxDocFactory; - - // XModel mo = unoQI(XModel.class, this.xCurrentComponent); - // XController co = mo.getCurrentController(); - - public XText xText; - - // xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); - public XTextViewCursorSupplier xViewCursorSupplier; - public XPropertyContainer userProperties; - public XPropertySet propertySet; + private XTextDocument mxDoc; public DocumentConnection(XTextDocument mxDoc) { // printServiceInfo(mxDoc); @@ -107,20 +91,33 @@ public DocumentConnection(XTextDocument mxDoc) { // "com.sun.star.text.TextDocument" this.mxDoc = mxDoc; - this.xCurrentComponent = unoQI(XComponent.class, mxDoc); - this.mxDocFactory = unoQI(XMultiServiceFactory.class, mxDoc); - // unoQI(XDocumentIndexesSupplier.class, component); + } - // get a reference to the body text of the document - this.xText = mxDoc.getText(); + /** + * Get a reference to the body text of the document + */ + public XText getText() { + return mxDoc.getText(); + } - XModel mo = unoQI(XModel.class, this.xCurrentComponent); - XController co = mo.getCurrentController(); - this.xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); + private XComponent asXComponent() { + return unoQI(XComponent.class, mxDoc); + } - XDocumentPropertiesSupplier supp = unoQI(XDocumentPropertiesSupplier.class, mxDoc); - this.userProperties = supp.getDocumentProperties().getUserDefinedProperties(); - this.propertySet = unoQI(XPropertySet.class, userProperties); + public XModel asXModel() { + return unoQI(XModel.class, mxDoc /* this.asXComponent() */); + } + + private XMultiServiceFactory asXMultiServiceFactory() { + return unoQI(XMultiServiceFactory.class, mxDoc); + } + + public XController getCurrentController() { + return this.asXModel().getCurrentController(); + } + + public XSelectionSupplier getSelectionSupplier() { + return unoQI(XSelectionSupplier.class, this.getCurrentController()); } /** @@ -134,11 +131,18 @@ private static T unoQI(Class zInterface, return UnoRuntime.queryInterface(zInterface, object); } - private XDocumentProperties getXDocumentProperties() { + private XDocumentProperties getDocumentProperties() { XDocumentPropertiesSupplier supp = unoQI(XDocumentPropertiesSupplier.class, mxDoc); return supp.getDocumentProperties(); } + private XPropertyContainer getUserDefinedProperties() { + return this.getDocumentProperties().getUserDefinedProperties(); + } + private XPropertySet getUserDefinedPropertiesAsXPropertySet() { + return unoQI(XPropertySet.class, this.getUserDefinedProperties()); + } + private short getRedlineDisplayType() throws UnknownPropertyException, @@ -413,18 +417,6 @@ public static void printServiceInfo(Object o) { } } - public XModel getModel() { - return unoQI(XModel.class, this.xCurrentComponent); - } - - public XController getCurrentController() { - return this.getModel().getCurrentController(); - } - - public XSelectionSupplier getSelectionSupplier() { - return unoQI(XSelectionSupplier.class, this.getCurrentController()); - } - /** * @return may be null, or some type supporting XServiceInfo * @@ -539,17 +531,17 @@ public void leaveUndoContext() * notifications for display updates are not broadcasted. */ public void lockControllers() { - XModel mo = unoQI(XModel.class, this.xCurrentComponent); + XModel mo = this.asXModel(); mo.lockControllers(); } public void unlockControllers() { - XModel mo = unoQI(XModel.class, this.xCurrentComponent); + XModel mo = this.asXModel(); mo.unlockControllers(); } public boolean hasControllersLocked() { - XModel mo = unoQI(XModel.class, this.xCurrentComponent); + XModel mo = this.asXModel(); return mo.hasControllersLocked(); } @@ -560,13 +552,7 @@ public boolean documentConnectionMissing() { boolean missing = false; // These are set by DocumentConnection constructor. - if (null == this.mxDoc - || null == this.xCurrentComponent - || null == this.mxDocFactory - || null == this.xText - || null == this.xViewCursorSupplier - || null == this.userProperties - || null == this.propertySet) { + if (null == this.mxDoc) { missing = true; } @@ -582,12 +568,6 @@ public boolean documentConnectionMissing() { if (missing) { // release it this.mxDoc = null; - this.xCurrentComponent = null; - this.mxDocFactory = null; - this.xText = null; - this.xViewCursorSupplier = null; - this.userProperties = null; - this.propertySet = null; } return missing; } @@ -628,9 +608,9 @@ public Optional getDocumentTitle() { } public List getCustomPropertyNames() { - assert (this.propertySet != null); - XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + XPropertySet ps = getUserDefinedPropertiesAsXPropertySet(); + XPropertySetInfo psi = ps.getPropertySetInfo(); List names = new ArrayList<>(); for (Property p : psi.getProperties()) { @@ -653,16 +633,12 @@ public Optional getCustomProperty(String property) throws WrappedTargetException { - assert (this.propertySet != null); - - XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + XPropertySet ps = getUserDefinedPropertiesAsXPropertySet(); + XPropertySetInfo psi = ps.getPropertySetInfo(); if (psi.hasPropertyByName(property)) { try { - String v = - this.propertySet - .getPropertyValue(property) - .toString(); + String v = ps.getPropertyValue(property).toString(); return Optional.ofNullable(v); } catch (UnknownPropertyException ex) { throw new RuntimeException("getCustomProperty: caught UnknownPropertyException"); @@ -684,14 +660,15 @@ public void setCustomProperty(String property, String value) IllegalTypeException, IllegalArgumentException { - XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + XPropertySet ps = getUserDefinedPropertiesAsXPropertySet(); + XPropertySetInfo psi = ps.getPropertySetInfo(); if (psi.hasPropertyByName(property)) { this.removeCustomProperty(property); } if (value != null) { - this.userProperties + this.getUserDefinedProperties() .addProperty(property, com.sun.star.beans.PropertyAttribute.REMOVEABLE, new Any(Type.STRING, value)); @@ -709,11 +686,12 @@ public void removeCustomProperty(String property) IllegalTypeException, IllegalArgumentException { - XPropertySetInfo psi = this.propertySet.getPropertySetInfo(); + XPropertySet ps = getUserDefinedPropertiesAsXPropertySet(); + XPropertySetInfo psi = ps.getPropertySetInfo(); if (psi.hasPropertyByName(property)) { try { - this.userProperties.removeProperty(property); + this.getUserDefinedProperties().removeProperty(property); } catch (UnknownPropertyException ex) { throw new RuntimeException("removeCustomProperty caught UnknownPropertyException" + " (should be impossible)"); @@ -733,7 +711,7 @@ public XNameAccess getReferenceMarks() NoDocumentException { XReferenceMarksSupplier supplier = unoQI(XReferenceMarksSupplier.class, - this.xCurrentComponent); + this.mxDoc); try { return supplier.getReferenceMarks(); } catch (DisposedException ex) { @@ -747,7 +725,7 @@ public XNameAccess getReferenceMarks() public XNameAccess getBookmarks() { XBookmarksSupplier supplier = unoQI(XBookmarksSupplier.class, - this.xCurrentComponent); + this.mxDoc); return supplier.getBookmarks(); } @@ -847,7 +825,7 @@ public void removeReferenceMark(String name) if (mark.isEmpty()) { return; } - this.xText.removeTextContent(mark.get()); + this.getText().removeTextContent(mark.get()); } } @@ -856,7 +834,9 @@ public void removeReferenceMark(String name) * */ public XTextViewCursor getViewCursor() { - return this.xViewCursorSupplier.getViewCursor(); + XController co = this.getCurrentController(); + XTextViewCursorSupplier xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); + return xViewCursorSupplier.getViewCursor(); } /** @@ -907,7 +887,7 @@ public Optional getReferenceMarkRange(String name) * "com.sun.star.text.Bookmark" or * "com.sun.star.text.TextSection". * - * Passed to this.mxDocFactory.createInstance(service) + * Passed to this.asXMultiServiceFactory().createInstance(service) * The result is expected to support the * XNamed and XTextContent interfaces. * @@ -936,7 +916,7 @@ private XNamed insertNamedTextContent(String service, Object xObject; try { - xObject = this.mxDocFactory.createInstance(service); + xObject = this.asXMultiServiceFactory().createInstance(service); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -1034,7 +1014,7 @@ public void insertReferenceToPageNumberOfReferenceMark(String referenceMarkName, try { String name = "com.sun.star.text.textfield.GetReference"; xFieldProps = (XPropertySet) unoQI(XPropertySet.class, - this.mxDocFactory.createInstance(name)); + this.asXMultiServiceFactory().createInstance(name)); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -1055,7 +1035,7 @@ public void insertReferenceToPageNumberOfReferenceMark(String referenceMarkName, XTextContent xRefContent = (XTextContent) unoQI(XTextContent.class, xFieldProps); // Insert the text field - this.xText.insertTextContent(cursor.getEnd(), xRefContent, false); + this.getText().insertTextContent(cursor.getEnd(), xRefContent, false); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index 9d7d76ca4d4..f8b7ddc526a 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -196,7 +196,7 @@ public int hashCode() { LOGGER.info("visualSort: initialSelection does not support TextRanges." + " We need to change the viewCursor."); } - XTextRange newSelection = documentConnection.xText.getStart(); + XTextRange newSelection = documentConnection.getText().getStart(); documentConnection.select(newSelection); } } else { From 45595415500b0810ba87c7eccadf82b95e1555d5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 10 May 2021 12:58:40 +0200 Subject: [PATCH 0688/1068] DocumentConnection is now almost fully static --- .../ManageCitationsDialogViewModel.java | 2 +- .../org/jabref/gui/openoffice/OOBibBase.java | 225 ++--- .../gui/openoffice/OOBibBaseConnect.java | 15 +- .../jabref/logic/openoffice/Backend52.java | 48 +- .../org/jabref/logic/openoffice/Codec52.java | 1 - .../logic/openoffice/DocumentConnection.java | 877 ++++++------------ .../openoffice/OOFormattedTextIntoOO.java | 7 +- .../openoffice/OOFormattedTextIntoOOV1.java | 7 +- .../jabref/logic/openoffice/OOFrontend.java | 6 +- .../logic/openoffice/RangeSortVisual.java | 15 +- .../jabref/logic/openoffice/StorageBase.java | 7 +- .../logic/openoffice/StorageBaseRefMark.java | 57 +- 12 files changed, 500 insertions(+), 767 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index f852ddd2162..59577d62654 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -57,7 +57,7 @@ public void storeSettings() { List ciationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); try { ooBase.applyCitationEntries(ciationEntries); - } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException | + } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | PropertyVetoException | IllegalTypeException | NoDocumentException | WrappedTargetException | IllegalArgumentException ex) { LOGGER.warn("Problem modifying citation", ex); diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f977b2c1076..81642c618e0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -53,6 +53,7 @@ import com.sun.star.lang.DisposedException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextSection; import com.sun.star.uno.Any; @@ -136,6 +137,12 @@ public DocumentConnection getDocumentConnectionOrThrow() return this.connection.getDocumentConnectionOrThrow(); } + public XTextDocument getXTextDocumentOrThrow() + throws + NoDocumentException { + return this.connection.getXTextDocumentOrThrow(); + } + /** * The title of the current document, or Optional.empty() */ @@ -196,6 +203,7 @@ public void applyCitationEntries(List citationEntries) UnknownPropertyException, NotRemoveableException, PropertyExistException, + PropertyVetoException, IllegalTypeException, IllegalArgumentException, NoDocumentException, @@ -306,55 +314,6 @@ private void createAndFillCitationGroup(OOFrontend fr, position.collapseToEnd(); } - /** - * Test if we have a problem applying character style prescribe by - * the style. - * - * If the style prescribes an character style, we insert a - * character, format it and delete it. - * - * An UndefinedCharacterFormatException may be raised, indicating - * that the style requested is not available in the document. - * - * @param cursor Provides location where we insert, format and - * remove a character. - */ - void assertCitationCharacterFormatIsOK(XTextCursor cursor, - OOBibStyle style) - throws UndefinedCharacterFormatException { - if (!style.isFormatCitations()) { - return; - } - - /* We do not want to change the cursor passed in, so using a copy. */ - XTextCursor c2 = cursor.getText().createTextCursorByRange(cursor.getEnd()); - - /* - * Inserting, formatting and removing a single character - * still leaves a style change in place. - * Let us try with two characters, formatting only the first. - */ - c2 - .getText() - .insertString(c2, "@*", false); - - String charStyle = style.getCitationCharacterFormat(); - try { - c2.goLeft((short) 1, false); // step over '*' - c2.goLeft((short) 1, true); // select '@' - // The next line may throw - // UndefinedCharacterFormatException(charStyle). - // We let that propagate. - DocumentConnection.setCharStyle(c2, charStyle); - } finally { - // Before leaving this scope, always delete the character we - // inserted: - c2.collapseToStart(); - c2.goRight((short) 2, true); // select '@*' - c2.setString(""); - } - } - /** * In insertEntry we receive BibEntry values from the GUI. * @@ -465,7 +424,8 @@ public void insertEntry(List entries, } final int nEntries = entries.size(); - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + XTextDocument doc = this.getXTextDocumentOrThrow(); checkStylesExistInTheDocument(style, documentConnection); checkIfOpenOfficeIsRecordingChanges(documentConnection); @@ -478,12 +438,12 @@ public void insertEntry(List entries, try { if (useUndoContext) { - documentConnection.enterUndoContext("Insert citation"); + DocumentConnection.enterUndoContext(doc, "Insert citation"); } XTextCursor cursor; // Get the cursor positioned by the user. try { - cursor = documentConnection.getViewCursor(); + cursor = DocumentConnection.getViewCursor(doc).orElse(null); } catch (RuntimeException ex) { // com.sun.star.uno.RuntimeException throw new JabRefException("Could not get the cursor", @@ -510,8 +470,6 @@ public void insertEntry(List entries, InTextCitationType itcType = OOProcess.citationTypeFromOptions(withText, inParenthesis); - assertCitationCharacterFormatIsOK(cursor, style); - // JabRef53 style pageInfo list List pageInfosForCitations = OOStyleDataModelVersion.fakePageInfosForCitations(pageInfo, nEntries); @@ -565,7 +523,7 @@ public void insertEntry(List entries, OOProcess.ProduceCitationMarkersResult x = OOProcess.produceCitationMarkers(fr2.cgs, allBases, style); try { - documentConnection.lockControllers(); + DocumentConnection.lockControllers(doc); applyNewCitationMarkers(documentConnection, fr2, x.citMarkers, @@ -577,7 +535,7 @@ public void insertEntry(List entries, x.getBibliography(), this.alwaysAddCitedOnPages); } finally { - documentConnection.unlockControllers(); + DocumentConnection.unlockControllers(doc); } /* @@ -599,7 +557,7 @@ public void insertEntry(List entries, throw new ConnectionLostException(ex.getMessage()); } finally { if (useUndoContext) { - documentConnection.leaveUndoContext(); + DocumentConnection.leaveUndoContext(doc); } } } @@ -637,21 +595,18 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, CreationException, WrappedTargetException, PropertyVetoException, - NoSuchElementException { + NoSuchElementException, + JabRefException { + + XTextDocument doc = documentConnection.asXTextDocument(); + + checkStylesExistInTheDocument(style, documentConnection); CitationGroups cgs = fr.cgs; - final boolean hadBibSection = (documentConnection - .getBookmarkRange(OOBibBase.BIB_SECTION_NAME) + final boolean hadBibSection = (DocumentConnection + .getBookmarkRange(doc, OOBibBase.BIB_SECTION_NAME) .isPresent()); - // If we are supposed to set character format for citations, - // must run a test before we delete old citation - // markers. Otherwise, if the specified character format - // doesn't exist, we end up deleting the markers before the - // process crashes due to a the missing format, with - // catastrophic consequences for the user. - boolean mustTestCharFormat = style.isFormatCitations(); - for (Map.Entry kv : citMarkers.entrySet()) { CitationGroupID cgid = kv.getKey(); @@ -669,11 +624,6 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, XTextCursor cursor = fr.getFillCursorForCitationGroup(documentConnection, cgid); - if (mustTestCharFormat) { - assertCitationCharacterFormatIsOK(cursor, style); - mustTestCharFormat = false; - } - fillCitationMarkInCursor(documentConnection, cursor, citationText, @@ -684,8 +634,8 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, } if (hadBibSection - && (documentConnection - .getBookmarkRange(OOBibBase.BIB_SECTION_NAME) + && (DocumentConnection + .getBookmarkRange(doc, OOBibBase.BIB_SECTION_NAME) .isEmpty())) { // Overwriting text already there is too harsh. // I am making it an error, to see if we ever get here. @@ -719,7 +669,8 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, CreationException, PropertyVetoException, UnknownPropertyException, - UndefinedParagraphFormatException { + UndefinedParagraphFormatException, + NoDocumentException { clearBibTextSectionContent2(documentConnection); @@ -740,15 +691,18 @@ private void createBibTextSection2(DocumentConnection documentConnection) IllegalArgumentException, CreationException { + XTextDocument doc = documentConnection.asXTextDocument(); + // Always creating at the end of documentConnection.getText() // Alternatively, we could receive a cursor. - XTextCursor textCursor = documentConnection.getText().createTextCursor(); + XTextCursor textCursor = doc.getText().createTextCursor(); textCursor.gotoEnd(false); // OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); textCursor.collapseToEnd(); - documentConnection.insertTextSection(OOBibBase.BIB_SECTION_NAME, + DocumentConnection.insertTextSection(doc, + OOBibBase.BIB_SECTION_NAME, textCursor, false); } @@ -764,9 +718,11 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) throws WrappedTargetException, IllegalArgumentException, - CreationException { + CreationException, + NoDocumentException { - XNameAccess nameAccess = documentConnection.getTextSections(); + XTextDocument doc = documentConnection.asXTextDocument(); + XNameAccess nameAccess = DocumentConnection.getTextSections(doc); if (!nameAccess.hasByName(OOBibBase.BIB_SECTION_NAME)) { createBibTextSection2(documentConnection); return; @@ -777,8 +733,8 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) XTextSection section = (XTextSection) a.getObject(); // Clear it: - XTextCursor cursor = (documentConnection.getText() - .createTextCursorByRange(section.getAnchor())); + XTextCursor cursor = + (documentConnection.getXText().createTextCursorByRange(section.getAnchor())); cursor.gotoRange(section.getAnchor(), false); cursor.setString(""); @@ -814,13 +770,14 @@ private void populateBibTextSection(DocumentConnection documentConnection, UndefinedParagraphFormatException, IllegalArgumentException, CreationException { + XTextDocument doc = documentConnection.asXTextDocument(); - XTextSection section = (documentConnection - .getTextSectionByName(OOBibBase.BIB_SECTION_NAME) + XTextSection section = (DocumentConnection + .getTextSectionByName(doc, OOBibBase.BIB_SECTION_NAME) .orElseThrow(RuntimeException::new)); - XTextCursor cursor = (documentConnection.getText() - .createTextCursorByRange(section.getAnchor())); + XTextCursor cursor = + (documentConnection.getXText().createTextCursorByRange(section.getAnchor())); // emit the title of the bibliography OOFormattedTextIntoOO.removeDirectFormatting(cursor); @@ -832,13 +789,14 @@ private void populateBibTextSection(DocumentConnection documentConnection, cursor.collapseToEnd(); // remove the inital empty paragraph from the section. - XTextCursor initialParagraph = (documentConnection.getText() - .createTextCursorByRange(section.getAnchor())); + XTextCursor initialParagraph = + (documentConnection.getXText().createTextCursorByRange(section.getAnchor())); initialParagraph.collapseToStart(); initialParagraph.goRight((short) 1, true); initialParagraph.setString(""); - documentConnection.insertBookmark(OOBibBase.BIB_SECTION_END_NAME, + DocumentConnection.insertBookmark(doc, + OOBibBase.BIB_SECTION_END_NAME, cursor, true); cursor.collapseToEnd(); @@ -883,13 +841,15 @@ public void combineCiteMarkers(List databases, final boolean useLockControllers = true; DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + XTextDocument doc = this.getXTextDocumentOrThrow(); + checkStylesExistInTheDocument(style, documentConnection); checkIfOpenOfficeIsRecordingChanges(documentConnection); OOFrontend fr = new OOFrontend(documentConnection); try { - documentConnection.enterUndoContext("Merge citations"); + DocumentConnection.enterUndoContext(doc, "Merge citations"); boolean madeModifications = false; @@ -902,7 +862,7 @@ public void combineCiteMarkers(List databases, try { if (useLockControllers) { - documentConnection.lockControllers(); + DocumentConnection.lockControllers(doc); } /* @@ -1115,11 +1075,6 @@ public void combineCiteMarkers(List databases, } } // if (referenceMarkNames.size() > 0) - if (joinableGroups.size() > 0) { - XTextCursor textCursor = joinableGroupsCursors.get(0); - assertCitationCharacterFormatIsOK(textCursor, style); - } - /* * Now we can process the joinable groups */ @@ -1183,12 +1138,12 @@ public void combineCiteMarkers(List databases, } finally { if (useLockControllers) { - documentConnection.unlockControllers(); + DocumentConnection.unlockControllers(doc); } } if (madeModifications) { - documentConnection.refresh(); + DocumentConnection.refresh(doc); OOFrontend fr2 = new OOFrontend(documentConnection); fr2.imposeGlobalOrder(documentConnection); OOProcess.ProduceCitationMarkersResult x = @@ -1197,7 +1152,7 @@ public void combineCiteMarkers(List databases, style); try { if (useLockControllers) { - documentConnection.lockControllers(); + DocumentConnection.lockControllers(doc); } applyNewCitationMarkers(documentConnection, fr2, @@ -1206,12 +1161,12 @@ public void combineCiteMarkers(List databases, // bibliography is not refreshed } finally { if (useLockControllers) { - documentConnection.unlockControllers(); + DocumentConnection.unlockControllers(doc); } } } } finally { - documentConnection.leaveUndoContext(); + DocumentConnection.leaveUndoContext(doc); } // documentConnection.refresh(); } // combineCiteMarkers @@ -1245,7 +1200,8 @@ public void unCombineCiteMarkers(List databases, Objects.requireNonNull(style); final boolean useLockControllers = true; - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + XTextDocument doc = this.getXTextDocumentOrThrow(); checkStylesExistInTheDocument(style, documentConnection); checkIfOpenOfficeIsRecordingChanges(documentConnection); @@ -1253,7 +1209,7 @@ public void unCombineCiteMarkers(List databases, OOFrontend fr = new OOFrontend(documentConnection); try { - documentConnection.enterUndoContext("Separate citations"); + DocumentConnection.enterUndoContext(doc, "Separate citations"); boolean madeModifications = false; // {@code names} does not need to be sorted. @@ -1261,11 +1217,10 @@ public void unCombineCiteMarkers(List databases, try { if (useLockControllers) { - documentConnection.lockControllers(); + DocumentConnection.lockControllers(doc); } int pivot = 0; - boolean setCharStyleTested = false; while (pivot < (names.size())) { CitationGroupID cgid = names.get(pivot); @@ -1275,16 +1230,6 @@ public void unCombineCiteMarkers(List databases, .orElseThrow(RuntimeException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); - // If we are supposed to set character format for - // citations, test this before making any changes. This - // way we can throw an exception before any reference - // marks are removed, preventing damage to the user's - // document: - if (!setCharStyleTested) { - assertCitationCharacterFormatIsOK(textCursor, style); - setCharStyleTested = true; - } - // Note: JabRef52 returns cg.pageInfo for the last citation. List pageInfosForCitations = fr.cgs.getPageInfosForCitations(cg); @@ -1329,30 +1274,30 @@ public void unCombineCiteMarkers(List databases, } } finally { if (useLockControllers) { - documentConnection.unlockControllers(); + DocumentConnection.unlockControllers(doc); } } if (madeModifications) { - documentConnection.refresh(); + DocumentConnection.refresh(doc); OOFrontend fr2 = new OOFrontend(documentConnection); fr2.imposeGlobalOrder(documentConnection); OOProcess.ProduceCitationMarkersResult x = OOProcess.produceCitationMarkers(fr2.cgs, databases, style); try { if (useLockControllers) { - documentConnection.lockControllers(); + DocumentConnection.lockControllers(doc); } applyNewCitationMarkers(documentConnection, fr2, x.citMarkers, style); // bibliography is not refreshed } finally { if (useLockControllers) { - documentConnection.unlockControllers(); + DocumentConnection.unlockControllers(doc); } } } } finally { - documentConnection.leaveUndoContext(); + DocumentConnection.leaveUndoContext(doc); } // documentConnection.refresh(); } @@ -1391,12 +1336,14 @@ public ExportCitedHelperResult exportCitedHelper(List databases, CreationException, InvalidStateException { - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + XTextDocument doc = this.getXTextDocumentOrThrow(); + try { - documentConnection.enterUndoContext("Changes during \"Export cited\""); + DocumentConnection.enterUndoContext(doc, "Changes during \"Export cited\""); return this.generateDatabase(databases, documentConnection); } finally { - documentConnection.leaveUndoContext(); + DocumentConnection.leaveUndoContext(doc); } } @@ -1475,11 +1422,9 @@ public void checkIfOpenOfficeIsRecordingChanges(DocumentConnection documentConne WrappedTargetException, PropertyVetoException, JabRefException { - /* We could do this: documentConnection.setRecordChanges(false); - * but it is more transparent to ask. - */ - boolean recordingChanges = documentConnection.getRecordChanges(); - int nRedlines = documentConnection.countRedlines(); + XTextDocument doc = documentConnection.asXTextDocument(); + boolean recordingChanges = DocumentConnection.getRecordChanges(doc); + int nRedlines = DocumentConnection.countRedlines(doc); if (recordingChanges || nRedlines > 0) { String msg = ""; if (recordingChanges) { @@ -1519,8 +1464,8 @@ public void checkParagraphStyleExistsInTheDocument(String styleName, JabRefException, NoSuchElementException, WrappedTargetException { - - Optional internalName = documentConnection.getInternalNameOfParagraphStyle(styleName); + XTextDocument doc = documentConnection.asXTextDocument(); + Optional internalName = DocumentConnection.getInternalNameOfParagraphStyle(doc, styleName); if (internalName.isEmpty()) { String msg = @@ -1559,9 +1504,9 @@ public void checkCharacterStyleExistsInTheDocument(String styleName, JabRefException, NoSuchElementException, WrappedTargetException { - - Optional internalName = (documentConnection - .getInternalNameOfCharacterStyle(styleName)); + XTextDocument doc = documentConnection.asXTextDocument(); + Optional internalName = (DocumentConnection + .getInternalNameOfCharacterStyle(doc, styleName)); if (internalName.isEmpty()) { String msg = @@ -1642,12 +1587,14 @@ public List updateDocumentActionHelper(List databases, styleIsRequired(style); - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); + DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + XTextDocument doc = this.getXTextDocumentOrThrow(); + checkStylesExistInTheDocument(style, documentConnection); checkIfOpenOfficeIsRecordingChanges(documentConnection); try { - documentConnection.enterUndoContext("Refresh bibliography"); + DocumentConnection.enterUndoContext(doc, "Refresh bibliography"); boolean requireSeparation = false; // CitationGroups cgs = new CitationGroups(documentConnection); @@ -1667,7 +1614,7 @@ public List updateDocumentActionHelper(List databases, style); try { if (useLockControllers) { - documentConnection.lockControllers(); + DocumentConnection.lockControllers(doc); } applyNewCitationMarkers(documentConnection, fr, @@ -1680,12 +1627,12 @@ public List updateDocumentActionHelper(List databases, this.alwaysAddCitedOnPages); return x.getUnresolvedKeys(); } finally { - if (useLockControllers && documentConnection.hasControllersLocked()) { - documentConnection.unlockControllers(); + if (useLockControllers && DocumentConnection.hasControllersLocked(doc)) { + DocumentConnection.unlockControllers(doc); } } } finally { - documentConnection.leaveUndoContext(); + DocumentConnection.leaveUndoContext(doc); } } diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index afd507f5aaa..325704171de 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -214,7 +214,12 @@ public boolean documentConnectionMissing() { if (this.xDocumentConnection == null) { return true; } - boolean res = this.xDocumentConnection.documentConnectionMissing(); + XTextDocument doc = this.xDocumentConnection.asXTextDocument(); + if (doc == null) { + forgetDocument(); + return true; + } + boolean res = DocumentConnection.documentConnectionMissing(doc); if (res) { forgetDocument(); } @@ -234,6 +239,12 @@ public DocumentConnection getDocumentConnectionOrThrow() return this.xDocumentConnection; } + public XTextDocument getXTextDocumentOrThrow() + throws + NoDocumentException { + return getDocumentConnectionOrThrow().asXTextDocument(); + } + /** * The title of the current document, or Optional.empty() */ @@ -241,7 +252,7 @@ public Optional getCurrentDocumentTitle() { if (documentConnectionMissing()) { return Optional.empty(); } else { - return this.xDocumentConnection.getDocumentTitle(); + return DocumentConnection.getDocumentTitle(this.xDocumentConnection.asXTextDocument()); } } diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 77bd8c4be62..2e8ab28fb72 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -19,10 +19,12 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,7 +50,8 @@ public Backend52() { public List getJabRefReferenceMarkNames(DocumentConnection documentConnection) throws NoDocumentException { - List allNames = this.citationStorageManager.getUsedNames(documentConnection); + XTextDocument doc = documentConnection.asXTextDocument(); + List allNames = this.citationStorageManager.getUsedNames(doc); return Codec52.filterIsJabRefReferenceMarkName(allNames); } @@ -61,13 +64,15 @@ public List getJabRefReferenceMarkNames(DocumentConnection documentConne */ private List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, List citationGroupNames) { + XTextDocument doc = documentConnection.asXTextDocument(); + // Collect unused jabrefPropertyNames Set citationGroupNamesSet = citationGroupNames.stream().collect(Collectors.toSet()); List pageInfoThrash = new ArrayList<>(); List jabrefPropertyNames = - documentConnection.getCustomPropertyNames() + DocumentConnection.getUserDefinedPropertiesNames(doc) .stream() .filter(Codec52::isJabRefReferenceMarkName) .collect(Collectors.toList()); @@ -123,6 +128,8 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc WrappedTargetException, NoDocumentException { + XTextDocument doc = documentConnection.asXTextDocument(); + Optional op = Codec52.parseMarkName(refMarkName); if (op.isEmpty()) { throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" @@ -134,13 +141,14 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc .map(Citation::new) .collect(Collectors.toList())); - Optional pageInfo = (documentConnection.getCustomProperty(refMarkName) - .map(OOFormattedText::fromString)); + Optional pageInfo = + (DocumentConnection.getUserDefinedStringPropertyValue(doc, refMarkName) + .map(OOFormattedText::fromString)); setPageInfoInData(citations, pageInfo); Optional sr = (citationStorageManager - .getFromDocument(documentConnection, refMarkName)); + .getFromDocument(doc, refMarkName)); if (sr.isEmpty()) { throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" @@ -240,13 +248,16 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, WrappedTargetException, NotRemoveableException, PropertyExistException, + PropertyVetoException, IllegalTypeException { + XTextDocument doc = documentConnection.asXTextDocument(); + String xkey = (citationKeys.stream() .collect(Collectors.joining(","))); Set usedNames = new HashSet<>(this.citationStorageManager - .getUsedNames(documentConnection)); + .getUsedNames(doc)); String refMarkName = Codec52.getUniqueMarkName(usedNames, xkey, @@ -288,11 +299,13 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, case JabRef52: Optional pageInfo = getJabRef52PageInfoFromList(pageInfosForCitations); if (pageInfo.isPresent() && !"".equals(OOFormattedText.toString(pageInfo.get()))) { - documentConnection.setCustomProperty(refMarkName, - OOFormattedText.toString(pageInfo.get())); + DocumentConnection.setOrCreateUserDefinedStringPropertyValue(doc, + refMarkName, + OOFormattedText + .toString(pageInfo.get())); } else { // do not inherit from trash - documentConnection.removeCustomProperty(refMarkName); + DocumentConnection.removeUserDefinedProperty(doc, refMarkName); } CitationGroup cg = new CitationGroup(cgid, sr, @@ -360,9 +373,11 @@ public void removeCitationGroup(CitationGroup cg, DocumentConnection documentCon IllegalTypeException, PropertyExistException { + XTextDocument doc = documentConnection.asXTextDocument(); + String refMarkName = cg.cgRangeStorage.getName(); - cg.cgRangeStorage.removeFromDocument(documentConnection); - documentConnection.removeCustomProperty(refMarkName); + cg.cgRangeStorage.removeFromDocument(doc); + DocumentConnection.removeUserDefinedProperty(doc, refMarkName); } /** @@ -463,16 +478,21 @@ public void applyCitationEntries(DocumentConnection documentConnection, UnknownPropertyException, NotRemoveableException, PropertyExistException, + PropertyVetoException, IllegalTypeException, IllegalArgumentException, - NoDocumentException { + NoDocumentException, + WrappedTargetException { + + XTextDocument doc = documentConnection.asXTextDocument(); switch (dataModel) { case JabRef52: for (CitationEntry entry : citationEntries) { Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { - documentConnection.setCustomProperty(entry.getRefMarkName(), - pageInfo.get()); + DocumentConnection.setOrCreateUserDefinedStringPropertyValue(doc, + entry.getRefMarkName(), + pageInfo.get()); } } break; diff --git a/src/main/java/org/jabref/logic/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/Codec52.java index b0df03e6f80..4e4c0e33e4f 100644 --- a/src/main/java/org/jabref/logic/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/Codec52.java @@ -94,7 +94,6 @@ public static String getUniqueMarkName(Set usedNames, InTextCitationType itcType) throws NoDocumentException { - // XNameAccess xNamedRefMarks = documentConnection.getReferenceMarks(); int i = 0; int j = InTextCitationTypeToInt(itcType); String name = BIB_CITATION + '_' + j + '_' + bibtexKey; diff --git a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java index da93400393f..83d973f179a 100644 --- a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java @@ -3,7 +3,9 @@ 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.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -30,9 +32,7 @@ import com.sun.star.frame.XModel; import com.sun.star.lang.DisposedException; import com.sun.star.lang.IllegalArgumentException; -import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; -import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XServiceInfo; import com.sun.star.style.XStyle; @@ -56,8 +56,6 @@ import com.sun.star.uno.Any; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XInterface; -import com.sun.star.util.DateTime; import com.sun.star.util.InvalidStateException; import com.sun.star.util.XRefreshable; import com.sun.star.view.XSelectionSupplier; @@ -77,91 +75,38 @@ public class DocumentConnection { private static final Logger LOGGER = LoggerFactory.getLogger(DocumentConnection.class); - private XTextDocument mxDoc; + private XTextDocument xTextDocument; - public DocumentConnection(XTextDocument mxDoc) { - // printServiceInfo(mxDoc); - // *** xserviceinfo - // object is OK - // xserviceinfo is OK - // .getImplementationName: "SwXTextDocument" - // .getSupportedServiceNames: - // "com.sun.star.document.OfficeDocument" - // "com.sun.star.text.GenericTextDocument" - // "com.sun.star.text.TextDocument" - - this.mxDoc = mxDoc; + public DocumentConnection(XTextDocument xTextDocument) { + this.xTextDocument = xTextDocument; } /** * Get a reference to the body text of the document */ - public XText getText() { - return mxDoc.getText(); - } - - private XComponent asXComponent() { - return unoQI(XComponent.class, mxDoc); - } - - public XModel asXModel() { - return unoQI(XModel.class, mxDoc /* this.asXComponent() */); - } - - private XMultiServiceFactory asXMultiServiceFactory() { - return unoQI(XMultiServiceFactory.class, mxDoc); - } - - public XController getCurrentController() { - return this.asXModel().getCurrentController(); + public XText getXText() { + return xTextDocument.getText(); } - public XSelectionSupplier getSelectionSupplier() { - return unoQI(XSelectionSupplier.class, this.getCurrentController()); + public XTextDocument asXTextDocument() { + return xTextDocument; } - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if available, - * otherwise null - */ - private static T unoQI(Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); + public Optional asOptionalXTextDocument() { + return Optional.ofNullable(xTextDocument); } - private XDocumentProperties getDocumentProperties() { - XDocumentPropertiesSupplier supp = unoQI(XDocumentPropertiesSupplier.class, mxDoc); - return supp.getDocumentProperties(); + private static Optional getXDocumentProperties(XTextDocument doc) { + return (Optional.ofNullable(doc) + .map(e -> unoQI(XDocumentPropertiesSupplier.class, e)) + .map(e -> e.getDocumentProperties())); } - private XPropertyContainer getUserDefinedProperties() { - return this.getDocumentProperties().getUserDefinedProperties(); - } - private XPropertySet getUserDefinedPropertiesAsXPropertySet() { - return unoQI(XPropertySet.class, this.getUserDefinedProperties()); - } - - private short getRedlineDisplayType() - throws - UnknownPropertyException, - WrappedTargetException { - // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/RedlineDisplayType.html - // Constants (short) - // 0 NONE no changes are displayed. - // 1 INSERTED only inserted parts are displayed and attributed. - // 2 INSERTED_AND_REMOVED only inserted parts are displayed and attributed. - // 3 REMOVED only removed parts are displayed and attributed. - XPropertySet ps = unoQI(XPropertySet.class, mxDoc); - return (short) ps.getPropertyValue("RedlineDisplayType"); - } - - public boolean getRecordChanges() + public static boolean getRecordChanges(XTextDocument doc) throws UnknownPropertyException, WrappedTargetException { - XPropertySet ps = unoQI(XPropertySet.class, mxDoc); + XPropertySet ps = unoQI(XPropertySet.class, doc); // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Settings // "Properties of com.sun.star.text.TextDocument" if (ps == null) { @@ -170,25 +115,15 @@ public boolean getRecordChanges() return (boolean) ps.getPropertyValue("RecordChanges"); } - public void setRecordChanges(boolean value) - throws - UnknownPropertyException, - WrappedTargetException, - PropertyVetoException { - XPropertySet ps = unoQI(XPropertySet.class, mxDoc); - ps.setPropertyValue("RecordChanges", value); + private static XRedlinesSupplier getRedlinesSupplier(XTextDocument doc) { + return unoQI(XRedlinesSupplier.class, doc); } - private XRedlinesSupplier getRedlinesSupplier() { - return unoQI(XRedlinesSupplier.class, mxDoc); - } - - public int countRedlines() { - XRedlinesSupplier rs = getRedlinesSupplier(); + public static int countRedlines(XTextDocument doc) { + XRedlinesSupplier rs = getRedlinesSupplier(doc); XEnumerationAccess ea = rs.getRedlines(); - XEnumeration e = ea.createEnumeration(); // null for empty + XEnumeration e = ea.createEnumeration(); if (e == null) { - // System.out.println("countRedLines: no redlines found"); return 0; } else { int count = 0; @@ -200,163 +135,18 @@ public int countRedlines() { break; } } - // System.out.println(String.format("countRedLines: found %d redlines", count)); return count; } } - private void printRedlines() { - // https://docs.libreoffice.org/sw/html/unoredline_8cxx_source.html#l00290 - // http://www.openoffice.org/api/docs/common/ref/com/sun/star/text/RedlinePortion.html - XRedlinesSupplier rs = getRedlinesSupplier(); - XEnumerationAccess ea = rs.getRedlines(); - XEnumeration e = ea.createEnumeration(); // null for empty - if (e == null) { - System.out.println("printRedLines: no redlines found"); - return; - } else { - int count = 0; - while (e.hasMoreElements()) { - try { - count++; - Object o = e.nextElement(); - XPropertySet ps = unoQI(XPropertySet.class, o); - if (ps == null) { - String msg = String.format("printRedLines: %d XPropertySet is null", count); - System.out.println(msg); - continue; - } - XPropertySetInfo psi = ps.getPropertySetInfo(); - if (psi == null) { - String msg = String.format("printRedLines: %d XPropertySetInfo is null", count); - System.out.println(msg); - } else { - String msg = String.format("printRedLines: %d XPropertySetInfo is OK", count); - System.out.println(msg); - int propertyCount = 0; - for (Property p : psi.getProperties()) { - propertyCount++; - String m = String.format("printRedLines: %d/%d '%s' %d %s", - count, - propertyCount, - p.Name, - p.Handle, - p.Type); - switch (p.Name) { - case "RedlineEnd": - // printRedLines: 1/1 'RedlineEnd' 0 Type[com.sun.star.uno.XInterface] - // UNO_NAME_REDLINE_END "RedlineEnd" - case "RedlineStart": - // printRedLines: 1/12 'RedlineStart' 0 Type[com.sun.star.uno.XInterface] - // UNO_NAME_REDLINE_START "RedlineStart" - XInterface xi = (XInterface) ps.getPropertyValue(p.Name); - // printServiceInfo(xi); - //*** xserviceinfo - // object is OK - // xserviceinfo is OK - // .getImplementationName: "SwXTextRange" - // .getSupportedServiceNames: - // "com.sun.star.text.TextRange" - // "com.sun.star.style.CharacterProperties" - // "com.sun.star.style.CharacterPropertiesAsian" - // "com.sun.star.style.CharacterPropertiesComplex" - // "com.sun.star.style.ParagraphProperties" - // "com.sun.star.style.ParagraphPropertiesAsian" - // "com.sun.star.style.ParagraphPropertiesComplex" - break; - case "RedlineAuthor": - // printRedLines: 1/2 'RedlineAuthor' 0 Type[string] - // UNO_NAME_REDLINE_AUTHOR "RedlineAuthor" - case "RedlineIdentifier": - // printRedLines: 1/3 'RedlineIdentifier' 0 Type[string] - // UNO_NAME_REDLINE_IDENTIFIER "RedlineIdentifier" - case "RedlineDescription": - // printRedLines: 1/5 'RedlineDescription' 0 Type[string] - // UNO_NAME_REDLINE_DESCRIPTION "RedlineDescription" - case "RedlineType": - // printRedLines: 1/7 'RedlineType' 0 Type[string] - // UNO_NAME_REDLINE_TYPE "RedlineType" - case "RedlineComment": - // printRedLines: 1/8 'RedlineComment' 0 Type[string] - // UNO_NAME_REDLINE_COMMENT "RedlineComment" - m += String.format(" '%s'", (String) ps.getPropertyValue(p.Name)); - break; - case "RedlineDateTime": - // printRedLines: 1/4 'RedlineDateTime' 0 Type[com.sun.star.util.DateTime] - // UNO_NAME_REDLINE_DATE_TIME "RedlineDateTime" - // OO http://www.openoffice.org/api/docs/common/ref/com/sun/star/util/DateTime.html - // LO https://api.libreoffice.org/docs/idl/ref/structcom_1_1sun_1_1star_1_1util_1_1DateTime.html - DateTime dt = (DateTime) ps.getPropertyValue(p.Name); - String s1 = String.format("%04d-%02d-%02d %02d:%02d:%02d", - dt.Year, dt.Month, dt.Day, - dt.Hours, dt.Minutes, dt.Seconds - /* OO: dt.HundredthSeconds */ - /* LO: dt.NanoSeconds (but zero anyway) */); - m += String.format(" '%s'", s1); - break; - - case "IsInHeaderFooter": - // printRedLines: 1/9 'IsInHeaderFooter' 0 Type[boolean] - // UNO_NAME_IS_IN_HEADER_FOOTER "IsInHeaderFooter" - case "MergeLastPara": - // printRedLines: 1/11 'MergeLastPara' 0 Type[boolean] - // UNO_NAME_MERGE_LAST_PARA "MergeLastPara" - boolean b = (boolean) ps.getPropertyValue(p.Name); - m += String.format(" '%s'", b); - break; - - case "RedlineText": - // printRedLines: 1/10 'RedlineText' 0 Type[com.sun.star.text.XText] - // UNO_NAME_REDLINE_TEXT "RedlineText" - - // RedlineText: provides access to the text of the - // redline. This interface is only - // provided if the change is not - // visible. The visibility depends on - // the redline display options that - // are set at the documents property - // set (RedlineDisplayType). - - XText t = null; - try { - t = (XText) ps.getPropertyValue(p.Name); - String s2 = t.getString(); - m += String.format(" '%s'", s2); - } catch (java.lang.ClassCastException ex) { - m += " NotAvailable"; - } - break; - // printRedLines: 1/6 'RedlineSuccessorData' 0 Type[[]com.sun.star.beans.PropertyValue] - // UNO_NAME_REDLINE_SUCCESSOR_DATA "RedlineSuccessorData" - - // printRedLines: 1/13 'StartRedline' 22275 Type[[]com.sun.star.beans.PropertyValue] - // UNO_NAME_START_REDLINE "StartRedline" - // "contains the properties of a redline at the start of the document." - - // printRedLines: 1/14 'EndRedline' 22276 Type[[]com.sun.star.beans.PropertyValue] - // UNO_NAME_END_REDLINE "EndRedline" - } - System.out.println(m); - } - } - - } catch (NoSuchElementException - | WrappedTargetException - | UnknownPropertyException ex) { - break; - } - } - System.out.println(String.format("printRedLines: found %d redlines", count)); - return; - } - } - - private Optional getStyleFromFamily(String familyName, String styleName) + private static Optional getStyleFromFamily(XTextDocument doc, + String familyName, + String styleName) throws NoSuchElementException, WrappedTargetException { - XStyleFamiliesSupplier fss = unoQI(XStyleFamiliesSupplier.class, mxDoc); + XStyleFamiliesSupplier fss = unoQI(XStyleFamiliesSupplier.class, doc); XNameAccess fs = unoQI(XNameAccess.class, fss.getStyleFamilies()); XNameContainer xFamily = unoQI(XNameContainer.class, fs.getByName(familyName)); @@ -369,56 +159,58 @@ private Optional getStyleFromFamily(String familyName, String styleName) } } - private Optional getParagraphStyle(String styleName) + private static Optional getParagraphStyle(XTextDocument doc, String styleName) throws NoSuchElementException, WrappedTargetException { - return getStyleFromFamily("ParagraphStyles", styleName); + return getStyleFromFamily(doc, "ParagraphStyles", styleName); } - private Optional getCharacterStyle(String styleName) + private static Optional getCharacterStyle(XTextDocument doc, String styleName) throws NoSuchElementException, WrappedTargetException { - return getStyleFromFamily("CharacterStyles", styleName); + return getStyleFromFamily(doc, "CharacterStyles", styleName); } - public Optional getInternalNameOfParagraphStyle(String name) + public static Optional getInternalNameOfParagraphStyle(XTextDocument doc, String name) throws NoSuchElementException, WrappedTargetException { - return (getParagraphStyle(name) + return (getParagraphStyle(doc, name) .map(e -> e.getName())); } - public Optional getInternalNameOfCharacterStyle(String name) + public static Optional getInternalNameOfCharacterStyle(XTextDocument doc, String name) throws NoSuchElementException, WrappedTargetException { - return (getCharacterStyle(name) + return (getCharacterStyle(doc, name) .map(e -> e.getName())); } - /** - * @param o An uno object, hopefully implementing XServiceInfo - */ - public static void printServiceInfo(Object o) { - XServiceInfo xserviceinfo = unoQI(XServiceInfo.class, o); - System.out.printf("*** xserviceinfo%n"); - System.out.printf(" object is %s%n", o == null ? "null" : "OK"); - System.out.printf(" xserviceinfo is %s%n", xserviceinfo == null ? "null" : "OK"); - if (xserviceinfo != null) { - System.out.printf(" .getImplementationName: \"%s\"%n", - xserviceinfo.getImplementationName()); - System.out.printf(" .getSupportedServiceNames:%n"); - for (String s : xserviceinfo.getSupportedServiceNames()) { - System.out.printf(" \"%s\"%n", s); - } - } + private static Optional getSelectionSupplier(XTextDocument doc) { + return (Optional.ofNullable(doc) + .map(e -> getCurrentController(e)) + .flatMap(e -> optUnoQI(XSelectionSupplier.class, e))); + } + + private static Optional asXModel(XTextDocument doc) { + return optUnoQI(XModel.class, doc); + } + + private static Optional getCurrentController(XTextDocument doc) { + return asXModel(doc).map(e -> e.getCurrentController()); } /** - * @return may be null, or some type supporting XServiceInfo + * @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. + * + * One way to do that is accessing its XServiceInfo interface. * * Experiments using printServiceInfo with cursor in various * positions in the document: @@ -427,11 +219,11 @@ public static void printServiceInfo(Object o) { * *** xserviceinfo.getImplementationName: "SwXTextRanges" * "com.sun.star.text.TextRanges" * - * With cursor somewehe else in text: + * With cursor somewhere else in text: * *** xserviceinfo.getImplementationName: "SwXTextRanges" * "com.sun.star.text.TextRanges" * - * With cursor in comment (AKA annotation): + * With cursor in comment (also known as "annotation"): * *** XSelectionSupplier is OK * *** Object initialSelection is null * *** xserviceinfo is null @@ -453,34 +245,11 @@ public static void printServiceInfo(Object o) { * "com.sun.star.text.TextContent" * "com.sun.star.document.LinkTarget" * "com.sun.star.text.TextGraphicObject" - * - */ - private Object getSelectionAsObject() { - XSelectionSupplier xss = this.getSelectionSupplier(); - return xss.getSelection(); - } - - /** - * So far it seems the first thing we have to do - * with a selection is to decide what do we have. - * - * One way to do that is accessing its XServiceInfo interface. - * - * Note: may return null. */ - public Optional getSelectionAsServiceInfo() { - Object o = getSelectionAsObject(); - if (o == null) { - return Optional.empty(); - } - XServiceInfo xserviceinfo = unoQI(XServiceInfo.class, o); - if (xserviceinfo == null) { - // I do not know if this is possible: make a note - // if it is. - LOGGER.warn("DocumentConnection.getSelectionAsObject:" - + " XServiceInfo is null when Object is not"); - } - return Optional.ofNullable(xserviceinfo); + public static Optional getSelectionAsXServiceInfo(XTextDocument doc) { + return (getSelectionSupplier(doc) + .flatMap(e -> Optional.ofNullable(e.getSelection())) + .flatMap(e -> optUnoQI(XServiceInfo.class, e))); } /** @@ -491,12 +260,15 @@ public Optional getSelectionAsServiceInfo() { * usually OK. It also accepted * {@code XTextRange newSelection = documentConnection.xText.getStart();} * - * @return Apparently always returns true. - * */ - public boolean select(Object newSelection) { - XSelectionSupplier xss = this.getSelectionSupplier(); - return xss.select(newSelection); + public static void select(XTextDocument doc, Object newSelection) { + getSelectionSupplier(doc).ifPresent(e -> e.select(newSelection)); + } + + public static Optional getXUndoManager(XTextDocument doc) { + // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html + return (optUnoQI(XUndoManagerSupplier.class, doc) + .map(e -> e.getUndoManager())); } /** @@ -504,20 +276,22 @@ public boolean select(Object newSelection) { * leaveUndoContext, otherwise, the document's undo stack is * left in an inconsistent state. */ - public void enterUndoContext(String title) { - XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); - XUndoManager um = mxUndoManagerSupplier.getUndoManager(); - // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html - um.enterUndoContext(title); + public static void enterUndoContext(XTextDocument doc, String title) { + Optional um = getXUndoManager(doc); + if (um.isPresent()) { + um.get().enterUndoContext(title); + } } - public void leaveUndoContext() - throws - InvalidStateException { - XUndoManagerSupplier mxUndoManagerSupplier = unoQI(XUndoManagerSupplier.class, mxDoc); - XUndoManager um = mxUndoManagerSupplier.getUndoManager(); - // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html - um.leaveUndoContext(); + public static void leaveUndoContext(XTextDocument doc) { + Optional um = getXUndoManager(doc); + if (um.isPresent()) { + try { + um.get().leaveUndoContext(); + } catch (InvalidStateException ex) { + throw new RuntimeException("leaveUndoContext reported InvalidStateException"); + } + } } /** @@ -530,53 +304,56 @@ public void leaveUndoContext() * While there is at least one lock remaining, some * notifications for display updates are not broadcasted. */ - public void lockControllers() { - XModel mo = this.asXModel(); - mo.lockControllers(); + public static void lockControllers(XTextDocument doc) { + XModel model = asXModel(doc).orElseThrow(RuntimeException::new); + model.lockControllers(); } - public void unlockControllers() { - XModel mo = this.asXModel(); - mo.unlockControllers(); + public static void unlockControllers(XTextDocument doc) { + XModel model = asXModel(doc).orElseThrow(RuntimeException::new); + model.unlockControllers(); } - public boolean hasControllersLocked() { - XModel mo = this.asXModel(); - return mo.hasControllersLocked(); + public static boolean hasControllersLocked(XTextDocument doc) { + XModel model = asXModel(doc).orElseThrow(RuntimeException::new); + return model.hasControllersLocked(); } /** * @return True if we cannot reach the current document. */ - public boolean documentConnectionMissing() { + public static boolean documentConnectionMissing(XTextDocument doc) { boolean missing = false; - // These are set by DocumentConnection constructor. - if (null == this.mxDoc) { + if (doc == null) { missing = true; } // Attempt to check document is really available if (!missing) { try { - getReferenceMarks(); + getReferenceMarks(doc); } catch (NoDocumentException ex) { missing = true; } } - - if (missing) { - // release it - this.mxDoc = null; - } return missing; } - public static Object getProperty(Object o, String property) - throws UnknownPropertyException, WrappedTargetException { - XPropertySet props = UnoRuntime.queryInterface( - XPropertySet.class, o); - return props.getPropertyValue(property); + public static Optional asXPropertySet(XFrame frame) { + return optUnoQI(XPropertySet.class, frame); + } + + public static Optional XPropertySetGetProperty(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(); + } } /** @@ -589,34 +366,59 @@ public static Optional getDocumentTitle(XTextDocument doc) { return Optional.empty(); } + XFrame frame = doc.getCurrentController().getFrame(); + Optional propertySet = asXPropertySet(frame); + if (propertySet.isEmpty()) { + return Optional.empty(); + } + try { - XFrame frame = doc.getCurrentController().getFrame(); - Object frameTitleObj = getProperty(frame, "Title"); - String frameTitleString = String.valueOf(frameTitleObj); - return Optional.of(frameTitleString); - } catch (UnknownPropertyException | WrappedTargetException e) { + Optional frameTitleObj = XPropertySetGetProperty(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(); } } - /** - * Get the title of the connected document. - */ - public Optional getDocumentTitle() { - return DocumentConnection.getDocumentTitle(this.mxDoc); + public static Optional + getUserDefinedPropertiesAsXPropertyContainer(XTextDocument doc) { + return getXDocumentProperties(doc).map(e -> e.getUserDefinedProperties()); } - public List getCustomPropertyNames() { + public static Optional asXPropertySet(XPropertyContainer xPropertyContainer) { + return optUnoQI(XPropertySet.class, xPropertyContainer); + } - XPropertySet ps = getUserDefinedPropertiesAsXPropertySet(); - XPropertySetInfo psi = ps.getPropertySetInfo(); + public static List getPropertyNames(Property[] properties) { + Objects.requireNonNull(properties); + return (Arrays.stream(properties) + .map(p -> p.Name) + .collect(Collectors.toList())); + } - List names = new ArrayList<>(); - for (Property p : psi.getProperties()) { - names.add(p.Name); - } - return names; + public static List getPropertyNames(XPropertySetInfo propertySetInfo) { + return getPropertyNames(propertySetInfo.getProperties()); + } + + public static List getPropertyNames(XPropertySet propertySet) { + return getPropertyNames(propertySet.getPropertySetInfo()); + } + + public static List getPropertyNames(XPropertyContainer propertyContainer) { + return (asXPropertySet(propertyContainer) + .map(DocumentConnection::getPropertyNames) + .orElse(new ArrayList<>())); + } + + public static List getUserDefinedPropertiesNames(XTextDocument doc) { + return (getUserDefinedPropertiesAsXPropertyContainer(doc) + .map(e -> getPropertyNames(e)) + .orElse(new ArrayList<>())); } /** @@ -629,73 +431,97 @@ public List getCustomPropertyNames() { * individual citation. In particular, the `pageInfo` part. * */ - public Optional getCustomProperty(String property) + public static Optional getUserDefinedStringPropertyValue(XTextDocument doc, String property) throws WrappedTargetException { - XPropertySet ps = getUserDefinedPropertiesAsXPropertySet(); - XPropertySetInfo psi = ps.getPropertySetInfo(); - - if (psi.hasPropertyByName(property)) { - try { - String v = ps.getPropertyValue(property).toString(); - return Optional.ofNullable(v); - } catch (UnknownPropertyException ex) { - throw new RuntimeException("getCustomProperty: caught UnknownPropertyException"); - } + Optional ps = (getUserDefinedPropertiesAsXPropertyContainer(doc) + .flatMap(DocumentConnection::asXPropertySet)); + if (ps.isEmpty()) { + throw new RuntimeException("getting UserDefinedProperties as XPropertySet failed"); + } + try { + String v = ps.get().getPropertyValue(property).toString(); + return Optional.ofNullable(v); + } catch (UnknownPropertyException ex) { + return Optional.empty(); } - return Optional.empty(); } /** * @param property Name of a custom document property in the - * current document. + * current document. Created if does not exist yet. * * @param value The value to be stored. */ - public void setCustomProperty(String property, String value) + public static void setOrCreateUserDefinedStringPropertyValue(XTextDocument doc, + String property, + String value) throws NotRemoveableException, PropertyExistException, IllegalTypeException, - IllegalArgumentException { + IllegalArgumentException, + PropertyVetoException, + WrappedTargetException { - XPropertySet ps = getUserDefinedPropertiesAsXPropertySet(); - XPropertySetInfo psi = ps.getPropertySetInfo(); + Objects.requireNonNull(property); + Objects.requireNonNull(value); - if (psi.hasPropertyByName(property)) { - this.removeCustomProperty(property); + Optional xPropertyContainer = + getUserDefinedPropertiesAsXPropertyContainer(doc); + + if (xPropertyContainer.isEmpty()) { + throw new RuntimeException("getUserDefinedPropertiesAsXPropertyContainer failed"); + } + + Optional ps = xPropertyContainer.flatMap(DocumentConnection::asXPropertySet); + if (ps.isEmpty()) { + throw new RuntimeException("asXPropertySet failed"); } - if (value != null) { - this.getUserDefinedProperties() - .addProperty(property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value)); + XPropertySetInfo psi = ps.get().getPropertySetInfo(); + + if (psi.hasPropertyByName(property)) { + try { + ps.get().setPropertyValue(property, value); + return; + } catch (UnknownPropertyException ex) { + // fall through to addProperty + } } + + xPropertyContainer.get().addProperty(property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value)); } /** * @param property Name of a custom document property in the * current document. */ - public void removeCustomProperty(String property) + public static void removeUserDefinedProperty(XTextDocument doc, String property) throws NotRemoveableException, PropertyExistException, IllegalTypeException, IllegalArgumentException { - XPropertySet ps = getUserDefinedPropertiesAsXPropertySet(); - XPropertySetInfo psi = ps.getPropertySetInfo(); + Objects.requireNonNull(property); - if (psi.hasPropertyByName(property)) { - try { - this.getUserDefinedProperties().removeProperty(property); - } catch (UnknownPropertyException ex) { - throw new RuntimeException("removeCustomProperty caught UnknownPropertyException" - + " (should be impossible)"); - } + Optional xPropertyContainer = + getUserDefinedPropertiesAsXPropertyContainer(doc); + + if (xPropertyContainer.isEmpty()) { + throw new RuntimeException("getUserDefinedPropertiesAsXPropertyContainer failed"); + } + + try { + xPropertyContainer.get().removeProperty(property); + } catch (UnknownPropertyException ex) { + LOGGER.warn(String.format("removeUserDefinedProperty(%s)" + + " This property was not there to remove", + property)); } } @@ -706,12 +532,12 @@ public void removeCustomProperty(String property) * we have a working connection. * */ - public XNameAccess getReferenceMarks() + public static XNameAccess getReferenceMarks(XTextDocument doc) throws NoDocumentException { - XReferenceMarksSupplier supplier = unoQI(XReferenceMarksSupplier.class, - this.mxDoc); + XReferenceMarksSupplier supplier = unoQI(XReferenceMarksSupplier.class, doc); + try { return supplier.getReferenceMarks(); } catch (DisposedException ex) { @@ -722,21 +548,31 @@ public XNameAccess getReferenceMarks() /** * Provides access to bookmarks by name. */ - public XNameAccess getBookmarks() { + public static XNameAccess getBookmarks(XTextDocument doc) + throws + NoDocumentException { - XBookmarksSupplier supplier = unoQI(XBookmarksSupplier.class, - this.mxDoc); - return supplier.getBookmarks(); + XBookmarksSupplier supplier = unoQI(XBookmarksSupplier.class, doc); + try { + return supplier.getBookmarks(); + } catch (DisposedException ex) { + throw new NoDocumentException("getBookmarks failed with" + ex); + } } /** * @return An XNameAccess to find sections by name. */ - public XNameAccess getTextSections() { + public static XNameAccess getTextSections(XTextDocument doc) + throws + NoDocumentException { - XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, - this.mxDoc); - return supplier.getTextSections(); + XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, doc); + try { + return supplier.getTextSections(); + } catch (DisposedException ex) { + throw new NoDocumentException("getTextSections failed with" + ex); + } } /** @@ -744,10 +580,10 @@ public XNameAccess getTextSections() { * * Empty list for nothing. */ - public List getReferenceMarkNames() + public static List getReferenceMarkNames(XTextDocument doc) throws NoDocumentException { - XNameAccess nameAccess = getReferenceMarks(); + XNameAccess nameAccess = getReferenceMarks(doc); String[] names = nameAccess.getElementNames(); if (names == null) { return new ArrayList<>(); @@ -755,18 +591,6 @@ public List getReferenceMarkNames() return Arrays.asList(names); } - /** - * Get the {@cod XTextContent} interface. - * - * @return null for null and for no-such-interface - */ - public static XTextContent asTextContent(Object mark) { - if (mark == null) { - return null; - } - return unoQI(XTextContent.class, mark); - } - /** * @return null if name not found, or if the result does not * support the XTextContent interface. @@ -775,19 +599,9 @@ public static Optional nameAccessGetTextContentByName(XNameAccess String name) throws WrappedTargetException { - - if (!nameAccess.hasByName(name)) { - return Optional.empty(); - } - try { - Object referenceMark = nameAccess.getByName(name); - return Optional.ofNullable(asTextContent(referenceMark)); + return optUnoQI(XTextContent.class, nameAccess.getByName(name)); } catch (NoSuchElementException ex) { - String msg = String.format("nameAccessGetTextContentByName got NoSuchElementException" - + " for '%s'", - name); - LOGGER.warn(msg); return Optional.empty(); } } @@ -798,13 +612,15 @@ public static Optional nameAccessGetTextContentByName(XNameAccess * @return null if mark is null, otherwise cursor. * */ - public static XTextCursor getTextCursorOfTextContent(XTextContent mark) { + public static Optional getTextCursorOfTextContent(XTextContent mark) { if (mark == null) { - return null; + return Optional.empty(); } XTextRange markAnchor = mark.getAnchor(); - return (markAnchor.getText() - .createTextCursorByRange(markAnchor)); + if (markAnchor == null) { + return Optional.empty(); + } + return Optional.of(markAnchor.getText().createTextCursorByRange(markAnchor)); } /** @@ -812,20 +628,20 @@ public static XTextCursor getTextCursorOfTextContent(XTextContent mark) { * * Removes both the text and the mark itself. */ - public void removeReferenceMark(String name) + public static void removeReferenceMark(XTextDocument doc, String name) throws WrappedTargetException, NoDocumentException, NoSuchElementException { - XNameAccess xReferenceMarks = this.getReferenceMarks(); + XNameAccess xReferenceMarks = getReferenceMarks(doc); if (xReferenceMarks.hasByName(name)) { Optional mark = nameAccessGetTextContentByName(xReferenceMarks, name); if (mark.isEmpty()) { return; } - this.getText().removeTextContent(mark.get()); + doc.getText().removeTextContent(mark.get()); } } @@ -833,10 +649,10 @@ public void removeReferenceMark(String name) * Get the cursor positioned by the user. * */ - public XTextViewCursor getViewCursor() { - XController co = this.getCurrentController(); - XTextViewCursorSupplier xViewCursorSupplier = unoQI(XTextViewCursorSupplier.class, co); - return xViewCursorSupplier.getViewCursor(); + public static Optional getViewCursor(XTextDocument doc) { + return (getCurrentController(doc) + .flatMap(e -> optUnoQI(XTextViewCursorSupplier.class, e)) + .map(e -> e.getViewCursor())); } /** @@ -845,11 +661,12 @@ public XTextViewCursor getViewCursor() { * @param name The name of the bookmark to find. * @return The XTextRange for the bookmark, or null. */ - public Optional getBookmarkRange(String name) + public static Optional getBookmarkRange(XTextDocument doc, String name) throws - WrappedTargetException { + WrappedTargetException, + NoDocumentException { - XNameAccess nameAccess = this.getBookmarks(); + XNameAccess nameAccess = getBookmarks(doc); return (nameAccessGetTextContentByName(nameAccess, name) .map(e -> e.getAnchor())); } @@ -857,24 +674,23 @@ public Optional getBookmarkRange(String name) /** * @return reference mark as XTextContent, Optional.empty if not found. */ - public Optional getReferenceMarkAsTextContent(String name) + public static Optional getReferenceMarkAsTextContent(XTextDocument doc, String name) throws NoDocumentException, WrappedTargetException { - XNameAccess nameAccess = this.getReferenceMarks(); + XNameAccess nameAccess = getReferenceMarks(doc); return nameAccessGetTextContentByName(nameAccess, name); } /** * XTextRange for the named reference mark, Optional.empty if not found. */ - public Optional getReferenceMarkRange(String name) + public static Optional getReferenceMarkRange(XTextDocument doc, String name) throws NoDocumentException, WrappedTargetException { - - return (getReferenceMarkAsTextContent(name) + return (getReferenceMarkAsTextContent(doc, name) .map(e -> e.getAnchor())); } @@ -907,16 +723,19 @@ public Optional getReferenceMarkRange(String name) * @return The XNamed interface, in case we need to check the actual name. * */ - private XNamed insertNamedTextContent(String service, - String name, - XTextRange range, - boolean absorb) + private static XNamed insertNamedTextContent(XTextDocument doc, + String service, + String name, + XTextRange range, + boolean absorb) throws CreationException { + XMultiServiceFactory msf = unoQI(XMultiServiceFactory.class, doc); + Object xObject; try { - xObject = this.asXMultiServiceFactory().createInstance(service); + xObject = msf.createInstance(service); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -948,13 +767,14 @@ private XNamed insertNamedTextContent(String service, * @param range Cursor marking the location or range for * the reference mark. */ - public XNamed insertReferenceMark(String name, - XTextRange range, - boolean absorb) + public static XNamed insertReferenceMark(XTextDocument doc, + String name, + XTextRange range, + boolean absorb) throws CreationException { - - return insertNamedTextContent("com.sun.star.text.ReferenceMark", + return insertNamedTextContent(doc, + "com.sun.star.text.ReferenceMark", name, range, absorb); @@ -977,14 +797,16 @@ public XNamed insertReferenceMark(String name, * caller, because its name may differ from the one * requested. */ - public XNamed insertBookmark(String name, - XTextRange range, - boolean absorb) + public static XNamed insertBookmark(XTextDocument doc, + String name, + XTextRange range, + boolean absorb) throws IllegalArgumentException, CreationException { - return insertNamedTextContent("com.sun.star.text.Bookmark", + return insertNamedTextContent(doc, + "com.sun.star.text.Bookmark", name, range, absorb); @@ -997,24 +819,24 @@ public XNamed insertBookmark(String name, * May need a documentConnection.refresh() after, to update * the text shown. */ - public void insertReferenceToPageNumberOfReferenceMark(String referenceMarkName, - XTextRange cursor) + public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, + String referenceMarkName, + XTextRange cursor) throws CreationException, UnknownPropertyException, PropertyVetoException, WrappedTargetException { - DocumentConnection documentConnection = this; // based on: https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Reference_Marks - + XMultiServiceFactory msf = unoQI(XMultiServiceFactory.class, doc); // 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 = (XPropertySet) unoQI(XPropertySet.class, - this.asXMultiServiceFactory().createInstance(name)); + msf.createInstance(name)); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -1035,15 +857,15 @@ public void insertReferenceToPageNumberOfReferenceMark(String referenceMarkName, XTextContent xRefContent = (XTextContent) unoQI(XTextContent.class, xFieldProps); // Insert the text field - this.getText().insertTextContent(cursor.getEnd(), xRefContent, false); + doc.getText().insertTextContent(cursor.getEnd(), xRefContent, false); } /** * Update TextFields, etc. */ - public void refresh() { + public static void refresh(XTextDocument doc) { // Refresh the document - XRefreshable xRefresh = unoQI(XRefreshable.class, this.mxDoc); + XRefreshable xRefresh = unoQI(XRefreshable.class, doc); xRefresh.refresh(); } @@ -1058,14 +880,16 @@ public void refresh() { * LibreOffice (6.4.6.2) creates a section with a name different from * what we requested, in "Section {number}" format. */ - public XNamed insertTextSection(String name, - XTextRange range, - boolean absorb) + public static XNamed insertTextSection(XTextDocument doc, + String name, + XTextRange range, + boolean absorb) throws IllegalArgumentException, CreationException { - return insertNamedTextContent("com.sun.star.text.TextSection", + return insertNamedTextContent(doc, + "com.sun.star.text.TextSection", name, range, absorb); @@ -1074,13 +898,13 @@ public XNamed insertTextSection(String name, /** * Get an XTextSection by name. */ - public Optional getTextSectionByName(String name) + public static Optional getTextSectionByName(XTextDocument doc, + String name) throws NoSuchElementException, WrappedTargetException { - XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, - this.mxDoc); + XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, doc); return Optional.ofNullable((XTextSection) ((Any) supplier.getTextSections().getByName(name)) @@ -1104,49 +928,11 @@ public static Optional getFootnoteMarkRange(XTextRange original) { return Optional.empty(); } - /** - * Apply a character style to a range of text selected by a - * cursor. - * - * @param position The range to apply to. - * @param charStyle Name of the character style as known by Openoffice. - */ - public static void setCharStyle(XTextCursor position, - String charStyle) - throws - UndefinedCharacterFormatException { - - XPropertySet xCursorProps = unoQI(XPropertySet.class, position); - - try { - xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - // Setting the character format failed, so we throw an exception that - // will result in an error message for the user: - throw new UndefinedCharacterFormatException(charStyle); - } - } - - public static String getCharStyle(XTextCursor position) - throws - UnknownPropertyException, - WrappedTargetException { - - XPropertySet xCursorProps = unoQI(XPropertySet.class, position); - return (String) xCursorProps.getPropertyValue(CHAR_STYLE_NAME); - } - public static void setParagraphStyle(XTextCursor cursor, String parStyle) throws UndefinedParagraphFormatException { XParagraphCursor parCursor = unoQI(XParagraphCursor.class, cursor); - - // Access the property set of the cursor, and set the currently selected text - // (which is the string we just inserted) to be bold XPropertySet props = unoQI(XPropertySet.class, parCursor); try { props.setPropertyValue(PARA_STYLE_NAME, parStyle); @@ -1158,55 +944,6 @@ public static void setParagraphStyle(XTextCursor cursor, } } - /** - * Apply direct character format "Italic" to a range of text. - * - * Ref: https://www.openoffice.org/api/docs/common/ref/com/sun/star/style/CharacterProperties.html - */ - public static void setCharFormatItalic(XTextRange textRange) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - XPropertySet xcp = unoQI(XPropertySet.class, textRange); - xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); - } - - /** - * Apply direct character format "Bold" to a range of text. - */ - public static void setCharFormatBold(XTextRange textRange) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - XPropertySet xcp = unoQI(XPropertySet.class, textRange); - xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD); - } - - /** - * Set language to [None] - * - * Note: "zxx" is an https://en.wikipedia.org/wiki/ISO_639 code for - * "No linguistic information at all" - */ - public static void setCharLocaleNone(XTextRange textRange) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - XPropertySet xcp = unoQI(XPropertySet.class, textRange); - xcp.setPropertyValue("CharLocale", new Locale("zxx", "", "")); - } - - public static Locale getCharLocale(XTextRange textRange) - throws - UnknownPropertyException, - WrappedTargetException { - XPropertySet xcp = unoQI(XPropertySet.class, textRange); - return (Locale) xcp.getPropertyValue("CharLocale"); - } - /** * Test if two XTextRange values are comparable (i.e. they share * the same getText()). @@ -1216,25 +953,6 @@ public static boolean comparableRanges(XTextRange a, return a.getText() == b.getText(); } - /** - * Test if two XTextRange values are equal. - */ - public static boolean equalRanges(XTextRange a, - XTextRange b) { - if (!comparableRanges(a, b)) { - return false; - } - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - a.getText()); - if (compare.compareRegionStarts(a, b) != 0) { - return false; - } - if (compare.compareRegionEnds(a, b) != 0) { - return false; - } - return true; - } - /** * @return follows OO conventions, the opposite of java conventions: * 1 if (a < b), 0 if same start, (-1) if (b < a) @@ -1282,4 +1000,19 @@ public static int javaCompareRegionEnds(XTextRange a, XTextRange b) { return (-1) * ooCompareRegionEnds(a, b); } + + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if available, + * otherwise null + */ + private static T unoQI(Class zInterface, Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + + private static Optional optUnoQI(Class zInterface, Object object) { + return Optional.ofNullable(UnoRuntime.queryInterface(zInterface, object)); + } + } // end DocumentConnection diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index b3383f0ab5a..d8b1cddfa32 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -35,6 +35,7 @@ import com.sun.star.style.CaseMap; import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; import com.sun.star.uno.UnoRuntime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -510,6 +511,8 @@ public static void write(DocumentConnection documentConnection, NoSuchElementException, CreationException { + XTextDocument doc = documentConnection.asXTextDocument(); + final boolean useSetString = true; String lText = OOFormattedText.toString(ootext); @@ -619,8 +622,8 @@ public static void write(DocumentConnection documentConnection, String value = kv.getValue(); switch (key) { case "target": - documentConnection - .insertReferenceToPageNumberOfReferenceMark(value, cursor); + DocumentConnection + .insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); break; default: LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java index c0e5f18ac6a..be52e392882 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java @@ -34,6 +34,7 @@ import com.sun.star.style.CaseMap; import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; import com.sun.star.uno.UnoRuntime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -156,6 +157,8 @@ public static void write(DocumentConnection documentConnection, NoSuchElementException, CreationException { + XTextDocument doc = documentConnection.asXTextDocument(); + String lText = OOFormattedText.toString(ootext); System.out.println(lText); @@ -252,8 +255,8 @@ public static void write(DocumentConnection documentConnection, String value = kv.getValue(); switch (key) { case "target": - documentConnection - .insertReferenceToPageNumberOfReferenceMark(value, cursor); + DocumentConnection + .insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); break; default: LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 19d11a4e3e1..a0fcb2645bd 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -21,6 +21,7 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; @@ -320,6 +321,7 @@ public CitationGroupID createCitationGroup(DocumentConnection documentConnection WrappedTargetException, NotRemoveableException, PropertyExistException, + PropertyVetoException, IllegalTypeException { CitationGroup cg = backend.createCitationGroup(documentConnection, @@ -613,9 +615,11 @@ public void applyCitationEntries(DocumentConnection documentConnection, UnknownPropertyException, NotRemoveableException, PropertyExistException, + PropertyVetoException, IllegalTypeException, IllegalArgumentException, - NoDocumentException { + NoDocumentException, + WrappedTargetException { this.backend.applyCitationEntries(documentConnection, citationEntries); } diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index f8b7ddc526a..f766908aca6 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -12,6 +12,7 @@ import com.sun.star.awt.Point; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XServiceInfo; +import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextViewCursor; import org.slf4j.Logger; @@ -145,9 +146,11 @@ public int hashCode() { NoDocumentException, JabRefException { + XTextDocument doc = documentConnection.asXTextDocument(); + final int inputSize = vses.size(); - if (documentConnection.hasControllersLocked()) { + if (DocumentConnection.hasControllersLocked(doc)) { LOGGER.warn("visualSort:" + " with ControllersLocked, viewCursor.gotoRange" + " is probably useless"); @@ -182,7 +185,7 @@ public int hashCode() { */ final boolean debugThisFun = false; - XServiceInfo initialSelection = documentConnection.getSelectionAsServiceInfo().orElse(null); + XServiceInfo initialSelection = DocumentConnection.getSelectionAsXServiceInfo(doc).orElse(null); if (initialSelection != null) { if (Arrays.stream(initialSelection.getSupportedServiceNames()) @@ -196,8 +199,8 @@ public int hashCode() { LOGGER.info("visualSort: initialSelection does not support TextRanges." + " We need to change the viewCursor."); } - XTextRange newSelection = documentConnection.getText().getStart(); - documentConnection.select(newSelection); + XTextRange newSelection = documentConnection.getXText().getStart(); + DocumentConnection.select(doc, newSelection); } } else { if (debugThisFun) { @@ -205,7 +208,7 @@ public int hashCode() { } } - XTextViewCursor viewCursor = documentConnection.getViewCursor(); + XTextViewCursor viewCursor = DocumentConnection.getViewCursor(doc).orElse(null); Objects.requireNonNull(viewCursor); try { viewCursor.getStart(); @@ -225,7 +228,7 @@ public int hashCode() { * Restore initial state of selection (and thus viewCursor) */ if (initialSelection != null) { - documentConnection.select(initialSelection); + DocumentConnection.select(doc, initialSelection); } if (positions.size() != inputSize) { diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBase.java b/src/main/java/org/jabref/logic/openoffice/StorageBase.java index ba159f91fc6..47fc12583fb 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBase.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBase.java @@ -6,6 +6,7 @@ import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; public class StorageBase { @@ -59,7 +60,7 @@ public void cleanFillCursor(DocumentConnection documentConnection) /** * Note: create is in NamedRangeManager */ - public void removeFromDocument(DocumentConnection documentConnection) + public void removeFromDocument(XTextDocument doc) throws WrappedTargetException, NoDocumentException, @@ -79,11 +80,11 @@ public NamedRange create(DocumentConnection documentConnection, throws CreationException; - public List getUsedNames(DocumentConnection documentConnection) + public List getUsedNames(XTextDocument doc) throws NoDocumentException; - public Optional getFromDocument(DocumentConnection documentConnection, + public Optional getFromDocument(XTextDocument doc, String refMarkName) throws NoDocumentException, diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index b11a1379982..fcf2c3da994 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -8,6 +8,7 @@ import com.sun.star.text.XText; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -79,6 +80,9 @@ private static void createReprInDocument(DocumentConnection documentConnection, boolean withoutBrackets) throws CreationException { + + XTextDocument doc = documentConnection.asXTextDocument(); + // The cursor we received: we push it before us. position.collapseToEnd(); @@ -104,7 +108,8 @@ private static void createReprInDocument(DocumentConnection documentConnection, bracketedContent, true); - documentConnection.insertReferenceMark(refMarkName, + DocumentConnection.insertReferenceMark(doc, + refMarkName, cursor, true /* absorb */); @@ -134,12 +139,12 @@ private static StorageBaseRefMark create(DocumentConnection documentConnection, /** * @return Optional.empty if there is no corresponding range. */ - private static Optional getFromDocument(DocumentConnection documentConnection, + private static Optional getFromDocument(XTextDocument doc, String refMarkName) throws NoDocumentException, WrappedTargetException { - return (documentConnection.getReferenceMarkRange(refMarkName) + return (DocumentConnection.getReferenceMarkRange(doc, refMarkName) .map(e -> new StorageBaseRefMark(refMarkName))); } @@ -149,12 +154,12 @@ private static Optional getFromDocument(DocumentConnection d * See: removeCitationGroups */ @Override - public void removeFromDocument(DocumentConnection documentConnection) + public void removeFromDocument(XTextDocument doc) throws WrappedTargetException, NoDocumentException, NoSuchElementException { - documentConnection.removeReferenceMark(this.getName()); + DocumentConnection.removeReferenceMark(doc, this.getName()); } @Override @@ -174,8 +179,9 @@ public Optional getMarkRange(DocumentConnection documentConnection) throws NoDocumentException, WrappedTargetException { + XTextDocument doc = documentConnection.asXTextDocument(); String name = this.getName(); - return documentConnection.getReferenceMarkRange(name); + return DocumentConnection.getReferenceMarkRange(doc, name); } /** @@ -194,11 +200,12 @@ public Optional getRawCursor(DocumentConnection documentConnection) WrappedTargetException, CreationException { + XTextDocument doc = documentConnection.asXTextDocument(); String name = this.getName(); - XTextCursor full = null; + Optional full = Optional.empty(); - Optional markAsTextContent = (documentConnection - .getReferenceMarkAsTextContent(name)); + Optional markAsTextContent = (DocumentConnection + .getReferenceMarkAsTextContent(doc, name)); if (markAsTextContent.isEmpty()) { String msg = String.format("getRawCursor: markAsTextContent(%s).isEmpty()", name); @@ -206,12 +213,12 @@ public Optional getRawCursor(DocumentConnection documentConnection) } full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent.get()); - if (full == null) { - String msg = "getRawCursor: full == null"; + if (full.isEmpty()) { + String msg = "getRawCursor: full.isEmpty()"; LOGGER.warn(msg); return Optional.empty(); } - return Optional.ofNullable(full); + return full; } /** @@ -224,6 +231,8 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) WrappedTargetException, CreationException { + XTextDocument doc = documentConnection.asXTextDocument(); + String name = this.getName(); final boolean debugThisFun = false; @@ -235,18 +244,18 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) XTextCursor full = null; String fullText = null; for (int i = 1; i <= 2; i++) { - XTextContent markAsTextContent = - documentConnection.getReferenceMarkAsTextContent(name).orElse(null); + Optional markAsTextContent = + DocumentConnection.getReferenceMarkAsTextContent(doc, name); - if (markAsTextContent == null) { + if (markAsTextContent.isEmpty()) { String msg = String.format("getFillCursor:" - + " markAsTextContent(%s) == null (attempt %d)", + + " markAsTextContent(%s).isEmpty (attempt %d)", name, i); throw new RuntimeException(msg); } - full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent); + full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent.get()).orElse(null); if (full == null) { String msg = String.format("getFillCursor: full == null (attempt %d)", i); throw new RuntimeException(msg); @@ -278,7 +287,7 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) } full.setString(""); try { - documentConnection.removeReferenceMark(name); + DocumentConnection.removeReferenceMark(doc, name); } catch (NoSuchElementException ex) { String msg = String.format("getFillCursor got NoSuchElementException" + " for '%s'", @@ -489,10 +498,10 @@ public void cleanFillCursor(DocumentConnection documentConnection) } } - private static List getUsedNames(DocumentConnection documentConnection) + private static List getUsedNames(XTextDocument doc) throws NoDocumentException { - return documentConnection.getReferenceMarkNames(); + return DocumentConnection.getReferenceMarkNames(doc); } public static class Manager implements StorageBase.NamedRangeManager { @@ -512,20 +521,20 @@ public StorageBase.NamedRange create(DocumentConnection documentConnection, } @Override - public List getUsedNames(DocumentConnection documentConnection) + public List getUsedNames(XTextDocument doc) throws NoDocumentException { - return StorageBaseRefMark.getUsedNames(documentConnection); + return StorageBaseRefMark.getUsedNames(doc); } @Override - public Optional getFromDocument(DocumentConnection documentConnection, + public Optional getFromDocument(XTextDocument doc, String refMarkName) throws NoDocumentException, WrappedTargetException { return (StorageBaseRefMark - .getFromDocument(documentConnection, refMarkName) + .getFromDocument(doc, refMarkName) .map(x -> x)); } } From d49b6ff4fa44d5055c31026cae72b4be7efff920 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 10 May 2021 13:08:11 +0200 Subject: [PATCH 0689/1068] moved setParagraphStyle to OOFormattedTextIntoOO --- .../logic/openoffice/DocumentConnection.java | 23 ------------------ .../openoffice/OOFormattedTextIntoOO.java | 24 ++++++++++++++++++- .../openoffice/OOFormattedTextIntoOOV1.java | 24 ++++++++++++++++++- 3 files changed, 46 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java index 83d973f179a..bf9b286ce37 100644 --- a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java @@ -41,7 +41,6 @@ import com.sun.star.text.ReferenceFieldSource; import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XFootnote; -import com.sun.star.text.XParagraphCursor; import com.sun.star.text.XReferenceMarksSupplier; import com.sun.star.text.XText; import com.sun.star.text.XTextContent; @@ -66,12 +65,6 @@ * Document-connection related variables. */ public class DocumentConnection { - /** https://wiki.openoffice.org/wiki/Documentation/BASIC_Guide/ - * Structure_of_Text_Documents#Character_Properties - * "CharStyleName" is an OpenOffice Property name. - */ - private static final String CHAR_STYLE_NAME = "CharStyleName"; - private static final String PARA_STYLE_NAME = "ParaStyleName"; private static final Logger LOGGER = LoggerFactory.getLogger(DocumentConnection.class); @@ -928,22 +921,6 @@ public static Optional getFootnoteMarkRange(XTextRange original) { return Optional.empty(); } - public static void setParagraphStyle(XTextCursor cursor, - String parStyle) - throws - UndefinedParagraphFormatException { - XParagraphCursor parCursor = unoQI(XParagraphCursor.class, cursor); - XPropertySet props = unoQI(XPropertySet.class, parCursor); - try { - props.setPropertyValue(PARA_STYLE_NAME, parStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - throw new UndefinedParagraphFormatException(parStyle); - } - } - /** * Test if two XTextRange values are comparable (i.e. they share * the same getText()). diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index d8b1cddfa32..4aa42488945 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -33,6 +33,7 @@ import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.style.CaseMap; +import com.sun.star.text.XParagraphCursor; import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; @@ -63,6 +64,11 @@ public class OOFormattedTextIntoOO { private static final Logger LOGGER = LoggerFactory.getLogger(OOFormattedTextIntoOO.class); + /** + * "ParaStyleName" is an OpenOffice Property name. + */ + private static final String PARA_STYLE_NAME = "ParaStyleName"; + /* * Character property names used in multiple locations below. */ @@ -601,7 +607,7 @@ public static void write(DocumentConnection documentConnection, if (value != null && !value.equals("")) { // LOGGER.warn(String.format("oo:ParaStyleName=\"%s\" found", value)); try { - DocumentConnection.setParagraphStyle(cursor, value); + setParagraphStyle(cursor, value); } catch (UndefinedParagraphFormatException ex) { LOGGER.warn(String.format("oo:ParaStyleName=\"%s\" failed with" + " UndefinedParagraphFormatException", value)); @@ -960,4 +966,20 @@ private static List> SuperScript(MyPropertyStack formatStac formatStack); } + public static void setParagraphStyle(XTextCursor cursor, + String parStyle) + throws + UndefinedParagraphFormatException { + XParagraphCursor parCursor = unoQI(XParagraphCursor.class, cursor); + XPropertySet props = unoQI(XPropertySet.class, parCursor); + try { + props.setPropertyValue(PARA_STYLE_NAME, parStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + throw new UndefinedParagraphFormatException(parStyle); + } + } + } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java index be52e392882..912a5db0713 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java @@ -32,6 +32,7 @@ import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.style.CaseMap; +import com.sun.star.text.XParagraphCursor; import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; @@ -62,6 +63,11 @@ public class OOFormattedTextIntoOOV1 { private static final Logger LOGGER = LoggerFactory.getLogger(OOFormattedTextIntoOO.class); + /** + * "ParaStyleName" is an OpenOffice Property name. + */ + private static final String PARA_STYLE_NAME = "ParaStyleName"; + /* * Character property names used in multiple locations below. */ @@ -237,7 +243,7 @@ public static void write(DocumentConnection documentConnection, //

if (value != null && !value.equals("")) { try { - DocumentConnection.setParagraphStyle(cursor, value); + setParagraphStyle(cursor, value); } catch (UndefinedParagraphFormatException ex) { // ignore silently } @@ -917,4 +923,20 @@ private static Formatter SuperScript() { return new CharEscapement(Optional.of(SUPERSCRIPT_VALUE), Optional.of(SUPERSCRIPT_HEIGHT), true); } + public static void setParagraphStyle(XTextCursor cursor, + String parStyle) + throws + UndefinedParagraphFormatException { + XParagraphCursor parCursor = unoQI(XParagraphCursor.class, cursor); + XPropertySet props = unoQI(XPropertySet.class, parCursor); + try { + props.setPropertyValue(PARA_STYLE_NAME, parStyle); + } catch (UnknownPropertyException + | PropertyVetoException + | IllegalArgumentException + | WrappedTargetException ex) { + throw new UndefinedParagraphFormatException(parStyle); + } + } + } From 0614fb205f7178262a9d18d2ee575ed8a1bef9d4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 10 May 2021 13:22:00 +0200 Subject: [PATCH 0690/1068] use XTextDocument instead of DocumentConnection instance --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 9 +++++---- .../java/org/jabref/logic/openoffice/Backend52.java | 4 ++-- .../jabref/logic/openoffice/DocumentConnection.java | 2 ++ .../logic/openoffice/OOFormattedTextIntoOO.java | 4 +--- .../logic/openoffice/OOFormattedTextIntoOOV1.java | 4 +--- .../org/jabref/logic/openoffice/OOFrontend.java | 12 +++++++----- .../org/jabref/logic/openoffice/StorageBase.java | 2 +- .../jabref/logic/openoffice/StorageBaseRefMark.java | 13 ++++++------- 8 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 81642c618e0..649babcfdc1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -231,6 +231,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti Objects.requireNonNull(cursor); Objects.requireNonNull(citationText); Objects.requireNonNull(style); + XTextDocument doc = documentConnection.asXTextDocument(); if (withText) { OOFormattedText citationText2 = OOFormat.setLocaleNone(citationText); @@ -241,7 +242,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti // inject a ZERO_WIDTH_SPACE to hold the initial character format final String ZERO_WIDTH_SPACE = "\u200b"; citationText2 = OOFormattedText.fromString(ZERO_WIDTH_SPACE + citationText2.asString()); - OOFormattedTextIntoOO.write(documentConnection, cursor, citationText2); + OOFormattedTextIntoOO.write(doc, cursor, citationText2); } else { cursor.setString(""); } @@ -785,7 +786,7 @@ private void populateBibTextSection(DocumentConnection documentConnection, bibliography, style, alwaysAddCitedOnPages); - OOFormattedTextIntoOO.write(documentConnection, cursor, bibliographyText); + OOFormattedTextIntoOO.write(doc, cursor, bibliographyText); cursor.collapseToEnd(); // remove the inital empty paragraph from the section. @@ -892,7 +893,7 @@ public void combineCiteMarkers(List databases, CitationGroup cg = fr.cgs.getCitationGroupOrThrow(cgid); XTextRange currentRange = (fr - .getMarkRange(documentConnection, cgid) + .getMarkRange(doc, cgid) .orElseThrow(RuntimeException::new)); boolean addToGroup = true; @@ -1226,7 +1227,7 @@ public void unCombineCiteMarkers(List databases, CitationGroupID cgid = names.get(pivot); CitationGroup cg = fr.cgs.getCitationGroupOrThrow(cgid); XTextRange range1 = (fr - .getMarkRange(documentConnection, cgid) + .getMarkRange(doc, cgid) .orElseThrow(RuntimeException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 2e8ab28fb72..10ca40c2033 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -386,12 +386,12 @@ public void removeCitationGroup(CitationGroup cg, DocumentConnection documentCon * */ public Optional getMarkRange(CitationGroup cg, - DocumentConnection documentConnection) + XTextDocument doc) throws NoDocumentException, WrappedTargetException { - return cg.cgRangeStorage.getMarkRange(documentConnection); + return cg.cgRangeStorage.getMarkRange(doc); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java index bf9b286ce37..155c63881c3 100644 --- a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java +++ b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java @@ -63,6 +63,8 @@ /** * Document-connection related variables. + * + * documentConnection.asXTextDocument() */ public class DocumentConnection { private static final Logger LOGGER = LoggerFactory.getLogger(DocumentConnection.class); diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index 4aa42488945..9a86935e48a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -506,7 +506,7 @@ Optional getPropertyValue(String name) { * @param position The cursor giving the insert location. Not modified. * @param ootext The marked-up text to insert. */ - public static void write(DocumentConnection documentConnection, + public static void write(XTextDocument doc, XTextCursor position, OOFormattedText ootext) throws @@ -517,8 +517,6 @@ public static void write(DocumentConnection documentConnection, NoSuchElementException, CreationException { - XTextDocument doc = documentConnection.asXTextDocument(); - final boolean useSetString = true; String lText = OOFormattedText.toString(ootext); diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java index 912a5db0713..70cee8e4222 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java @@ -152,7 +152,7 @@ private OOFormattedTextIntoOOV1() { * @param position The cursor giving the insert location. Not modified. * @param ootext The marked-up text to insert. */ - public static void write(DocumentConnection documentConnection, + public static void write(XTextDocument doc, XTextCursor position, OOFormattedText ootext) throws @@ -163,8 +163,6 @@ public static void write(DocumentConnection documentConnection, NoSuchElementException, CreationException { - XTextDocument doc = documentConnection.asXTextDocument(); - String lText = OOFormattedText.toString(ootext); System.out.println(lText); diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index a0fcb2645bd..0ddc985590e 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -26,6 +26,7 @@ import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -111,12 +112,13 @@ public Optional healthReport(DocumentConnection documentConnection) NoDocumentException, WrappedTargetException { + XTextDocument doc = documentConnection.asXTextDocument(); List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); List vses = new ArrayList<>(); for (CitationGroupID cgid : cgids) { XTextRange range = (this - .getMarkRange(documentConnection, cgid) + .getMarkRange(doc, cgid) .orElseThrow(RuntimeException::new)); vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); } @@ -387,14 +389,13 @@ public void removeCitationGroups(List xcgs, DocumentConnection do * @return Null if the reference mark is missing. * */ - public Optional getMarkRange(DocumentConnection documentConnection, + public Optional getMarkRange(XTextDocument doc, CitationGroupID cgid) throws NoDocumentException, WrappedTargetException { - CitationGroup cg = this.cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return backend.getMarkRange(cg, documentConnection); + return backend.getMarkRange(cg, doc); } /** @@ -451,12 +452,13 @@ public List citationRanges(DocumentConnection documentConn NoDocumentException, WrappedTargetException { + XTextDocument doc = documentConnection.asXTextDocument(); List xs = new ArrayList<>(cgs.numberOfCitationGroups()); List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); for (CitationGroupID cgid : cgids) { - XTextRange r = this.getMarkRange(documentConnection, cgid).orElseThrow(RuntimeException::new); + XTextRange r = this.getMarkRange(doc, cgid).orElseThrow(RuntimeException::new); CitationGroup cg = cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); String name = cg.cgRangeStorage.getName(); xs.add(new RangeForOverlapCheck(r, diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBase.java b/src/main/java/org/jabref/logic/openoffice/StorageBase.java index 47fc12583fb..c9d8e1a8e5d 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBase.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBase.java @@ -20,7 +20,7 @@ interface HasTextRange { /** * @return Optional.empty if the mark is missing from the document. */ - public Optional getMarkRange(DocumentConnection documentConnection) + public Optional getMarkRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException; diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index fcf2c3da994..053aa37c402 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -73,7 +73,7 @@ private static XTextCursor safeInsertSpacesBetweenReferenceMarks(XTextRange posi return cursor; } - private static void createReprInDocument(DocumentConnection documentConnection, + private static void createReprInDocument(XTextDocument doc, String refMarkName, XTextCursor position, boolean insertSpaceAfter, @@ -81,8 +81,6 @@ private static void createReprInDocument(DocumentConnection documentConnection, throws CreationException { - XTextDocument doc = documentConnection.asXTextDocument(); - // The cursor we received: we push it before us. position.collapseToEnd(); @@ -128,7 +126,9 @@ private static StorageBaseRefMark create(DocumentConnection documentConnection, boolean withoutBrackets) throws CreationException { - createReprInDocument(documentConnection, + XTextDocument doc = documentConnection.asXTextDocument(); + + createReprInDocument(doc, refMarkName, position, insertSpaceAfter, @@ -175,11 +175,10 @@ public String getName() { * See: getReferenceMarkRange */ @Override - public Optional getMarkRange(DocumentConnection documentConnection) + public Optional getMarkRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - XTextDocument doc = documentConnection.asXTextDocument(); String name = this.getName(); return DocumentConnection.getReferenceMarkRange(doc, name); } @@ -294,7 +293,7 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) name); LOGGER.warn(msg); } - createReprInDocument(documentConnection, + createReprInDocument(doc, name, full, false, /* insertSpaceAfter */ From f8a3e811903d98db9cecb470a2601d7b14189dcd Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 12:10:45 +0200 Subject: [PATCH 0691/1068] refactor: DocumentConnection split to smaller classes (named Uno*) --- .../org/jabref/gui/openoffice/OOBibBase.java | 368 +++---- .../gui/openoffice/OOBibBaseConnect.java | 69 +- .../gui/openoffice/OpenOfficePanel.java | 9 +- .../jabref/logic/openoffice/Backend52.java | 76 +- .../logic/openoffice/DocumentConnection.java | 997 ------------------ .../openoffice/OOFormattedTextIntoOO.java | 41 +- .../openoffice/OOFormattedTextIntoOOV1.java | 43 +- .../jabref/logic/openoffice/OOFrontend.java | 91 +- .../org/jabref/logic/openoffice/OOUtil.java | 4 +- .../logic/openoffice/RangeKeyedMap.java | 4 +- .../logic/openoffice/RangeKeyedMapList.java | 2 +- .../logic/openoffice/RangeSortVisual.java | 18 +- .../jabref/logic/openoffice/StorageBase.java | 13 +- .../logic/openoffice/StorageBaseRefMark.java | 49 +- .../jabref/logic/openoffice/UnoBookmark.java | 76 ++ .../org/jabref/logic/openoffice/UnoCast.java | 24 + .../jabref/logic/openoffice/UnoCrossRef.java | 75 ++ .../jabref/logic/openoffice/UnoCursor.java | 41 + .../logic/openoffice/UnoNameAccess.java | 27 + .../org/jabref/logic/openoffice/UnoNamed.java | 68 ++ .../logic/openoffice/UnoProperties.java | 95 ++ .../jabref/logic/openoffice/UnoRedlines.java | 52 + .../logic/openoffice/UnoReferenceMark.java | 133 +++ .../logic/openoffice/UnoScreenRefresh.java | 33 + .../jabref/logic/openoffice/UnoSelection.java | 83 ++ .../org/jabref/logic/openoffice/UnoStyle.java | 69 ++ .../logic/openoffice/UnoTextDocument.java | 82 ++ .../jabref/logic/openoffice/UnoTextRange.java | 63 ++ .../logic/openoffice/UnoTextSection.java | 70 ++ .../org/jabref/logic/openoffice/UnoUndo.java | 45 + .../openoffice/UnoUserDefinedProperty.java | 143 +++ 31 files changed, 1497 insertions(+), 1466 deletions(-) delete mode 100644 src/main/java/org/jabref/logic/openoffice/DocumentConnection.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoBookmark.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoCast.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoCursor.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoNameAccess.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoNamed.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoProperties.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoRedlines.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoScreenRefresh.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoSelection.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoStyle.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoTextRange.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoTextSection.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoUndo.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 649babcfdc1..bb711584098 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -11,7 +11,6 @@ import java.util.Set; import java.util.stream.Collectors; -import org.jabref.architecture.AllowedToUseAwt; import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; @@ -27,12 +26,20 @@ import org.jabref.logic.oostyle.OOFormatBibliography; import org.jabref.logic.oostyle.OOProcess; import org.jabref.logic.openoffice.CreationException; -import org.jabref.logic.openoffice.DocumentConnection; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.OOFormattedTextIntoOO; import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.UndefinedCharacterFormatException; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; +import org.jabref.logic.openoffice.UnoBookmark; +import org.jabref.logic.openoffice.UnoCrossRef; +import org.jabref.logic.openoffice.UnoCursor; +import org.jabref.logic.openoffice.UnoRedlines; +import org.jabref.logic.openoffice.UnoScreenRefresh; +import org.jabref.logic.openoffice.UnoStyle; +import org.jabref.logic.openoffice.UnoTextRange; +import org.jabref.logic.openoffice.UnoTextSection; +import org.jabref.logic.openoffice.UnoUndo; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; @@ -65,7 +72,6 @@ * Class for manipulating the Bibliography of the currently started * document in OpenOffice. */ -@AllowedToUseAwt("Requires AWT for italics and bold") class OOBibBase { private static final String BIB_SECTION_NAME = "JR_bib"; @@ -78,20 +84,12 @@ class OOBibBase { private final DialogService dialogService; private final boolean alwaysAddCitedOnPages; - /** - * Created when connected to a document. - * - * Cleared (to null) when we discover we lost the connection. - */ - // private DocumentConnection xDocumentConnection; - - private OOBibBaseConnect connection; + private final OOBibBaseConnect connection; /* * Constructor */ - public OOBibBase(Path loPath, - DialogService dialogService) + public OOBibBase(Path loPath, DialogService dialogService) throws BootstrapException, CreationException { @@ -112,8 +110,8 @@ public void selectDocument() /** * A simple test for document availability. * - * See also `documentConnectionMissing` for a test - * actually attempting to use teh connection. + * See also `isDocumentConnectionMissing` for a test + * actually attempting to use the connection. * */ public boolean isConnectedToDocument() { @@ -123,20 +121,14 @@ public boolean isConnectedToDocument() { /** * @return true if we are connected to a document */ - public boolean documentConnectionMissing() { - return this.connection.documentConnectionMissing(); + public boolean isDocumentConnectionMissing() { + return this.connection.isDocumentConnectionMissing(); } /** - * Either return a valid DocumentConnection or throw + * Either return an XTextDocument or throw * NoDocumentException. */ - public DocumentConnection getDocumentConnectionOrThrow() - throws - NoDocumentException { - return this.connection.getDocumentConnectionOrThrow(); - } - public XTextDocument getXTextDocumentOrThrow() throws NoDocumentException { @@ -165,12 +157,11 @@ public List getCitationEntries() PropertyVetoException, JabRefException { - DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); - - checkIfOpenOfficeIsRecordingChanges(documentConnection); + XTextDocument doc = this.getXTextDocumentOrThrow(); - OOFrontend fr = new OOFrontend(documentConnection); - return fr.getCitationEntries(documentConnection); + checkIfOpenOfficeIsRecordingChanges(doc); + OOFrontend fr = new OOFrontend(doc); + return fr.getCitationEntries(doc); } /** @@ -180,7 +171,7 @@ public List getCitationEntries() * Does not change presentation. * * Note: we use no undo context here, because only - * documentConnection.setCustomProperty() is called, + * DocumentConnection.setUserDefinedStringPropertyValue() is called, * and Undo in LO will not undo that. * * GUI: "Manage citations" dialog "OK" button. @@ -209,12 +200,12 @@ public void applyCitationEntries(List citationEntries) NoDocumentException, WrappedTargetException { - DocumentConnection documentConnection = getDocumentConnectionOrThrow(); - OOFrontend fr = new OOFrontend(documentConnection); - fr.applyCitationEntries(documentConnection, citationEntries); + XTextDocument doc = this.getXTextDocumentOrThrow(); + OOFrontend fr = new OOFrontend(doc); + fr.applyCitationEntries(doc, citationEntries); } - private static void fillCitationMarkInCursor(DocumentConnection documentConnection, + private static void fillCitationMarkInCursor(XTextDocument doc, XTextCursor cursor, OOFormattedText citationText, boolean withText, @@ -231,7 +222,6 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti Objects.requireNonNull(cursor); Objects.requireNonNull(citationText); Objects.requireNonNull(style); - XTextDocument doc = documentConnection.asXTextDocument(); if (withText) { OOFormattedText citationText2 = OOFormat.setLocaleNone(citationText); @@ -251,8 +241,6 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti /** * Inserts a citation group in the document: creates and fills it. * - * @param fr - * @param documentConnection Connection to a document. * @param citationKeys BibTeX keys of * @param pageInfosForCitations * @param itcType @@ -269,7 +257,7 @@ private static void fillCitationMarkInCursor(DocumentConnection documentConnecti * reference mark. */ private void createAndFillCitationGroup(OOFrontend fr, - DocumentConnection documentConnection, + XTextDocument doc, List citationKeys, List pageInfosForCitations, InTextCitationType itcType, @@ -292,7 +280,7 @@ private void createAndFillCitationGroup(OOFrontend fr, IllegalTypeException, NoSuchElementException { - CitationGroupID cgid = fr.createCitationGroup(documentConnection, + CitationGroupID cgid = fr.createCitationGroup(doc, citationKeys, pageInfosForCitations, itcType, @@ -301,16 +289,11 @@ private void createAndFillCitationGroup(OOFrontend fr, !withText /* withoutBrackets */); if (withText) { - XTextCursor c2 = fr.getFillCursorForCitationGroup(documentConnection, - cgid); + XTextCursor c2 = fr.getFillCursorForCitationGroup(doc, cgid); - fillCitationMarkInCursor(documentConnection, - c2, - citationText, - withText, - style); + fillCitationMarkInCursor(doc, c2, citationText, withText, style); - fr.cleanFillCursorForCitationGroup(documentConnection, cgid); + fr.cleanFillCursorForCitationGroup(doc, cgid); } position.collapseToEnd(); } @@ -425,26 +408,23 @@ public void insertEntry(List entries, } final int nEntries = entries.size(); - DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); XTextDocument doc = this.getXTextDocumentOrThrow(); - checkStylesExistInTheDocument(style, documentConnection); - checkIfOpenOfficeIsRecordingChanges(documentConnection); + checkStylesExistInTheDocument(style, doc); + checkIfOpenOfficeIsRecordingChanges(doc); - OOFrontend fr = new OOFrontend(documentConnection); - // CitationGroups cgs = new CitationGroups(documentConnection); - // TODO: imposeLocalOrder + OOFrontend fr = new OOFrontend(doc); boolean useUndoContext = true; try { if (useUndoContext) { - DocumentConnection.enterUndoContext(doc, "Insert citation"); + UnoUndo.enterUndoContext(doc, "Insert citation"); } XTextCursor cursor; // Get the cursor positioned by the user. try { - cursor = DocumentConnection.getViewCursor(doc).orElse(null); + cursor = UnoCursor.getViewCursor(doc).orElse(null); } catch (RuntimeException ex) { // com.sun.star.uno.RuntimeException throw new JabRefException("Could not get the cursor", @@ -502,7 +482,7 @@ public void insertEntry(List entries, } createAndFillCitationGroup(fr, - documentConnection, + doc, citationKeys, pageInfosForCitations, itcType, @@ -519,24 +499,24 @@ public void insertEntry(List entries, if (sync) { // To account for numbering and for uniqueLetters, we // must refresh the cite markers: - OOFrontend fr2 = new OOFrontend(documentConnection); - fr2.imposeGlobalOrder(documentConnection); + OOFrontend fr2 = new OOFrontend(doc); + fr2.imposeGlobalOrder(doc); OOProcess.ProduceCitationMarkersResult x = OOProcess.produceCitationMarkers(fr2.cgs, allBases, style); try { - DocumentConnection.lockControllers(doc); - applyNewCitationMarkers(documentConnection, + UnoScreenRefresh.lockControllers(doc); + applyNewCitationMarkers(doc, fr2, x.citMarkers, style); // Insert it at the current position: - rebuildBibTextSection(documentConnection, + rebuildBibTextSection(doc, style, fr2, x.getBibliography(), this.alwaysAddCitedOnPages); } finally { - DocumentConnection.unlockControllers(doc); + UnoScreenRefresh.unlockControllers(doc); } /* @@ -558,7 +538,7 @@ public void insertEntry(List entries, throw new ConnectionLostException(ex.getMessage()); } finally { if (useUndoContext) { - DocumentConnection.leaveUndoContext(doc); + UnoUndo.leaveUndoContext(doc); } } } @@ -576,7 +556,6 @@ public void insertEntry(List entries, * After each fillCitationMarkInCursor call check if we lost the * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. * - * @param documentConnection * @param fr * * @param citMarkers Corresponding text for each reference mark, @@ -585,7 +564,7 @@ public void insertEntry(List entries, * @param style Bibliography style to use. * */ - private void applyNewCitationMarkers(DocumentConnection documentConnection, + private void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, Map citMarkers, OOBibStyle style) @@ -599,13 +578,10 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, NoSuchElementException, JabRefException { - XTextDocument doc = documentConnection.asXTextDocument(); - - checkStylesExistInTheDocument(style, documentConnection); + checkStylesExistInTheDocument(style, doc); CitationGroups cgs = fr.cgs; - final boolean hadBibSection = (DocumentConnection - .getBookmarkRange(doc, OOBibBase.BIB_SECTION_NAME) + final boolean hadBibSection = (UnoBookmark.getTextRange(doc, OOBibBase.BIB_SECTION_NAME) .isPresent()); for (Map.Entry kv : citMarkers.entrySet()) { @@ -622,21 +598,15 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, if (withText) { - XTextCursor cursor = fr.getFillCursorForCitationGroup(documentConnection, - cgid); + XTextCursor cursor = fr.getFillCursorForCitationGroup(doc, cgid); - fillCitationMarkInCursor(documentConnection, - cursor, - citationText, - withText, - style); + fillCitationMarkInCursor(doc, cursor, citationText, withText, style); - fr.cleanFillCursorForCitationGroup(documentConnection, cgid); + fr.cleanFillCursorForCitationGroup(doc, cgid); } if (hadBibSection - && (DocumentConnection - .getBookmarkRange(doc, OOBibBase.BIB_SECTION_NAME) + && (UnoBookmark.getTextRange(doc, OOBibBase.BIB_SECTION_NAME) .isEmpty())) { // Overwriting text already there is too harsh. // I am making it an error, to see if we ever get here. @@ -658,7 +628,7 @@ private void applyNewCitationMarkers(DocumentConnection documentConnection, * Note: assumes fresh `jabRefReferenceMarkNamesSortedByPosition` * if `style.isSortByPosition()` */ - private void rebuildBibTextSection(DocumentConnection documentConnection, + private void rebuildBibTextSection(XTextDocument doc, OOBibStyle style, OOFrontend fr, CitedKeys bibliography, @@ -673,9 +643,9 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, UndefinedParagraphFormatException, NoDocumentException { - clearBibTextSectionContent2(documentConnection); + clearBibTextSectionContent2(doc); - populateBibTextSection(documentConnection, + populateBibTextSection(doc, fr, bibliography, style, @@ -687,25 +657,21 @@ private void rebuildBibTextSection(DocumentConnection documentConnection, * * Only called from `clearBibTextSectionContent2` */ - private void createBibTextSection2(DocumentConnection documentConnection) + private void createBibTextSection2(XTextDocument doc) throws IllegalArgumentException, CreationException { - XTextDocument doc = documentConnection.asXTextDocument(); - - // Always creating at the end of documentConnection.getText() + // Always creating at the end of the document. // Alternatively, we could receive a cursor. XTextCursor textCursor = doc.getText().createTextCursor(); textCursor.gotoEnd(false); - - // OOUtil.insertParagraphBreak(documentConnection.xText, textCursor); textCursor.collapseToEnd(); - DocumentConnection.insertTextSection(doc, - OOBibBase.BIB_SECTION_NAME, - textCursor, - false); + UnoTextSection.create(doc, + OOBibBase.BIB_SECTION_NAME, + textCursor, + false); } /** @@ -715,17 +681,16 @@ private void createBibTextSection2(DocumentConnection documentConnection) * Only called from: `rebuildBibTextSection` * */ - private void clearBibTextSectionContent2(DocumentConnection documentConnection) + private void clearBibTextSectionContent2(XTextDocument doc) throws WrappedTargetException, IllegalArgumentException, CreationException, NoDocumentException { - XTextDocument doc = documentConnection.asXTextDocument(); - XNameAccess nameAccess = DocumentConnection.getTextSections(doc); + XNameAccess nameAccess = UnoTextSection.getTextSections(doc); if (!nameAccess.hasByName(OOBibBase.BIB_SECTION_NAME)) { - createBibTextSection2(documentConnection); + createBibTextSection2(doc); return; } @@ -734,8 +699,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) XTextSection section = (XTextSection) a.getObject(); // Clear it: - XTextCursor cursor = - (documentConnection.getXText().createTextCursorByRange(section.getAnchor())); + XTextCursor cursor = doc.getText().createTextCursorByRange(section.getAnchor()); cursor.gotoRange(section.getAnchor(), false); cursor.setString(""); @@ -749,7 +713,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) // Try to create. LOGGER.warn("Could not get section '" + OOBibBase.BIB_SECTION_NAME + "'", ex); - createBibTextSection2(documentConnection); + createBibTextSection2(doc); } } @@ -758,7 +722,7 @@ private void clearBibTextSectionContent2(DocumentConnection documentConnection) * * Assumes the section named `OOBibBase.BIB_SECTION_NAME` exists. */ - private void populateBibTextSection(DocumentConnection documentConnection, + private void populateBibTextSection(XTextDocument doc, OOFrontend fr, CitedKeys bibliography, OOBibStyle style, @@ -771,14 +735,11 @@ private void populateBibTextSection(DocumentConnection documentConnection, UndefinedParagraphFormatException, IllegalArgumentException, CreationException { - XTextDocument doc = documentConnection.asXTextDocument(); - XTextSection section = (DocumentConnection - .getTextSectionByName(doc, OOBibBase.BIB_SECTION_NAME) + XTextSection section = (UnoTextSection.getByName(doc, OOBibBase.BIB_SECTION_NAME) .orElseThrow(RuntimeException::new)); - XTextCursor cursor = - (documentConnection.getXText().createTextCursorByRange(section.getAnchor())); + XTextCursor cursor = doc.getText().createTextCursorByRange(section.getAnchor()); // emit the title of the bibliography OOFormattedTextIntoOO.removeDirectFormatting(cursor); @@ -790,16 +751,12 @@ private void populateBibTextSection(DocumentConnection documentConnection, cursor.collapseToEnd(); // remove the inital empty paragraph from the section. - XTextCursor initialParagraph = - (documentConnection.getXText().createTextCursorByRange(section.getAnchor())); + XTextCursor initialParagraph = doc.getText().createTextCursorByRange(section.getAnchor()); initialParagraph.collapseToStart(); initialParagraph.goRight((short) 1, true); initialParagraph.setString(""); - DocumentConnection.insertBookmark(doc, - OOBibBase.BIB_SECTION_END_NAME, - cursor, - true); + UnoBookmark.create(doc, OOBibBase.BIB_SECTION_END_NAME, cursor, true); cursor.collapseToEnd(); } @@ -841,21 +798,21 @@ public void combineCiteMarkers(List databases, Objects.requireNonNull(style); final boolean useLockControllers = true; - DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + XTextDocument doc = this.getXTextDocumentOrThrow(); - checkStylesExistInTheDocument(style, documentConnection); - checkIfOpenOfficeIsRecordingChanges(documentConnection); + checkStylesExistInTheDocument(style, doc); + checkIfOpenOfficeIsRecordingChanges(doc); - OOFrontend fr = new OOFrontend(documentConnection); + OOFrontend fr = new OOFrontend(doc); try { - DocumentConnection.enterUndoContext(doc, "Merge citations"); + UnoUndo.enterUndoContext(doc, "Merge citations"); boolean madeModifications = false; List referenceMarkNames = - fr.getCitationGroupIDsSortedWithinPartitions(documentConnection, + fr.getCitationGroupIDsSortedWithinPartitions(doc, false /* mapFootnotesToFootnoteMarks */); final int nRefMarks = referenceMarkNames.size(); @@ -863,7 +820,7 @@ public void combineCiteMarkers(List databases, try { if (useLockControllers) { - DocumentConnection.lockControllers(doc); + UnoScreenRefresh.lockControllers(doc); } /* @@ -920,12 +877,11 @@ public void combineCiteMarkers(List databases, if (addToGroup && prev != null) { Objects.requireNonNull(prevRange); Objects.requireNonNull(currentRange); - if (!DocumentConnection.comparableRanges(prevRange, currentRange)) { + if (!UnoTextRange.comparables(prevRange, currentRange)) { addToGroup = false; } else { - int textOrder = DocumentConnection.javaCompareRegionStarts(prevRange, - currentRange); + int textOrder = UnoTextRange.compareStarts(prevRange, currentRange); if (textOrder != (-1)) { String msg = @@ -947,8 +903,7 @@ public void combineCiteMarkers(List databases, if (addToGroup && (cursorBetween != null)) { Objects.requireNonNull(currentGroupCursor); // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() - if (DocumentConnection - .javaCompareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { String msg = ("combineCiteMarkers:" + " cursorBetween.end != currentGroupCursor.end"); throw new RuntimeException(msg); @@ -963,8 +918,7 @@ public void combineCiteMarkers(List databases, .createTextCursorByRange(cursorBetween.getEnd())); while (couldExpand && - (DocumentConnection - .javaCompareRegionEnds(cursorBetween, rangeStart) < 0)) { + (UnoTextRange.compareEnds(cursorBetween, rangeStart) < 0)) { couldExpand = cursorBetween.goRight((short) 1, true); currentGroupCursor.goRight((short) 1, true); // @@ -976,8 +930,7 @@ public void combineCiteMarkers(List databases, || !thisChar.trim().isEmpty()) { couldExpand = false; } - if (DocumentConnection - .javaCompareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { String msg = ("combineCiteMarkers:" + " cursorBetween.end != currentGroupCursor.end" + " (during expand)"); @@ -1029,8 +982,7 @@ public void combineCiteMarkers(List databases, // include self in currentGroupCursor currentGroupCursor.goRight((short) (currentRange.getString().length()), true); - if (DocumentConnection - .javaCompareRegionEnds(cursorBetween, currentGroupCursor) != 0) { + if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { /* * A problem discovered using this check: * when viewing the document in @@ -1055,9 +1007,7 @@ public void combineCiteMarkers(List databases, + "cursorBetween: '%s'\n" + "currentRange: '%s'\n" + "currentGroupCursor: '%s'\n", - DocumentConnection - .javaCompareRegionEnds(cursorBetween, - currentGroupCursor), + UnoTextRange.compareEnds(cursorBetween, currentGroupCursor), cursorBetween.getString(), currentRange.getString(), currentGroupCursor.getString()) @@ -1106,7 +1056,7 @@ public void combineCiteMarkers(List databases, // Remove the old citation groups from the document. for (int gj = 0; gj < joinableGroup.size(); gj++) { - fr.removeCitationGroups(joinableGroup, documentConnection); + fr.removeCitationGroups(joinableGroup, doc); } XTextCursor textCursor = joinableGroupsCursors.get(gi); @@ -1124,7 +1074,7 @@ public void combineCiteMarkers(List databases, */ boolean insertSpaceAfter = false; createAndFillCitationGroup(fr, - documentConnection, + doc, citationKeys, pageInfosForCitations, itcType, // InTextCitationType.AUTHORYEAR_PAR @@ -1139,37 +1089,36 @@ public void combineCiteMarkers(List databases, } finally { if (useLockControllers) { - DocumentConnection.unlockControllers(doc); + UnoScreenRefresh.unlockControllers(doc); } } if (madeModifications) { - DocumentConnection.refresh(doc); - OOFrontend fr2 = new OOFrontend(documentConnection); - fr2.imposeGlobalOrder(documentConnection); + UnoCrossRef.refresh(doc); + OOFrontend fr2 = new OOFrontend(doc); + fr2.imposeGlobalOrder(doc); OOProcess.ProduceCitationMarkersResult x = OOProcess.produceCitationMarkers(fr2.cgs, databases, style); try { if (useLockControllers) { - DocumentConnection.lockControllers(doc); + UnoScreenRefresh.lockControllers(doc); } - applyNewCitationMarkers(documentConnection, + applyNewCitationMarkers(doc, fr2, x.citMarkers, style); // bibliography is not refreshed } finally { if (useLockControllers) { - DocumentConnection.unlockControllers(doc); + UnoScreenRefresh.unlockControllers(doc); } } } } finally { - DocumentConnection.leaveUndoContext(doc); + UnoUndo.leaveUndoContext(doc); } - // documentConnection.refresh(); } // combineCiteMarkers /** @@ -1201,16 +1150,16 @@ public void unCombineCiteMarkers(List databases, Objects.requireNonNull(style); final boolean useLockControllers = true; - DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); + XTextDocument doc = this.getXTextDocumentOrThrow(); - checkStylesExistInTheDocument(style, documentConnection); - checkIfOpenOfficeIsRecordingChanges(documentConnection); + checkStylesExistInTheDocument(style, doc); + checkIfOpenOfficeIsRecordingChanges(doc); - OOFrontend fr = new OOFrontend(documentConnection); + OOFrontend fr = new OOFrontend(doc); try { - DocumentConnection.enterUndoContext(doc, "Separate citations"); + UnoUndo.enterUndoContext(doc, "Separate citations"); boolean madeModifications = false; // {@code names} does not need to be sorted. @@ -1218,7 +1167,7 @@ public void unCombineCiteMarkers(List databases, try { if (useLockControllers) { - DocumentConnection.lockControllers(doc); + UnoScreenRefresh.lockControllers(doc); } int pivot = 0; @@ -1243,7 +1192,7 @@ public void unCombineCiteMarkers(List databases, List keys = cits.stream().map(cit -> cit.citationKey).collect(Collectors.toList()); - fr.removeCitationGroup(cg, documentConnection); + fr.removeCitationGroup(cg, doc); // Now we own the content of cits @@ -1258,7 +1207,7 @@ public void unCombineCiteMarkers(List databases, boolean insertSpaceAfter = (i != last); boolean withText = cg.itcType != InTextCitationType.INVISIBLE_CIT; // true createAndFillCitationGroup(fr, - documentConnection, + doc, keys.subList(i, i + 1), // citationKeys, pageInfosForCitations.subList(i, i + 1), // pageInfos, InTextCitationType.AUTHORYEAR_PAR, // itcType, @@ -1275,32 +1224,31 @@ public void unCombineCiteMarkers(List databases, } } finally { if (useLockControllers) { - DocumentConnection.unlockControllers(doc); + UnoScreenRefresh.unlockControllers(doc); } } if (madeModifications) { - DocumentConnection.refresh(doc); - OOFrontend fr2 = new OOFrontend(documentConnection); - fr2.imposeGlobalOrder(documentConnection); + UnoCrossRef.refresh(doc); + OOFrontend fr2 = new OOFrontend(doc); + fr2.imposeGlobalOrder(doc); OOProcess.ProduceCitationMarkersResult x = OOProcess.produceCitationMarkers(fr2.cgs, databases, style); try { if (useLockControllers) { - DocumentConnection.lockControllers(doc); + UnoScreenRefresh.lockControllers(doc); } - applyNewCitationMarkers(documentConnection, fr2, x.citMarkers, style); + applyNewCitationMarkers(doc, fr2, x.citMarkers, style); // bibliography is not refreshed } finally { if (useLockControllers) { - DocumentConnection.unlockControllers(doc); + UnoScreenRefresh.unlockControllers(doc); } } } } finally { - DocumentConnection.leaveUndoContext(doc); + UnoUndo.leaveUndoContext(doc); } - // documentConnection.refresh(); } static class ExportCitedHelperResult { @@ -1317,15 +1265,11 @@ static class ExportCitedHelperResult { } /** - * Helper for GUI action "Export cited" - * - * Refreshes citation markers, (although the user did not ask for that). - * Actually, we only call produceCitationMarkers to get x.unresolvedKeys + * GUI action for "Export cited" * * Does not refresh the bibliography. */ - public ExportCitedHelperResult exportCitedHelper(List databases, - OOBibStyle style) + public ExportCitedHelperResult exportCitedHelper(List databases) throws WrappedTargetException, NoSuchElementException, @@ -1337,14 +1281,13 @@ public ExportCitedHelperResult exportCitedHelper(List databases, CreationException, InvalidStateException { - DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); XTextDocument doc = this.getXTextDocumentOrThrow(); try { - DocumentConnection.enterUndoContext(doc, "Changes during \"Export cited\""); - return this.generateDatabase(databases, documentConnection); + UnoUndo.enterUndoContext(doc, "Changes during \"Export cited\""); + return this.generateDatabase(databases, doc); } finally { - DocumentConnection.leaveUndoContext(doc); + UnoUndo.leaveUndoContext(doc); } } @@ -1352,7 +1295,6 @@ public ExportCitedHelperResult exportCitedHelper(List databases, * Used from GUI: "Export cited" * * @param databases The databases to look up the citation keys in the document from. - * @param documentConnection * @return A new database, with cloned entries. * * If a key is not found, it is added to result.unresolvedKeys @@ -1362,14 +1304,14 @@ public ExportCitedHelperResult exportCitedHelper(List databases, * If it is not found, it is silently ignored. */ private ExportCitedHelperResult generateDatabase(List databases, - DocumentConnection documentConnection) + XTextDocument doc) throws NoSuchElementException, WrappedTargetException, NoDocumentException, UnknownPropertyException { - OOFrontend fr = new OOFrontend(documentConnection); + OOFrontend fr = new OOFrontend(doc); CitedKeys cks = fr.cgs.getCitedKeys(); cks.lookupInDatabases(databases); @@ -1417,15 +1359,14 @@ private ExportCitedHelperResult generateDatabase(List databases, * Throw JabRefException if recording changes or the document contains * recorded changes. */ - public void checkIfOpenOfficeIsRecordingChanges(DocumentConnection documentConnection) + private static void checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) throws UnknownPropertyException, WrappedTargetException, PropertyVetoException, JabRefException { - XTextDocument doc = documentConnection.asXTextDocument(); - boolean recordingChanges = DocumentConnection.getRecordChanges(doc); - int nRedlines = DocumentConnection.countRedlines(doc); + boolean recordingChanges = UnoRedlines.getRecordChanges(doc); + int nRedlines = UnoRedlines.countRedlines(doc); if (recordingChanges || nRedlines > 0) { String msg = ""; if (recordingChanges) { @@ -1446,6 +1387,20 @@ public void checkIfOpenOfficeIsRecordingChanges(DocumentConnection documentConne } } + /* + * Called from GUI. + */ + public void checkIfOpenOfficeIsRecordingChanges() + throws + UnknownPropertyException, + WrappedTargetException, + PropertyVetoException, + JabRefException, + NoDocumentException { + XTextDocument doc = this.getXTextDocumentOrThrow(); + checkIfOpenOfficeIsRecordingChanges(doc); + } + void styleIsRequired(OOBibStyle style) throws JabRefException { @@ -1458,15 +1413,15 @@ void styleIsRequired(OOBibStyle style) } public void checkParagraphStyleExistsInTheDocument(String styleName, - DocumentConnection documentConnection, + XTextDocument doc, String labelInJstyleFile, String pathToStyleFile) throws JabRefException, NoSuchElementException, WrappedTargetException { - XTextDocument doc = documentConnection.asXTextDocument(); - Optional internalName = DocumentConnection.getInternalNameOfParagraphStyle(doc, styleName); + + Optional internalName = UnoStyle.getInternalNameOfParagraphStyle(doc, styleName); if (internalName.isEmpty()) { String msg = @@ -1498,16 +1453,15 @@ public void checkParagraphStyleExistsInTheDocument(String styleName, } public void checkCharacterStyleExistsInTheDocument(String styleName, - DocumentConnection documentConnection, + XTextDocument doc, String labelInJstyleFile, String pathToStyleFile) throws JabRefException, NoSuchElementException, WrappedTargetException { - XTextDocument doc = documentConnection.asXTextDocument(); - Optional internalName = (DocumentConnection - .getInternalNameOfCharacterStyle(doc, styleName)); + + Optional internalName = UnoStyle.getInternalNameOfCharacterStyle(doc, styleName); if (internalName.isEmpty()) { String msg = @@ -1537,7 +1491,7 @@ public void checkCharacterStyleExistsInTheDocument(String styleName, } } - public void checkStylesExistInTheDocument(OOBibStyle style, DocumentConnection documentConnection) + public void checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) throws JabRefException, NoSuchElementException, @@ -1546,17 +1500,17 @@ public void checkStylesExistInTheDocument(OOBibStyle style, DocumentConnection d String pathToStyleFile = style.getPath(); checkParagraphStyleExistsInTheDocument(style.getReferenceHeaderParagraphFormat(), - documentConnection, + doc, "ReferenceHeaderParagraphFormat", pathToStyleFile); checkParagraphStyleExistsInTheDocument(style.getReferenceParagraphFormat(), - documentConnection, + doc, "ReferenceParagraphFormat", pathToStyleFile); if (style.isFormatCitations()) { checkCharacterStyleExistsInTheDocument(style.getCitationCharacterFormat(), - documentConnection, + doc, "CitationCharacterFormat", pathToStyleFile); } @@ -1588,52 +1542,44 @@ public List updateDocumentActionHelper(List databases, styleIsRequired(style); - DocumentConnection documentConnection = this.getDocumentConnectionOrThrow(); XTextDocument doc = this.getXTextDocumentOrThrow(); - checkStylesExistInTheDocument(style, documentConnection); - checkIfOpenOfficeIsRecordingChanges(documentConnection); + checkStylesExistInTheDocument(style, doc); + checkIfOpenOfficeIsRecordingChanges(doc); try { - DocumentConnection.enterUndoContext(doc, "Refresh bibliography"); + UnoUndo.enterUndoContext(doc, "Refresh bibliography"); boolean requireSeparation = false; - // CitationGroups cgs = new CitationGroups(documentConnection); - OOFrontend fr = new OOFrontend(documentConnection); + + OOFrontend fr = new OOFrontend(doc); // Check Range overlaps int maxReportedOverlaps = 10; - fr.checkRangeOverlaps(documentConnection, - requireSeparation, - maxReportedOverlaps); + fr.checkRangeOverlaps(doc, requireSeparation, maxReportedOverlaps); final boolean useLockControllers = true; - fr.imposeGlobalOrder(documentConnection); + fr.imposeGlobalOrder(doc); OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr.cgs, - databases, - style); + OOProcess.produceCitationMarkers(fr.cgs, databases, style); try { if (useLockControllers) { - DocumentConnection.lockControllers(doc); + UnoScreenRefresh.lockControllers(doc); } - applyNewCitationMarkers(documentConnection, - fr, - x.citMarkers, - style); - rebuildBibTextSection(documentConnection, + applyNewCitationMarkers(doc, fr, x.citMarkers, style); + rebuildBibTextSection(doc, style, fr, x.getBibliography(), this.alwaysAddCitedOnPages); return x.getUnresolvedKeys(); } finally { - if (useLockControllers && DocumentConnection.hasControllersLocked(doc)) { - DocumentConnection.unlockControllers(doc); + if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { + UnoScreenRefresh.unlockControllers(doc); } } } finally { - DocumentConnection.leaveUndoContext(doc); + UnoUndo.leaveUndoContext(doc); } } diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 325704171de..4a428a653df 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -9,8 +9,9 @@ import org.jabref.gui.DialogService; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.CreationException; -import org.jabref.logic.openoffice.DocumentConnection; import org.jabref.logic.openoffice.NoDocumentException; +import org.jabref.logic.openoffice.UnoCast; +import org.jabref.logic.openoffice.UnoTextDocument; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; @@ -21,7 +22,6 @@ import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.text.XTextDocument; -import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,7 +42,7 @@ class OOBibBaseConnect { * * Cleared (to null) when we discover we lost the connection. */ - private DocumentConnection xDocumentConnection; + private XTextDocument xTextDocument; /* * Constructor @@ -74,7 +74,7 @@ private XDesktop simpleBootstrap(Path loPath) } catch (Exception e) { throw new CreationException(e.getMessage()); } - return unoQI(XDesktop.class, desktop); + return UnoCast.unoQI(XDesktop.class, desktop); } private static List getTextDocuments(XDesktop desktop) @@ -89,8 +89,8 @@ private static List getTextDocuments(XDesktop desktop) while (compEnum.hasMoreElements()) { Object next = compEnum.nextElement(); - XComponent comp = unoQI(XComponent.class, next); - XTextDocument doc = unoQI(XTextDocument.class, comp); + XComponent comp = UnoCast.unoQI(XComponent.class, next); + XTextDocument doc = UnoCast.unoQI(XTextDocument.class, comp); if (doc != null) { result.add(doc); } @@ -115,7 +115,7 @@ class DocumentTitleViewModel { public DocumentTitleViewModel(XTextDocument xTextDocument) { this.xTextDocument = xTextDocument; - this.description = DocumentConnection.getDocumentTitle(xTextDocument).orElse(""); + this.description = UnoTextDocument.getFrameTitle(xTextDocument).orElse(""); } public XTextDocument getXtextDocument() { @@ -160,7 +160,7 @@ public String toString() { * and extracts some frequently used parts (starting points for * managing its content). * - * Finally initializes this.xDocumentConnection with the selected + * Finally initializes this.xTextDocument with the selected * document and parts extracted. * */ @@ -185,7 +185,7 @@ public void selectDocument() return; } - this.xDocumentConnection = new DocumentConnection(selected); + this.xTextDocument = selected; } /** @@ -193,78 +193,59 @@ public void selectDocument() * */ private void forgetDocument() { - this.xDocumentConnection = null; + this.xTextDocument = null; } /** * A simple test for document availability. * - * See also `documentConnectionMissing` for a test + * See also `isDocumentConnectionMissing` for a test * actually attempting to use teh connection. * */ public boolean isConnectedToDocument() { - return this.xDocumentConnection != null; + return this.xTextDocument != null; } /** * @return true if we are connected to a document */ - public boolean documentConnectionMissing() { - if (this.xDocumentConnection == null) { - return true; - } - XTextDocument doc = this.xDocumentConnection.asXTextDocument(); + public boolean isDocumentConnectionMissing() { + XTextDocument doc = this.xTextDocument; + if (doc == null) { - forgetDocument(); return true; } - boolean res = DocumentConnection.documentConnectionMissing(doc); - if (res) { + + if (UnoTextDocument.isDocumentConnectionMissing(doc)) { forgetDocument(); + return true; } - return res; + return false; } /** - * Either return a valid DocumentConnection or throw + * Either return a valid XTextDocument or throw * NoDocumentException. */ - public DocumentConnection getDocumentConnectionOrThrow() + public XTextDocument getXTextDocumentOrThrow() throws NoDocumentException { - if (documentConnectionMissing()) { + if (isDocumentConnectionMissing()) { throw new NoDocumentException("Not connected to document"); } - return this.xDocumentConnection; - } - - public XTextDocument getXTextDocumentOrThrow() - throws - NoDocumentException { - return getDocumentConnectionOrThrow().asXTextDocument(); + return this.xTextDocument; } /** * The title of the current document, or Optional.empty() */ public Optional getCurrentDocumentTitle() { - if (documentConnectionMissing()) { + if (isDocumentConnectionMissing()) { return Optional.empty(); } else { - return DocumentConnection.getDocumentTitle(this.xDocumentConnection.asXTextDocument()); + return UnoTextDocument.getFrameTitle(this.xTextDocument); } } - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if - * available, otherwise null. - */ - private static T unoQI(Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - } // end of OOBibBaseConnect diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 0b8bffd44f4..0d8e933c03e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -48,7 +48,6 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.StyleLoader; import org.jabref.logic.openoffice.CreationException; -import org.jabref.logic.openoffice.DocumentConnection; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; @@ -282,8 +281,7 @@ private void initPanel() { manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { try { - DocumentConnection documentConnection = ooBase.getDocumentConnectionOrThrow(); - ooBase.checkIfOpenOfficeIsRecordingChanges(documentConnection); + ooBase.checkIfOpenOfficeIsRecordingChanges(); } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( Localization.lang("JabRefException"), @@ -347,7 +345,7 @@ private void exportEntries() { return; } - OOBibBase.ExportCitedHelperResult r = ooBase.exportCitedHelper(databases, style); + OOBibBase.ExportCitedHelperResult r = ooBase.exportCitedHelper(databases); List unresolvedKeys = r.unresolvedKeys; BibDatabase newDatabase = r.newDatabase; if (!unresolvedKeys.isEmpty()) { @@ -520,8 +518,7 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP } try { - DocumentConnection documentConnection = ooBase.getDocumentConnectionOrThrow(); - ooBase.checkIfOpenOfficeIsRecordingChanges(documentConnection); + ooBase.checkIfOpenOfficeIsRecordingChanges(); } catch (JabRefException ex) { dialogService.showErrorDialogAndWait( Localization.lang("JabRefException"), diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 10ca40c2033..29698b4f8b1 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -47,10 +47,9 @@ public Backend52() { * Note: the names returned are in arbitrary order. * */ - public List getJabRefReferenceMarkNames(DocumentConnection documentConnection) + public List getJabRefReferenceMarkNames(XTextDocument doc) throws NoDocumentException { - XTextDocument doc = documentConnection.asXTextDocument(); List allNames = this.citationStorageManager.getUsedNames(doc); return Codec52.filterIsJabRefReferenceMarkName(allNames); } @@ -62,9 +61,8 @@ public List getJabRefReferenceMarkNames(DocumentConnection documentConne * @param citationGroupNames These are the names that are used. * */ - private List findUnusedJabrefPropertyNames(DocumentConnection documentConnection, + private List findUnusedJabrefPropertyNames(XTextDocument doc, List citationGroupNames) { - XTextDocument doc = documentConnection.asXTextDocument(); // Collect unused jabrefPropertyNames Set citationGroupNamesSet = @@ -72,7 +70,7 @@ private List findUnusedJabrefPropertyNames(DocumentConnection documentCo List pageInfoThrash = new ArrayList<>(); List jabrefPropertyNames = - DocumentConnection.getUserDefinedPropertiesNames(doc) + UnoUserDefinedProperty.getListOfNames(doc) .stream() .filter(Codec52::isJabRefReferenceMarkName) .collect(Collectors.toList()); @@ -87,12 +85,11 @@ private List findUnusedJabrefPropertyNames(DocumentConnection documentCo /** * @return Optional.empty if all is OK, message text otherwise. */ - public Optional healthReport(DocumentConnection documentConnection) + public Optional healthReport(XTextDocument doc) throws NoDocumentException { List pageInfoThrash = - this.findUnusedJabrefPropertyNames(documentConnection, - this.getJabRefReferenceMarkNames(documentConnection)); + this.findUnusedJabrefPropertyNames(doc, this.getJabRefReferenceMarkNames(doc)); if (pageInfoThrash.isEmpty()) { return Optional.empty(); // "Backend52: found no unused pageInfo data"; } @@ -122,14 +119,11 @@ private static Optional getPageInfoFromData(List cita * We have circular dependency here: backend uses * class from ... */ - public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection documentConnection, - String refMarkName) + public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, String refMarkName) throws WrappedTargetException, NoDocumentException { - XTextDocument doc = documentConnection.asXTextDocument(); - Optional op = Codec52.parseMarkName(refMarkName); if (op.isEmpty()) { throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" @@ -142,7 +136,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(DocumentConnection doc .collect(Collectors.toList())); Optional pageInfo = - (DocumentConnection.getUserDefinedStringPropertyValue(doc, refMarkName) + (UnoUserDefinedProperty.getStringValue(doc, refMarkName) .map(OOFormattedText::fromString)); setPageInfoInData(citations, pageInfo); @@ -225,7 +219,6 @@ static Optional normalizePageInfoToOptional(OOFormattedText o) * On return {@code position} is collapsed, and is after the * inserted space, or at the end of the reference mark. * - * @param documentConnection Connection to document. * @param position Collapsed to its end. * @param insertSpaceAfter We insert a space after the mark, that * carries on format of characters from @@ -235,7 +228,7 @@ static Optional normalizePageInfoToOptional(OOFormattedText o) * For use with INVISIBLE_CIT. * */ - public CitationGroup createCitationGroup(DocumentConnection documentConnection, + public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, List pageInfosForCitations, InTextCitationType itcType, @@ -251,8 +244,6 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, PropertyVetoException, IllegalTypeException { - XTextDocument doc = documentConnection.asXTextDocument(); - String xkey = (citationKeys.stream() .collect(Collectors.joining(","))); @@ -289,7 +280,7 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, /* * Apply to document */ - StorageBase.NamedRange sr = this.citationStorageManager.create(documentConnection, + StorageBase.NamedRange sr = this.citationStorageManager.create(doc, refMarkName, position, insertSpaceAfter, @@ -299,13 +290,11 @@ public CitationGroup createCitationGroup(DocumentConnection documentConnection, case JabRef52: Optional pageInfo = getJabRef52PageInfoFromList(pageInfosForCitations); if (pageInfo.isPresent() && !"".equals(OOFormattedText.toString(pageInfo.get()))) { - DocumentConnection.setOrCreateUserDefinedStringPropertyValue(doc, - refMarkName, - OOFormattedText - .toString(pageInfo.get())); + String pageInfoString = OOFormattedText.toString(pageInfo.get()); + UnoUserDefinedProperty.createStringProperty(doc, refMarkName, pageInfoString); } else { // do not inherit from trash - DocumentConnection.removeUserDefinedProperty(doc, refMarkName); + UnoUserDefinedProperty.remove(doc, refMarkName); } CitationGroup cg = new CitationGroup(cgid, sr, @@ -364,7 +353,7 @@ public List combinePageInfos(List joinableGroup) return combinePageInfosCommon(this.dataModel, joinableGroup); } - public void removeCitationGroup(CitationGroup cg, DocumentConnection documentConnection) + public void removeCitationGroup(CitationGroup cg, XTextDocument doc) throws WrappedTargetException, NoDocumentException, @@ -373,11 +362,9 @@ public void removeCitationGroup(CitationGroup cg, DocumentConnection documentCon IllegalTypeException, PropertyExistException { - XTextDocument doc = documentConnection.asXTextDocument(); - String refMarkName = cg.cgRangeStorage.getName(); cg.cgRangeStorage.removeFromDocument(doc); - DocumentConnection.removeUserDefinedProperty(doc, refMarkName); + UnoUserDefinedProperty.remove(doc, refMarkName); } /** @@ -385,8 +372,7 @@ public void removeCitationGroup(CitationGroup cg, DocumentConnection documentCon * @return Optional.empty if the reference mark is missing. * */ - public Optional getMarkRange(CitationGroup cg, - XTextDocument doc) + public Optional getMarkRange(CitationGroup cg, XTextDocument doc) throws NoDocumentException, WrappedTargetException { @@ -398,40 +384,36 @@ public Optional getMarkRange(CitationGroup cg, * Cursor for the reference marks as is, not prepared for filling, * but does not need cleanFillCursorForCitationGroup either. */ - public Optional getRawCursorForCitationGroup(CitationGroup cg, - DocumentConnection documentConnection) + public Optional getRawCursorForCitationGroup(CitationGroup cg, XTextDocument doc) throws NoDocumentException, WrappedTargetException, CreationException { - return cg.cgRangeStorage.getRawCursor(documentConnection); + return cg.cgRangeStorage.getRawCursor(doc); } /** * Must be followed by call to cleanFillCursorForCitationGroup */ - public XTextCursor getFillCursorForCitationGroup(CitationGroup cg, - DocumentConnection documentConnection) + public XTextCursor getFillCursorForCitationGroup(CitationGroup cg, XTextDocument doc) throws NoDocumentException, WrappedTargetException, CreationException { - return cg.cgRangeStorage.getFillCursor(documentConnection); + return cg.cgRangeStorage.getFillCursor(doc); } /** To be called after getFillCursorForCitationGroup */ - public void cleanFillCursorForCitationGroup(CitationGroup cg, - DocumentConnection documentConnection) + public void cleanFillCursorForCitationGroup(CitationGroup cg, XTextDocument doc) throws NoDocumentException, WrappedTargetException, CreationException { - cg.cgRangeStorage.cleanFillCursor(documentConnection); + cg.cgRangeStorage.cleanFillCursor(doc); } - public List getCitationEntries(DocumentConnection documentConnection, - CitationGroups cgs) + public List getCitationEntries(XTextDocument doc, CitationGroups cgs) throws UnknownPropertyException, WrappedTargetException, @@ -448,10 +430,9 @@ public List getCitationEntries(DocumentConnection documentConnect CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); String name = cgid.asString(); XTextCursor cursor = (this - .getRawCursorForCitationGroup(cg, documentConnection) + .getRawCursorForCitationGroup(cg, doc) .orElseThrow(RuntimeException::new)); - String context = OOUtil.getCursorStringWithContext(documentConnection, - cursor, 30, 30, true); + String context = OOUtil.getCursorStringWithContext(cursor, 30, 30, true); Optional pageInfo = (cg.citations.size() > 0 ? (cg.citations .get(cg.citations.size() - 1) @@ -472,8 +453,7 @@ public List getCitationEntries(DocumentConnection documentConnect } } - public void applyCitationEntries(DocumentConnection documentConnection, - List citationEntries) + public void applyCitationEntries(XTextDocument doc, List citationEntries) throws UnknownPropertyException, NotRemoveableException, @@ -484,15 +464,13 @@ public void applyCitationEntries(DocumentConnection documentConnection, NoDocumentException, WrappedTargetException { - XTextDocument doc = documentConnection.asXTextDocument(); switch (dataModel) { case JabRef52: for (CitationEntry entry : citationEntries) { Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { - DocumentConnection.setOrCreateUserDefinedStringPropertyValue(doc, - entry.getRefMarkName(), - pageInfo.get()); + String name = entry.getRefMarkName(); + UnoUserDefinedProperty.createStringProperty(doc, name, pageInfo.get()); } } break; diff --git a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java b/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java deleted file mode 100644 index 155c63881c3..00000000000 --- a/src/main/java/org/jabref/logic/openoffice/DocumentConnection.java +++ /dev/null @@ -1,997 +0,0 @@ -package org.jabref.logic.openoffice; - -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.IllegalTypeException; -import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.Property; -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.container.NoSuchElementException; -import com.sun.star.container.XEnumeration; -import com.sun.star.container.XEnumerationAccess; -import com.sun.star.container.XNameAccess; -import com.sun.star.container.XNameContainer; -import com.sun.star.container.XNamed; -import com.sun.star.document.XDocumentProperties; -import com.sun.star.document.XDocumentPropertiesSupplier; -import com.sun.star.document.XRedlinesSupplier; -import com.sun.star.document.XUndoManager; -import com.sun.star.document.XUndoManagerSupplier; -import com.sun.star.frame.XController; -import com.sun.star.frame.XFrame; -import com.sun.star.frame.XModel; -import com.sun.star.lang.DisposedException; -import com.sun.star.lang.IllegalArgumentException; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.lang.XMultiServiceFactory; -import com.sun.star.lang.XServiceInfo; -import com.sun.star.style.XStyle; -import com.sun.star.style.XStyleFamiliesSupplier; -import com.sun.star.text.ReferenceFieldPart; -import com.sun.star.text.ReferenceFieldSource; -import com.sun.star.text.XBookmarksSupplier; -import com.sun.star.text.XFootnote; -import com.sun.star.text.XReferenceMarksSupplier; -import com.sun.star.text.XText; -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.XTextRangeCompare; -import com.sun.star.text.XTextSection; -import com.sun.star.text.XTextSectionsSupplier; -import com.sun.star.text.XTextViewCursor; -import com.sun.star.text.XTextViewCursorSupplier; -import com.sun.star.uno.Any; -import com.sun.star.uno.Type; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.util.InvalidStateException; -import com.sun.star.util.XRefreshable; -import com.sun.star.view.XSelectionSupplier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Document-connection related variables. - * - * documentConnection.asXTextDocument() - */ -public class DocumentConnection { - private static final Logger LOGGER = LoggerFactory.getLogger(DocumentConnection.class); - - - private XTextDocument xTextDocument; - - public DocumentConnection(XTextDocument xTextDocument) { - this.xTextDocument = xTextDocument; - } - - /** - * Get a reference to the body text of the document - */ - public XText getXText() { - return xTextDocument.getText(); - } - - public XTextDocument asXTextDocument() { - return xTextDocument; - } - - public Optional asOptionalXTextDocument() { - return Optional.ofNullable(xTextDocument); - } - - private static Optional getXDocumentProperties(XTextDocument doc) { - return (Optional.ofNullable(doc) - .map(e -> unoQI(XDocumentPropertiesSupplier.class, e)) - .map(e -> e.getDocumentProperties())); - } - - public static boolean getRecordChanges(XTextDocument doc) - throws - UnknownPropertyException, - WrappedTargetException { - XPropertySet ps = unoQI(XPropertySet.class, doc); - // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Settings - // "Properties of com.sun.star.text.TextDocument" - if (ps == null) { - throw new RuntimeException("getRecordChanges: ps is null"); - } - return (boolean) ps.getPropertyValue("RecordChanges"); - } - - private static XRedlinesSupplier getRedlinesSupplier(XTextDocument doc) { - return unoQI(XRedlinesSupplier.class, doc); - } - - public static int countRedlines(XTextDocument doc) { - XRedlinesSupplier rs = getRedlinesSupplier(doc); - XEnumerationAccess ea = rs.getRedlines(); - XEnumeration e = ea.createEnumeration(); - if (e == null) { - return 0; - } else { - int count = 0; - while (e.hasMoreElements()) { - try { - e.nextElement(); - count++; - } catch (NoSuchElementException | WrappedTargetException ex) { - break; - } - } - return count; - } - } - - private static Optional getStyleFromFamily(XTextDocument doc, - String familyName, - String styleName) - throws - NoSuchElementException, - WrappedTargetException { - - XStyleFamiliesSupplier fss = unoQI(XStyleFamiliesSupplier.class, doc); - XNameAccess fs = unoQI(XNameAccess.class, fss.getStyleFamilies()); - XNameContainer xFamily = unoQI(XNameContainer.class, fs.getByName(familyName)); - - try { - Object s = xFamily.getByName(styleName); - XStyle xs = (XStyle) unoQI(XStyle.class, s); - return Optional.ofNullable(xs); - } catch (NoSuchElementException ex) { - return Optional.empty(); - } - } - - private static Optional getParagraphStyle(XTextDocument doc, String styleName) - throws - NoSuchElementException, - WrappedTargetException { - return getStyleFromFamily(doc, "ParagraphStyles", styleName); - } - - private static Optional getCharacterStyle(XTextDocument doc, String styleName) - throws - NoSuchElementException, - WrappedTargetException { - return getStyleFromFamily(doc, "CharacterStyles", styleName); - } - - public static Optional getInternalNameOfParagraphStyle(XTextDocument doc, String name) - throws - NoSuchElementException, - WrappedTargetException { - return (getParagraphStyle(doc, name) - .map(e -> e.getName())); - } - - public static Optional getInternalNameOfCharacterStyle(XTextDocument doc, String name) - throws - NoSuchElementException, - WrappedTargetException { - return (getCharacterStyle(doc, name) - .map(e -> e.getName())); - } - - private static Optional getSelectionSupplier(XTextDocument doc) { - return (Optional.ofNullable(doc) - .map(e -> getCurrentController(e)) - .flatMap(e -> optUnoQI(XSelectionSupplier.class, e))); - } - - private static Optional asXModel(XTextDocument doc) { - return optUnoQI(XModel.class, doc); - } - - private static Optional getCurrentController(XTextDocument doc) { - return asXModel(doc).map(e -> e.getCurrentController()); - } - - /** - * @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. - * - * One way to do that is accessing its XServiceInfo interface. - * - * Experiments using printServiceInfo with cursor in various - * positions in the document: - * - * With cursor within the frame, in text: - * *** xserviceinfo.getImplementationName: "SwXTextRanges" - * "com.sun.star.text.TextRanges" - * - * With cursor somewhere else in text: - * *** xserviceinfo.getImplementationName: "SwXTextRanges" - * "com.sun.star.text.TextRanges" - * - * With cursor in comment (also known as "annotation"): - * *** XSelectionSupplier is OK - * *** Object initialSelection is null - * *** xserviceinfo is null - * - * 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" - * - * 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 getSelectionAsXServiceInfo(XTextDocument doc) { - return (getSelectionSupplier(doc) - .flatMap(e -> Optional.ofNullable(e.getSelection())) - .flatMap(e -> optUnoQI(XServiceInfo.class, e))); - } - - /** - * Select the object represented by {@code newSelection} if it is - * known and selectable in this {@code XSelectionSupplier} object. - * - * Presumably result from {@code XSelectionSupplier.getSelection()} is - * usually OK. It also accepted - * {@code XTextRange newSelection = documentConnection.xText.getStart();} - * - */ - public static void select(XTextDocument doc, Object newSelection) { - getSelectionSupplier(doc).ifPresent(e -> e.select(newSelection)); - } - - public static Optional getXUndoManager(XTextDocument doc) { - // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html - return (optUnoQI(XUndoManagerSupplier.class, doc) - .map(e -> e.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) { - Optional um = getXUndoManager(doc); - if (um.isPresent()) { - um.get().enterUndoContext(title); - } - } - - public static void leaveUndoContext(XTextDocument doc) { - Optional um = getXUndoManager(doc); - if (um.isPresent()) { - try { - um.get().leaveUndoContext(); - } catch (InvalidStateException ex) { - throw new RuntimeException("leaveUndoContext reported InvalidStateException"); - } - } - } - - /** - * Disable screen refresh. - * - * Must be paired with unlockControllers() - * - * https://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XModel.html - * - * While there is at least one lock remaining, some - * notifications for display updates are not broadcasted. - */ - public static void lockControllers(XTextDocument doc) { - XModel model = asXModel(doc).orElseThrow(RuntimeException::new); - model.lockControllers(); - } - - public static void unlockControllers(XTextDocument doc) { - XModel model = asXModel(doc).orElseThrow(RuntimeException::new); - model.unlockControllers(); - } - - public static boolean hasControllersLocked(XTextDocument doc) { - XModel model = asXModel(doc).orElseThrow(RuntimeException::new); - return model.hasControllersLocked(); - } - - /** - * @return True if we cannot reach the current document. - */ - public static boolean documentConnectionMissing(XTextDocument doc) { - - boolean missing = false; - if (doc == null) { - missing = true; - } - - // Attempt to check document is really available - if (!missing) { - try { - getReferenceMarks(doc); - } catch (NoDocumentException ex) { - missing = true; - } - } - return missing; - } - - public static Optional asXPropertySet(XFrame frame) { - return optUnoQI(XPropertySet.class, frame); - } - - public static Optional XPropertySetGetProperty(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(); - } - } - - /** - * @param doc The XTextDocument we want the title for. Null allowed. - * @return The title or Optional.empty() - */ - public static Optional getDocumentTitle(XTextDocument doc) { - - if (doc == null) { - return Optional.empty(); - } - - XFrame frame = doc.getCurrentController().getFrame(); - Optional propertySet = asXPropertySet(frame); - if (propertySet.isEmpty()) { - return Optional.empty(); - } - - try { - Optional frameTitleObj = XPropertySetGetProperty(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(); - } - } - - public static Optional - getUserDefinedPropertiesAsXPropertyContainer(XTextDocument doc) { - return getXDocumentProperties(doc).map(e -> e.getUserDefinedProperties()); - } - - public static Optional asXPropertySet(XPropertyContainer xPropertyContainer) { - return optUnoQI(XPropertySet.class, xPropertyContainer); - } - - public static List getPropertyNames(Property[] properties) { - Objects.requireNonNull(properties); - return (Arrays.stream(properties) - .map(p -> p.Name) - .collect(Collectors.toList())); - } - - public static List getPropertyNames(XPropertySetInfo propertySetInfo) { - return getPropertyNames(propertySetInfo.getProperties()); - } - - public static List getPropertyNames(XPropertySet propertySet) { - return getPropertyNames(propertySet.getPropertySetInfo()); - } - - public static List getPropertyNames(XPropertyContainer propertyContainer) { - return (asXPropertySet(propertyContainer) - .map(DocumentConnection::getPropertyNames) - .orElse(new ArrayList<>())); - } - - public static List getUserDefinedPropertiesNames(XTextDocument doc) { - return (getUserDefinedPropertiesAsXPropertyContainer(doc) - .map(e -> getPropertyNames(e)) - .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 getUserDefinedStringPropertyValue(XTextDocument doc, String property) - throws - WrappedTargetException { - - Optional ps = (getUserDefinedPropertiesAsXPropertyContainer(doc) - .flatMap(DocumentConnection::asXPropertySet)); - if (ps.isEmpty()) { - throw new RuntimeException("getting UserDefinedProperties as XPropertySet failed"); - } - try { - String v = ps.get().getPropertyValue(property).toString(); - return Optional.ofNullable(v); - } 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 setOrCreateUserDefinedStringPropertyValue(XTextDocument doc, - String property, - String value) - throws - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException, - PropertyVetoException, - WrappedTargetException { - - Objects.requireNonNull(property); - Objects.requireNonNull(value); - - Optional xPropertyContainer = - getUserDefinedPropertiesAsXPropertyContainer(doc); - - if (xPropertyContainer.isEmpty()) { - throw new RuntimeException("getUserDefinedPropertiesAsXPropertyContainer failed"); - } - - Optional ps = xPropertyContainer.flatMap(DocumentConnection::asXPropertySet); - if (ps.isEmpty()) { - throw new RuntimeException("asXPropertySet failed"); - } - - XPropertySetInfo psi = ps.get().getPropertySetInfo(); - - if (psi.hasPropertyByName(property)) { - try { - ps.get().setPropertyValue(property, value); - return; - } catch (UnknownPropertyException ex) { - // fall through to addProperty - } - } - - xPropertyContainer.get().addProperty(property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value)); - } - - /** - * @param property Name of a custom document property in the - * current document. - */ - public static void removeUserDefinedProperty(XTextDocument doc, String property) - throws - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException { - - Objects.requireNonNull(property); - - Optional xPropertyContainer = - getUserDefinedPropertiesAsXPropertyContainer(doc); - - if (xPropertyContainer.isEmpty()) { - throw new RuntimeException("getUserDefinedPropertiesAsXPropertyContainer failed"); - } - - try { - xPropertyContainer.get().removeProperty(property); - } catch (UnknownPropertyException ex) { - LOGGER.warn(String.format("removeUserDefinedProperty(%s)" - + " This property was not there to remove", - property)); - } - } - - /** - * @throws NoDocumentException If cannot get reference marks - * - * Note: also used by `documentConnectionMissing` to test if - * we have a working connection. - * - */ - public static XNameAccess getReferenceMarks(XTextDocument doc) - throws - NoDocumentException { - - XReferenceMarksSupplier supplier = unoQI(XReferenceMarksSupplier.class, doc); - - try { - return supplier.getReferenceMarks(); - } catch (DisposedException ex) { - throw new NoDocumentException("getReferenceMarks failed with" + ex); - } - } - - /** - * Provides access to bookmarks by name. - */ - public static XNameAccess getBookmarks(XTextDocument doc) - throws - NoDocumentException { - - XBookmarksSupplier supplier = unoQI(XBookmarksSupplier.class, doc); - try { - return supplier.getBookmarks(); - } catch (DisposedException ex) { - throw new NoDocumentException("getBookmarks failed with" + ex); - } - } - - /** - * @return An XNameAccess to find sections by name. - */ - public static XNameAccess getTextSections(XTextDocument doc) - throws - NoDocumentException { - - XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, doc); - try { - return supplier.getTextSections(); - } catch (DisposedException ex) { - throw new NoDocumentException("getTextSections failed with" + ex); - } - } - - /** - * Names of all reference marks. - * - * Empty list for nothing. - */ - public static List getReferenceMarkNames(XTextDocument doc) - throws NoDocumentException { - - XNameAccess nameAccess = getReferenceMarks(doc); - String[] names = nameAccess.getElementNames(); - if (names == null) { - return new ArrayList<>(); - } - return Arrays.asList(names); - } - - /** - * @return null if name not found, or if the result does not - * support the XTextContent interface. - */ - public static Optional nameAccessGetTextContentByName(XNameAccess nameAccess, - String name) - throws - WrappedTargetException { - try { - return optUnoQI(XTextContent.class, nameAccess.getByName(name)); - } catch (NoSuchElementException ex) { - return Optional.empty(); - } - } - - /** - * Create a text cursor for a textContent. - * - * @return null if mark is null, otherwise cursor. - * - */ - public static Optional getTextCursorOfTextContent(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)); - } - - /** - * Remove the named reference mark. - * - * Removes both the text and the mark itself. - */ - public static void removeReferenceMark(XTextDocument doc, String name) - throws - WrappedTargetException, - NoDocumentException, - NoSuchElementException { - - XNameAccess xReferenceMarks = getReferenceMarks(doc); - - if (xReferenceMarks.hasByName(name)) { - Optional mark = nameAccessGetTextContentByName(xReferenceMarks, name); - if (mark.isEmpty()) { - return; - } - doc.getText().removeTextContent(mark.get()); - } - } - - /** - * Get the cursor positioned by the user. - * - */ - public static Optional getViewCursor(XTextDocument doc) { - return (getCurrentController(doc) - .flatMap(e -> optUnoQI(XTextViewCursorSupplier.class, e)) - .map(e -> e.getViewCursor())); - } - - /** - * Get the XTextRange corresponding to the named bookmark. - * - * @param name The name of the bookmark to find. - * @return The XTextRange for the bookmark, or null. - */ - public static Optional getBookmarkRange(XTextDocument doc, String name) - throws - WrappedTargetException, - NoDocumentException { - - XNameAccess nameAccess = getBookmarks(doc); - return (nameAccessGetTextContentByName(nameAccess, name) - .map(e -> e.getAnchor())); - } - - /** - * @return reference mark as XTextContent, Optional.empty if not found. - */ - public static Optional getReferenceMarkAsTextContent(XTextDocument doc, String name) - throws - NoDocumentException, - WrappedTargetException { - - XNameAccess nameAccess = getReferenceMarks(doc); - return nameAccessGetTextContentByName(nameAccess, name); - } - - /** - * XTextRange for the named reference mark, Optional.empty if not found. - */ - public static Optional getReferenceMarkRange(XTextDocument doc, String name) - throws - NoDocumentException, - WrappedTargetException { - return (getReferenceMarkAsTextContent(doc, name) - .map(e -> e.getAnchor())); - } - - /** - * 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". - * - * 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. - * - */ - private static XNamed insertNamedTextContent(XTextDocument doc, - String service, - String name, - XTextRange range, - boolean absorb) - throws - CreationException { - - XMultiServiceFactory msf = unoQI(XMultiServiceFactory.class, doc); - - Object xObject; - try { - xObject = msf.createInstance(service); - } catch (Exception e) { - throw new CreationException(e.getMessage()); - } - - XNamed xNamed = unoQI(XNamed.class, xObject); - xNamed.setName(name); - - // get XTextContent interface - XTextContent xTextContent = unoQI(XTextContent.class, xObject); - range.getText().insertTextContent(range, xTextContent, absorb); - return xNamed; - } - - /** - * Insert a new reference mark at the provided cursor - * position. - * - * The text in the cursor range will be the text with gray - * background. - * - * 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 insertReferenceMark(XTextDocument doc, - String name, - XTextRange range, - boolean absorb) - throws - CreationException { - return insertNamedTextContent(doc, - "com.sun.star.text.ReferenceMark", - name, - range, - absorb); - } - - /** - * 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. - * - * 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 insertBookmark(XTextDocument doc, - String name, - XTextRange range, - boolean absorb) - throws - IllegalArgumentException, - CreationException { - - return insertNamedTextContent(doc, - "com.sun.star.text.Bookmark", - name, - range, - absorb); - } - - /** - * Insert a clickable cross-reference to a reference mark, - * with a label containing the target's page number. - * - * May need a documentConnection.refresh() after, to update - * the text shown. - */ - public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, - String referenceMarkName, - XTextRange cursor) - throws - CreationException, - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - - // based on: https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Reference_Marks - XMultiServiceFactory msf = unoQI(XMultiServiceFactory.class, doc); - // 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 = (XPropertySet) unoQI(XPropertySet.class, - msf.createInstance(name)); - } catch (Exception e) { - throw new CreationException(e.getMessage()); - } - - // Set the SourceName of the GetReference text field to the referenceMarkName - xFieldProps.setPropertyValue("SourceName", referenceMarkName); - - // specify that the source is a reference mark (could also be a footnote, - // bookmark or sequence field) - xFieldProps.setPropertyValue("ReferenceFieldSource", - new Short(ReferenceFieldSource.REFERENCE_MARK)); - - // We want the reference displayed as page number - xFieldProps.setPropertyValue("ReferenceFieldPart", - new Short(ReferenceFieldPart.PAGE)); - - // Get the XTextContent interface of the GetReference text field - XTextContent xRefContent = (XTextContent) unoQI(XTextContent.class, xFieldProps); - - // Insert the text field - doc.getText().insertTextContent(cursor.getEnd(), xRefContent, false); - } - - /** - * Update TextFields, etc. - */ - public static void refresh(XTextDocument doc) { - // Refresh the document - XRefreshable xRefresh = unoQI(XRefreshable.class, doc); - xRefresh.refresh(); - } - - /** - * 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. - * - * 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 insertTextSection(XTextDocument doc, - String name, - XTextRange range, - boolean absorb) - throws - IllegalArgumentException, - CreationException { - - return insertNamedTextContent(doc, - "com.sun.star.text.TextSection", - name, - range, - absorb); - } - - /** - * Get an XTextSection by name. - */ - public static Optional getTextSectionByName(XTextDocument doc, - String name) - throws - NoSuchElementException, - WrappedTargetException { - - XTextSectionsSupplier supplier = unoQI(XTextSectionsSupplier.class, doc); - - return Optional.ofNullable((XTextSection) - ((Any) supplier.getTextSections().getByName(name)) - .getObject()); - } - - /** - * If original is in a footnote, return a range containing - * the corresponding footnote marker. - * - * Returns Optional.empty if not in a footnote. - */ - public static Optional getFootnoteMarkRange(XTextRange original) { - XFootnote footer = unoQI(XFootnote.class, original.getText()); - if (footer != null) { - // If we are inside a footnote, - // find the linking footnote marker: - // The footnote's anchor gives the correct position in the text: - return Optional.ofNullable(footer.getAnchor()); - } - return Optional.empty(); - } - - /** - * Test if two XTextRange values are comparable (i.e. they share - * the same getText()). - */ - public static boolean comparableRanges(XTextRange a, - XTextRange b) { - return a.getText() == b.getText(); - } - - /** - * @return follows OO conventions, the opposite of java conventions: - * 1 if (a < b), 0 if same start, (-1) if (b < a) - */ - private static int ooCompareRegionStarts(XTextRange a, - XTextRange b) { - if (!comparableRanges(a, b)) { - throw new RuntimeException("ooCompareRegionStarts: got incomparable regions"); - } - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - a.getText()); - return compare.compareRegionStarts(a, b); - } - - /** - * @return follows OO conventions, the opposite of java conventions: - * 1 if (a < b), 0 if same start, (-1) if (b < a) - */ - private static int ooCompareRegionEnds(XTextRange a, - XTextRange b) { - if (!comparableRanges(a, b)) { - throw new RuntimeException("ooCompareRegionEnds: got incomparable regions"); - } - final XTextRangeCompare compare = unoQI(XTextRangeCompare.class, - a.getText()); - return compare.compareRegionEnds(a, b); - } - - /** - * @return follows java conventions - * - * 1 if (a > b); (-1) if (a < b) - */ - public static int javaCompareRegionStarts(XTextRange a, - XTextRange b) { - return (-1) * ooCompareRegionStarts(a, b); - } - - /** - * @return follows java conventions - * - * 1 if (a > b); (-1) if (a < b) - */ - public static int javaCompareRegionEnds(XTextRange a, - XTextRange b) { - return (-1) * ooCompareRegionEnds(a, b); - } - - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if available, - * otherwise null - */ - private static T unoQI(Class zInterface, Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - - private static Optional optUnoQI(Class zInterface, Object object) { - return Optional.ofNullable(UnoRuntime.queryInterface(zInterface, object)); - } - -} // end DocumentConnection diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index 9a86935e48a..c9815d876ff 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -37,7 +37,6 @@ import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; -import com.sun.star.uno.UnoRuntime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -324,7 +323,7 @@ static class MyPropertyStack { MyPropertyStack(XTextCursor cursor) throws UnknownPropertyException { - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); XPropertySetInfo psi = propertySet.getPropertySetInfo(); this.goodNameToIndex = new HashMap<>(); @@ -362,17 +361,17 @@ static class MyPropertyStack { */ // This throws: - // XPropertyAccess xPropertyAccess = unoQI(XPropertyAccess.class, cursor); + // XPropertyAccess xPropertyAccess = UnoCast.unoQI(XPropertyAccess.class, cursor); // if (xPropertyAccess == null) { // throw new RuntimeException("MyPropertyStack: xPropertyAccess is null"); // } // we could use: // import com.sun.star.beans.XMultiPropertyStates; - XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); + XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); PropertyState[] propertyStates = mpss.getPropertyStates(goodNames); - XMultiPropertySet mps = unoQI(XMultiPropertySet.class, cursor); + XMultiPropertySet mps = UnoCast.unoQI(XMultiPropertySet.class, cursor); Object[] initialValues = mps.getPropertyValues(goodNames); ArrayList> initialValuesOpt = new ArrayList<>(goodSize); @@ -415,8 +414,8 @@ void popLayer() { void apply(XTextCursor cursor) { // removeDirectFormatting(cursor); - XMultiPropertySet mps = unoQI(XMultiPropertySet.class, cursor); - XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); + XMultiPropertySet mps = UnoCast.unoQI(XMultiPropertySet.class, cursor); + XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); ArrayList> topLayer = layers.peek(); try { // select values to be set @@ -626,8 +625,7 @@ public static void write(XTextDocument doc, String value = kv.getValue(); switch (key) { case "target": - DocumentConnection - .insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); + UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); break; default: LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); @@ -725,7 +723,7 @@ public static void write(XTextDocument doc, */ public static void removeDirectFormatting(XTextCursor cursor) { - XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); + XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); /* * Now that we have setAllPropertiesToDefault, check which properties @@ -734,8 +732,8 @@ public static void removeDirectFormatting(XTextCursor cursor) { * Note: tested with LibreOffice : 6.4.6.2 */ - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); + XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); try { // Special handling @@ -763,7 +761,7 @@ public static void removeDirectFormatting(XTextCursor cursor) { "ParaStyleName"); // query again, just in case it matters - propertySet = unoQI(XPropertySet.class, cursor); + propertySet = UnoCast.unoQI(XPropertySet.class, cursor); XPropertySetInfo psi = propertySet.getPropertySetInfo(); // check the result @@ -817,17 +815,6 @@ private static List> parseAttributes(String s) { return res; } - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if available, - * otherwise null - */ - private static T unoQI(Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - /* * We rely on property values being either DIRECT_VALUE or * DEFAULT_VALUE (not AMBIGUOUS_VALUE). If the cursor covers a homogeneous region, @@ -836,7 +823,7 @@ private static T unoQI(Class zInterface, private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) throws UnknownPropertyException { - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); PropertyState pst = propertyState.getPropertyState(propertyName); if (pst == PropertyState.AMBIGUOUS_VALUE) { throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE" @@ -968,8 +955,8 @@ public static void setParagraphStyle(XTextCursor cursor, String parStyle) throws UndefinedParagraphFormatException { - XParagraphCursor parCursor = unoQI(XParagraphCursor.class, cursor); - XPropertySet props = unoQI(XPropertySet.class, parCursor); + XParagraphCursor parCursor = UnoCast.unoQI(XParagraphCursor.class, cursor); + XPropertySet props = UnoCast.unoQI(XPropertySet.class, parCursor); try { props.setPropertyValue(PARA_STYLE_NAME, parStyle); } catch (UnknownPropertyException diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java index 70cee8e4222..73323b54e19 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java @@ -36,7 +36,6 @@ import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; -import com.sun.star.uno.UnoRuntime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -259,8 +258,7 @@ public static void write(XTextDocument doc, String value = kv.getValue(); switch (key) { case "target": - DocumentConnection - .insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); + UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); break; default: LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); @@ -351,7 +349,7 @@ public static void write(XTextDocument doc, */ public static void removeDirectFormatting(XTextCursor cursor) { - XMultiPropertyStates mpss = unoQI(XMultiPropertyStates.class, cursor); + XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); /* * Now that we have setAllPropertiesToDefault, check which properties @@ -360,8 +358,8 @@ public static void removeDirectFormatting(XTextCursor cursor) { * Note: tested with LibreOffice : 6.4.6.2 */ - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); + XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); try { // Special handling @@ -389,7 +387,7 @@ public static void removeDirectFormatting(XTextCursor cursor) { "ParaStyleName"); // query again, just in case it matters - propertySet = unoQI(XPropertySet.class, cursor); + propertySet = UnoCast.unoQI(XPropertySet.class, cursor); XPropertySetInfo psi = propertySet.getPropertySetInfo(); // check the result @@ -443,17 +441,6 @@ private static List> parseAttributes(String s) { return res; } - /** - * unoQI : short for UnoRuntime.queryInterface - * - * @return A reference to the requested UNO interface type if available, - * otherwise null - */ - private static T unoQI(Class zInterface, - Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - /** * Remove direct formatting of propertyName from propertySet. * @@ -499,7 +486,7 @@ private static void setPropertyToDefault(XTextCursor cursor, String propertyName if (false) { // This is what should "simply work". // However it loses e.g. font color when propertyName is "CharWeight". - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); propertyState.setPropertyToDefault(propertyName); } else if (false) { @@ -519,9 +506,9 @@ private static void setPropertyToDefault(XTextCursor cursor, String propertyName // from the level above" happens to be a different value, // then the two behaviours yield different results. - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); Object value = propertyState.getPropertyDefault(propertyName); - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); propertySet.setPropertyValue(propertyName, value); } else { @@ -575,7 +562,7 @@ private static void setPropertyToDefault(XTextCursor cursor, String propertyName } else { namesToDefault.add(propertyName); } - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); XPropertySetInfo psi = propertySet.getPropertySetInfo(); // Remember those we shall we restore later @@ -628,7 +615,7 @@ private static void setPropertyToDefault(XTextCursor cursor, String propertyName private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) throws UnknownPropertyException { - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); PropertyState pst = propertyState.getPropertyState(propertyName); if (pst == PropertyState.AMBIGUOUS_VALUE) { throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE" @@ -647,7 +634,7 @@ private static Optional getPropertyValue(XTextCursor cursor, String prop if (isPropertyDefault(cursor, propertyName)) { return Optional.empty(); } else { - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); return Optional.of(propertySet.getPropertyValue(propertyName)); } } @@ -660,7 +647,7 @@ private static void setPropertyValue(XTextCursor cursor, String propertyName UnknownPropertyException, PropertyVetoException, WrappedTargetException { - XPropertySet propertySet = unoQI(XPropertySet.class, cursor); + XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); if (value.isPresent()) { propertySet.setPropertyValue(propertyName, value.get()); } else { @@ -782,7 +769,7 @@ public void apply(XTextCursor cursor) if (!started) { oldValue = getPropertyValue(cursor, propertyName).map(e -> (T) e); - XPropertyState propertyState = unoQI(XPropertyState.class, cursor); + XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); started = true; } @@ -925,8 +912,8 @@ public static void setParagraphStyle(XTextCursor cursor, String parStyle) throws UndefinedParagraphFormatException { - XParagraphCursor parCursor = unoQI(XParagraphCursor.class, cursor); - XPropertySet props = unoQI(XPropertySet.class, parCursor); + XParagraphCursor parCursor = UnoCast.unoQI(XParagraphCursor.class, cursor); + XPropertySet props = UnoCast.unoQI(XPropertySet.class, parCursor); try { props.setPropertyValue(PARA_STYLE_NAME, parStyle); } catch (UnknownPropertyException diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 0ddc985590e..086dc8fa842 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -36,7 +36,7 @@ public class OOFrontend { public final Backend52 backend; public final CitationGroups cgs; - public OOFrontend(DocumentConnection documentConnection) + public OOFrontend(XTextDocument doc) throws NoDocumentException, WrappedTargetException { @@ -47,11 +47,11 @@ public OOFrontend(DocumentConnection documentConnection) this.backend = new Backend52(); // Get the citationGroupNames - List citationGroupNames = this.backend.getJabRefReferenceMarkNames(documentConnection); + List citationGroupNames = this.backend.getJabRefReferenceMarkNames(doc); Map citationGroups = readCitationGroupsFromDocument(this.backend, - documentConnection, + doc, citationGroupNames); this.cgs = new CitationGroups(backend.dataModel, citationGroups); } @@ -60,15 +60,15 @@ public OOStyleDataModelVersion getDataModel() { return backend.dataModel; } - public Optional healthReport(DocumentConnection documentConnection) + public Optional healthReport(XTextDocument doc) throws NoDocumentException { - return backend.healthReport(documentConnection); + return backend.healthReport(doc); } private static Map readCitationGroupsFromDocument(Backend52 backend, - DocumentConnection documentConnection, + XTextDocument doc, List citationGroupNames) throws WrappedTargetException, @@ -78,7 +78,7 @@ public Optional healthReport(DocumentConnection documentConnection) for (int i = 0; i < citationGroupNames.size(); i++) { final String name = citationGroupNames.get(i); CitationGroup cg = - backend.readCitationGroupFromDocumentOrThrow(documentConnection, name); + backend.readCitationGroupFromDocumentOrThrow(doc, name); citationGroups.put(cg.cgid, cg); } return citationGroups; @@ -99,20 +99,18 @@ public Optional healthReport(DocumentConnection documentConnection) * unique indexes within the original partition (not after * mapFootnotesToFootnoteMarks). * - * @param documentConnection Connection to the document. * @param mapFootnotesToFootnoteMarks If true, replace ranges in * footnotes with the range of the corresponding footnote * mark. This is used for numbering the citations. * */ private List> - createVisualSortInput(DocumentConnection documentConnection, + createVisualSortInput(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) throws NoDocumentException, WrappedTargetException { - XTextDocument doc = documentConnection.asXTextDocument(); List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); List vses = new ArrayList<>(); @@ -167,7 +165,7 @@ public Optional healthReport(DocumentConnection documentConnection) RangeSort.RangeSortEntry v = avs.get(j); v.indexInPosition = indexInPartition++; if (mapFootnotesToFootnoteMarks) { - Optional fmr = DocumentConnection.getFootnoteMarkRange(v.getRange()); + Optional fmr = UnoTextRange.getFootnoteMarkRange(v.getRange()); // Adjust range if we are inside a footnote: if (fmr.isPresent()) { v.range = fmr.get(); @@ -198,7 +196,7 @@ public Optional healthReport(DocumentConnection documentConnection) * order. * */ - private List getVisuallySortedCitationGroupIDs(DocumentConnection documentConnection, + private List getVisuallySortedCitationGroupIDs(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) throws WrappedTargetException, @@ -206,7 +204,7 @@ private List getVisuallySortedCitationGroupIDs(DocumentConnecti JabRefException { List> vses = - createVisualSortInput(documentConnection, + createVisualSortInput(doc, mapFootnotesToFootnoteMarks); if (vses.size() != this.cgs.numberOfCitationGroups()) { @@ -222,7 +220,7 @@ private List getVisuallySortedCitationGroupIDs(DocumentConnecti + " but could not get it."); List> sorted = RangeSortVisual.visualSort(vses, - documentConnection, + doc, messageOnFailureToObtainAFunctionalXTextViewCursor); if (sorted.size() != this.cgs.numberOfCitationGroups()) { @@ -240,7 +238,7 @@ private List getVisuallySortedCitationGroupIDs(DocumentConnecti * Calculate and return citation group IDs in visual order. */ public List - getCitationGroupIDsSortedWithinPartitions(DocumentConnection documentConnection, + getCitationGroupIDsSortedWithinPartitions(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) throws NoDocumentException, @@ -248,7 +246,7 @@ private List getVisuallySortedCitationGroupIDs(DocumentConnecti // This is like getVisuallySortedCitationGroupIDs, // but we skip the visualSort part. List> vses = - createVisualSortInput(documentConnection, + createVisualSortInput(doc, mapFootnotesToFootnoteMarks); if (vses.size() != this.cgs.numberOfCitationGroups()) { @@ -297,7 +295,6 @@ private List getVisuallySortedCitationGroupIDs(DocumentConnecti * On return {@code position} is collapsed, and is after the * inserted space, or at the end of the reference mark. * - * @param documentConnection Connection to document. * @param citationKeys * @param pageInfosForCitations * @param itcType @@ -310,7 +307,7 @@ private List getVisuallySortedCitationGroupIDs(DocumentConnecti * For use with INVISIBLE_CIT. * */ - public CitationGroupID createCitationGroup(DocumentConnection documentConnection, + public CitationGroupID createCitationGroup(XTextDocument doc, List citationKeys, List pageInfosForCitations, InTextCitationType itcType, @@ -326,7 +323,7 @@ public CitationGroupID createCitationGroup(DocumentConnection documentConnection PropertyVetoException, IllegalTypeException { - CitationGroup cg = backend.createCitationGroup(documentConnection, + CitationGroup cg = backend.createCitationGroup(doc, citationKeys, pageInfosForCitations, itcType, @@ -353,8 +350,7 @@ public CitationGroupID createCitationGroup(DocumentConnection documentConnection * it is easier to reread everything for a refresh. * */ - public void removeCitationGroup(CitationGroup cg, - DocumentConnection documentConnection) + public void removeCitationGroup(CitationGroup cg, XTextDocument doc) throws WrappedTargetException, NoDocumentException, @@ -364,11 +360,11 @@ public void removeCitationGroup(CitationGroup cg, IllegalTypeException { // Apply - backend.removeCitationGroup(cg, documentConnection); + backend.removeCitationGroup(cg, doc); this.cgs.afterRemoveCitationGroup(cg); } - public void removeCitationGroups(List xcgs, DocumentConnection documentConnection) + public void removeCitationGroups(List xcgs, XTextDocument doc) throws WrappedTargetException, NoDocumentException, @@ -378,7 +374,7 @@ public void removeCitationGroups(List xcgs, DocumentConnection do IllegalTypeException { for (CitationGroup cg : xcgs) { - removeCitationGroup(cg, documentConnection); + removeCitationGroup(cg, doc); } } @@ -389,8 +385,7 @@ public void removeCitationGroups(List xcgs, DocumentConnection do * @return Null if the reference mark is missing. * */ - public Optional getMarkRange(XTextDocument doc, - CitationGroupID cgid) + public Optional getMarkRange(XTextDocument doc, CitationGroupID cgid) throws NoDocumentException, WrappedTargetException { @@ -402,8 +397,7 @@ public Optional getMarkRange(XTextDocument doc, * Cursor for the reference marks as is, not prepared for filling, * but does not need cleanFillCursorForCitationGroup either. */ - public Optional getRawCursorForCitationGroup(CitationGroupID cgid, - DocumentConnection documentConnection) + public Optional getRawCursorForCitationGroup(CitationGroupID cgid, XTextDocument doc) throws NoDocumentException, WrappedTargetException, @@ -413,33 +407,31 @@ public Optional getRawCursorForCitationGroup(CitationGroupID cgid, if (cg.isEmpty()) { return Optional.empty(); } - return backend.getRawCursorForCitationGroup(cg.get(), documentConnection); + return backend.getRawCursorForCitationGroup(cg.get(), doc); } - public XTextCursor getFillCursorForCitationGroup(DocumentConnection documentConnection, - CitationGroupID cgid) + public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGroupID cgid) throws NoDocumentException, WrappedTargetException, CreationException { CitationGroup cg = this.cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - return backend.getFillCursorForCitationGroup(cg, documentConnection); + return backend.getFillCursorForCitationGroup(cg, doc); } /** * Remove brackets, but if the result would become empty, leave * them; if the result would be a single characer, leave the left bracket. */ - public void cleanFillCursorForCitationGroup(DocumentConnection documentConnection, - CitationGroupID cgid) + public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroupID cgid) throws NoDocumentException, WrappedTargetException, CreationException { CitationGroup cg = this.cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); - backend.cleanFillCursorForCitationGroup(cg, documentConnection); + backend.cleanFillCursorForCitationGroup(cg, doc); } /** @@ -447,12 +439,11 @@ public void cleanFillCursorForCitationGroup(DocumentConnection documentConnectio * * result.size() == nRefMarks */ - public List citationRanges(DocumentConnection documentConnection) + public List citationRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - XTextDocument doc = documentConnection.asXTextDocument(); List xs = new ArrayList<>(cgs.numberOfCitationGroups()); List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); @@ -483,7 +474,7 @@ public List citationRanges(DocumentConnection documentConn * footnote marks does not depend on how do we mark or * structure those ranges. */ - public List footnoteMarkRanges(DocumentConnection documentConnection) + public List footnoteMarkRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { @@ -494,12 +485,12 @@ public List footnoteMarkRanges(DocumentConnection document List xs = new ArrayList<>(); - List citRanges = citationRanges(documentConnection); + List citRanges = citationRanges(doc); for (RangeForOverlapCheck base : citRanges) { XTextRange r = base.range; - Optional footnoteMarkRange = DocumentConnection.getFootnoteMarkRange(r); + Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(r); if (footnoteMarkRange.isEmpty()) { // not in footnote @@ -523,7 +514,7 @@ public List footnoteMarkRanges(DocumentConnection document * @param reportAtMost Limit number of overlaps reported (0 for no limit) * */ - public void checkRangeOverlaps(DocumentConnection documentConnection, + public void checkRangeOverlaps(XTextDocument doc, boolean requireSeparation, int reportAtMost) throws @@ -533,8 +524,8 @@ public void checkRangeOverlaps(DocumentConnection documentConnection, final boolean debugPartitions = false; - List xs = citationRanges(documentConnection); - xs.addAll(footnoteMarkRanges(documentConnection)); + List xs = citationRanges(doc); + xs.addAll(footnoteMarkRanges(doc)); RangeKeyedMapList xall = new RangeKeyedMapList<>(); for (RangeForOverlapCheck x : xs) { @@ -602,17 +593,16 @@ public void checkRangeOverlaps(DocumentConnection documentConnection, * the GUI could move the cursor in the document to * the entry. */ - public List getCitationEntries(DocumentConnection documentConnection) + public List getCitationEntries(XTextDocument doc) throws UnknownPropertyException, WrappedTargetException, NoDocumentException, CreationException { - return this.backend.getCitationEntries(documentConnection, cgs); + return this.backend.getCitationEntries(doc, cgs); } - public void applyCitationEntries(DocumentConnection documentConnection, - List citationEntries) + public void applyCitationEntries(XTextDocument doc, List citationEntries) throws UnknownPropertyException, NotRemoveableException, @@ -622,10 +612,10 @@ public void applyCitationEntries(DocumentConnection documentConnection, IllegalArgumentException, NoDocumentException, WrappedTargetException { - this.backend.applyCitationEntries(documentConnection, citationEntries); + this.backend.applyCitationEntries(doc, citationEntries); } - public void imposeGlobalOrder(DocumentConnection documentConnection) + public void imposeGlobalOrder(XTextDocument doc) throws WrappedTargetException, NoDocumentException, @@ -633,8 +623,7 @@ public void imposeGlobalOrder(DocumentConnection documentConnection) boolean mapFootnotesToFootnoteMarks = true; List sortedCitationGroupIDs = - getVisuallySortedCitationGroupIDs(documentConnection, - mapFootnotesToFootnoteMarks); + getVisuallySortedCitationGroupIDs(doc, mapFootnotesToFootnoteMarks); cgs.setGlobalOrder(sortedCitationGroupIDs); } } diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 08d83590c6d..e65d83d36a8 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -48,7 +48,6 @@ public static void insertTextAtCurrentLocation(XTextCursor cursor, * * The actual context may be smaller than requested. * - * @param documentConnection * @param cursor * @param charBefore Number of characters requested. * @param charAfter Number of characters requested. @@ -56,8 +55,7 @@ public static void insertTextAtCurrentLocation(XTextCursor cursor, * reference mark is surrounded by bold html tag. * */ - public static String getCursorStringWithContext(DocumentConnection documentConnection, - XTextCursor cursor, + public static String getCursorStringWithContext(XTextCursor cursor, int charBefore, int charAfter, boolean htmlMarkup) diff --git a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java index af85875532e..832ba13ed8e 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java @@ -52,11 +52,11 @@ public V get(XTextRange r) { } private static int comparator(XTextRange a, XTextRange b) { - int startOrder = DocumentConnection.javaCompareRegionStarts(a, b); + int startOrder = UnoTextRange.compareStarts(a, b); if (startOrder != 0) { return startOrder; } - return DocumentConnection.javaCompareRegionEnds(a, b); + return UnoTextRange.compareEnds(a, b); } public V put(XTextRange r, V value) { diff --git a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java index bc1b579b8f1..d39abb67335 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java @@ -100,7 +100,7 @@ public List findOverlappingRanges(int atMost, boolean includeTouch } if ((i + 1) < oxs.size()) { XTextRange b = oxs.get(i + 1); - int cmp = DocumentConnection.javaCompareRegionStarts(a.getEnd(), b.getStart()); + int cmp = UnoTextRange.compareStarts(a.getEnd(), b.getStart()); if (cmp > 0 || (includeTouching && (cmp == 0))) { // found overlap or touch List bvs = xs.get(b); diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index f766908aca6..e45bec419c1 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -139,18 +139,16 @@ public int hashCode() { */ public static List> visualSort(List> vses, - DocumentConnection documentConnection, + XTextDocument doc, String messageOnFailureToObtainAFunctionalXTextViewCursor) throws WrappedTargetException, NoDocumentException, JabRefException { - XTextDocument doc = documentConnection.asXTextDocument(); - final int inputSize = vses.size(); - if (DocumentConnection.hasControllersLocked(doc)) { + if (UnoScreenRefresh.hasControllersLocked(doc)) { LOGGER.warn("visualSort:" + " with ControllersLocked, viewCursor.gotoRange" + " is probably useless"); @@ -174,7 +172,7 @@ public int hashCode() { * * Still, we have a problem when the cursor is in a comment * (referred to as "annotation" in OO API): in this case - * initialSelection is null, and documentConnection.select() + * initialSelection is null, and Documentconnection.select() * does not help to get a function viewCursor. Having no * better idea, we ask the user to move the cursor into the * document. @@ -185,7 +183,7 @@ public int hashCode() { */ final boolean debugThisFun = false; - XServiceInfo initialSelection = DocumentConnection.getSelectionAsXServiceInfo(doc).orElse(null); + XServiceInfo initialSelection = UnoSelection.getSelectionAsXServiceInfo(doc).orElse(null); if (initialSelection != null) { if (Arrays.stream(initialSelection.getSupportedServiceNames()) @@ -199,8 +197,8 @@ public int hashCode() { LOGGER.info("visualSort: initialSelection does not support TextRanges." + " We need to change the viewCursor."); } - XTextRange newSelection = documentConnection.getXText().getStart(); - DocumentConnection.select(doc, newSelection); + XTextRange newSelection = doc.getText().getStart(); + UnoSelection.select(doc, newSelection); } } else { if (debugThisFun) { @@ -208,7 +206,7 @@ public int hashCode() { } } - XTextViewCursor viewCursor = DocumentConnection.getViewCursor(doc).orElse(null); + XTextViewCursor viewCursor = UnoCursor.getViewCursor(doc).orElse(null); Objects.requireNonNull(viewCursor); try { viewCursor.getStart(); @@ -228,7 +226,7 @@ public int hashCode() { * Restore initial state of selection (and thus viewCursor) */ if (initialSelection != null) { - DocumentConnection.select(doc, initialSelection); + UnoSelection.select(doc, initialSelection); } if (positions.size() != inputSize) { diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBase.java b/src/main/java/org/jabref/logic/openoffice/StorageBase.java index c9d8e1a8e5d..eef0fb29c12 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBase.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBase.java @@ -29,7 +29,7 @@ public Optional getMarkRange(XTextDocument doc) * Cursor for the reference marks as is, not prepared for filling, * but does not need cleanFillCursorForCitationGroup either. */ - public Optional getRawCursor(DocumentConnection documentConnection) + public Optional getRawCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, @@ -40,7 +40,7 @@ public Optional getRawCursor(DocumentConnection documentConnection) * * Must be followed by cleanFillCursor() */ - public XTextCursor getFillCursor(DocumentConnection documentConnection) + public XTextCursor getFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, @@ -51,7 +51,7 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) * them; if the result would be a single characer, leave the left bracket. * */ - public void cleanFillCursor(DocumentConnection documentConnection) + public void cleanFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, @@ -72,8 +72,8 @@ public interface NamedRange extends HasName, HasTextRange { } interface NamedRangeManager { - public NamedRange create(DocumentConnection documentConnection, - String refMarkName, + public NamedRange create(XTextDocument doc, + String markName, XTextCursor position, boolean insertSpaceAfter, boolean withoutBrackets) @@ -84,8 +84,7 @@ public List getUsedNames(XTextDocument doc) throws NoDocumentException; - public Optional getFromDocument(XTextDocument doc, - String refMarkName) + public Optional getFromDocument(XTextDocument doc, String markName) throws NoDocumentException, WrappedTargetException; diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index 053aa37c402..a11d53add77 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -102,14 +102,9 @@ private static void createReprInDocument(XTextDocument doc, ? "" : left + right); - cursor.getText().insertString(cursor, - bracketedContent, - true); + cursor.getText().insertString(cursor, bracketedContent, true); - DocumentConnection.insertReferenceMark(doc, - refMarkName, - cursor, - true /* absorb */); + UnoReferenceMark.create(doc, refMarkName, cursor, true /* absorb */); cursorBefore.goRight((short) 1, true); cursorBefore.setString(""); @@ -119,14 +114,13 @@ private static void createReprInDocument(XTextDocument doc, } } - private static StorageBaseRefMark create(DocumentConnection documentConnection, + private static StorageBaseRefMark create(XTextDocument doc, String refMarkName, XTextCursor position, boolean insertSpaceAfter, boolean withoutBrackets) throws CreationException { - XTextDocument doc = documentConnection.asXTextDocument(); createReprInDocument(doc, refMarkName, @@ -144,7 +138,7 @@ private static Optional getFromDocument(XTextDocument doc, throws NoDocumentException, WrappedTargetException { - return (DocumentConnection.getReferenceMarkRange(doc, refMarkName) + return (UnoReferenceMark.getTextRange(doc, refMarkName) .map(e -> new StorageBaseRefMark(refMarkName))); } @@ -159,7 +153,7 @@ public void removeFromDocument(XTextDocument doc) WrappedTargetException, NoDocumentException, NoSuchElementException { - DocumentConnection.removeReferenceMark(doc, this.getName()); + UnoReferenceMark.remove(doc, this.getName()); } @Override @@ -172,7 +166,7 @@ public String getName() { * * @return Optional.empty if the reference mark is missing. * - * See: getReferenceMarkRange + * See: UnoReferenceMark.getTextRange */ @Override public Optional getMarkRange(XTextDocument doc) @@ -180,7 +174,7 @@ public Optional getMarkRange(XTextDocument doc) NoDocumentException, WrappedTargetException { String name = this.getName(); - return DocumentConnection.getReferenceMarkRange(doc, name); + return UnoReferenceMark.getTextRange(doc, name); } /** @@ -193,25 +187,23 @@ public Optional getMarkRange(XTextDocument doc) * See: getRawCursorForCitationGroup */ @Override - public Optional getRawCursor(DocumentConnection documentConnection) + public Optional getRawCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, CreationException { - XTextDocument doc = documentConnection.asXTextDocument(); String name = this.getName(); Optional full = Optional.empty(); - Optional markAsTextContent = (DocumentConnection - .getReferenceMarkAsTextContent(doc, name)); + Optional markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name); if (markAsTextContent.isEmpty()) { String msg = String.format("getRawCursor: markAsTextContent(%s).isEmpty()", name); LOGGER.warn(msg); } - full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent.get()); + full = UnoCursor.getTextCursorOfTextContent(markAsTextContent.get()); if (full.isEmpty()) { String msg = "getRawCursor: full.isEmpty()"; LOGGER.warn(msg); @@ -224,14 +216,12 @@ public Optional getRawCursor(DocumentConnection documentConnection) * See: getFillCursorForCitationGroup */ @Override - public XTextCursor getFillCursor(DocumentConnection documentConnection) + public XTextCursor getFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, CreationException { - XTextDocument doc = documentConnection.asXTextDocument(); - String name = this.getName(); final boolean debugThisFun = false; @@ -243,8 +233,7 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) XTextCursor full = null; String fullText = null; for (int i = 1; i <= 2; i++) { - Optional markAsTextContent = - DocumentConnection.getReferenceMarkAsTextContent(doc, name); + Optional markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name); if (markAsTextContent.isEmpty()) { String msg = String.format("getFillCursor:" @@ -254,7 +243,7 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) throw new RuntimeException(msg); } - full = DocumentConnection.getTextCursorOfTextContent(markAsTextContent.get()).orElse(null); + full = UnoCursor.getTextCursorOfTextContent(markAsTextContent.get()).orElse(null); if (full == null) { String msg = String.format("getFillCursor: full == null (attempt %d)", i); throw new RuntimeException(msg); @@ -286,7 +275,7 @@ public XTextCursor getFillCursor(DocumentConnection documentConnection) } full.setString(""); try { - DocumentConnection.removeReferenceMark(doc, name); + UnoReferenceMark.remove(doc, name); } catch (NoSuchElementException ex) { String msg = String.format("getFillCursor got NoSuchElementException" + " for '%s'", @@ -423,7 +412,7 @@ public static void checkFillCursor(XTextCursor cursor) { * See: cleanFillCursorForCitationGroup */ @Override - public void cleanFillCursor(DocumentConnection documentConnection) + public void cleanFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, @@ -444,7 +433,7 @@ public void cleanFillCursor(DocumentConnection documentConnection) String name = this.getName(); - XTextCursor full = this.getRawCursor(documentConnection).orElseThrow(RuntimeException::new); + XTextCursor full = this.getRawCursor(doc).orElseThrow(RuntimeException::new); final String fullText = full.getString(); final int fullTextLength = fullText.length(); @@ -500,19 +489,19 @@ public void cleanFillCursor(DocumentConnection documentConnection) private static List getUsedNames(XTextDocument doc) throws NoDocumentException { - return DocumentConnection.getReferenceMarkNames(doc); + return UnoReferenceMark.getListOfNames(doc); } public static class Manager implements StorageBase.NamedRangeManager { @Override - public StorageBase.NamedRange create(DocumentConnection documentConnection, + public StorageBase.NamedRange create(XTextDocument doc, String refMarkName, XTextCursor position, boolean insertSpaceAfter, boolean withoutBrackets) throws CreationException { - return StorageBaseRefMark.create(documentConnection, + return StorageBaseRefMark.create(doc, refMarkName, position, insertSpaceAfter, diff --git a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java new file mode 100644 index 00000000000..87c54e87f45 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java @@ -0,0 +1,76 @@ +package org.jabref.logic.openoffice; + +import java.util.Optional; + +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNamed; +import com.sun.star.lang.DisposedException; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XBookmarksSupplier; +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.unoQI(XBookmarksSupplier.class, doc); + 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 null. + */ + public static Optional getTextRange(XTextDocument doc, String name) + throws + WrappedTargetException, + NoDocumentException { + + XNameAccess nameAccess = getNameAccess(doc); + return (UnoNameAccess.getTextContentByName(nameAccess, name) + .map(e -> e.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. + * + * 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 + IllegalArgumentException, + CreationException { + return UnoNamed.insertNamedTextContent(doc, + "com.sun.star.text.Bookmark", + name, + range, + absorb); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCast.java b/src/main/java/org/jabref/logic/openoffice/UnoCast.java new file mode 100644 index 00000000000..77e1c8c7a1d --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoCast.java @@ -0,0 +1,24 @@ +package org.jabref.logic.openoffice; + +import java.util.Optional; + +import com.sun.star.uno.UnoRuntime; + +public class UnoCast { + + private UnoCast() { } + + /** + * unoQI : short for UnoRuntime.queryInterface + * + * @return A reference to the requested UNO interface type if available, + * otherwise null + */ + public static T unoQI(Class zInterface, Object object) { + return UnoRuntime.queryInterface(zInterface, object); + } + + public static Optional optUnoQI(Class zInterface, Object object) { + return Optional.ofNullable(UnoRuntime.queryInterface(zInterface, object)); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java b/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java new file mode 100644 index 00000000000..53ea40e3738 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java @@ -0,0 +1,75 @@ +package org.jabref.logic.openoffice; + +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.unoQI(XRefreshable.class, doc); + xRefresh.refresh(); + } + + /** + * Insert a clickable cross-reference to a reference mark, + * with a label containing the target's page number. + * + * May need a documentConnection.refresh() after, to update + * the text shown. + */ + public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, + String referenceMarkName, + XTextRange cursor) + throws + CreationException, + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException { + + // based on: https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Reference_Marks + XMultiServiceFactory msf = UnoCast.unoQI(XMultiServiceFactory.class, doc); + // 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 = (XPropertySet) UnoCast.unoQI(XPropertySet.class, + msf.createInstance(name)); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + + // Set the SourceName of the GetReference text field to the referenceMarkName + xFieldProps.setPropertyValue("SourceName", referenceMarkName); + + // specify that the source is a reference mark (could also be a footnote, + // bookmark or sequence field) + xFieldProps.setPropertyValue("ReferenceFieldSource", + new Short(ReferenceFieldSource.REFERENCE_MARK)); + + // We want the reference displayed as page number + xFieldProps.setPropertyValue("ReferenceFieldPart", + new Short(ReferenceFieldPart.PAGE)); + + // Get the XTextContent interface of the GetReference text field + XTextContent xRefContent = (XTextContent) UnoCast.unoQI(XTextContent.class, xFieldProps); + + // Insert the text field + doc.getText().insertTextContent(cursor.getEnd(), xRefContent, false); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCursor.java b/src/main/java/org/jabref/logic/openoffice/UnoCursor.java new file mode 100644 index 00000000000..18a6872a46a --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoCursor.java @@ -0,0 +1,41 @@ +package org.jabref.logic.openoffice; + +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 getViewCursor(XTextDocument doc) { + return (UnoTextDocument.getCurrentController(doc) + .flatMap(e -> UnoCast.optUnoQI(XTextViewCursorSupplier.class, e)) + .map(e -> e.getViewCursor())); + } + + /** + * Create a text cursor for a textContent. + * + * @return null if mark is null, otherwise cursor. + * + */ + public static Optional getTextCursorOfTextContent(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)); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoNameAccess.java b/src/main/java/org/jabref/logic/openoffice/UnoNameAccess.java new file mode 100644 index 00000000000..b8d26edfb0e --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoNameAccess.java @@ -0,0 +1,27 @@ +package org.jabref.logic.openoffice; + +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 getTextContentByName(XNameAccess nameAccess, String name) + throws + WrappedTargetException { + try { + return UnoCast.optUnoQI(XTextContent.class, nameAccess.getByName(name)); + } catch (NoSuchElementException ex) { + return Optional.empty(); + } + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoNamed.java b/src/main/java/org/jabref/logic/openoffice/UnoNamed.java new file mode 100644 index 00000000000..58bb9a3905b --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoNamed.java @@ -0,0 +1,68 @@ +package org.jabref.logic.openoffice; + +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". + * + * 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.unoQI(XMultiServiceFactory.class, doc); + + Object xObject; + try { + xObject = msf.createInstance(service); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + + XNamed xNamed = UnoCast.unoQI(XNamed.class, xObject); + xNamed.setName(name); + + // get XTextContent interface + XTextContent xTextContent = UnoCast.unoQI(XTextContent.class, xObject); + range.getText().insertTextContent(range, xTextContent, absorb); + return xNamed; + } + +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoProperties.java b/src/main/java/org/jabref/logic/openoffice/UnoProperties.java new file mode 100644 index 00000000000..b1d3c56a367 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoProperties.java @@ -0,0 +1,95 @@ +package org.jabref.logic.openoffice; + +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() { } + + /* + * asPropertySet + */ + + public static Optional asPropertySet(XPropertyContainer propertyContainer) { + return UnoCast.optUnoQI(XPropertySet.class, propertyContainer); + } + + /* + * getPropertySetInfo + */ + + public static Optional getPropertySetInfo(XPropertySet propertySet) { + return (Optional.ofNullable(propertySet) + .flatMap(e -> Optional.ofNullable(e.getPropertySetInfo()))); + } + + public static Optional getPropertySetInfo(XPropertyContainer propertyContainer) { + return Optional.ofNullable(propertyContainer).flatMap(UnoProperties::getPropertySetInfo); + } + + /* + * getPropertyNames + */ + + public static List getPropertyNames(Property[] properties) { + Objects.requireNonNull(properties); + return (Arrays.stream(properties) + .map(p -> p.Name) + .collect(Collectors.toList())); + } + + public static List getPropertyNames(XPropertySetInfo propertySetInfo) { + return getPropertyNames(propertySetInfo.getProperties()); + } + + public static List getPropertyNames(XPropertySet propertySet) { + return getPropertyNames(propertySet.getPropertySetInfo()); + } + + public static List getPropertyNames(XPropertyContainer propertyContainer) { + return (asPropertySet(propertyContainer) + .map(UnoProperties::getPropertyNames) + .orElse(new ArrayList<>())); + } + + /* + * getPropertyValue + */ + + public static Optional 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 getValueAsObject(XPropertyContainer propertyContainer, String property) + throws + WrappedTargetException { + Optional propertySet = asPropertySet(propertyContainer); + if (propertySet.isEmpty()) { + return Optional.empty(); + } + return UnoProperties.getValueAsObject(propertySet.get(), property); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoRedlines.java b/src/main/java/org/jabref/logic/openoffice/UnoRedlines.java new file mode 100644 index 00000000000..8ec36f6a85c --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoRedlines.java @@ -0,0 +1,52 @@ +package org.jabref.logic.openoffice; + +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 + UnknownPropertyException, + WrappedTargetException { + + // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Settings + // "Properties of com.sun.star.text.TextDocument" + + XPropertySet ps = UnoCast.optUnoQI(XPropertySet.class, doc).orElseThrow(RuntimeException::new); + return (boolean) ps.getPropertyValue("RecordChanges"); + } + + private static XRedlinesSupplier getRedlinesSupplier(XTextDocument doc) { + return UnoCast.unoQI(XRedlinesSupplier.class, doc); + } + + public static int countRedlines(XTextDocument doc) { + XRedlinesSupplier rs = getRedlinesSupplier(doc); + XEnumerationAccess ea = rs.getRedlines(); + XEnumeration e = ea.createEnumeration(); + if (e == null) { + return 0; + } else { + int count = 0; + while (e.hasMoreElements()) { + try { + e.nextElement(); + count++; + } catch (NoSuchElementException | WrappedTargetException ex) { + break; + } + } + return count; + } + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java new file mode 100644 index 00000000000..418a934d3f0 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java @@ -0,0 +1,133 @@ +package org.jabref.logic.openoffice; + +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 + * + * Note: also used by `isDocumentConnectionMissing` to test if + * we have a working connection. + * + */ + public static XNameAccess getNameAccess(XTextDocument doc) + throws + NoDocumentException { + + XReferenceMarksSupplier supplier = UnoCast.unoQI(XReferenceMarksSupplier.class, doc); + + try { + return supplier.getReferenceMarks(); + } catch (DisposedException ex) { + throw new NoDocumentException("UnoReferenceMarks.getNameAccess failed with" + ex); + } + } + + /** + * Names of all reference marks. + * + * Empty list for nothing. + */ + public static List 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. + * + * Removes both the text and the mark itself. + */ + public static void remove(XTextDocument doc, String name) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException { + + XNameAccess xReferenceMarks = UnoReferenceMark.getNameAccess(doc); + + if (xReferenceMarks.hasByName(name)) { + Optional mark = UnoNameAccess.getTextContentByName(xReferenceMarks, name); + if (mark.isEmpty()) { + return; + } + doc.getText().removeTextContent(mark.get()); + } + } + + /** + * @return reference mark as XTextContent, Optional.empty if not found. + */ + public static Optional 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 getTextRange(XTextDocument doc, String name) + throws + NoDocumentException, + WrappedTargetException { + return (UnoReferenceMark.getAsTextContent(doc, name) + .map(e -> e.getAnchor())); + } + + /** + * Insert a new reference mark at the provided cursor + * position. + * + * The text in the cursor range will be the text with gray + * background. + * + * 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); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoScreenRefresh.java b/src/main/java/org/jabref/logic/openoffice/UnoScreenRefresh.java new file mode 100644 index 00000000000..92591f119b3 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoScreenRefresh.java @@ -0,0 +1,33 @@ +package org.jabref.logic.openoffice; + +import com.sun.star.text.XTextDocument; + +/** + * Disable/enable screen refresh. + */ +public class UnoScreenRefresh { + + private UnoScreenRefresh() { } + + /** + * Disable screen refresh. + * + * Must be paired with unlockControllers() + * + * https://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XModel.html + * + * 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(); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoSelection.java b/src/main/java/org/jabref/logic/openoffice/UnoSelection.java new file mode 100644 index 00000000000..ff558388893 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoSelection.java @@ -0,0 +1,83 @@ +package org.jabref.logic.openoffice; + +import java.util.Optional; + +import com.sun.star.lang.XServiceInfo; +import com.sun.star.text.XTextDocument; +import com.sun.star.view.XSelectionSupplier; + +/** + * Selection in the document. + */ +public class UnoSelection { + + private UnoSelection() { } + + private static Optional getSelectionSupplier(XTextDocument doc) { + return (Optional.ofNullable(doc) + .map(e -> UnoTextDocument.getCurrentController(e)) + .flatMap(e -> UnoCast.optUnoQI(XSelectionSupplier.class, e))); + } + + /** + * @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. + * + * One way to do that is accessing its XServiceInfo interface. + * + * Experiments using printServiceInfo with cursor in various + * positions in the document: + * + * With cursor within the frame, in text: + * *** xserviceinfo.getImplementationName: "SwXTextRanges" + * "com.sun.star.text.TextRanges" + * + * With cursor somewhere else in text: + * *** xserviceinfo.getImplementationName: "SwXTextRanges" + * "com.sun.star.text.TextRanges" + * + * With cursor in comment (also known as "annotation"): + * *** XSelectionSupplier is OK + * *** Object initialSelection is null + * *** xserviceinfo is null + * + * 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" + * + * 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 getSelectionAsXServiceInfo(XTextDocument doc) { + return (getSelectionSupplier(doc) + .flatMap(e -> Optional.ofNullable(e.getSelection())) + .flatMap(e -> UnoCast.optUnoQI(XServiceInfo.class, e))); + } + + /** + * Select the object represented by {@code newSelection} if it is + * known and selectable in this {@code XSelectionSupplier} object. + * + * Presumably result from {@code XSelectionSupplier.getSelection()} is + * usually OK. It also accepted + * {@code XTextRange newSelection = documentConnection.xText.getStart();} + * + */ + public static void select(XTextDocument doc, Object newSelection) { + getSelectionSupplier(doc).ifPresent(e -> e.select(newSelection)); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoStyle.java b/src/main/java/org/jabref/logic/openoffice/UnoStyle.java new file mode 100644 index 00000000000..d6518d33f25 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoStyle.java @@ -0,0 +1,69 @@ +package org.jabref.logic.openoffice; + +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 { + + private UnoStyle() { } + + private static Optional getStyleFromFamily(XTextDocument doc, + String familyName, + String styleName) + throws + NoSuchElementException, + WrappedTargetException { + + XStyleFamiliesSupplier fss = UnoCast.unoQI(XStyleFamiliesSupplier.class, doc); + XNameAccess fs = UnoCast.unoQI(XNameAccess.class, fss.getStyleFamilies()); + XNameContainer xFamily = UnoCast.unoQI(XNameContainer.class, fs.getByName(familyName)); + + try { + Object s = xFamily.getByName(styleName); + XStyle xs = (XStyle) UnoCast.unoQI(XStyle.class, s); + return Optional.ofNullable(xs); + } catch (NoSuchElementException ex) { + return Optional.empty(); + } + } + + public static Optional getParagraphStyle(XTextDocument doc, String styleName) + throws + NoSuchElementException, + WrappedTargetException { + return getStyleFromFamily(doc, "ParagraphStyles", styleName); + } + + public static Optional getCharacterStyle(XTextDocument doc, String styleName) + throws + NoSuchElementException, + WrappedTargetException { + return getStyleFromFamily(doc, "CharacterStyles", styleName); + } + + public static Optional getInternalNameOfParagraphStyle(XTextDocument doc, String name) + throws + NoSuchElementException, + WrappedTargetException { + return (getParagraphStyle(doc, name) + .map(e -> e.getName())); + } + + public static Optional getInternalNameOfCharacterStyle(XTextDocument doc, String name) + throws + NoSuchElementException, + WrappedTargetException { + return (getCharacterStyle(doc, name) + .map(e -> e.getName())); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java new file mode 100644 index 00000000000..08e1dfa9fb9 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java @@ -0,0 +1,82 @@ +package org.jabref.logic.openoffice; + +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.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 = false; + if (doc == null) { + missing = true; + } + + // Attempt to check document is really available + if (!missing) { + try { + UnoReferenceMark.getNameAccess(doc); + } catch (NoDocumentException ex) { + missing = true; + } + } + return missing; + } + + public static Optional getCurrentController(XTextDocument doc) { + return Optional.ofNullable(doc).flatMap(e -> Optional.ofNullable(e.getCurrentController())); + } + + /** + * @param doc The XTextDocument we want the title for. Null allowed. + * @return The title or Optional.empty() + */ + public static Optional getFrameTitle(XTextDocument doc) { + + Optional frame = getCurrentController(doc).map(e -> e.getFrame()); + if (frame.isEmpty()) { + return Optional.empty(); + } + + Optional propertySet = UnoCast.optUnoQI(XPropertySet.class, frame.get()); + if (propertySet.isEmpty()) { + return Optional.empty(); + } + + try { + Optional 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 getDocumentProperties(XTextDocument doc) { + return (Optional.ofNullable(doc) + .map(e -> UnoCast.unoQI(XDocumentPropertiesSupplier.class, e)) + .map(e -> e.getDocumentProperties())); + } +} + diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextRange.java b/src/main/java/org/jabref/logic/openoffice/UnoTextRange.java new file mode 100644 index 00000000000..42995d7cb81 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextRange.java @@ -0,0 +1,63 @@ +package org.jabref.logic.openoffice; + +import java.util.Optional; + +import com.sun.star.text.XFootnote; +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. + * + * Returns Optional.empty if not in a footnote. + */ + public static Optional getFootnoteMarkRange(XTextRange original) { + XFootnote footer = UnoCast.unoQI(XFootnote.class, original.getText()); + if (footer != null) { + // If we are inside a footnote, + // find the linking footnote marker: + // The footnote's anchor gives the correct position in the text: + return Optional.ofNullable(footer.getAnchor()); + } + return Optional.empty(); + } + + /** + * 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 > b); (-1) if (a < b) + */ + public static int compareStarts(XTextRange a, XTextRange b) { + if (!comparables(a, b)) { + throw new RuntimeException("compareStarts: got incomparable regions"); + } + final XTextRangeCompare compare = UnoCast.unoQI(XTextRangeCompare.class, a.getText()); + return (-1) * compare.compareRegionStarts(a, b); + } + + /** + * @return follows java conventions + * + * 1 if (a > b); (-1) if (a < b) + */ + public static int compareEnds(XTextRange a, XTextRange b) { + if (!comparables(a, b)) { + throw new RuntimeException("compareEnds: got incomparable regions"); + } + final XTextRangeCompare compare = UnoCast.unoQI(XTextRangeCompare.class, a.getText()); + return (-1) * compare.compareRegionEnds(a, b); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java new file mode 100644 index 00000000000..e3b03a5523f --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java @@ -0,0 +1,70 @@ +package org.jabref.logic.openoffice; + +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.IllegalArgumentException; +import com.sun.star.lang.WrappedTargetException; +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 getTextSections(XTextDocument doc) + throws + NoDocumentException { + + XTextSectionsSupplier supplier = UnoCast.unoQI(XTextSectionsSupplier.class, doc); + try { + return supplier.getTextSections(); + } catch (DisposedException ex) { + throw new NoDocumentException("getTextSections failed with" + ex); + } + } + + /** + * 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. + * + * 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 + IllegalArgumentException, + CreationException { + + return UnoNamed.insertNamedTextContent(doc, + "com.sun.star.text.TextSection", + name, + range, + absorb); + } + + /** + * Get an XTextSection by name. + */ + public static Optional getByName(XTextDocument doc, String name) + throws + NoSuchElementException, + WrappedTargetException { + XTextSectionsSupplier supplier = UnoCast.unoQI(XTextSectionsSupplier.class, doc); + return Optional.ofNullable((XTextSection) + ((Any) supplier.getTextSections().getByName(name)) + .getObject()); + } +} + diff --git a/src/main/java/org/jabref/logic/openoffice/UnoUndo.java b/src/main/java/org/jabref/logic/openoffice/UnoUndo.java new file mode 100644 index 00000000000..05037f8228f --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoUndo.java @@ -0,0 +1,45 @@ +package org.jabref.logic.openoffice; + +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 + */ +public class UnoUndo { + + private UnoUndo() { } + + public static Optional getXUndoManager(XTextDocument doc) { + // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html + return (UnoCast.optUnoQI(XUndoManagerSupplier.class, doc) + .map(e -> e.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) { + Optional um = getXUndoManager(doc); + if (um.isPresent()) { + um.get().enterUndoContext(title); + } + } + + public static void leaveUndoContext(XTextDocument doc) { + Optional um = getXUndoManager(doc); + if (um.isPresent()) { + try { + um.get().leaveUndoContext(); + } catch (InvalidStateException ex) { + throw new RuntimeException("leaveUndoContext reported InvalidStateException"); + } + } + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java b/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java new file mode 100644 index 00000000000..b2f885539de --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java @@ -0,0 +1,143 @@ +package org.jabref.logic.openoffice; + +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.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.lang.IllegalArgumentException; +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. + */ +public class UnoUserDefinedProperty { + + private static final Logger LOGGER = LoggerFactory.getLogger(UnoUserDefinedProperty.class); + + private UnoUserDefinedProperty() { } + + public static Optional getPropertyContainer(XTextDocument doc) { + return UnoTextDocument.getDocumentProperties(doc).map(e -> e.getUserDefinedProperties()); + } + + public static List 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 getStringValue(XTextDocument doc, String property) + throws + WrappedTargetException { + Optional ps = (UnoUserDefinedProperty.getPropertyContainer(doc) + .flatMap(UnoProperties::asPropertySet)); + if (ps.isEmpty()) { + throw new RuntimeException("getting UserDefinedProperties as XPropertySet failed"); + } + try { + String v = ps.get().getPropertyValue(property).toString(); + return Optional.ofNullable(v); + } 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 createStringProperty(XTextDocument doc, String property, String value) + throws + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException, + PropertyVetoException, + WrappedTargetException { + + Objects.requireNonNull(property); + Objects.requireNonNull(value); + + Optional xPropertyContainer = + UnoUserDefinedProperty.getPropertyContainer(doc); + + if (xPropertyContainer.isEmpty()) { + throw new RuntimeException("UnoUserDefinedProperty.getPropertyContainer failed"); + } + + Optional ps = + xPropertyContainer.flatMap(UnoProperties::asPropertySet); + if (ps.isEmpty()) { + throw new RuntimeException("asPropertySet failed"); + } + + XPropertySetInfo psi = ps.get().getPropertySetInfo(); + + if (psi.hasPropertyByName(property)) { + try { + ps.get().setPropertyValue(property, value); + return; + } catch (UnknownPropertyException ex) { + // fall through to addProperty + } + } + + xPropertyContainer.get().addProperty(property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value)); + } + + /** + * @param property Name of a custom document property in the + * current document. + */ + public static void remove(XTextDocument doc, String property) + throws + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException { + + Objects.requireNonNull(property); + + Optional xPropertyContainer = UnoUserDefinedProperty.getPropertyContainer(doc); + + if (xPropertyContainer.isEmpty()) { + throw new RuntimeException("getUserDefinedPropertiesAsXPropertyContainer failed"); + } + + try { + xPropertyContainer.get().removeProperty(property); + } catch (UnknownPropertyException ex) { + LOGGER.warn(String.format("UnoUserDefinedProperty.remove(%s)" + + " This property was not there to remove", + property)); + } + } +} From 4aed380527826964f50aa6c2907c3263f582db93 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 12:11:53 +0200 Subject: [PATCH 0692/1068] avoid NullPointerException if there is no LibraryTab --- src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 0d8e933c03e..b39cc402be4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -374,7 +374,10 @@ private List getBaseList() { databases.add(libraryTab.getDatabase()); } } else { - databases.add(frame.getCurrentLibraryTab().getDatabase()); + LibraryTab libraryTab = frame.getCurrentLibraryTab(); + if (libraryTab != null) { + databases.add(libraryTab.getDatabase()); + } } return databases; From 70045a34aad86bc281dfdfe61132ca72270c9ebd Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 12:12:47 +0200 Subject: [PATCH 0693/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index bb711584098..260f99252c6 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1007,7 +1007,8 @@ public void combineCiteMarkers(List databases, + "cursorBetween: '%s'\n" + "currentRange: '%s'\n" + "currentGroupCursor: '%s'\n", - UnoTextRange.compareEnds(cursorBetween, currentGroupCursor), + UnoTextRange.compareEnds(cursorBetween, + currentGroupCursor), cursorBetween.getString(), currentRange.getString(), currentGroupCursor.getString()) From 30bb1c4e5f242dc2ec5ffea40f8d91711e845e5f Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 12:24:23 +0200 Subject: [PATCH 0694/1068] No stacktrace for removed (not found) jstyle files --- src/main/java/org/jabref/logic/oostyle/StyleLoader.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/oostyle/StyleLoader.java b/src/main/java/org/jabref/logic/oostyle/StyleLoader.java index 14ea2c5e5b1..14f9710e4e8 100644 --- a/src/main/java/org/jabref/logic/oostyle/StyleLoader.java +++ b/src/main/java/org/jabref/logic/oostyle/StyleLoader.java @@ -92,7 +92,7 @@ private void loadExternalStyles() { } } catch (FileNotFoundException e) { // The file couldn't be found... should we tell anyone? - LOGGER.info("Cannot find external style file " + filename, e); + LOGGER.info("Cannot find external style file " + filename); } catch (IOException e) { LOGGER.info("Problem reading external style file " + filename, e); } From 85d13f9052afa7ce25c2b5b7f6e0e5877a14c1df Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 14:07:18 +0200 Subject: [PATCH 0695/1068] keep silent on attempt to remove non-existant pageInfo --- .../jabref/logic/openoffice/Backend52.java | 4 +-- .../openoffice/UnoUserDefinedProperty.java | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 29698b4f8b1..c1bfc4b83bc 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -294,7 +294,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, UnoUserDefinedProperty.createStringProperty(doc, refMarkName, pageInfoString); } else { // do not inherit from trash - UnoUserDefinedProperty.remove(doc, refMarkName); + UnoUserDefinedProperty.removeIfExists(doc, refMarkName); } CitationGroup cg = new CitationGroup(cgid, sr, @@ -364,7 +364,7 @@ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) String refMarkName = cg.cgRangeStorage.getName(); cg.cgRangeStorage.removeFromDocument(doc); - UnoUserDefinedProperty.remove(doc, refMarkName); + UnoUserDefinedProperty.removeIfExists(doc, refMarkName); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java b/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java index b2f885539de..599dbd54872 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java @@ -140,4 +140,30 @@ public static void remove(XTextDocument doc, String property) property)); } } + + /** + * @param property Name of a custom document property in the + * current document. + */ + public static void removeIfExists(XTextDocument doc, String property) + throws + NotRemoveableException, + PropertyExistException, + IllegalTypeException, + IllegalArgumentException { + + Objects.requireNonNull(property); + + Optional xPropertyContainer = UnoUserDefinedProperty.getPropertyContainer(doc); + + if (xPropertyContainer.isEmpty()) { + throw new RuntimeException("getUserDefinedPropertiesAsXPropertyContainer failed"); + } + + try { + xPropertyContainer.get().removeProperty(property); + } catch (UnknownPropertyException ex) { + // did not exist + } + } } From fa111b772eb0c8a07d0c4e597be6fcb095fc25de Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 14:57:17 +0200 Subject: [PATCH 0696/1068] doc comments --- src/main/java/org/jabref/logic/openoffice/UnoUndo.java | 2 +- .../jabref/logic/openoffice/UnoUserDefinedProperty.java | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/UnoUndo.java b/src/main/java/org/jabref/logic/openoffice/UnoUndo.java index 05037f8228f..902b0eadf29 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoUndo.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoUndo.java @@ -8,7 +8,7 @@ import com.sun.star.util.InvalidStateException; /** - * Undo + * Undo : group document changes into larger Undo actions. */ public class UnoUndo { diff --git a/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java b/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java index 599dbd54872..5b2b65ec407 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java @@ -23,6 +23,8 @@ /** * Document level user-defined properties. + * + * LibreOffice GUI: [File]/[Properties]/[Custom Properties] */ public class UnoUserDefinedProperty { @@ -115,7 +117,9 @@ public static void createStringProperty(XTextDocument doc, String property, Stri /** * @param property Name of a custom document property in the - * current document. + * current document. + * + * Logs warning if does not exist. */ public static void remove(XTextDocument doc, String property) throws @@ -144,6 +148,8 @@ public static void remove(XTextDocument doc, String property) /** * @param property Name of a custom document property in the * current document. + * + * Keep silent if property dids not exist. */ public static void removeIfExists(XTextDocument doc, String property) throws From f36e5425454b0fcd8595146a7b35fd7b6c7b95b3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 14:58:31 +0200 Subject: [PATCH 0697/1068] renamed UnoTextSection.getTextSections to getNameAccess --- .../java/org/jabref/logic/openoffice/UnoTextSection.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java index e3b03a5523f..328cbb79f38 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java @@ -19,7 +19,7 @@ public class UnoTextSection { /** * @return An XNameAccess to find sections by name. */ - public static XNameAccess getTextSections(XTextDocument doc) + public static XNameAccess getNameAccess(XTextDocument doc) throws NoDocumentException { @@ -27,7 +27,10 @@ public static XNameAccess getTextSections(XTextDocument doc) try { return supplier.getTextSections(); } catch (DisposedException ex) { - throw new NoDocumentException("getTextSections failed with" + ex); + throw new NoDocumentException("UnoTextSection.getNameAccess failed with" + ex); + } + } + } } From 326084a3fd84de4134b32186d06fe248c690554f Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 14:59:32 +0200 Subject: [PATCH 0698/1068] UnoTextSection.getByName doe not throw NoSuchElementException --- .../logic/openoffice/UnoTextSection.java | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java index 328cbb79f38..3087bc45fb3 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java @@ -31,6 +31,20 @@ public static XNameAccess getNameAccess(XTextDocument doc) } } + /** + * Get an XTextSection by name. + */ + public static Optional 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(); } } @@ -56,18 +70,5 @@ public static XNamed create(XTextDocument doc, String name, XTextRange range, bo range, absorb); } - - /** - * Get an XTextSection by name. - */ - public static Optional getByName(XTextDocument doc, String name) - throws - NoSuchElementException, - WrappedTargetException { - XTextSectionsSupplier supplier = UnoCast.unoQI(XTextSectionsSupplier.class, doc); - return Optional.ofNullable((XTextSection) - ((Any) supplier.getTextSections().getByName(name)) - .getObject()); - } } From 09be5711c9c3dafd3922ef56daf9a766620314a4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 14:59:55 +0200 Subject: [PATCH 0699/1068] use UnoTextSection in OOBibBase --- .../org/jabref/gui/openoffice/OOBibBase.java | 31 ++++--------------- 1 file changed, 6 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 260f99252c6..0fb3550dcbd 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -56,14 +56,12 @@ import com.sun.star.beans.UnknownPropertyException; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XNameAccess; import com.sun.star.lang.DisposedException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextSection; -import com.sun.star.uno.Any; import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -688,32 +686,14 @@ private void clearBibTextSectionContent2(XTextDocument doc) CreationException, NoDocumentException { - XNameAccess nameAccess = UnoTextSection.getTextSections(doc); - if (!nameAccess.hasByName(OOBibBase.BIB_SECTION_NAME)) { + Optional section = UnoTextSection.getByName(doc, OOBibBase.BIB_SECTION_NAME); + if (section.isEmpty()) { createBibTextSection2(doc); return; - } - - try { - Any a = ((Any) nameAccess.getByName(OOBibBase.BIB_SECTION_NAME)); - XTextSection section = (XTextSection) a.getObject(); - // Clear it: - - XTextCursor cursor = doc.getText().createTextCursorByRange(section.getAnchor()); - - cursor.gotoRange(section.getAnchor(), false); + } else { + // Clear it + XTextCursor cursor = doc.getText().createTextCursorByRange(section.get().getAnchor()); cursor.setString(""); - } catch (NoSuchElementException ex) { - // NoSuchElementException: is thrown by child access - // methods of collections, if the addressed child does - // not exist. - - // We got this exception from nameAccess.getByName() despite - // the nameAccess.hasByName() check just above. - - // Try to create. - LOGGER.warn("Could not get section '" + OOBibBase.BIB_SECTION_NAME + "'", ex); - createBibTextSection2(doc); } } @@ -729,6 +709,7 @@ private void populateBibTextSection(XTextDocument doc, boolean alwaysAddCitedOnPages) throws NoSuchElementException, + NoDocumentException, WrappedTargetException, PropertyVetoException, UnknownPropertyException, From 8e62a076beea30c235b5ab17b71221ba1a0f63b0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 15:14:37 +0200 Subject: [PATCH 0700/1068] doc --- src/main/java/org/jabref/logic/openoffice/UnoBookmark.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java index 87c54e87f45..59b194147d2 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java @@ -34,7 +34,7 @@ public static XNameAccess getNameAccess(XTextDocument doc) * Get the XTextRange corresponding to the named bookmark. * * @param name The name of the bookmark to find. - * @return The XTextRange for the bookmark, or null. + * @return The XTextRange for the bookmark, or Optional.empty(). */ public static Optional getTextRange(XTextDocument doc, String name) throws From 62d5af32dc876d597d90df07d2e28caf55bc9d01 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 15:15:05 +0200 Subject: [PATCH 0701/1068] add UnoTextSection.getTextRange --- .../org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- .../jabref/logic/openoffice/UnoTextSection.java | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0fb3550dcbd..52486ff8312 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -686,13 +686,13 @@ private void clearBibTextSectionContent2(XTextDocument doc) CreationException, NoDocumentException { - Optional section = UnoTextSection.getByName(doc, OOBibBase.BIB_SECTION_NAME); - if (section.isEmpty()) { + Optional sectionRange = UnoTextSection.getTextRange(doc, OOBibBase.BIB_SECTION_NAME); + if (sectionRange.isEmpty()) { createBibTextSection2(doc); return; } else { // Clear it - XTextCursor cursor = doc.getText().createTextCursorByRange(section.get().getAnchor()); + XTextCursor cursor = doc.getText().createTextCursorByRange(sectionRange.get()); cursor.setString(""); } } diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java index 3087bc45fb3..804e01e4254 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java @@ -48,6 +48,22 @@ public static Optional getByName(XTextDocument doc, String name) } } + /** + * 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 getTextRange(XTextDocument doc, String name) + throws + WrappedTargetException, + NoDocumentException { + + XNameAccess nameAccess = getNameAccess(doc); + return (UnoNameAccess.getTextContentByName(nameAccess, name) + .map(e -> e.getAnchor())); + } + /** * Create a text section with the provided name and insert it at * the provided cursor. From f4efed3d7d7d189acd2f7d95341d37fc16d8e769 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 15:19:36 +0200 Subject: [PATCH 0702/1068] drop superfluous collapseToEnd --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 52486ff8312..5e198e6a6ab 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -664,8 +664,6 @@ private void createBibTextSection2(XTextDocument doc) // Alternatively, we could receive a cursor. XTextCursor textCursor = doc.getText().createTextCursor(); textCursor.gotoEnd(false); - textCursor.collapseToEnd(); - UnoTextSection.create(doc, OOBibBase.BIB_SECTION_NAME, textCursor, From 4174da7a99ac0b5edbc8c283f28f2cbe0d24ec10 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 15:43:47 +0200 Subject: [PATCH 0703/1068] getTextRange renamed to getAnchor --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- .../org/jabref/logic/openoffice/StorageBaseRefMark.java | 6 +++--- src/main/java/org/jabref/logic/openoffice/UnoBookmark.java | 2 +- .../java/org/jabref/logic/openoffice/UnoReferenceMark.java | 2 +- .../java/org/jabref/logic/openoffice/UnoTextSection.java | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5e198e6a6ab..7fecd6518d3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -579,7 +579,7 @@ private void applyNewCitationMarkers(XTextDocument doc, checkStylesExistInTheDocument(style, doc); CitationGroups cgs = fr.cgs; - final boolean hadBibSection = (UnoBookmark.getTextRange(doc, OOBibBase.BIB_SECTION_NAME) + final boolean hadBibSection = (UnoBookmark.getAnchor(doc, OOBibBase.BIB_SECTION_NAME) .isPresent()); for (Map.Entry kv : citMarkers.entrySet()) { @@ -604,7 +604,7 @@ private void applyNewCitationMarkers(XTextDocument doc, } if (hadBibSection - && (UnoBookmark.getTextRange(doc, OOBibBase.BIB_SECTION_NAME) + && (UnoBookmark.getAnchor(doc, OOBibBase.BIB_SECTION_NAME) .isEmpty())) { // Overwriting text already there is too harsh. // I am making it an error, to see if we ever get here. @@ -684,7 +684,7 @@ private void clearBibTextSectionContent2(XTextDocument doc) CreationException, NoDocumentException { - Optional sectionRange = UnoTextSection.getTextRange(doc, OOBibBase.BIB_SECTION_NAME); + Optional sectionRange = UnoTextSection.getAnchor(doc, OOBibBase.BIB_SECTION_NAME); if (sectionRange.isEmpty()) { createBibTextSection2(doc); return; diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index a11d53add77..38a4cdfa56f 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -138,7 +138,7 @@ private static Optional getFromDocument(XTextDocument doc, throws NoDocumentException, WrappedTargetException { - return (UnoReferenceMark.getTextRange(doc, refMarkName) + return (UnoReferenceMark.getAnchor(doc, refMarkName) .map(e -> new StorageBaseRefMark(refMarkName))); } @@ -166,7 +166,7 @@ public String getName() { * * @return Optional.empty if the reference mark is missing. * - * See: UnoReferenceMark.getTextRange + * See: UnoReferenceMark.getAnchor */ @Override public Optional getMarkRange(XTextDocument doc) @@ -174,7 +174,7 @@ public Optional getMarkRange(XTextDocument doc) NoDocumentException, WrappedTargetException { String name = this.getName(); - return UnoReferenceMark.getTextRange(doc, name); + return UnoReferenceMark.getAnchor(doc, name); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java index 59b194147d2..61c5c89e1c2 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java @@ -36,7 +36,7 @@ public static XNameAccess getNameAccess(XTextDocument doc) * @param name The name of the bookmark to find. * @return The XTextRange for the bookmark, or Optional.empty(). */ - public static Optional getTextRange(XTextDocument doc, String name) + public static Optional getAnchor(XTextDocument doc, String name) throws WrappedTargetException, NoDocumentException { diff --git a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java index 418a934d3f0..15576f26e8d 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java @@ -92,7 +92,7 @@ public static Optional getAsTextContent(XTextDocument doc, String /** * XTextRange for the named reference mark, Optional.empty if not found. */ - public static Optional getTextRange(XTextDocument doc, String name) + public static Optional getAnchor(XTextDocument doc, String name) throws NoDocumentException, WrappedTargetException { diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java index 804e01e4254..02a9de1bb50 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java @@ -54,7 +54,7 @@ public static Optional getByName(XTextDocument doc, String name) * @param name The name of the section to find. * @return The XTextRange for the section, or Optional.empty(). */ - public static Optional getTextRange(XTextDocument doc, String name) + public static Optional getAnchor(XTextDocument doc, String name) throws WrappedTargetException, NoDocumentException { From b4f4507e6e0b710afc3e157a5083d60f3f371dd3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 16:33:20 +0200 Subject: [PATCH 0704/1068] reviewed Uno* --- .../java/org/jabref/logic/openoffice/StorageBaseRefMark.java | 4 ++-- src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java | 2 +- src/main/java/org/jabref/logic/openoffice/UnoCursor.java | 2 +- .../java/org/jabref/logic/openoffice/UnoReferenceMark.java | 4 ++-- src/main/java/org/jabref/logic/openoffice/UnoSelection.java | 2 +- .../java/org/jabref/logic/openoffice/UnoTextDocument.java | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index 38a4cdfa56f..79f991e5b2f 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -203,7 +203,7 @@ public Optional getRawCursor(XTextDocument doc) LOGGER.warn(msg); } - full = UnoCursor.getTextCursorOfTextContent(markAsTextContent.get()); + full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()); if (full.isEmpty()) { String msg = "getRawCursor: full.isEmpty()"; LOGGER.warn(msg); @@ -243,7 +243,7 @@ public XTextCursor getFillCursor(XTextDocument doc) throw new RuntimeException(msg); } - full = UnoCursor.getTextCursorOfTextContent(markAsTextContent.get()).orElse(null); + full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()).orElse(null); if (full == null) { String msg = String.format("getFillCursor: full == null (attempt %d)", i); throw new RuntimeException(msg); diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java b/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java index 53ea40e3738..89ba5bd8b09 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java @@ -70,6 +70,6 @@ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, XTextContent xRefContent = (XTextContent) UnoCast.unoQI(XTextContent.class, xFieldProps); // Insert the text field - doc.getText().insertTextContent(cursor.getEnd(), xRefContent, false); + cursor.getText().insertTextContent(cursor.getEnd(), xRefContent, false); } } diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCursor.java b/src/main/java/org/jabref/logic/openoffice/UnoCursor.java index 18a6872a46a..d495f5c8960 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoCursor.java @@ -28,7 +28,7 @@ public static Optional getViewCursor(XTextDocument doc) { * @return null if mark is null, otherwise cursor. * */ - public static Optional getTextCursorOfTextContent(XTextContent mark) { + public static Optional getTextCursorOfTextContentAnchor(XTextContent mark) { if (mark == null) { return Optional.empty(); } diff --git a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java index 15576f26e8d..fb9458a5fd2 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java @@ -104,8 +104,8 @@ public static Optional getAnchor(XTextDocument doc, String name) * Insert a new reference mark at the provided cursor * position. * - * The text in the cursor range will be the text with gray - * background. + * If {@code absorb} is true, the text in the cursor range will become + * the text with gray background. * * Note: LibreOffice 6.4.6.2 will create multiple reference marks * with the same name without error or renaming. diff --git a/src/main/java/org/jabref/logic/openoffice/UnoSelection.java b/src/main/java/org/jabref/logic/openoffice/UnoSelection.java index ff558388893..ac5c2285d2c 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoSelection.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoSelection.java @@ -74,7 +74,7 @@ public static Optional getSelectionAsXServiceInfo(XTextDocument do * * Presumably result from {@code XSelectionSupplier.getSelection()} is * usually OK. It also accepted - * {@code XTextRange newSelection = documentConnection.xText.getStart();} + * {@code XTextRange newSelection = doc.getText().getStart();} * */ public static void select(XTextDocument doc, Object newSelection) { diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java index 08e1dfa9fb9..4a2031d8dc2 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java @@ -44,7 +44,7 @@ public static Optional getCurrentController(XTextDocument doc) { } /** - * @param doc The XTextDocument we want the title for. Null allowed. + * @param doc The XTextDocument we want the frame title for. Null allowed. * @return The title or Optional.empty() */ public static Optional getFrameTitle(XTextDocument doc) { From f77a75d3d77612db96576c1773246d87d218acc5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 11 May 2021 21:01:51 +0200 Subject: [PATCH 0705/1068] longer names, clarify pageInfosForCitations order --- .../org/jabref/gui/openoffice/OOBibBase.java | 42 +++---- .../jabref/logic/oostyle/CitationGroup.java | 83 ++++++++++--- .../jabref/logic/oostyle/CitationGroups.java | 115 +++++++++++------- .../org/jabref/logic/oostyle/OOProcess.java | 24 ++-- .../jabref/logic/openoffice/Backend52.java | 58 ++++----- .../org/jabref/logic/openoffice/Codec52.java | 22 ++-- .../jabref/logic/openoffice/OOFrontend.java | 8 +- .../model/oostyle/InTextCitationType.java | 2 +- 8 files changed, 210 insertions(+), 144 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 7fecd6518d3..021a0b292dd 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -241,7 +241,7 @@ private static void fillCitationMarkInCursor(XTextDocument doc, * * @param citationKeys BibTeX keys of * @param pageInfosForCitations - * @param itcType + * @param citationType * * @param citationText Text for the citation. A citation mark or * placeholder if not yet available. @@ -258,7 +258,7 @@ private void createAndFillCitationGroup(OOFrontend fr, XTextDocument doc, List citationKeys, List pageInfosForCitations, - InTextCitationType itcType, + InTextCitationType citationType, OOFormattedText citationText, XTextCursor position, boolean withText, @@ -281,7 +281,7 @@ private void createAndFillCitationGroup(OOFrontend fr, CitationGroupID cgid = fr.createCitationGroup(doc, citationKeys, pageInfosForCitations, - itcType, + citationType, position, insertSpaceAfter, !withText /* withoutBrackets */); @@ -447,7 +447,7 @@ public void insertEntry(List entries, .map(OOBibBase::insertEntryGetCitationKey) .collect(Collectors.toList()); - InTextCitationType itcType = OOProcess.citationTypeFromOptions(withText, inParenthesis); + InTextCitationType citationType = OOProcess.citationTypeFromOptions(withText, inParenthesis); // JabRef53 style pageInfo list List pageInfosForCitations = @@ -483,7 +483,7 @@ public void insertEntry(List entries, doc, citationKeys, pageInfosForCitations, - itcType, + citationType, citeText, cursor, withText, @@ -592,7 +592,7 @@ private void applyNewCitationMarkers(XTextDocument doc, CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - boolean withText = (cg.itcType != InTextCitationType.INVISIBLE_CIT); + boolean withText = (cg.citationType != InTextCitationType.INVISIBLE_CIT); if (withText) { @@ -811,11 +811,9 @@ public void combineCiteMarkers(List databases, List> joinableGroups = new ArrayList<>(); List joinableGroupsCursors = new ArrayList<>(); - // Since we only join groups with identical itcTypes, we - // can get itcType from the first element of each + // Since we only join groups with identical citationTypes, we + // can get citationType from the first element of each // joinableGroup. - // - // List itcTypes = new ArrayList<>(); if (referenceMarkNames.size() > 0) { // current group of CitationGroup values @@ -838,17 +836,14 @@ public void combineCiteMarkers(List databases, */ // Only combine (Author 2000) type citations - if (cg.itcType != InTextCitationType.AUTHORYEAR_PAR - // allow "Author (2000)" - // && itcTypes[i] != InTextCitationType.AUTHORYEAR_INTEXT - ) { + if (cg.citationType != InTextCitationType.AUTHORYEAR_PAR) { addToGroup = false; } // Even if we combine AUTHORYEAR_INTEXT citations, we // would not mix them with AUTHORYEAR_PAR if (addToGroup && (prev != null)) { - if (cg.itcType != prev.itcType) { + if (cg.citationType != prev.citationType) { addToGroup = false; } } @@ -928,7 +923,7 @@ public void combineCiteMarkers(List databases, * * Can it start a new group? */ - boolean canStartGroup = (cg.itcType == InTextCitationType.AUTHORYEAR_PAR); + boolean canStartGroup = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); if (!addToGroup) { // close currentGroup @@ -1023,10 +1018,10 @@ public void combineCiteMarkers(List databases, List newGroupCitations = new ArrayList<>(); for (CitationGroup rk : joinableGroup) { - newGroupCitations.addAll(rk.citations); + newGroupCitations.addAll(rk.citationsInStorageOrder); } - InTextCitationType itcType = joinableGroup.get(0).itcType; + InTextCitationType citationType = joinableGroup.get(0).citationType; // cgPageInfos belong to the CitationGroup (DataModel JabRef52), // but it is not clear how should we handle them here. @@ -1057,7 +1052,7 @@ public void combineCiteMarkers(List databases, doc, citationKeys, pageInfosForCitations, - itcType, // InTextCitationType.AUTHORYEAR_PAR + citationType, // InTextCitationType.AUTHORYEAR_PAR OOFormattedText.fromString("tmp"), textCursor, true, // withText @@ -1161,9 +1156,10 @@ public void unCombineCiteMarkers(List databases, XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); // Note: JabRef52 returns cg.pageInfo for the last citation. - List pageInfosForCitations = fr.cgs.getPageInfosForCitations(cg); + List pageInfosForCitations = + fr.cgs.getPageInfosForCitationsInStorageOrder(cg); - List cits = cg.citations; + List cits = cg.citationsInStorageOrder; if (cits.size() <= 1) { pivot++; continue; @@ -1185,12 +1181,12 @@ public void unCombineCiteMarkers(List databases, // We just reread below. boolean insertSpaceAfter = (i != last); - boolean withText = cg.itcType != InTextCitationType.INVISIBLE_CIT; // true + boolean withText = cg.citationType != InTextCitationType.INVISIBLE_CIT; // true createAndFillCitationGroup(fr, doc, keys.subList(i, i + 1), // citationKeys, pageInfosForCitations.subList(i, i + 1), // pageInfos, - InTextCitationType.AUTHORYEAR_PAR, // itcType, + InTextCitationType.AUTHORYEAR_PAR, // citationType, OOFormattedText.fromString("tmp"), textCursor, withText, diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index b5281dc4b6f..509e6fc2121 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -13,35 +13,74 @@ import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; +/* + * A CitationGroup describes a group of citations. + */ public class CitationGroup { + + /* + * Identifies this citation group. + */ public CitationGroupID cgid; - public StorageBase.NamedRange cgRangeStorage; // knows referenceMarkName - public InTextCitationType itcType; - public List citations; + /* + * Identifies location in the document for the backend. + * Could be moved to the backend (which is currently stateless), + * and use cgid to identify. + */ + public StorageBase.NamedRange cgRangeStorage; + + + /* + * The core data, stored in the document: + * The type of citation and citations in storage order. + */ + public InTextCitationType citationType; + public List citationsInStorageOrder; + + /* + * Extra data added during processing: + */ + + /* + * Indices into citations: citations[localOrder[i]] provides ith + * citation according to the currently imposed local order for + * presentation. + */ public List localOrder; /* * A name of a reference mark to link to by formatCitedOnPages. * May be empty, if Backend does not use reference marks. + * + * produceCitationMarkers might want fill it to support + * cross-references to citation groups from the bibliography. */ private Optional referenceMarkNameForLinking; + + /* + * "Cited on pages" uses this to sort the cross-references. + */ private Optional indexInGlobalOrder; public CitationGroup(CitationGroupID cgid, StorageBase.NamedRange cgRangeStorage, - InTextCitationType itcType, - List citations, + InTextCitationType citationType, + List citationsInStorageOrder, Optional referenceMarkNameForLinking) { this.cgid = cgid; this.cgRangeStorage = cgRangeStorage; - this.itcType = itcType; - this.citations = citations; - this.localOrder = makeIndices(citations.size()); + this.citationType = citationType; + this.citationsInStorageOrder = citationsInStorageOrder; + this.localOrder = makeIndices(citationsInStorageOrder.size()); this.referenceMarkNameForLinking = referenceMarkNameForLinking; this.indexInGlobalOrder = Optional.empty(); } + public int numberOfCitations() { + return citationsInStorageOrder.size(); + } + public void setIndexInGlobalOrder(Optional i) { this.indexInGlobalOrder = i; } @@ -64,20 +103,28 @@ static List makeIndices(int n) { } public List getCitationsInLocalOrder() { - List res = new ArrayList<>(citations.size()); + List res = new ArrayList<>(citationsInStorageOrder.size()); for (int i : localOrder) { - res.add(citations.get(i)); + res.add(citationsInStorageOrder.get(i)); } return res; } - public List getSortedNumbers() { + /* + * Values of the number fields of the citations according to + * localOrder. + */ + public List getCitationNumbersInLocalOrder() { List cits = getCitationsInLocalOrder(); return (cits.stream() .map(cit -> cit.number.orElseThrow(RuntimeException::new)) .collect(Collectors.toList())); } + /* + * Helper class for imposeLocalOrderByComparator: a citation + * paired with its storage index. + */ class CitationAndIndex implements CitationSort.ComparableCitation { Citation c; int i; @@ -107,14 +154,20 @@ public Optional getPageInfo() { * Sort citations for presentation within a CitationGroup. */ void imposeLocalOrderByComparator(Comparator entryComparator) { - List cks = new ArrayList<>(); - for (int i = 0; i < citations.size(); i++) { - Citation c = citations.get(i); + + // Pair citations with their storage index in citations + final int nCitations = citationsInStorageOrder.size(); + List cks = new ArrayList<>(nCitations); + for (int i = 0; i < nCitations; i++) { + Citation c = citationsInStorageOrder.get(i); cks.add(new CitationAndIndex(c, i)); } + + // Sort the list cks.sort(new CitationSort.CitationComparator(entryComparator, true)); - List o = new ArrayList<>(); + // Copy ordered storage indices to localOrder + List o = new ArrayList<>(nCitations); for (CitationAndIndex ck : cks) { o.add(ck.i); } diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 41382014700..5898486674e 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -80,7 +80,7 @@ public void setDatabaseLookupResults(Set where, LOGGER.warn("CitationGroups.setDatabaseLookupResult: group missing"); continue; } - Citation cit = cg.citations.get(p.storageIndexInGroup); + Citation cit = cg.citationsInStorageOrder.get(p.storageIndexInGroup); cit.db = db; } } @@ -103,7 +103,7 @@ public void setNumbers(Set where, LOGGER.warn("CitationGroups.setNumbers: group missing"); continue; } - Citation cit = cg.citations.get(p.storageIndexInGroup); + Citation cit = cg.citationsInStorageOrder.get(p.storageIndexInGroup); cit.number = number; } } @@ -116,7 +116,7 @@ public void setUniqueLetters(Set where, LOGGER.warn("CitationGroups.setUniqueLetters: group missing"); continue; } - Citation cit = cg.citations.get(p.storageIndexInGroup); + Citation cit = cg.citationsInStorageOrder.get(p.storageIndexInGroup); cit.uniqueLetter = uniqueLetter; } } @@ -131,7 +131,7 @@ public CitedKeys getCitedKeys() { LinkedHashMap res = new LinkedHashMap<>(); for (CitationGroup cg : citationGroups.values()) { int storageIndexInGroup = 0; - for (Citation cit : cg.citations) { + for (Citation cit : cg.citationsInStorageOrder) { String key = cit.citationKey; CitationPath p = new CitationPath(cg.cgid, storageIndexInGroup); if (res.containsKey(key)) { @@ -161,7 +161,7 @@ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { CitationGroup cg = getCitationGroup(cgid) .orElseThrow(RuntimeException::new); for (int i : cg.localOrder) { - Citation cit = cg.citations.get(i); + Citation cit = cg.citationsInStorageOrder.get(i); String citationKey = cit.citationKey; CitationPath p = new CitationPath(cgid, i); if (res.containsKey(citationKey)) { @@ -249,24 +249,24 @@ public void setGlobalOrder(List globalOrder) { } public Optional getCitationGroup(CitationGroupID cgid) { - CitationGroup e = citationGroups.get(cgid); - return Optional.ofNullable(e); + CitationGroup cg = citationGroups.get(cgid); + return Optional.ofNullable(cg); } /** * Call this when the citation group is unquestionably there. */ public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { - CitationGroup e = citationGroups.get(cgid); - if (e == null) { + CitationGroup cg = citationGroups.get(cgid); + if (cg == null) { throw new RuntimeException("getCitationGroupOrThrow:" + " the requested CitationGroup is not available"); } - return e; + return cg; } - private Optional getItcType(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.itcType); + private Optional getCitationType(CitationGroupID cgid) { + return getCitationGroup(cgid).map(cg -> cg.citationType); } public int numberOfCitationGroups() { @@ -290,50 +290,84 @@ public int numberOfCitationGroups() { * * TODO: we may want class DataModel52, DataModel53 and split this. */ - private static List getPageInfosForCitations(OOStyleDataModelVersion dataModel, - CitationGroup cg) { + private static List + getPageInfosForCitationsInStorageOrder(OOStyleDataModelVersion dataModel, + CitationGroup cg) { switch (dataModel) { case JabRef52: // check conformance to dataModel - final int nCitations = cg.citations.size(); - for (int i = 0; i < nCitations - 1; i++) { - if (cg.citations.get(i).pageInfo.isPresent()) { - throw new RuntimeException("getPageInfosForCitations:" - + " found Citation.pageInfo" - + " outside last citation under JabRef52 dataModel"); + final int nCitations = cg.numberOfCitations(); + final int last = nCitations - 1; + final boolean checkDataModelConformance = false; + if (checkDataModelConformance) { + for (int i = 0; i < last; i++) { + if (cg.citationsInStorageOrder.get(i).pageInfo.isPresent()) { + throw new RuntimeException("getPageInfosForCitations:" + + " found Citation.pageInfo" + + " outside last citation under JabRef52 dataModel"); + } } } - // A list of null values, except the last that comes from this.pageInfo - List result = new ArrayList<>(cg.citations.size()); + OOFormattedText thePageInfo = cg.citationsInStorageOrder.get(last).pageInfo.orElse(null); + + // For JabRef52 the citation last in localOrder gets the pageInfo. + final int theLastInLocalOrder = cg.localOrder.get(last); + List result = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { - int j = cg.localOrder.get(i); - OOFormattedText value = cg.citations.get(j).pageInfo.orElse(null); - result.add(value); + if (i == theLastInLocalOrder) { + result.add(thePageInfo); + } else { + result.add(null); + } } return result; case JabRef53: // pageInfo values from citations, empty mapped to null. - return (cg.citations.stream() + return (cg.citationsInStorageOrder.stream() .map(cit -> cit.pageInfo.orElse(null)) .collect(Collectors.toList())); default: - throw new RuntimeException("getPageInfosForCitations:" + throw new RuntimeException("getPageInfosForCitationsInStorageOrder:" + "unhandled dataModel"); } } - public List getPageInfosForCitations(CitationGroup cg) { - return getPageInfosForCitations(this.dataModel, cg); + /** + * @return List of nullable pageInfo values, one for each citation, + * in localOrder. + */ + private static List + getPageInfosForCitationsInLocalOrder(OOStyleDataModelVersion dataModel, CitationGroup cg) { + final int nCitations = cg.numberOfCitations(); + List result = new ArrayList<>(nCitations); + List inStorageOrder = getPageInfosForCitationsInStorageOrder(dataModel, cg); + for (int i = 0; i < nCitations; i++) { + result.add(inStorageOrder.get(cg.localOrder.get(i))); + } + return result; + } + + public List getPageInfosForCitationsInStorageOrder(CitationGroup cg) { + return getPageInfosForCitationsInStorageOrder(this.dataModel, cg); } - public List getPageInfosForCitations(CitationGroupID cgid) { + public List getPageInfosForCitationsInStorageOrder(CitationGroupID cgid) { CitationGroup cg = getCitationGroupOrThrow(cgid); - return getPageInfosForCitations(cg); + return getPageInfosForCitationsInStorageOrder(cg); + } + + public List getPageInfosForCitationsInLocalOrder(CitationGroup cg) { + return getPageInfosForCitationsInLocalOrder(this.dataModel, cg); + } + + public List getPageInfosForCitationsInLocalOrder(CitationGroupID cgid) { + CitationGroup cg = getCitationGroupOrThrow(cgid); + return getPageInfosForCitationsInLocalOrder(cg); } public Optional> getCitations(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.citations); + return getCitationGroup(cgid).map(cg -> cg.citationsInStorageOrder); } public List getCitationsInLocalOrder(CitationGroupID cgid) { @@ -357,12 +391,12 @@ public boolean citationGroupsProvideReferenceMarkNameForLinking() { } public void afterCreateCitationGroup(CitationGroup cg) { - // add to our data this.citationGroups.put(cg.cgid, cg); // invalidate globalOrder. - // TODO: look out for localOrder! this.globalOrder = Optional.empty(); + // Note: we cannot impose localOrder, since we do not know + // how it was imposed. We leave it to an upper level. } public void afterRemoveCitationGroup(CitationGroup cg) { @@ -374,18 +408,7 @@ public void afterRemoveCitationGroup(CitationGroup cg) { // Invalidate what we cannot this.bibliography = Optional.empty(); // Could also: reset citation.number, citation.uniqueLetter. - } - - /** - * This is for debugging, can be removed. - */ - public void xshow() { - System.out.printf("CitationGroups%n"); - System.out.printf(" citationGroups.size: %d%n", citationGroups.size()); - System.out.printf(" globalOrder: %s%n", - (globalOrder.isEmpty() - ? "isEmpty" - : String.format("%d", globalOrder.get().size()))); + // Proper update would need style, we do not do it here. } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 7f0072cf693..72706cfe5e2 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -183,7 +183,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, /** * Given the withText and inParenthesis options, - * return the corresponding itcType. + * return the corresponding citationType. * * @param withText False means invisible citation (no text). * @param inParenthesis True means "(Au and Thor 2000)". @@ -252,8 +252,8 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - List numbers = cg.getSortedNumbers(); - List pageInfos = cgs.getPageInfosForCitations(cg); + List numbers = cg.getCitationNumbersInLocalOrder(); + List pageInfos = cgs.getPageInfosForCitationsInLocalOrder(cg); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, @@ -281,8 +281,8 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - List numbers = cg.getSortedNumbers(); - List pageInfos = cgs.getPageInfosForCitations(cg); + List numbers = cg.getCitationNumbersInLocalOrder(); + List pageInfos = cgs.getPageInfosForCitationsInLocalOrder(cg); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, @@ -322,9 +322,10 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + List cits = cg.getCitationsInLocalOrder(); final int nCitedEntries = cits.size(); - List pageInfosForCitations = cgs.getPageInfosForCitations(cg); + List pageInfosForCitations = cgs.getPageInfosForCitationsInLocalOrder(cg); List citationMarkerEntries = new ArrayList<>(nCitedEntries); @@ -359,6 +360,9 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole // maybe the fall back to ungrouped citations here is // not needed anymore. + final boolean inParenthesis = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); + final OOBibStyle.NonUniqueCitationMarker strictlyUnique = + OOBibStyle.NonUniqueCitationMarker.THROWS; if (hasUnresolved) { /* * Some entries are unresolved. @@ -370,8 +374,8 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole if (cm.getBibEntry().isPresent()) { s = (s + style.getCitationMarker(citationMarkerEntries.subList(j, j + 1), - cg.itcType == InTextCitationType.AUTHORYEAR_PAR, - OOBibStyle.NonUniqueCitationMarker.THROWS)); + inParenthesis, + strictlyUnique)); } else { s = s + String.format("(Unresolved(%s))", cm.getCitationKey()); } @@ -383,8 +387,8 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole */ OOFormattedText citMarker = style.getCitationMarker(citationMarkerEntries, - cg.itcType == InTextCitationType.AUTHORYEAR_PAR, - OOBibStyle.NonUniqueCitationMarker.THROWS); + inParenthesis, + strictlyUnique); citMarkers.put(cgid, citMarker); } } diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index c1bfc4b83bc..8ca0571af14 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -141,17 +141,17 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str setPageInfoInData(citations, pageInfo); - Optional sr = (citationStorageManager - .getFromDocument(doc, refMarkName)); + Optional storedRange = (citationStorageManager + .getFromDocument(doc, refMarkName)); - if (sr.isEmpty()) { + if (storedRange.isEmpty()) { throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" + " referenceMarkName is not in the document"); } CitationGroup cg = new CitationGroup(id, - sr.get(), - ov.itcType, + storedRange.get(), + ov.citationType, citations, Optional.of(refMarkName)); return cg; @@ -206,7 +206,7 @@ static Optional normalizePageInfoToOptional(OOFormattedText o) * cleanFillCursorForCitationGroup overrides this, and for empty * citations it will remove the brackets, leaving an empty * reference mark. The idea behind this is that we do not need to - * refill empty marks (itcTypes INVISIBLE_CIT), and the caller + * refill empty marks (citationType: INVISIBLE_CIT), and the caller * can tell us that we are dealing with one of these. * * Thus the only user-visible difference in citation marks is @@ -231,7 +231,7 @@ static Optional normalizePageInfoToOptional(OOFormattedText o) public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, List pageInfosForCitations, - InTextCitationType itcType, + InTextCitationType citationType, XTextCursor position, boolean insertSpaceAfter, boolean withoutBrackets) @@ -244,15 +244,9 @@ public CitationGroup createCitationGroup(XTextDocument doc, PropertyVetoException, IllegalTypeException { - String xkey = (citationKeys.stream() - .collect(Collectors.joining(","))); - - Set usedNames = new HashSet<>(this.citationStorageManager - .getUsedNames(doc)); - - String refMarkName = Codec52.getUniqueMarkName(usedNames, - xkey, - itcType); + Set usedNames = new HashSet<>(this.citationStorageManager.getUsedNames(doc)); + String xkey = (citationKeys.stream().collect(Collectors.joining(","))); + String refMarkName = Codec52.getUniqueMarkName(usedNames, xkey, citationType); CitationGroupID cgid = new CitationGroupID(refMarkName); @@ -280,11 +274,9 @@ public CitationGroup createCitationGroup(XTextDocument doc, /* * Apply to document */ - StorageBase.NamedRange sr = this.citationStorageManager.create(doc, - refMarkName, - position, - insertSpaceAfter, - withoutBrackets); + StorageBase.NamedRange storedRange = + this.citationStorageManager.create(doc, refMarkName, position, insertSpaceAfter, + withoutBrackets); switch (dataModel) { case JabRef52: @@ -296,11 +288,8 @@ public CitationGroup createCitationGroup(XTextDocument doc, // do not inherit from trash UnoUserDefinedProperty.removeIfExists(doc, refMarkName); } - CitationGroup cg = new CitationGroup(cgid, - sr, - itcType, - citations, - Optional.of(refMarkName)); + CitationGroup cg = + new CitationGroup(cgid, storedRange, citationType, citations, Optional.of(refMarkName)); return cg; default: throw new RuntimeException("Backend52 requires JabRef52 dataModel"); @@ -319,9 +308,10 @@ public static List combinePageInfosCommon(OOStyleDataModelVersi switch (dataModel) { case JabRef52: // collect to cgPageInfos - List> cgPageInfos = (joinableGroup.stream() - .map(cg -> getPageInfoFromData(cg.citations)) - .collect(Collectors.toList())); + List> cgPageInfos = + (joinableGroup.stream() + .map(cg -> getPageInfoFromData(cg.citationsInStorageOrder)) + .collect(Collectors.toList())); // Try to do something of the cgPageInfos. String cgPageInfo = (cgPageInfos.stream() @@ -331,14 +321,14 @@ public static List combinePageInfosCommon(OOStyleDataModelVersi .collect(Collectors.joining("; "))); int nCitations = (joinableGroup.stream() - .map(cg -> cg.citations.size()) + .map(cg -> cg.numberOfCitations()) .mapToInt(Integer::intValue).sum()); return OOStyleDataModelVersion.fakePageInfosForCitations(cgPageInfo, nCitations); case JabRef53: return (joinableGroup.stream() - .flatMap(cg -> (cg.citations.stream() + .flatMap(cg -> (cg.citationsInStorageOrder.stream() .map(cit -> cit.pageInfo.orElse(null)))) .collect(Collectors.toList())); default: @@ -433,9 +423,9 @@ public List getCitationEntries(XTextDocument doc, CitationGroups .getRawCursorForCitationGroup(cg, doc) .orElseThrow(RuntimeException::new)); String context = OOUtil.getCursorStringWithContext(cursor, 30, 30, true); - Optional pageInfo = (cg.citations.size() > 0 - ? (cg.citations - .get(cg.citations.size() - 1) + Optional pageInfo = (cg.numberOfCitations() > 0 + ? (cg.citationsInStorageOrder + .get(cg.numberOfCitations() - 1) .getPageInfo() .map(e -> OOFormattedText.toString(e))) : Optional.empty()); diff --git a/src/main/java/org/jabref/logic/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/Codec52.java index 4e4c0e33e4f..4ab1611eefd 100644 --- a/src/main/java/org/jabref/logic/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/Codec52.java @@ -21,7 +21,7 @@ class Codec52 { private static final String BIB_CITATION = "JR_cite"; private static final Pattern CITE_PATTERN = // Pattern.compile(BIB_CITATION + "(\\d*)_(\\d*)_(.*)"); - // itcType is always "1" "2" or "3" + // citationType is always "1" "2" or "3" Pattern.compile(BIB_CITATION + "(\\d*)_([123])_(.*)"); /** @@ -32,15 +32,15 @@ public static class ParsedMarkName { /** "", "0", "1" ... */ public final String i; /** in-text-citation type */ - public final InTextCitationType itcType; + public final InTextCitationType citationType; /** Citation keys embedded in the reference mark. */ public final List citationKeys; - ParsedMarkName(String i, InTextCitationType itcType, List citationKeys) { + ParsedMarkName(String i, InTextCitationType citationType, List citationKeys) { Objects.requireNonNull(i); Objects.requireNonNull(citationKeys); this.i = i; - this.itcType = itcType; + this.citationType = citationType; this.citationKeys = citationKeys; } } @@ -77,12 +77,12 @@ public static int InTextCitationTypeToInt(InTextCitationType i) { /** * Produce a reference mark name for JabRef for the given citation - * key and itcType that does not yet appear among the reference + * key and citationType that does not yet appear among the reference * marks of the document. * * @param bibtexKey The citation key. - * @param itcType Encodes the effect of withText and - * inParenthesis options. + * @param citationType Encodes the effect of withText and + * inParenthesis options. * * The first occurrence of bibtexKey gets no serial number, the * second gets 0, the third 1 ... @@ -91,11 +91,11 @@ public static int InTextCitationTypeToInt(InTextCitationType i) { */ public static String getUniqueMarkName(Set usedNames, String bibtexKey, - InTextCitationType itcType) + InTextCitationType citationType) throws NoDocumentException { int i = 0; - int j = InTextCitationTypeToInt(itcType); + int j = InTextCitationTypeToInt(citationType); String name = BIB_CITATION + '_' + j + '_' + bibtexKey; while (usedNames.contains(name)) { name = BIB_CITATION + i + '_' + j + '_' + bibtexKey; @@ -120,8 +120,8 @@ public static Optional parseMarkName(String refMarkName) { List keys = Arrays.asList(citeMatcher.group(3).split(",")); String i = citeMatcher.group(1); int j = Integer.parseInt(citeMatcher.group(2)); - InTextCitationType itcType = InTextCitationTypeFromInt(j); - return (Optional.of(new Codec52.ParsedMarkName(i, itcType, keys))); + InTextCitationType citationType = InTextCitationTypeFromInt(j); + return (Optional.of(new Codec52.ParsedMarkName(i, citationType, keys))); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 086dc8fa842..d7eaf93b19a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -282,7 +282,7 @@ private List getVisuallySortedCitationGroupIDs(XTextDocument do * cleanFillCursorForCitationGroup overrides this, and for empty * citations it will remove the brackets, leaving an empty * reference mark. The idea behind this is that we do not need to - * refill empty marks (itcTypes INVISIBLE_CIT), and the caller + * refill empty marks (citationType INVISIBLE_CIT), and the caller * can tell us that we are dealing with one of these. * * Thus the only user-visible difference in citation marks is @@ -297,7 +297,7 @@ private List getVisuallySortedCitationGroupIDs(XTextDocument do * * @param citationKeys * @param pageInfosForCitations - * @param itcType + * @param citationType * @param position Collapsed to its end. * @param insertSpaceAfter If true, we insert a space after the mark, that * carries on format of characters from @@ -310,7 +310,7 @@ private List getVisuallySortedCitationGroupIDs(XTextDocument do public CitationGroupID createCitationGroup(XTextDocument doc, List citationKeys, List pageInfosForCitations, - InTextCitationType itcType, + InTextCitationType citationType, XTextCursor position, boolean insertSpaceAfter, boolean withoutBrackets) @@ -326,7 +326,7 @@ public CitationGroupID createCitationGroup(XTextDocument doc, CitationGroup cg = backend.createCitationGroup(doc, citationKeys, pageInfosForCitations, - itcType, + citationType, position, insertSpaceAfter, withoutBrackets); diff --git a/src/main/java/org/jabref/model/oostyle/InTextCitationType.java b/src/main/java/org/jabref/model/oostyle/InTextCitationType.java index d3a16956c28..060d54082c2 100644 --- a/src/main/java/org/jabref/model/oostyle/InTextCitationType.java +++ b/src/main/java/org/jabref/model/oostyle/InTextCitationType.java @@ -1,7 +1,7 @@ package org.jabref.model.oostyle; /* - * Types of in-text citation. (itcType) + * Types of in-text citation. (citationType) */ public enum InTextCitationType { AUTHORYEAR_PAR, From fcf3724e83d7bf52761538edc29b9741fa8d4b18 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 12 May 2021 08:53:33 +0200 Subject: [PATCH 0706/1068] CitationGroup.localOrder is private --- .../org/jabref/logic/oostyle/CitationGroup.java | 17 ++++++++++++----- .../jabref/logic/oostyle/CitationGroups.java | 6 +++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index 509e6fc2121..62f0908d342 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -1,6 +1,7 @@ package org.jabref.logic.oostyle; import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Optional; @@ -21,22 +22,22 @@ public class CitationGroup { /* * Identifies this citation group. */ - public CitationGroupID cgid; + public final CitationGroupID cgid; /* * Identifies location in the document for the backend. * Could be moved to the backend (which is currently stateless), * and use cgid to identify. */ - public StorageBase.NamedRange cgRangeStorage; + public final StorageBase.NamedRange cgRangeStorage; /* * The core data, stored in the document: * The type of citation and citations in storage order. */ - public InTextCitationType citationType; - public List citationsInStorageOrder; + public final InTextCitationType citationType; + public final List citationsInStorageOrder; /* * Extra data added during processing: @@ -46,8 +47,10 @@ public class CitationGroup { * Indices into citations: citations[localOrder[i]] provides ith * citation according to the currently imposed local order for * presentation. + * + * Initialized to (0..(nCitations-1)) in the constructor. */ - public List localOrder; + private List localOrder; /* * A name of a reference mark to link to by formatCitedOnPages. @@ -81,6 +84,10 @@ public int numberOfCitations() { return citationsInStorageOrder.size(); } + public List getLocalOrder() { + return Collections.unmodifiableList(localOrder); + } + public void setIndexInGlobalOrder(Optional i) { this.indexInGlobalOrder = i; } diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 5898486674e..3f11787d8ff 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -160,7 +160,7 @@ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { for (CitationGroupID cgid : globalOrder.get()) { CitationGroup cg = getCitationGroup(cgid) .orElseThrow(RuntimeException::new); - for (int i : cg.localOrder) { + for (int i : cg.getLocalOrder()) { Citation cit = cg.citationsInStorageOrder.get(i); String citationKey = cit.citationKey; CitationPath p = new CitationPath(cgid, i); @@ -311,7 +311,7 @@ public int numberOfCitationGroups() { OOFormattedText thePageInfo = cg.citationsInStorageOrder.get(last).pageInfo.orElse(null); // For JabRef52 the citation last in localOrder gets the pageInfo. - final int theLastInLocalOrder = cg.localOrder.get(last); + final int theLastInLocalOrder = cg.getLocalOrder().get(last); List result = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { if (i == theLastInLocalOrder) { @@ -343,7 +343,7 @@ public int numberOfCitationGroups() { List result = new ArrayList<>(nCitations); List inStorageOrder = getPageInfosForCitationsInStorageOrder(dataModel, cg); for (int i = 0; i < nCitations; i++) { - result.add(inStorageOrder.get(cg.localOrder.get(i))); + result.add(inStorageOrder.get(cg.getLocalOrder().get(i))); } return result; } From d4a95cbaaa6787411de7a564a1fcdbbdf65e12c4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 12 May 2021 12:15:49 +0200 Subject: [PATCH 0707/1068] add Pair --- .../org/jabref/gui/openoffice/OOBibBase.java | 4 +- .../org/jabref/logic/oostyle/Citation.java | 16 ++ .../jabref/logic/oostyle/CitationGroup.java | 140 ++++++++++-------- .../jabref/logic/oostyle/CitationGroups.java | 136 ++++++++--------- .../jabref/logic/openoffice/Backend52.java | 10 +- .../openoffice/OOFormattedTextIntoOO.java | 33 +---- .../openoffice/OOFormattedTextIntoOOV1.java | 29 +--- .../jabref/logic/openoffice/OOFrontend.java | 4 +- .../org/jabref/logic/openoffice/Pair.java | 11 ++ 9 files changed, 195 insertions(+), 188 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/Pair.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 021a0b292dd..05d1f91a377 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1138,7 +1138,7 @@ public void unCombineCiteMarkers(List databases, boolean madeModifications = false; // {@code names} does not need to be sorted. - List names = new ArrayList<>(fr.cgs.getCitationGroupIDs()); + List names = new ArrayList<>(fr.cgs.getCitationGroupIDsUnordered()); try { if (useLockControllers) { @@ -1288,7 +1288,7 @@ private ExportCitedHelperResult generateDatabase(List databases, UnknownPropertyException { OOFrontend fr = new OOFrontend(doc); - CitedKeys cks = fr.cgs.getCitedKeys(); + CitedKeys cks = fr.cgs.getCitedKeysUnordered(); cks.lookupInDatabases(databases); List unresolvedKeys = new ArrayList<>(); diff --git a/src/main/java/org/jabref/logic/oostyle/Citation.java b/src/main/java/org/jabref/logic/oostyle/Citation.java index 5badb760c4f..821e2c50807 100644 --- a/src/main/java/org/jabref/logic/oostyle/Citation.java +++ b/src/main/java/org/jabref/logic/oostyle/Citation.java @@ -2,6 +2,7 @@ import java.util.Optional; +import org.jabref.logic.openoffice.Pair; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.OOFormattedText; @@ -51,4 +52,19 @@ public Optional getBibEntry() { ? Optional.of(db.get().entry) : Optional.empty()); } + + public static void setDatabaseLookupResult(Pair> x) { + Citation cit = x.a; + cit.db = x.b; + } + + public static void setNumber(Pair> x) { + Citation cit = x.a; + cit.number = x.b; + } + + public static void setUniqueLetter(Pair> x) { + Citation cit = x.a; + cit.uniqueLetter = x.b; + } } diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index 62f0908d342..e9ef0a05e19 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -13,12 +13,15 @@ import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOStyleDataModelVersion; /* * A CitationGroup describes a group of citations. */ public class CitationGroup { + public final OOStyleDataModelVersion dataModel; + /* * Identifies this citation group. */ @@ -26,12 +29,9 @@ public class CitationGroup { /* * Identifies location in the document for the backend. - * Could be moved to the backend (which is currently stateless), - * and use cgid to identify. */ public final StorageBase.NamedRange cgRangeStorage; - /* * The core data, stored in the document: * The type of citation and citations in storage order. @@ -40,8 +40,17 @@ public class CitationGroup { public final List citationsInStorageOrder; /* - * Extra data added during processing: + * Extra data + */ + + /* + * A name of a reference mark to link to by formatCitedOnPages. + * May be ininitially empty, if backend does not use reference marks. + * + * produceCitationMarkers might want fill it to support + * cross-references to citation groups from the bibliography. */ + private Optional referenceMarkNameForLinking; /* * Indices into citations: citations[localOrder[i]] provides ith @@ -52,29 +61,22 @@ public class CitationGroup { */ private List localOrder; - /* - * A name of a reference mark to link to by formatCitedOnPages. - * May be empty, if Backend does not use reference marks. - * - * produceCitationMarkers might want fill it to support - * cross-references to citation groups from the bibliography. - */ - private Optional referenceMarkNameForLinking; - /* * "Cited on pages" uses this to sort the cross-references. */ private Optional indexInGlobalOrder; - public CitationGroup(CitationGroupID cgid, + public CitationGroup(OOStyleDataModelVersion dataModel, + CitationGroupID cgid, StorageBase.NamedRange cgRangeStorage, InTextCitationType citationType, List citationsInStorageOrder, Optional referenceMarkNameForLinking) { + this.dataModel = dataModel; this.cgid = cgid; this.cgRangeStorage = cgRangeStorage; this.citationType = citationType; - this.citationsInStorageOrder = citationsInStorageOrder; + this.citationsInStorageOrder = Collections.unmodifiableList(citationsInStorageOrder); this.localOrder = makeIndices(citationsInStorageOrder.size()); this.referenceMarkNameForLinking = referenceMarkNameForLinking; this.indexInGlobalOrder = Optional.empty(); @@ -84,55 +86,20 @@ public int numberOfCitations() { return citationsInStorageOrder.size(); } - public List getLocalOrder() { - return Collections.unmodifiableList(localOrder); - } - - public void setIndexInGlobalOrder(Optional i) { - this.indexInGlobalOrder = i; - } - - public Optional getIndexInGlobalOrder() { - return this.indexInGlobalOrder; - } - - public Optional getReferenceMarkNameForLinking() { - return referenceMarkNameForLinking; - } - - public void setReferenceMarkNameForLinking(Optional referenceMarkNameForLinking) { - this.referenceMarkNameForLinking = referenceMarkNameForLinking; - } + /* + * localOrder + */ /** Integers 0..(n-1) */ static List makeIndices(int n) { return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); } - public List getCitationsInLocalOrder() { - List res = new ArrayList<>(citationsInStorageOrder.size()); - for (int i : localOrder) { - res.add(citationsInStorageOrder.get(i)); - } - return res; - } - - /* - * Values of the number fields of the citations according to - * localOrder. - */ - public List getCitationNumbersInLocalOrder() { - List cits = getCitationsInLocalOrder(); - return (cits.stream() - .map(cit -> cit.number.orElseThrow(RuntimeException::new)) - .collect(Collectors.toList())); - } - /* * Helper class for imposeLocalOrderByComparator: a citation * paired with its storage index. */ - class CitationAndIndex implements CitationSort.ComparableCitation { + private class CitationAndIndex implements CitationSort.ComparableCitation { Citation c; int i; @@ -164,20 +131,71 @@ void imposeLocalOrderByComparator(Comparator entryComparator) { // Pair citations with their storage index in citations final int nCitations = citationsInStorageOrder.size(); - List cks = new ArrayList<>(nCitations); + List cis = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { Citation c = citationsInStorageOrder.get(i); - cks.add(new CitationAndIndex(c, i)); + cis.add(new CitationAndIndex(c, i)); } // Sort the list - cks.sort(new CitationSort.CitationComparator(entryComparator, true)); + cis.sort(new CitationSort.CitationComparator(entryComparator, true)); // Copy ordered storage indices to localOrder - List o = new ArrayList<>(nCitations); - for (CitationAndIndex ck : cks) { - o.add(ck.i); + List ordered = new ArrayList<>(nCitations); + for (CitationAndIndex ci : cis) { + ordered.add(ci.i); } - this.localOrder = o; + this.localOrder = ordered; + } + + public List getLocalOrder() { + return Collections.unmodifiableList(localOrder); + } + + /* + * citations + */ + + public List getCitationsInLocalOrder() { + List res = new ArrayList<>(citationsInStorageOrder.size()); + for (int i : localOrder) { + res.add(citationsInStorageOrder.get(i)); + } + return res; + } + + /* + * Values of the number fields of the citations according to + * localOrder. + */ + public List getCitationNumbersInLocalOrder() { + List cits = getCitationsInLocalOrder(); + return (cits.stream() + .map(cit -> cit.number.orElseThrow(RuntimeException::new)) + .collect(Collectors.toList())); + } + + /* + * indexInGlobalOrder + */ + + public void setIndexInGlobalOrder(Optional i) { + this.indexInGlobalOrder = i; + } + + public Optional getIndexInGlobalOrder() { + return this.indexInGlobalOrder; + } + + /* + * referenceMarkNameForLinking + */ + + public Optional getReferenceMarkNameForLinking() { + return referenceMarkNameForLinking; + } + + public void setReferenceMarkNameForLinking(Optional referenceMarkNameForLinking) { + this.referenceMarkNameForLinking = referenceMarkNameForLinking; } } // class CitationGroup diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 3f11787d8ff..45169802c2e 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -8,8 +8,10 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.function.Consumer; import java.util.stream.Collectors; +import org.jabref.logic.openoffice.Pair; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.CitationDatabaseLookup; @@ -35,7 +37,7 @@ public class CitationGroups { /** * Original CitationGroups Data */ - private Map citationGroups; + private Map citationGroupsUnordered; /* * Extra Data @@ -62,7 +64,7 @@ public CitationGroups(OOStyleDataModelVersion dataModel, Map citationGroups) { this.dataModel = dataModel; - this.citationGroups = citationGroups; + this.citationGroupsUnordered = citationGroups; // Now we have almost every information from the document about citations. // What is left out: the ranges controlled by the reference marks. @@ -72,64 +74,88 @@ public CitationGroups(OOStyleDataModelVersion dataModel, this.bibliography = Optional.empty(); } - public void setDatabaseLookupResults(Set where, - Optional db) { + public int numberOfCitationGroups() { + return citationGroupsUnordered.size(); + } + + /** + * For each citation in {@code where} + * call {@code fun.accept(new Pair(citation, value));} + */ + public void distribute(Set where, + Consumer> fun, + T value) { + for (CitationPath p : where) { - CitationGroup cg = this.citationGroups.get(p.group); + CitationGroup cg = this.citationGroupsUnordered.get(p.group); if (cg == null) { - LOGGER.warn("CitationGroups.setDatabaseLookupResult: group missing"); + LOGGER.warn("CitationGroups.distribute: group missing"); continue; } Citation cit = cg.citationsInStorageOrder.get(p.storageIndexInGroup); - cit.db = db; + fun.accept(new Pair(cit, value)); } } + public void setDatabaseLookupResults(Set where, + Optional db) { + distribute(where, Citation::setDatabaseLookupResult, db); + } + public CitedKeys lookupEntriesInDatabases(List databases) { CitationGroups cgs = this; - - CitedKeys cks = cgs.getCitedKeys(); + CitedKeys cks = cgs.getCitedKeysUnordered(); cks.lookupInDatabases(databases); cks.distributeDatabaseLookupResults(cgs); return cks; } - public void setNumbers(Set where, - Optional number) { - for (CitationPath p : where) { - CitationGroup cg = this.citationGroups.get(p.group); - if (cg == null) { - LOGGER.warn("CitationGroups.setNumbers: group missing"); - continue; - } - Citation cit = cg.citationsInStorageOrder.get(p.storageIndexInGroup); - cit.number = number; + public Set getCitationGroupIDsUnordered() { + return citationGroupsUnordered.keySet(); + } + + /** + * Citation group IDs in {@code globalOrder} + */ + public List getSortedCitationGroupIDs() { + if (globalOrder.isEmpty()) { + throw new RuntimeException("getSortedCitationGroupIDs: not ordered yet"); } + return globalOrder.get(); } - public void setUniqueLetters(Set where, - Optional uniqueLetter) { - for (CitationPath p : where) { - CitationGroup cg = this.citationGroups.get(p.group); - if (cg == null) { - LOGGER.warn("CitationGroups.setUniqueLetters: group missing"); - continue; - } - Citation cit = cg.citationsInStorageOrder.get(p.storageIndexInGroup); - cit.uniqueLetter = uniqueLetter; + public void setGlobalOrder(List globalOrder) { + Objects.requireNonNull(globalOrder); + if (globalOrder.size() != citationGroupsUnordered.size()) { + throw new RuntimeException("setGlobalOrder:" + + " globalOrder.size() != citationGroups.size()"); } + this.globalOrder = Optional.of(globalOrder); + int i = 0; + for (CitationGroupID cgid : globalOrder) { + citationGroupsUnordered.get(cgid).setIndexInGlobalOrder(Optional.of(i)); + i++; + } + } + + public void setNumbers(Set where, Optional number) { + distribute(where, Citation::setNumber, number); + } + + public void setUniqueLetters(Set where, Optional uniqueLetter) { + distribute(where, Citation::setUniqueLetter, uniqueLetter); } public void imposeLocalOrderByComparator(Comparator entryComparator) { - for (CitationGroup cg : citationGroups.values()) { + for (CitationGroup cg : citationGroupsUnordered.values()) { cg.imposeLocalOrderByComparator(entryComparator); } } - public CitedKeys getCitedKeys() { + public CitedKeys getCitedKeysUnordered() { LinkedHashMap res = new LinkedHashMap<>(); - for (CitationGroup cg : citationGroups.values()) { + for (CitationGroup cg : citationGroupsUnordered.values()) { int storageIndexInGroup = 0; for (Citation cit : cg.citationsInStorageOrder) { String key = cit.citationKey; @@ -199,7 +225,7 @@ public void createPlainBibliographySortedByComparator(Comparator entry throw new RuntimeException("createPlainBibliographySortedByComparator:" + " already have a bibliography"); } - CitedKeys citedKeys = cgs.getCitedKeys(); + CitedKeys citedKeys = cgs.getCitedKeysUnordered(); citedKeys.sortByComparator(entryComparator); this.bibliography = Optional.of(citedKeys); } @@ -213,43 +239,15 @@ public void createNumberedBibliographySortedByComparator(Comparator en throw new RuntimeException("createNumberedBibliographySortedByComparator:" + " already have a bibliography"); } - CitedKeys citedKeys = cgs.getCitedKeys(); + CitedKeys citedKeys = cgs.getCitedKeysUnordered(); citedKeys.sortByComparator(entryComparator); citedKeys.numberCitedKeysInCurrentOrder(); citedKeys.distributeNumbers(cgs); this.bibliography = Optional.of(citedKeys); } - public Set getCitationGroupIDs() { - return citationGroups.keySet(); - } - - /** - * Citation group IDs in {@code globalOrder} - */ - public List getSortedCitationGroupIDs() { - if (globalOrder.isEmpty()) { - throw new RuntimeException("getSortedCitationGroupIDs: not ordered yet"); - } - return globalOrder.get(); - } - - public void setGlobalOrder(List globalOrder) { - Objects.requireNonNull(globalOrder); - if (globalOrder.size() != citationGroups.size()) { - throw new RuntimeException("setGlobalOrder:" - + " globalOrder.size() != citationGroups.size()"); - } - this.globalOrder = Optional.of(globalOrder); - int i = 0; - for (CitationGroupID cgid : globalOrder) { - citationGroups.get(cgid).setIndexInGlobalOrder(Optional.of(i)); - i++; - } - } - public Optional getCitationGroup(CitationGroupID cgid) { - CitationGroup cg = citationGroups.get(cgid); + CitationGroup cg = citationGroupsUnordered.get(cgid); return Optional.ofNullable(cg); } @@ -257,7 +255,7 @@ public Optional getCitationGroup(CitationGroupID cgid) { * Call this when the citation group is unquestionably there. */ public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { - CitationGroup cg = citationGroups.get(cgid); + CitationGroup cg = citationGroupsUnordered.get(cgid); if (cg == null) { throw new RuntimeException("getCitationGroupOrThrow:" + " the requested CitationGroup is not available"); @@ -269,10 +267,6 @@ private Optional getCitationType(CitationGroupID cgid) { return getCitationGroup(cgid).map(cg -> cg.citationType); } - public int numberOfCitationGroups() { - return citationGroups.size(); - } - /** * @return List of nullable pageInfo values, one for each citation, * instrage order. @@ -382,7 +376,7 @@ public List getCitationsInLocalOrder(CitationGroupID cgid) { * @return true if all citation groups have referenceMarkNameForLinking */ public boolean citationGroupsProvideReferenceMarkNameForLinking() { - for (CitationGroup cg : citationGroups.values()) { + for (CitationGroup cg : citationGroupsUnordered.values()) { if (cg.getReferenceMarkNameForLinking().isEmpty()) { return false; } @@ -392,7 +386,7 @@ public boolean citationGroupsProvideReferenceMarkNameForLinking() { public void afterCreateCitationGroup(CitationGroup cg) { // add to our data - this.citationGroups.put(cg.cgid, cg); + this.citationGroupsUnordered.put(cg.cgid, cg); // invalidate globalOrder. this.globalOrder = Optional.empty(); // Note: we cannot impose localOrder, since we do not know @@ -401,7 +395,7 @@ public void afterCreateCitationGroup(CitationGroup cg) { public void afterRemoveCitationGroup(CitationGroup cg) { - this.citationGroups.remove(cg.cgid); + this.citationGroupsUnordered.remove(cg.cgid); // Update what we can. this.globalOrder.map(l -> l.remove(cg.cgid)); diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 8ca0571af14..f924099e5e7 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -149,7 +149,8 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str + " referenceMarkName is not in the document"); } - CitationGroup cg = new CitationGroup(id, + CitationGroup cg = new CitationGroup(OOStyleDataModelVersion.JabRef52, + id, storedRange.get(), ov.citationType, citations, @@ -288,8 +289,9 @@ public CitationGroup createCitationGroup(XTextDocument doc, // do not inherit from trash UnoUserDefinedProperty.removeIfExists(doc, refMarkName); } - CitationGroup cg = - new CitationGroup(cgid, storedRange, citationType, citations, Optional.of(refMarkName)); + CitationGroup cg = new CitationGroup(OOStyleDataModelVersion.JabRef52, + cgid, storedRange, citationType, citations, + Optional.of(refMarkName)); return cg; default: throw new RuntimeException("Backend52 requires JabRef52 dataModel"); @@ -416,7 +418,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups // For DataModel.JabRef53 (Backend53) we need one context per Citation int n = cgs.numberOfCitationGroups(); List citations = new ArrayList<>(n); - for (CitationGroupID cgid : cgs.getCitationGroupIDs()) { + for (CitationGroupID cgid : cgs.getCitationGroupIDsUnordered()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); String name = cgid.asString(); XTextCursor cursor = (this diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index c9815d876ff..8c23ca0db89 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -392,13 +392,13 @@ void pushLayer(List> settings) { ArrayList> oldLayer = layers.peek(); ArrayList> newLayer = new ArrayList<>(oldLayer); for (Pair kv : settings) { - String name = kv.getKey(); + String name = kv.a; Integer i = goodNameToIndex.get(name); if (i == null) { LOGGER.warn(String.format("pushLayer: '%s' is not in goodNameToIndex", name)); continue; } - Object newValue = kv.getValue(); + Object newValue = kv.b; newLayer.set(i, Optional.ofNullable(newValue)); } layers.push(newLayer); @@ -596,8 +596,8 @@ public static void write(XTextDocument doc, OOUtil.insertParagraphBreak(text, cursor); cursor.collapseToEnd(); for (Pair kv : attributes) { - String key = kv.getKey(); - String value = kv.getValue(); + String key = kv.a; + String value = kv.b; switch (key) { case "oo:ParaStyleName": //

@@ -621,8 +621,8 @@ public static void write(XTextDocument doc, break; case "oo:referenceToPageNumberOfReferenceMark": for (Pair kv : attributes) { - String key = kv.getKey(); - String value = kv.getValue(); + String key = kv.a; + String value = kv.b; switch (key) { case "target": UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); @@ -641,8 +641,8 @@ public static void write(XTextDocument doc, case "span": List> settings = new ArrayList<>(); for (Pair kv : attributes) { - String key = kv.getKey(); - String value = kv.getValue(); + String key = kv.a; + String value = kv.b; switch (key) { case "oo:CharStyleName": // @@ -784,23 +784,6 @@ public static void removeDirectFormatting(XTextCursor cursor) { } } - private static class Pair { - K key; - V value; - public Pair(K k, V v) { - key = k; - value = v; - } - - K getKey() { - return key; - } - - V getValue() { - return value; - } - } - private static List> parseAttributes(String s) { List> res = new ArrayList<>(); if (s == null) { diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java index 73323b54e19..b32c5f73bd1 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java @@ -233,8 +233,8 @@ public static void write(XTextDocument doc, OOUtil.insertParagraphBreak(text, cursor); cursor.collapseToEnd(); for (Pair kv : attributes) { - String key = kv.getKey(); - String value = kv.getValue(); + String key = kv.a; + String value = kv.b; switch (key) { case "oo:ParaStyleName": //

@@ -254,8 +254,8 @@ public static void write(XTextDocument doc, break; case "oo:referenceToPageNumberOfReferenceMark": for (Pair kv : attributes) { - String key = kv.getKey(); - String value = kv.getValue(); + String key = kv.a; + String value = kv.b; switch (key) { case "target": UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); @@ -274,8 +274,8 @@ public static void write(XTextDocument doc, case "span": Formatters fs = new Formatters(); for (Pair kv : attributes) { - String key = kv.getKey(); - String value = kv.getValue(); + String key = kv.a; + String value = kv.b; switch (key) { case "oo:CharStyleName": // @@ -410,23 +410,6 @@ public static void removeDirectFormatting(XTextCursor cursor) { } } - private static class Pair { - K key; - V value; - public Pair(K k, V v) { - key = k; - value = v; - } - - K getKey() { - return key; - } - - V getValue() { - return value; - } - } - private static List> parseAttributes(String s) { List> res = new ArrayList<>(); if (s == null) { diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index d7eaf93b19a..c5986d76a3d 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -111,7 +111,7 @@ public Optional healthReport(XTextDocument doc) NoDocumentException, WrappedTargetException { - List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); + List cgids = new ArrayList<>(cgs.getCitationGroupIDsUnordered()); List vses = new ArrayList<>(); for (CitationGroupID cgid : cgids) { @@ -446,7 +446,7 @@ public List citationRanges(XTextDocument doc) List xs = new ArrayList<>(cgs.numberOfCitationGroups()); - List cgids = new ArrayList<>(cgs.getCitationGroupIDs()); + List cgids = new ArrayList<>(cgs.getCitationGroupIDsUnordered()); for (CitationGroupID cgid : cgids) { XTextRange r = this.getMarkRange(doc, cgid).orElseThrow(RuntimeException::new); diff --git a/src/main/java/org/jabref/logic/openoffice/Pair.java b/src/main/java/org/jabref/logic/openoffice/Pair.java new file mode 100644 index 00000000000..b4c2a7bab90 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/Pair.java @@ -0,0 +1,11 @@ +package org.jabref.logic.openoffice; + +public class Pair { + public final A a; + public final B b; + public Pair(A a, B b) { + this.a = a; + this.b = b; + } +} + From ba173282069b07a28911819345b0424777655b81 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 12 May 2021 13:49:25 +0200 Subject: [PATCH 0708/1068] pageInfo order for JabRef52 changed Before: always in last-in-storage-order citation Now: always in last-in-lcoal-order citation --- .../org/jabref/gui/openoffice/OOBibBase.java | 6 +- .../jabref/logic/oostyle/CitationGroup.java | 42 +++++++ .../jabref/logic/oostyle/CitationGroups.java | 113 +++--------------- .../org/jabref/logic/oostyle/OOProcess.java | 6 +- .../jabref/logic/openoffice/Backend52.java | 102 ++++++---------- .../jabref/logic/openoffice/OOFrontend.java | 19 +-- 6 files changed, 110 insertions(+), 178 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 05d1f91a377..6aba35bc069 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -278,6 +278,10 @@ private void createAndFillCitationGroup(OOFrontend fr, IllegalTypeException, NoSuchElementException { + Objects.requireNonNull(pageInfosForCitations); + if (pageInfosForCitations.size() != citationKeys.size()) { + throw new RuntimeException("pageInfosForCitations.size != citationKeys.size"); + } CitationGroupID cgid = fr.createCitationGroup(doc, citationKeys, pageInfosForCitations, @@ -1157,7 +1161,7 @@ public void unCombineCiteMarkers(List databases, // Note: JabRef52 returns cg.pageInfo for the last citation. List pageInfosForCitations = - fr.cgs.getPageInfosForCitationsInStorageOrder(cg); + cg.getPageInfosForCitationsInStorageOrder(); List cits = cg.citationsInStorageOrder; if (cits.size() <= 1) { diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index e9ef0a05e19..72962d96b63 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -131,6 +131,17 @@ void imposeLocalOrderByComparator(Comparator entryComparator) { // Pair citations with their storage index in citations final int nCitations = citationsInStorageOrder.size(); + + // For JabRef52 the single pageInfo is always in the + // last-in-localorder citation. + // We adjust here accordingly. + final int last = nCitations - 1; + Optional lastPageInfo = Optional.empty(); + if (dataModel == OOStyleDataModelVersion.JabRef52) { + lastPageInfo = getCitationsInLocalOrder().get(last).pageInfo; + getCitationsInLocalOrder().get(last).pageInfo = Optional.empty(); + } + List cis = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { Citation c = citationsInStorageOrder.get(i); @@ -146,6 +157,10 @@ void imposeLocalOrderByComparator(Comparator entryComparator) { ordered.add(ci.i); } this.localOrder = ordered; + + if (dataModel == OOStyleDataModelVersion.JabRef52) { + getCitationsInLocalOrder().get(last).pageInfo = lastPageInfo; + } } public List getLocalOrder() { @@ -175,6 +190,33 @@ public List getCitationNumbersInLocalOrder() { .collect(Collectors.toList())); } + /** + * @return List of nullable pageInfo values, one for each citation, + * instrage order. + * + * Result contains null for missing pageInfo values. + * The list itself is not null. + * + */ + public List getPageInfosForCitationsInStorageOrder() { + CitationGroup cg = this; + // pageInfo values from citations, empty mapped to null. + return (cg.citationsInStorageOrder.stream() + .map(cit -> cit.pageInfo.orElse(null)) + .collect(Collectors.toList())); + } + + /** + * @return List of nullable pageInfo values, one for each citation, in localOrder. + */ + public List getPageInfosForCitationsInLocalOrder() { + CitationGroup cg = this; + // pageInfo values from citations, empty mapped to null. + return (cg.getCitationsInLocalOrder().stream() + .map(cit -> cit.pageInfo.orElse(null)) + .collect(Collectors.toList())); + } + /* * indexInGlobalOrder */ diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 45169802c2e..b3bde86e027 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -1,6 +1,5 @@ package org.jabref.logic.oostyle; -import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; @@ -9,7 +8,6 @@ import java.util.Optional; import java.util.Set; import java.util.function.Consumer; -import java.util.stream.Collectors; import org.jabref.logic.openoffice.Pair; import org.jabref.model.database.BibDatabase; @@ -17,7 +15,6 @@ import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; -import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.slf4j.Logger; @@ -180,7 +177,7 @@ public boolean hasGlobalOrder() { */ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { LinkedHashMap res = new LinkedHashMap<>(); - if (globalOrder.isEmpty()) { + if (!hasGlobalOrder()) { throw new RuntimeException("getSortedCitedKeys: no globalOrder"); } for (CitationGroupID cgid : globalOrder.get()) { @@ -267,100 +264,7 @@ private Optional getCitationType(CitationGroupID cgid) { return getCitationGroup(cgid).map(cg -> cg.citationType); } - /** - * @return List of nullable pageInfo values, one for each citation, - * instrage order. - * - * Result contains null for missing pageInfo values. - * The list itself is not null. - * - * For JabRef52 compatibility the last citation in - * localOrder gets the single pageInfo from the last in - * storage order, to make sure it is presented after the citations. - * This can only be done after localOrder is set. - * - * The result is passed to OOBibStyle.getCitationMarker or - * OOBibStyle.getNumCitationMarker - * - * TODO: we may want class DataModel52, DataModel53 and split this. - */ - private static List - getPageInfosForCitationsInStorageOrder(OOStyleDataModelVersion dataModel, - CitationGroup cg) { - switch (dataModel) { - case JabRef52: - // check conformance to dataModel - final int nCitations = cg.numberOfCitations(); - final int last = nCitations - 1; - final boolean checkDataModelConformance = false; - if (checkDataModelConformance) { - for (int i = 0; i < last; i++) { - if (cg.citationsInStorageOrder.get(i).pageInfo.isPresent()) { - throw new RuntimeException("getPageInfosForCitations:" - + " found Citation.pageInfo" - + " outside last citation under JabRef52 dataModel"); - } - } - } - OOFormattedText thePageInfo = cg.citationsInStorageOrder.get(last).pageInfo.orElse(null); - - // For JabRef52 the citation last in localOrder gets the pageInfo. - final int theLastInLocalOrder = cg.getLocalOrder().get(last); - List result = new ArrayList<>(nCitations); - for (int i = 0; i < nCitations; i++) { - if (i == theLastInLocalOrder) { - result.add(thePageInfo); - } else { - result.add(null); - } - } - return result; - case JabRef53: - // pageInfo values from citations, empty mapped to null. - return (cg.citationsInStorageOrder.stream() - .map(cit -> cit.pageInfo.orElse(null)) - .collect(Collectors.toList())); - - default: - throw new RuntimeException("getPageInfosForCitationsInStorageOrder:" - + "unhandled dataModel"); - } - } - - /** - * @return List of nullable pageInfo values, one for each citation, - * in localOrder. - */ - private static List - getPageInfosForCitationsInLocalOrder(OOStyleDataModelVersion dataModel, CitationGroup cg) { - final int nCitations = cg.numberOfCitations(); - List result = new ArrayList<>(nCitations); - List inStorageOrder = getPageInfosForCitationsInStorageOrder(dataModel, cg); - for (int i = 0; i < nCitations; i++) { - result.add(inStorageOrder.get(cg.getLocalOrder().get(i))); - } - return result; - } - - public List getPageInfosForCitationsInStorageOrder(CitationGroup cg) { - return getPageInfosForCitationsInStorageOrder(this.dataModel, cg); - } - - public List getPageInfosForCitationsInStorageOrder(CitationGroupID cgid) { - CitationGroup cg = getCitationGroupOrThrow(cgid); - return getPageInfosForCitationsInStorageOrder(cg); - } - - public List getPageInfosForCitationsInLocalOrder(CitationGroup cg) { - return getPageInfosForCitationsInLocalOrder(this.dataModel, cg); - } - - public List getPageInfosForCitationsInLocalOrder(CitationGroupID cgid) { - CitationGroup cg = getCitationGroupOrThrow(cgid); - return getPageInfosForCitationsInLocalOrder(cg); - } - - public Optional> getCitations(CitationGroupID cgid) { + public Optional> getCitationsInStorageOrder(CitationGroupID cgid) { return getCitationGroup(cgid).map(cg -> cg.citationsInStorageOrder); } @@ -393,6 +297,19 @@ public void afterCreateCitationGroup(CitationGroup cg) { // how it was imposed. We leave it to an upper level. } + /* + * Note: we invalidate the extra data we are storing + * (bibliography). + * + * Update would be complicated, since we do not know how the + * bibliography was generated: it was partially done outside + * CitationGroups, and we did not store how. + * + * So we stay with invalidating. + * Note: localOrder, numbering, uniqueLetters are not adjusted, + * it is easier to reread everything for a refresh. + * + */ public void afterRemoveCitationGroup(CitationGroup cg) { this.citationGroupsUnordered.remove(cg.cgid); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 72706cfe5e2..e1d6b01625b 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -253,7 +253,7 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getCitationNumbersInLocalOrder(); - List pageInfos = cgs.getPageInfosForCitationsInLocalOrder(cg); + List pageInfos = cg.getPageInfosForCitationsInLocalOrder(); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, @@ -282,7 +282,7 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getCitationNumbersInLocalOrder(); - List pageInfos = cgs.getPageInfosForCitationsInLocalOrder(cg); + List pageInfos = cg.getPageInfosForCitationsInLocalOrder(); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, @@ -325,7 +325,7 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole List cits = cg.getCitationsInLocalOrder(); final int nCitedEntries = cits.size(); - List pageInfosForCitations = cgs.getPageInfosForCitationsInLocalOrder(cg); + List pageInfosForCitations = cg.getPageInfosForCitationsInLocalOrder(); List citationMarkerEntries = new ArrayList<>(nCitedEntries); diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index f924099e5e7..e80076fed68 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -65,8 +66,7 @@ private List findUnusedJabrefPropertyNames(XTextDocument doc, List citationGroupNames) { // Collect unused jabrefPropertyNames - Set citationGroupNamesSet = - citationGroupNames.stream().collect(Collectors.toSet()); + Set citationGroupNamesSet = citationGroupNames.stream().collect(Collectors.toSet()); List pageInfoThrash = new ArrayList<>(); List jabrefPropertyNames = @@ -100,14 +100,24 @@ public Optional healthReport(XTextDocument doc) return Optional.of(msg); } - private static void setPageInfoInData(List citations, Optional pageInfo) { - // attribute to last citation (in storage order) + private static void setPageInfoInDataInitial(List citations, + Optional pageInfo) { + // attribute to last citation (initially localOrder == storageOrder) if (citations.size() > 0) { citations.get(citations.size() - 1).pageInfo = pageInfo; } } - private static Optional getPageInfoFromData(List citations) { + private static void setPageInfoInData(CitationGroup cg, + Optional pageInfo) { + List citations = cg.getCitationsInLocalOrder(); + if (citations.size() > 0) { + citations.get(citations.size() - 1).pageInfo = pageInfo; + } + } + + private static Optional getPageInfoFromData(CitationGroup cg) { + List citations = cg.getCitationsInLocalOrder(); if (citations.size() > 0) { return citations.get(citations.size() - 1).pageInfo; } else { @@ -139,7 +149,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str (UnoUserDefinedProperty.getStringValue(doc, refMarkName) .map(OOFormattedText::fromString)); - setPageInfoInData(citations, pageInfo); + setPageInfoInDataInitial(citations, pageInfo); Optional storedRange = (citationStorageManager .getFromDocument(doc, refMarkName)); @@ -168,55 +178,10 @@ static Optional normalizePageInfoToOptional(OOFormattedText o) return Optional.ofNullable(OOFormattedText.fromString(s)); } - /** - * Return the last pageInfo from the list, if there is one. - */ - private static Optional - getJabRef52PageInfoFromList(List pageInfosForCitations) { - if (pageInfosForCitations == null) { - return Optional.empty(); - } - int n = pageInfosForCitations.size(); - if (n == 0) { - return Optional.empty(); - } - return normalizePageInfoToOptional(pageInfosForCitations.get(n - 1)); - } - /** * Create a reference mark with the given name, at the * end of position. * - * To reduce the difference from the original representation, we - * only insist on having at least two characters inside reference - * marks. These may be ZERO_WIDTH_SPACE characters or other - * placeholder not likely to appear in a citation mark. - * - * This placeholder is only needed if the citation mark is - * otherwise empty (e.g. when we just create it). - * - * getFillCursorForCitationGroup yields a bracketed cursor, that - * can be used to fill in / overwrite the value inside. - * - * After each getFillCursorForCitationGroup, we require a call to - * cleanFillCursorForCitationGroup, which removes the brackets, - * unless if it would make the content less than two - * characters. If we need only one placeholder, we keep the left - * bracket. If we need two, then the content is empty. The - * removeBracketsFromEmpty parameter of - * cleanFillCursorForCitationGroup overrides this, and for empty - * citations it will remove the brackets, leaving an empty - * reference mark. The idea behind this is that we do not need to - * refill empty marks (citationType: INVISIBLE_CIT), and the caller - * can tell us that we are dealing with one of these. - * - * Thus the only user-visible difference in citation marks is - * that instead of empty marks we use two brackets, for - * single-character marks we add a left bracket before. - * - * Character-attribute inheritance: updates inherit from the - * first character inside, not from the left. - * * On return {@code position} is collapsed, and is after the * inserted space, or at the end of the reference mark. * @@ -245,21 +210,31 @@ public CitationGroup createCitationGroup(XTextDocument doc, PropertyVetoException, IllegalTypeException { + Objects.requireNonNull(pageInfosForCitations); + if (pageInfosForCitations.size() != citationKeys.size()) { + throw new RuntimeException("pageInfosForCitations.size != citationKeys.size"); + } + + // Get a new refMarkName Set usedNames = new HashSet<>(this.citationStorageManager.getUsedNames(doc)); String xkey = (citationKeys.stream().collect(Collectors.joining(","))); String refMarkName = Codec52.getUniqueMarkName(usedNames, xkey, citationType); CitationGroupID cgid = new CitationGroupID(refMarkName); - List citations = new ArrayList<>(citationKeys.size()); - for (int i = 0; i < citationKeys.size(); i++) { + final int nCitations = citationKeys.size(); + final int last = nCitations - 1; + + // Build citations, add pageInfo to each citation + List citations = new ArrayList<>(nCitations); + for (int i = 0; i < nCitations; i++) { Citation cit = new Citation(citationKeys.get(i)); citations.add(cit); Optional pageInfo = normalizePageInfoToOptional(pageInfosForCitations.get(i)); switch (dataModel) { case JabRef52: - if (i == citationKeys.size() - 1) { + if (i == last) { cit.pageInfo = pageInfo; } else { if (pageInfo.isPresent()) { @@ -281,7 +256,9 @@ public CitationGroup createCitationGroup(XTextDocument doc, switch (dataModel) { case JabRef52: - Optional pageInfo = getJabRef52PageInfoFromList(pageInfosForCitations); + Optional pageInfo = + normalizePageInfoToOptional(pageInfosForCitations.get(last)); + if (pageInfo.isPresent() && !"".equals(OOFormattedText.toString(pageInfo.get()))) { String pageInfoString = OOFormattedText.toString(pageInfo.get()); UnoUserDefinedProperty.createStringProperty(doc, refMarkName, pageInfoString); @@ -299,7 +276,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, } /** - * @return A list with one nullable pageInfo entry for each citation in + * @return A list with a nullable pageInfo entry for each citation in * joinableGroups. * * TODO: JabRef52 combinePageInfos is not reversible. Should warn @@ -312,7 +289,7 @@ public static List combinePageInfosCommon(OOStyleDataModelVersi // collect to cgPageInfos List> cgPageInfos = (joinableGroup.stream() - .map(cg -> getPageInfoFromData(cg.citationsInStorageOrder)) + .map(cg -> getPageInfoFromData(cg)) .collect(Collectors.toList())); // Try to do something of the cgPageInfos. @@ -426,14 +403,10 @@ public List getCitationEntries(XTextDocument doc, CitationGroups .orElseThrow(RuntimeException::new)); String context = OOUtil.getCursorStringWithContext(cursor, 30, 30, true); Optional pageInfo = (cg.numberOfCitations() > 0 - ? (cg.citationsInStorageOrder - .get(cg.numberOfCitations() - 1) - .getPageInfo() + ? (getPageInfoFromData(cg) .map(e -> OOFormattedText.toString(e))) : Optional.empty()); - CitationEntry entry = new CitationEntry(name, - context, - pageInfo); + CitationEntry entry = new CitationEntry(name, context, pageInfo); citations.add(entry); } return citations; @@ -445,6 +418,9 @@ public List getCitationEntries(XTextDocument doc, CitationGroups } } + /* + * Only applies to storage. Citation markers are not changed. + */ public void applyCitationEntries(XTextDocument doc, List citationEntries) throws UnknownPropertyException, diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index c5986d76a3d..b0409882a9d 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -4,6 +4,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.TreeMap; import java.util.stream.Collectors; @@ -323,6 +324,10 @@ public CitationGroupID createCitationGroup(XTextDocument doc, PropertyVetoException, IllegalTypeException { + Objects.requireNonNull(pageInfosForCitations); + if (pageInfosForCitations.size() != citationKeys.size()) { + throw new RuntimeException("pageInfosForCitations.size != citationKeys.size"); + } CitationGroup cg = backend.createCitationGroup(doc, citationKeys, pageInfosForCitations, @@ -336,19 +341,7 @@ public CitationGroupID createCitationGroup(XTextDocument doc, } /** - * Remove {@code cg} both from {@code cgs} and the document. - * - * Note: we invalidate the extra data we are storing - * (bibliography). - * - * Update would be complicated, since we do not know how the - * bibliography was generated: it was partially done outside - * CitationGroups, and we did not store how. - * - * So we stay with invalidating. - * Note: localOrder, numbering, uniqueLetters are not adjusted, - * it is easier to reread everything for a refresh. - * + * Remove {@code cg} both from the document and notify {@code cgs} */ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) throws From c32a7e6369a35dfa46d2b9871857f9645bb845dc Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 12 May 2021 14:21:22 +0200 Subject: [PATCH 0709/1068] OOFrontend.cgs renamed to citationGroups --- .../org/jabref/gui/openoffice/OOBibBase.java | 21 ++--- .../jabref/logic/oostyle/CitationGroups.java | 13 +-- .../jabref/logic/openoffice/OOFrontend.java | 90 +++++++++---------- 3 files changed, 52 insertions(+), 72 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6aba35bc069..307214d135c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -504,7 +504,7 @@ public void insertEntry(List entries, OOFrontend fr2 = new OOFrontend(doc); fr2.imposeGlobalOrder(doc); OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr2.cgs, allBases, style); + OOProcess.produceCitationMarkers(fr2.citationGroups, allBases, style); try { UnoScreenRefresh.lockControllers(doc); applyNewCitationMarkers(doc, @@ -582,7 +582,7 @@ private void applyNewCitationMarkers(XTextDocument doc, checkStylesExistInTheDocument(style, doc); - CitationGroups cgs = fr.cgs; + CitationGroups cgs = fr.citationGroups; final boolean hadBibSection = (UnoBookmark.getAnchor(doc, OOBibBase.BIB_SECTION_NAME) .isPresent()); @@ -726,7 +726,7 @@ private void populateBibTextSection(XTextDocument doc, // emit the title of the bibliography OOFormattedTextIntoOO.removeDirectFormatting(cursor); - OOFormattedText bibliographyText = OOFormatBibliography.formatBibliography(fr.cgs, + OOFormattedText bibliographyText = OOFormatBibliography.formatBibliography(fr.citationGroups, bibliography, style, alwaysAddCitedOnPages); @@ -828,7 +828,7 @@ public void combineCiteMarkers(List databases, XTextRange prevRange = null; for (CitationGroupID cgid : referenceMarkNames) { - CitationGroup cg = fr.cgs.getCitationGroupOrThrow(cgid); + CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); XTextRange currentRange = (fr .getMarkRange(doc, cgid) @@ -1077,7 +1077,7 @@ public void combineCiteMarkers(List databases, OOFrontend fr2 = new OOFrontend(doc); fr2.imposeGlobalOrder(doc); OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr2.cgs, + OOProcess.produceCitationMarkers(fr2.citationGroups, databases, style); try { @@ -1142,7 +1142,8 @@ public void unCombineCiteMarkers(List databases, boolean madeModifications = false; // {@code names} does not need to be sorted. - List names = new ArrayList<>(fr.cgs.getCitationGroupIDsUnordered()); + List names = + new ArrayList<>(fr.citationGroups.getCitationGroupIDsUnordered()); try { if (useLockControllers) { @@ -1153,7 +1154,7 @@ public void unCombineCiteMarkers(List databases, while (pivot < (names.size())) { CitationGroupID cgid = names.get(pivot); - CitationGroup cg = fr.cgs.getCitationGroupOrThrow(cgid); + CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); XTextRange range1 = (fr .getMarkRange(doc, cgid) .orElseThrow(RuntimeException::new)); @@ -1213,7 +1214,7 @@ public void unCombineCiteMarkers(List databases, OOFrontend fr2 = new OOFrontend(doc); fr2.imposeGlobalOrder(doc); OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr2.cgs, databases, style); + OOProcess.produceCitationMarkers(fr2.citationGroups, databases, style); try { if (useLockControllers) { UnoScreenRefresh.lockControllers(doc); @@ -1292,7 +1293,7 @@ private ExportCitedHelperResult generateDatabase(List databases, UnknownPropertyException { OOFrontend fr = new OOFrontend(doc); - CitedKeys cks = fr.cgs.getCitedKeysUnordered(); + CitedKeys cks = fr.citationGroups.getCitedKeysUnordered(); cks.lookupInDatabases(databases); List unresolvedKeys = new ArrayList<>(); @@ -1541,7 +1542,7 @@ public List updateDocumentActionHelper(List databases, final boolean useLockControllers = true; fr.imposeGlobalOrder(doc); OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr.cgs, databases, style); + OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); try { if (useLockControllers) { UnoScreenRefresh.lockControllers(doc); diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index b3bde86e027..468033c8130 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -15,22 +15,17 @@ import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; -import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * CitationGroups : the set of citation groups in the document. - * - * */ public class CitationGroups { private static final Logger LOGGER = LoggerFactory.getLogger(CitationGroups.class); - private final OOStyleDataModelVersion dataModel; - /** * Original CitationGroups Data */ @@ -57,16 +52,10 @@ public class CitationGroups { /** * Constructor */ - public CitationGroups(OOStyleDataModelVersion dataModel, - Map citationGroups) { + public CitationGroups(Map citationGroups) { - this.dataModel = dataModel; this.citationGroupsUnordered = citationGroups; - // Now we have almost every information from the document about citations. - // What is left out: the ranges controlled by the reference marks. - // But (I guess) those change too easily, so we only ask when actually needed. - this.globalOrder = Optional.empty(); this.bibliography = Optional.empty(); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index b0409882a9d..7e631d32257 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -35,7 +35,7 @@ public class OOFrontend { private static final Logger LOGGER = LoggerFactory.getLogger(OOFrontend.class); public final Backend52 backend; - public final CitationGroups cgs; + public final CitationGroups citationGroups; public OOFrontend(XTextDocument doc) throws @@ -51,10 +51,8 @@ public OOFrontend(XTextDocument doc) List citationGroupNames = this.backend.getJabRefReferenceMarkNames(doc); Map citationGroups = - readCitationGroupsFromDocument(this.backend, - doc, - citationGroupNames); - this.cgs = new CitationGroups(backend.dataModel, citationGroups); + readCitationGroupsFromDocument(this.backend, doc, citationGroupNames); + this.citationGroups = new CitationGroups(citationGroups); } public OOStyleDataModelVersion getDataModel() { @@ -78,8 +76,7 @@ public Optional healthReport(XTextDocument doc) Map citationGroups = new HashMap<>(); for (int i = 0; i < citationGroupNames.size(); i++) { final String name = citationGroupNames.get(i); - CitationGroup cg = - backend.readCitationGroupFromDocumentOrThrow(doc, name); + CitationGroup cg = backend.readCitationGroupFromDocumentOrThrow(doc, name); citationGroups.put(cg.cgid, cg); } return citationGroups; @@ -106,33 +103,32 @@ public Optional healthReport(XTextDocument doc) * */ private List> - createVisualSortInput(XTextDocument doc, - boolean mapFootnotesToFootnoteMarks) + createVisualSortInput(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) throws NoDocumentException, WrappedTargetException { - List cgids = new ArrayList<>(cgs.getCitationGroupIDsUnordered()); + List cgids = new ArrayList<>(citationGroups.getCitationGroupIDsUnordered()); - List vses = new ArrayList<>(); + List sortables = new ArrayList<>(); for (CitationGroupID cgid : cgids) { XTextRange range = (this .getMarkRange(doc, cgid) .orElseThrow(RuntimeException::new)); - vses.add(new RangeSort.RangeSortEntry(range, 0, cgid)); + sortables.add(new RangeSort.RangeSortEntry(range, 0, cgid)); } /* - * At this point we are almost ready to return vses. + * At this point we are almost ready to return sortables. * - * For example we may want to number citations in a footnote + * But we may want to number citations in a footnote * as if it appeared where the footnote mark is. * * The following code replaces ranges within footnotes with * the range for the corresponding footnote mark. * * This brings further ambiguity if we have multiple - * citations within the same footnote: for the comparison + * citation groups within the same footnote: for the comparison * they become indistinguishable. Numbering between them is * not controlled. Also combineCiteMarkers will see them in * the wrong order (if we use this comparison), and will not @@ -143,10 +139,8 @@ public Optional healthReport(XTextDocument doc) */ // Sort within partitions - RangeKeyedMapList> xxs - = new RangeKeyedMapList<>(); - - for (RangeSort.RangeSortEntry v : vses) { + RangeKeyedMapList> xxs = new RangeKeyedMapList<>(); + for (RangeSort.RangeSortEntry v : sortables) { xxs.add(v.getRange(), v); } @@ -156,11 +150,11 @@ public Optional healthReport(XTextDocument doc) for (TreeMap>> xs : xxs.partitionValues()) { - List oxs = new ArrayList<>(xs.keySet()); + List orderedRanges = new ArrayList<>(xs.keySet()); int indexInPartition = 0; - for (int i = 0; i < oxs.size(); i++) { - XTextRange a = oxs.get(i); + for (int i = 0; i < orderedRanges.size(); i++) { + XTextRange a = orderedRanges.get(i); List> avs = xs.get(a); for (int j = 0; j < avs.size(); j++) { RangeSort.RangeSortEntry v = avs.get(j); @@ -204,13 +198,13 @@ private List getVisuallySortedCitationGroupIDs(XTextDocument do NoDocumentException, JabRefException { - List> vses = + List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); - if (vses.size() != this.cgs.numberOfCitationGroups()) { + if (sortables.size() != this.citationGroups.numberOfCitationGroups()) { throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " vses.size() != cgs.citationGroups.size()"); + + " sortables.size() != cgs.citationGroups.size()"); } String messageOnFailureToObtainAFunctionalXTextViewCursor = @@ -220,11 +214,11 @@ private List getVisuallySortedCitationGroupIDs(XTextDocument do + " I need to move the cursor around," + " but could not get it."); List> sorted = - RangeSortVisual.visualSort(vses, + RangeSortVisual.visualSort(sortables, doc, messageOnFailureToObtainAFunctionalXTextViewCursor); - if (sorted.size() != this.cgs.numberOfCitationGroups()) { + if (sorted.size() != this.citationGroups.numberOfCitationGroups()) { // This Fired throw new RuntimeException("getVisuallySortedCitationGroupIDs:" + " sorted.size() != cgs.numberOfCitationGroups()"); @@ -239,24 +233,21 @@ private List getVisuallySortedCitationGroupIDs(XTextDocument do * Calculate and return citation group IDs in visual order. */ public List - getCitationGroupIDsSortedWithinPartitions(XTextDocument doc, - boolean mapFootnotesToFootnoteMarks) + getCitationGroupIDsSortedWithinPartitions(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) throws NoDocumentException, WrappedTargetException { // This is like getVisuallySortedCitationGroupIDs, // but we skip the visualSort part. - List> vses = - createVisualSortInput(doc, - mapFootnotesToFootnoteMarks); + List> sortables = + createVisualSortInput(doc, mapFootnotesToFootnoteMarks); - if (vses.size() != this.cgs.numberOfCitationGroups()) { + if (sortables.size() != this.citationGroups.numberOfCitationGroups()) { throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" - + " vses.size() != cgs.numberOfCitationGroups()"); + + " sortables.size() != citationGroups.numberOfCitationGroups()"); } - return (vses.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList())); + + return (sortables.stream().map(e -> e.getContent()).collect(Collectors.toList())); } /** @@ -336,12 +327,12 @@ public CitationGroupID createCitationGroup(XTextDocument doc, insertSpaceAfter, withoutBrackets); - this.cgs.afterCreateCitationGroup(cg); + this.citationGroups.afterCreateCitationGroup(cg); return cg.cgid; } /** - * Remove {@code cg} both from the document and notify {@code cgs} + * Remove {@code cg} both from the document and notify {@code citationGroups} */ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) throws @@ -354,7 +345,7 @@ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) // Apply backend.removeCitationGroup(cg, doc); - this.cgs.afterRemoveCitationGroup(cg); + this.citationGroups.afterRemoveCitationGroup(cg); } public void removeCitationGroups(List xcgs, XTextDocument doc) @@ -382,7 +373,7 @@ public Optional getMarkRange(XTextDocument doc, CitationGroupID cgid throws NoDocumentException, WrappedTargetException { - CitationGroup cg = this.cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + CitationGroup cg = this.citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); return backend.getMarkRange(cg, doc); } @@ -396,7 +387,7 @@ public Optional getRawCursorForCitationGroup(CitationGroupID cgid, WrappedTargetException, CreationException { - Optional cg = this.cgs.getCitationGroup(cgid); + Optional cg = this.citationGroups.getCitationGroup(cgid); if (cg.isEmpty()) { return Optional.empty(); } @@ -409,7 +400,7 @@ public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGrou WrappedTargetException, CreationException { - CitationGroup cg = this.cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + CitationGroup cg = this.citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); return backend.getFillCursorForCitationGroup(cg, doc); } @@ -423,7 +414,7 @@ public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroupID c WrappedTargetException, CreationException { - CitationGroup cg = this.cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + CitationGroup cg = this.citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); backend.cleanFillCursorForCitationGroup(cg, doc); } @@ -437,13 +428,13 @@ public List citationRanges(XTextDocument doc) NoDocumentException, WrappedTargetException { - List xs = new ArrayList<>(cgs.numberOfCitationGroups()); + List xs = new ArrayList<>(citationGroups.numberOfCitationGroups()); - List cgids = new ArrayList<>(cgs.getCitationGroupIDsUnordered()); + List cgids = new ArrayList<>(citationGroups.getCitationGroupIDsUnordered()); for (CitationGroupID cgid : cgids) { XTextRange r = this.getMarkRange(doc, cgid).orElseThrow(RuntimeException::new); - CitationGroup cg = cgs.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + CitationGroup cg = citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); String name = cg.cgRangeStorage.getName(); xs.add(new RangeForOverlapCheck(r, cgid, @@ -529,7 +520,6 @@ public void checkRangeOverlaps(XTextDocument doc, List.RangeOverlap> ovs = xall.findOverlappingRanges(reportAtMost, requireSeparation); - // checkSortedPartitionForOverlap(requireSeparation, oxs); if (ovs.size() > 0) { String msg = ""; for (RangeKeyedMapList.RangeOverlap e : ovs) { @@ -592,7 +582,7 @@ public List getCitationEntries(XTextDocument doc) WrappedTargetException, NoDocumentException, CreationException { - return this.backend.getCitationEntries(doc, cgs); + return this.backend.getCitationEntries(doc, citationGroups); } public void applyCitationEntries(XTextDocument doc, List citationEntries) @@ -617,6 +607,6 @@ public void imposeGlobalOrder(XTextDocument doc) boolean mapFootnotesToFootnoteMarks = true; List sortedCitationGroupIDs = getVisuallySortedCitationGroupIDs(doc, mapFootnotesToFootnoteMarks); - cgs.setGlobalOrder(sortedCitationGroupIDs); + citationGroups.setGlobalOrder(sortedCitationGroupIDs); } } From e3f9dd2c52515ca913e190f72237efbf3ebefc10 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 12 May 2021 23:33:20 +0200 Subject: [PATCH 0710/1068] moving error dialogs to OOBibBase --- .../openoffice/ManageCitationsDialogView.java | 9 +- .../ManageCitationsDialogViewModel.java | 46 +-- .../org/jabref/gui/openoffice/OOBibBase.java | 374 ++++++++++++------ .../gui/openoffice/OOBibBaseConnect.java | 13 + .../gui/openoffice/OpenOfficePanel.java | 101 ++--- .../jabref/logic/openoffice/Backend52.java | 6 +- .../jabref/logic/openoffice/OOFrontend.java | 181 +++------ .../org/jabref/logic/openoffice/OOUtil.java | 3 +- .../org/jabref/logic/openoffice/Result.java | 84 ++++ .../org/jabref/logic/openoffice/Settable.java | 26 ++ .../jabref/logic/openoffice/StorageBase.java | 3 +- .../logic/openoffice/StorageBaseRefMark.java | 3 +- .../jabref/logic/openoffice/VoidResult.java | 43 ++ src/main/resources/l10n/JabRef_en.properties | 3 +- 14 files changed, 530 insertions(+), 365 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/Result.java create mode 100644 src/main/java/org/jabref/logic/openoffice/Settable.java create mode 100644 src/main/java/org/jabref/logic/openoffice/VoidResult.java diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index 8fdd929ce2d..508b238ac90 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -1,5 +1,7 @@ package org.jabref.gui.openoffice; +import java.util.List; + import javax.inject.Inject; import javafx.fxml.FXML; @@ -17,6 +19,7 @@ import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; +import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.strings.StringUtil; import com.airhacks.afterburner.views.ViewLoader; @@ -30,6 +33,7 @@ public class ManageCitationsDialogView extends BaseDialog { private static final String HTML_BOLD_START_TAG = ""; private final OOBibBase ooBase; + private final List citations; @FXML private TableView citationsTableView; @FXML private TableColumn citation; @@ -39,8 +43,9 @@ public class ManageCitationsDialogView extends BaseDialog { private ManageCitationsDialogViewModel viewModel; - public ManageCitationsDialogView(OOBibBase ooBase) { + public ManageCitationsDialogView(OOBibBase ooBase, List citations) { this.ooBase = ooBase; + this.citations = citations; ViewLoader.view(this) .load() @@ -59,7 +64,7 @@ public ManageCitationsDialogView(OOBibBase ooBase) { @FXML private void initialize() throws NoSuchElementException, WrappedTargetException, UnknownPropertyException, JabRefException { - viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); + viewModel = new ManageCitationsDialogViewModel(ooBase, citations, dialogService); citation.setCellValueFactory(cellData -> cellData.getValue().citationProperty()); new ValueTableCellFactory().withGraphic(this::getText).install(citation); diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 59577d62654..53f74179ca0 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -8,61 +8,29 @@ import javafx.collections.FXCollections; import org.jabref.gui.DialogService; -import org.jabref.logic.JabRefException; -import org.jabref.logic.l10n.Localization; -import org.jabref.logic.openoffice.CreationException; -import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.model.openoffice.CitationEntry; -import com.sun.star.beans.IllegalTypeException; -import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; -import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.lang.IllegalArgumentException; -import com.sun.star.lang.WrappedTargetException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class ManageCitationsDialogViewModel { - private static final Logger LOGGER = LoggerFactory.getLogger(ManageCitationsDialogViewModel.class); - private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList()); private final OOBibBase ooBase; private final DialogService dialogService; - public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) { + public ManageCitationsDialogViewModel(OOBibBase ooBase, + List citationEntries, + DialogService dialogService) { this.ooBase = ooBase; this.dialogService = dialogService; - try { - List cts = ooBase.getCitationEntries(); - for (CitationEntry entry : cts) { - CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); - citations.add(itemViewModelEntry); - } - } catch (UnknownPropertyException - | WrappedTargetException - | NoDocumentException - | PropertyVetoException - | JabRefException - | CreationException ex) { - LOGGER.warn("Problem collecting citations", ex); - dialogService.showErrorDialogAndWait(Localization.lang("Problem collecting citations"), ex); + for (CitationEntry entry : citationEntries) { + CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); + citations.add(itemViewModelEntry); } } public void storeSettings() { List ciationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); - try { - ooBase.applyCitationEntries(ciationEntries); - } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | PropertyVetoException | IllegalTypeException | - NoDocumentException | WrappedTargetException | - IllegalArgumentException ex) { - LOGGER.warn("Problem modifying citation", ex); - dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex); - } + ooBase.applyCitationEntries(ciationEntries); } public ListProperty citationsProperty() { diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 307214d135c..b43b907377e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -29,6 +29,7 @@ import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.OOFormattedTextIntoOO; import org.jabref.logic.openoffice.OOFrontend; +import org.jabref.logic.openoffice.Result; import org.jabref.logic.openoffice.UndefinedCharacterFormatException; import org.jabref.logic.openoffice.UndefinedParagraphFormatException; import org.jabref.logic.openoffice.UnoBookmark; @@ -40,6 +41,7 @@ import org.jabref.logic.openoffice.UnoTextRange; import org.jabref.logic.openoffice.UnoTextSection; import org.jabref.logic.openoffice.UnoUndo; +import org.jabref.logic.openoffice.VoidResult; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; @@ -124,13 +126,19 @@ public boolean isDocumentConnectionMissing() { } /** - * Either return an XTextDocument or throw - * NoDocumentException. + * Either return an XTextDocument or return JabRefException. */ + public Result getXTextDocument() { + return this.connection.getXTextDocument(); + } + public XTextDocument getXTextDocumentOrThrow() - throws - NoDocumentException { - return this.connection.getXTextDocumentOrThrow(); + throws JabRefException { + Result res = this.getXTextDocument(); + if (res.isEmpty()) { + throw res.getError(); + } + return res.get(); } /** @@ -146,20 +154,45 @@ public Optional getCurrentDocumentTitle() { * * ****************************/ - public List getCitationEntries() - throws - UnknownPropertyException, - WrappedTargetException, - NoDocumentException, - CreationException, - PropertyVetoException, - JabRefException { + void showDialog(String title, JabRefException ex) { + dialogService.showErrorDialogAndWait(title, ex.getLocalizedMessage()); + } - XTextDocument doc = this.getXTextDocumentOrThrow(); + boolean testDialog(String title, VoidResult res) { + return res.ifError(e -> showDialog(title, e)).isError(); + } - checkIfOpenOfficeIsRecordingChanges(doc); - OOFrontend fr = new OOFrontend(doc); - return fr.getCitationEntries(doc); + private Optional getOrDialog(String title, Result res) { + if (res.isOK()) { + return res.getOptional(); + } + showDialog(title, res.getError()); + return Optional.empty(); + } + + public Optional> getCitationEntries() { + + final String title = Localization.lang("Problem collecting citations"); + try { + Optional odoc = getOrDialog(title, getXTextDocument()); + if (odoc.isEmpty() + || testDialog(title, checkIfOpenOfficeIsRecordingChanges2(odoc.get()))) { + LOGGER.warn(title); + return Optional.empty(); + } + + XTextDocument doc = odoc.get(); + OOFrontend fr = new OOFrontend(doc); + return Optional.of(fr.getCitationEntries(doc)); + + } catch (NoDocumentException ex) { + OpenOfficePanel.showNoDocumentErrorMessage(dialogService); + return Optional.empty(); + } catch (UnknownPropertyException + | WrappedTargetException ex) { + LOGGER.warn(title, ex); + return Optional.empty(); + } } /** @@ -187,20 +220,29 @@ public List getCitationEntries() * citation from the text). * */ - public void applyCitationEntries(List citationEntries) - throws - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - PropertyVetoException, - IllegalTypeException, - IllegalArgumentException, - NoDocumentException, - WrappedTargetException { + public void applyCitationEntries(List citationEntries) { - XTextDocument doc = this.getXTextDocumentOrThrow(); - OOFrontend fr = new OOFrontend(doc); - fr.applyCitationEntries(doc, citationEntries); + final String title = Localization.lang("Problem modifying citation"); + try { + Optional odoc = getOrDialog(title, getXTextDocument()); + if (odoc.isEmpty()) { + return; + } + + XTextDocument doc = odoc.get(); + OOFrontend fr = new OOFrontend(doc); + fr.applyCitationEntries(doc, citationEntries); + } catch (UnknownPropertyException + | NotRemoveableException + | PropertyExistException + | PropertyVetoException + | IllegalTypeException + | NoDocumentException + | WrappedTargetException + | IllegalArgumentException ex) { + LOGGER.warn(title, ex); + dialogService.showErrorDialogAndWait(title, ex); + } } private static void fillCitationMarkInCursor(XTextDocument doc, @@ -381,41 +423,27 @@ public void insertEntry(List entries, boolean inParenthesis, boolean withText, String pageInfo, - boolean sync) - throws - JabRefException, - IllegalArgumentException, - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - UndefinedCharacterFormatException, - WrappedTargetException, - NoSuchElementException, - PropertyVetoException, - IOException, - CreationException, - UndefinedParagraphFormatException, - NoDocumentException, - InvalidStateException { + boolean sync) { - styleIsRequired(style); + final String title = "Could not insert entry"; + if (testDialog(title, styleIsRequired(style))) { + return; + } if (entries == null || entries.size() == 0) { - String title = "No bibliography entries selected"; + // String title = "No bibliography entries selected"; String msg = (Localization.lang("No bibliography entries are selected for citation.") + "\n" + Localization.lang("Select some before citing.")); - throw new JabRefException(title, msg); + showDialog(title, new JabRefException(title, msg)); } final int nEntries = entries.size(); - XTextDocument doc = this.getXTextDocumentOrThrow(); - - checkStylesExistInTheDocument(style, doc); - checkIfOpenOfficeIsRecordingChanges(doc); - - OOFrontend fr = new OOFrontend(doc); + Optional odoc = getOrDialog(title, getXTextDocument()); + if (odoc.isEmpty()) { + return; + } + XTextDocument doc = odoc.get(); boolean useUndoContext = true; @@ -423,14 +451,32 @@ public void insertEntry(List entries, if (useUndoContext) { UnoUndo.enterUndoContext(doc, "Insert citation"); } + + try { + checkStylesExistInTheDocument(style, doc); + checkIfOpenOfficeIsRecordingChanges(doc); + } catch (JabRefException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("JabRefException"), + ex.getLocalizedMessage()); + return; + } + + OOFrontend fr = new OOFrontend(doc); + XTextCursor cursor; // Get the cursor positioned by the user. try { cursor = UnoCursor.getViewCursor(doc).orElse(null); } catch (RuntimeException ex) { - // com.sun.star.uno.RuntimeException - throw new JabRefException("Could not get the cursor", - Localization.lang("Could not get the cursor.")); + cursor = null; + } + + if (cursor == null) { + showDialog(title, + new JabRefException("Could not get the cursor", + Localization.lang("Could not get the cursor."))); + return; } // Check for crippled XTextViewCursor @@ -443,7 +489,8 @@ public void insertEntry(List entries, + " to the location for the new citation.") + "\n" + Localization.lang("I cannot insert to the cursors current location."); - throw new JabRefException(msg, ex); + showDialog(title, new JabRefException(msg, ex)); + return; } List citationKeys = @@ -533,11 +580,38 @@ public void insertEntry(List entries, + " Could not go back to end of in-text citation", ex); } } + } catch (NoDocumentException ex) { + OpenOfficePanel.showNoDocumentErrorMessage(dialogService); + return; } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference // or catch a DisposedException (which is in a OO JAR file). - throw new ConnectionLostException(ex.getMessage()); + // throw new ConnectionLostException(ex.getMessage()); + OpenOfficePanel.showConnectionLostErrorMessage(dialogService); + return; + } catch (UndefinedCharacterFormatException ex) { + OpenOfficePanel.reportUndefinedCharacterFormat(dialogService, ex); + return; + } catch (UndefinedParagraphFormatException ex) { + OpenOfficePanel.reportUndefinedParagraphFormat(dialogService, ex); + return; + } catch (JabRefException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("JabRefException"), + ex.getLocalizedMessage()); + return; + } catch (com.sun.star.lang.IllegalArgumentException + | UnknownPropertyException + | PropertyVetoException + | CreationException + | NoSuchElementException + | WrappedTargetException + | IllegalTypeException + | PropertyExistException + | NotRemoveableException ex) { + LOGGER.warn("Could not insert entry", ex); + return; } finally { if (useUndoContext) { UnoUndo.leaveUndoContext(doc); @@ -775,7 +849,10 @@ public void combineCiteMarkers(List databases, JabRefException, InvalidStateException { - styleIsRequired(style); + final String title = "Could not merge citations"; + if (testDialog(title, styleIsRequired(style))) { + return; + } Objects.requireNonNull(databases); Objects.requireNonNull(style); @@ -1124,7 +1201,10 @@ public void unCombineCiteMarkers(List databases, JabRefException, InvalidStateException { - styleIsRequired(style); + final String title = "Could not separate citations"; + if (testDialog(title, styleIsRequired(style))) { + return; + } Objects.requireNonNull(databases); Objects.requireNonNull(style); @@ -1260,7 +1340,8 @@ public ExportCitedHelperResult exportCitedHelper(List databases) PropertyVetoException, IOException, CreationException, - InvalidStateException { + InvalidStateException, + JabRefException { XTextDocument doc = this.getXTextDocumentOrThrow(); @@ -1344,7 +1425,6 @@ private static void checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) throws UnknownPropertyException, WrappedTargetException, - PropertyVetoException, JabRefException { boolean recordingChanges = UnoRedlines.getRecordChanges(doc); int nRedlines = UnoRedlines.countRedlines(doc); @@ -1368,6 +1448,38 @@ private static void checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) } } + private static VoidResult checkIfOpenOfficeIsRecordingChanges2(XTextDocument doc) { + + String title = Localization.lang("Recording and/or Recorded changes"); + try { + boolean recordingChanges = UnoRedlines.getRecordChanges(doc); + int nRedlines = UnoRedlines.countRedlines(doc); + if (recordingChanges || nRedlines > 0) { + String msg = ""; + if (recordingChanges) { + msg += Localization.lang("Cannot work with" + + " [Edit]/[Track Changes]/[Record] turned on."); + } + if (nRedlines > 0) { + if (recordingChanges) { + msg += "\n"; + } + msg += Localization.lang("Changes by JabRef" + + " could result in unexpected interactions with" + + " recorded changes."); + msg += "\n"; + msg += Localization.lang("Use [Edit]/[Track Changes]/[Manage] to resolve them first."); + } + return VoidResult.Error(new JabRefException(title, msg)); + } + } catch (UnknownPropertyException | WrappedTargetException ex) { + String msg = Localization.lang("Error while checking if Writer" + + " is recording changes or has recorded changes."); + return VoidResult.Error(new JabRefException(title, msg, ex)); + } + return VoidResult.OK(); + } + /* * Called from GUI. */ @@ -1382,14 +1494,15 @@ public void checkIfOpenOfficeIsRecordingChanges() checkIfOpenOfficeIsRecordingChanges(doc); } - void styleIsRequired(OOBibStyle style) - throws - JabRefException { + VoidResult styleIsRequired(OOBibStyle style) { if (style == null) { - throw new JabRefException("This operation requires a style", - Localization.lang("This operation requires a style.") - + "\n" - + Localization.lang("Please select one.")); + return VoidResult.Error( + new JabRefException("This operation requires a style", + Localization.lang("This operation requires a style.") + + "\n" + + Localization.lang("Please select one."))); + } else { + return VoidResult.OK(); } } @@ -1502,65 +1615,90 @@ public void checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) * * @param databases Must have at least one. * @param style Style. - * @return List of unresolved citation keys. * */ - public List updateDocumentActionHelper(List databases, - OOBibStyle style) - throws - NoSuchElementException, - WrappedTargetException, - IllegalArgumentException, - CreationException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - NoDocumentException, - UndefinedCharacterFormatException, - IOException, - JabRefException, - InvalidStateException { - - styleIsRequired(style); + public void updateDocumentActionHelper(List databases, OOBibStyle style) { - XTextDocument doc = this.getXTextDocumentOrThrow(); - - checkStylesExistInTheDocument(style, doc); - checkIfOpenOfficeIsRecordingChanges(doc); + final String title = Localization.lang("Unable to synchronize bibliography"); try { - UnoUndo.enterUndoContext(doc, "Refresh bibliography"); - boolean requireSeparation = false; + Optional odoc = getOrDialog(title, getXTextDocument()); + if (odoc.isEmpty() + || testDialog(title, styleIsRequired(style))) { + return; + } - OOFrontend fr = new OOFrontend(doc); + XTextDocument doc = odoc.get(); - // Check Range overlaps - int maxReportedOverlaps = 10; - fr.checkRangeOverlaps(doc, requireSeparation, maxReportedOverlaps); + checkStylesExistInTheDocument(style, doc); + checkIfOpenOfficeIsRecordingChanges(doc); - final boolean useLockControllers = true; - fr.imposeGlobalOrder(doc); - OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); try { - if (useLockControllers) { - UnoScreenRefresh.lockControllers(doc); + UnoUndo.enterUndoContext(doc, "Refresh bibliography"); + + OOFrontend fr = new OOFrontend(doc); + + // Check Range overlaps + boolean requireSeparation = false; + int maxReportedOverlaps = 10; + if (testDialog(title, fr.checkRangeOverlaps(doc, + requireSeparation, + maxReportedOverlaps))) { + return; } - applyNewCitationMarkers(doc, fr, x.citMarkers, style); - rebuildBibTextSection(doc, - style, - fr, - x.getBibliography(), - this.alwaysAddCitedOnPages); - return x.getUnresolvedKeys(); - } finally { - if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { - UnoScreenRefresh.unlockControllers(doc); + + final boolean useLockControllers = true; + fr.imposeGlobalOrder(doc); + OOProcess.ProduceCitationMarkersResult x = + OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); + try { + if (useLockControllers) { + UnoScreenRefresh.lockControllers(doc); + } + applyNewCitationMarkers(doc, fr, x.citMarkers, style); + rebuildBibTextSection(doc, + style, + fr, + x.getBibliography(), + this.alwaysAddCitedOnPages); + List unresolvedKeys = x.getUnresolvedKeys(); + if (!unresolvedKeys.isEmpty()) { + String msg = Localization.lang("Your OpenOffice/LibreOffice document" + + " references the citation key '%0'," + + " which could not be found" + + " in your current library.", + unresolvedKeys.get(0)); + dialogService.showErrorDialogAndWait(title, msg); + return; + } + } finally { + if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { + UnoScreenRefresh.unlockControllers(doc); + } } + } finally { + UnoUndo.leaveUndoContext(doc); } - } finally { - UnoUndo.leaveUndoContext(doc); + } catch (JabRefException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("JabRefException"), + ex.getLocalizedMessage()); + } catch (UndefinedCharacterFormatException ex) { + OpenOfficePanel.reportUndefinedCharacterFormat(dialogService, ex); + } catch (UndefinedParagraphFormatException ex) { + OpenOfficePanel.reportUndefinedParagraphFormat(dialogService, ex); + } catch (ConnectionLostException ex) { + OpenOfficePanel.showConnectionLostErrorMessage(dialogService); + } catch (NoDocumentException ex) { + OpenOfficePanel.showNoDocumentErrorMessage(dialogService); + } catch (com.sun.star.lang.IllegalArgumentException + | PropertyVetoException + | UnknownPropertyException + | WrappedTargetException + | NoSuchElementException + | CreationException ex) { + LOGGER.warn("Could not update bibliography", ex); } } diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 4a428a653df..13ddc505139 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -7,9 +7,11 @@ import java.util.stream.Collectors; import org.jabref.gui.DialogService; +import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.NoDocumentException; +import org.jabref.logic.openoffice.Result; import org.jabref.logic.openoffice.UnoCast; import org.jabref.logic.openoffice.UnoTextDocument; @@ -237,6 +239,17 @@ public XTextDocument getXTextDocumentOrThrow() return this.xTextDocument; } + public Result getXTextDocument() { + if (isDocumentConnectionMissing()) { + final String msg = Localization.lang("Not connected to any Writer document." + + " Please make sure a document is open," + + " and use the 'Select Writer document' button" + + " to connect to it."); + return Result.Error(new JabRefException("Not connected to document", msg)); + } + return Result.OK(this.xTextDocument); + } + /** * The title of the current document, or Optional.empty() */ diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index b39cc402be4..9220c3f13c7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -1,6 +1,5 @@ package org.jabref.gui.openoffice; -import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; @@ -56,6 +55,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; +import org.jabref.model.openoffice.CitationEntry; import org.jabref.preferences.PreferencesService; import com.sun.star.beans.IllegalTypeException; @@ -202,32 +202,15 @@ private void initPanel() { } List databases = getBaseList(); - List unresolvedKeys = ooBase.updateDocumentActionHelper(databases, style); + ooBase.updateDocumentActionHelper(databases, style); - if (!unresolvedKeys.isEmpty()) { - dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), - Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - unresolvedKeys.get(0))); - } - } catch (JabRefException ex) { - dialogService.showErrorDialogAndWait( - Localization.lang("JabRefException"), - ex.getLocalizedMessage()); - } catch (UndefinedCharacterFormatException ex) { - reportUndefinedCharacterFormat(ex); - } catch (UndefinedParagraphFormatException ex) { - reportUndefinedParagraphFormat(ex); } catch (ConnectionLostException ex) { - showConnectionLostErrorMessage(); - } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(); + showConnectionLostErrorMessage(dialogService); } catch (IOException ex) { LOGGER.warn("Problem with style file", ex); dialogService.showErrorDialogAndWait(Localization.lang("No valid style file defined"), Localization.lang("You must select either a valid style file, or use one of the default styles.")); - } catch (com.sun.star.lang.IllegalArgumentException | PropertyVetoException | UnknownPropertyException | WrappedTargetException | NoSuchElementException | - InvalidStateException | - CreationException ex) { + } catch (com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Could not update bibliography", ex); } }); @@ -242,9 +225,9 @@ private void initPanel() { Localization.lang("JabRefException"), ex.getLocalizedMessage()); } catch (UndefinedCharacterFormatException ex) { - reportUndefinedCharacterFormat(ex); + reportUndefinedCharacterFormat(dialogService, ex); } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(); + showNoDocumentErrorMessage(dialogService); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | NotRemoveableException | IllegalTypeException | InvalidStateException | @@ -263,9 +246,9 @@ private void initPanel() { Localization.lang("JabRefException"), ex.getLocalizedMessage()); } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(); + showNoDocumentErrorMessage(dialogService); } catch (UndefinedCharacterFormatException ex) { - reportUndefinedCharacterFormat(ex); + reportUndefinedCharacterFormat(dialogService, ex); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | PropertyExistException | IllegalTypeException | NotRemoveableException | @@ -280,22 +263,11 @@ private void initPanel() { settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { - try { - ooBase.checkIfOpenOfficeIsRecordingChanges(); - } catch (JabRefException ex) { - dialogService.showErrorDialogAndWait( - Localization.lang("JabRefException"), - ex.getLocalizedMessage()); - return; - } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(); - return; - } catch (UnknownPropertyException - | PropertyVetoException - | WrappedTargetException ex) { - LOGGER.warn("Problem during checkIfOpenOfficeIsRecordingChanges", ex); - } - dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); + Optional> citations = ooBase.getCitationEntries(); + if (citations.isPresent()) { + dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase, + citations.get())); + } }); exportCitations.setMaxWidth(Double.MAX_VALUE); @@ -357,8 +329,12 @@ private void exportEntries() { BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase); this.frame.addTab(databaseContext, true); + } catch (JabRefException ex) { + dialogService.showErrorDialogAndWait( + Localization.lang("JabRefException"), + ex.getLocalizedMessage()); } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(); + showNoDocumentErrorMessage(dialogService); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | UndefinedCharacterFormatException | NoSuchElementException | WrappedTargetException | IOException | InvalidStateException | @@ -528,7 +504,7 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP ex.getLocalizedMessage()); return; } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(); + showNoDocumentErrorMessage(dialogService); return; } catch (UnknownPropertyException | PropertyVetoException @@ -580,40 +556,21 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP style = loader.getUsedStyle(); if (style == null) { dialogService.showErrorDialogAndWait( - Localization.lang("No style for citation"), + Localization.lang("No valid style file defined"), Localization.lang( "No bibliography style is selected for citation.") + "\n" - + Localization.lang("Select one before citing.")); + + Localization.lang("Select one before citing.") + + "\n" + + Localization.lang("You must select either a valid style file, or use one of the default styles.")); return; } } ooBase.insertEntry(entries, database, getBaseList(), style, inParenthesis, withText, pageInfo, ooPrefs.getSyncWhenCiting()); - } catch (FileNotFoundException ex) { - - dialogService.showErrorDialogAndWait( - Localization.lang("No valid style file defined"), - Localization.lang("You must select either a valid style file, or use one of the default styles.")); - - LOGGER.warn("Problem with style file", ex); - } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(); } catch (ConnectionLostException ex) { - showConnectionLostErrorMessage(); - } catch (UndefinedCharacterFormatException ex) { - reportUndefinedCharacterFormat(ex); - } catch (UndefinedParagraphFormatException ex) { - reportUndefinedParagraphFormat(ex); - } catch (JabRefException ex) { - dialogService.showErrorDialogAndWait( - Localization.lang("JabRefException"), - ex.getLocalizedMessage()); - } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | - CreationException | NoSuchElementException | WrappedTargetException | IOException | - IllegalTypeException | PropertyExistException | - InvalidStateException | - NotRemoveableException ex) { + showConnectionLostErrorMessage(dialogService); + } catch (com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Could not insert entry", ex); } } @@ -680,24 +637,24 @@ private boolean checkThatEntriesHaveKeys(List entries) { } } - private void showConnectionLostErrorMessage() { + public static void showConnectionLostErrorMessage(DialogService dialogService) { dialogService.showErrorDialogAndWait(Localization.lang("Connection lost"), Localization.lang("Connection to OpenOffice/LibreOffice has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); } - private void showNoDocumentErrorMessage() { + public static void showNoDocumentErrorMessage(DialogService dialogService) { dialogService.showErrorDialogAndWait(Localization.lang("Connection to document lost"), Localization.lang("Connection to OpenOffice/LibreOffice document has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); } - private void reportUndefinedParagraphFormat(UndefinedParagraphFormatException ex) { + public static void reportUndefinedParagraphFormat(DialogService dialogService, UndefinedParagraphFormatException ex) { dialogService.showErrorDialogAndWait(Localization.lang("Undefined paragraph format"), Localization.lang("Your style file specifies the paragraph format '%0', " + "which is undefined in your current OpenOffice/LibreOffice document.", ex.getFormatName()) + "\n" + Localization.lang("The paragraph format is controlled by the property 'ReferenceParagraphFormat' or 'ReferenceHeaderParagraphFormat' in the style file.")); } - private void reportUndefinedCharacterFormat(UndefinedCharacterFormatException ex) { + public static void reportUndefinedCharacterFormat(DialogService dialogService, UndefinedCharacterFormatException ex) { dialogService.showErrorDialogAndWait(Localization.lang("Undefined character format"), Localization.lang("Your style file specifies the character format '%0', " + "which is undefined in your current OpenOffice/LibreOffice document.", diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index e80076fed68..46aad42d008 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -356,8 +356,7 @@ public Optional getMarkRange(CitationGroup cg, XTextDocument doc) public Optional getRawCursorForCitationGroup(CitationGroup cg, XTextDocument doc) throws NoDocumentException, - WrappedTargetException, - CreationException { + WrappedTargetException { return cg.cgRangeStorage.getRawCursor(doc); } @@ -386,8 +385,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups throws UnknownPropertyException, WrappedTargetException, - NoDocumentException, - CreationException { + NoDocumentException { switch (dataModel) { case JabRef52: diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 7e631d32257..ddfaf084afe 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -139,41 +139,38 @@ public Optional healthReport(XTextDocument doc) */ // Sort within partitions - RangeKeyedMapList> xxs = new RangeKeyedMapList<>(); - for (RangeSort.RangeSortEntry v : sortables) { - xxs.add(v.getRange(), v); + RangeKeyedMapList> rangeSorter = + new RangeKeyedMapList<>(); + for (RangeSort.RangeSortEntry sortable : sortables) { + rangeSorter.add(sortable.getRange(), sortable); } // build final list List> res = new ArrayList<>(); for (TreeMap>> - xs : xxs.partitionValues()) { + partition : rangeSorter.partitionValues()) { - List orderedRanges = new ArrayList<>(xs.keySet()); + List orderedRanges = new ArrayList<>(partition.keySet()); int indexInPartition = 0; for (int i = 0; i < orderedRanges.size(); i++) { - XTextRange a = orderedRanges.get(i); - List> avs = xs.get(a); - for (int j = 0; j < avs.size(); j++) { - RangeSort.RangeSortEntry v = avs.get(j); - v.indexInPosition = indexInPartition++; + XTextRange aRange = orderedRanges.get(i); + List> sortablesAtARange = partition.get(aRange); + for (RangeSort.RangeSortEntry sortable : sortablesAtARange) { + sortable.indexInPosition = indexInPartition++; if (mapFootnotesToFootnoteMarks) { - Optional fmr = UnoTextRange.getFootnoteMarkRange(v.getRange()); + Optional footnoteMarkRange = + UnoTextRange.getFootnoteMarkRange(sortable.getRange()); // Adjust range if we are inside a footnote: - if (fmr.isPresent()) { - v.range = fmr.get(); + if (footnoteMarkRange.isPresent()) { + sortable.range = footnoteMarkRange.get(); } } - res.add(v); + res.add(sortable); } } } - // convert - // List> - // to - // List> return res.stream().map(e -> e).collect(Collectors.toList()); } @@ -191,21 +188,15 @@ public Optional healthReport(XTextDocument doc) * order. * */ - private List getVisuallySortedCitationGroupIDs(XTextDocument doc, - boolean mapFootnotesToFootnoteMarks) + private List + getVisuallySortedCitationGroupIDs(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) throws WrappedTargetException, NoDocumentException, JabRefException { List> sortables = - createVisualSortInput(doc, - mapFootnotesToFootnoteMarks); - - if (sortables.size() != this.citationGroups.numberOfCitationGroups()) { - throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " sortables.size() != cgs.citationGroups.size()"); - } + createVisualSortInput(doc, mapFootnotesToFootnoteMarks); String messageOnFailureToObtainAFunctionalXTextViewCursor = Localization.lang("Please move the cursor into the document text.") @@ -218,19 +209,16 @@ private List getVisuallySortedCitationGroupIDs(XTextDocument do doc, messageOnFailureToObtainAFunctionalXTextViewCursor); - if (sorted.size() != this.citationGroups.numberOfCitationGroups()) { - // This Fired - throw new RuntimeException("getVisuallySortedCitationGroupIDs:" - + " sorted.size() != cgs.numberOfCitationGroups()"); - } - - return (sorted.stream() - .map(e -> e.getContent()) - .collect(Collectors.toList())); + return (sorted.stream().map(e -> e.getContent()).collect(Collectors.toList())); } /** - * Calculate and return citation group IDs in visual order. + * Calculate and return citation group IDs in visual order within + * (but not across) XText partitions. + * + * This is (1) sufficient for combineCiteMarkers which looks for + * consecutive XTextRanges within each XText, (2) not confused by + * multicolumn layout or multipage display. */ public List getCitationGroupIDsSortedWithinPartitions(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) @@ -242,11 +230,6 @@ private List getVisuallySortedCitationGroupIDs(XTextDocument do List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); - if (sortables.size() != this.citationGroups.numberOfCitationGroups()) { - throw new RuntimeException("getCitationGroupIDsSortedWithinPartitions:" - + " sortables.size() != citationGroups.numberOfCitationGroups()"); - } - return (sortables.stream().map(e -> e.getContent()).collect(Collectors.toList())); } @@ -254,41 +237,11 @@ private List getVisuallySortedCitationGroupIDs(XTextDocument do * Create a citation group for the given citation keys, at the * end of position. * - * To reduce the difference from the original representation, we - * only insist on having at least two characters inside reference - * marks. These may be ZERO_WIDTH_SPACE characters or other - * placeholder not likely to appear in a citation mark. - * - * This placeholder is only needed if the citation mark is - * otherwise empty (e.g. when we just create it). - * - * getFillCursorForCitationGroup yields a bracketed cursor, that - * can be used to fill in / overwrite the value inside. - * - * After each getFillCursorForCitationGroup, we require a call to - * cleanFillCursorForCitationGroup, which removes the brackets, - * unless if it would make the content less than two - * characters. If we need only one placeholder, we keep the left - * bracket. If we need two, then the content is empty. The - * removeBracketsFromEmpty parameter of - * cleanFillCursorForCitationGroup overrides this, and for empty - * citations it will remove the brackets, leaving an empty - * reference mark. The idea behind this is that we do not need to - * refill empty marks (citationType INVISIBLE_CIT), and the caller - * can tell us that we are dealing with one of these. - * - * Thus the only user-visible difference in citation marks is - * that instead of empty marks we use two brackets, for - * single-character marks we add a left bracket before. - * - * Character-attribute inheritance: updates inherit from the - * first character inside, not from the left. - * * On return {@code position} is collapsed, and is after the * inserted space, or at the end of the reference mark. * - * @param citationKeys - * @param pageInfosForCitations + * @param citationKeys In storage order + * @param pageInfosForCitations In storage order * @param citationType * @param position Collapsed to its end. * @param insertSpaceAfter If true, we insert a space after the mark, that @@ -343,12 +296,11 @@ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) PropertyExistException, IllegalTypeException { - // Apply backend.removeCitationGroup(cg, doc); this.citationGroups.afterRemoveCitationGroup(cg); } - public void removeCitationGroups(List xcgs, XTextDocument doc) + public void removeCitationGroups(List cgs, XTextDocument doc) throws WrappedTargetException, NoDocumentException, @@ -357,7 +309,7 @@ public void removeCitationGroups(List xcgs, XTextDocument doc) PropertyExistException, IllegalTypeException { - for (CitationGroup cg : xcgs) { + for (CitationGroup cg : cgs) { removeCitationGroup(cg, doc); } } @@ -366,7 +318,7 @@ public void removeCitationGroups(List xcgs, XTextDocument doc) * ranges controlled by citation groups should not overlap with each other. * * @param cgid : Must be known, throws if not. - * @return Null if the reference mark is missing. + * @return Optional.empty() if the reference mark is missing. * */ public Optional getMarkRange(XTextDocument doc, CitationGroupID cgid) @@ -377,23 +329,6 @@ public Optional getMarkRange(XTextDocument doc, CitationGroupID cgid return backend.getMarkRange(cg, doc); } - /** - * Cursor for the reference marks as is, not prepared for filling, - * but does not need cleanFillCursorForCitationGroup either. - */ - public Optional getRawCursorForCitationGroup(CitationGroupID cgid, XTextDocument doc) - throws - NoDocumentException, - WrappedTargetException, - CreationException { - - Optional cg = this.citationGroups.getCitationGroup(cgid); - if (cg.isEmpty()) { - return Optional.empty(); - } - return backend.getRawCursorForCitationGroup(cg.get(), doc); - } - public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGroupID cgid) throws NoDocumentException, @@ -404,9 +339,10 @@ public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGrou return backend.getFillCursorForCitationGroup(cg, doc); } - /** - * Remove brackets, but if the result would become empty, leave - * them; if the result would be a single characer, leave the left bracket. + /** + * Remove brackets added by getFillCursorForCitationGroup. + * + * @param cgid : Must be known, throws if not. */ public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroupID cgid) throws @@ -423,25 +359,25 @@ public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroupID c * * result.size() == nRefMarks */ - public List citationRanges(XTextDocument doc) + private List citationRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - List xs = new ArrayList<>(citationGroups.numberOfCitationGroups()); + List result = new ArrayList<>(citationGroups.numberOfCitationGroups()); List cgids = new ArrayList<>(citationGroups.getCitationGroupIDsUnordered()); for (CitationGroupID cgid : cgids) { - XTextRange r = this.getMarkRange(doc, cgid).orElseThrow(RuntimeException::new); + XTextRange range = this.getMarkRange(doc, cgid).orElseThrow(RuntimeException::new); CitationGroup cg = citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); String name = cg.cgRangeStorage.getName(); - xs.add(new RangeForOverlapCheck(r, - cgid, - RangeForOverlapCheck.REFERENCE_MARK_KIND, - name)); + result.add(new RangeForOverlapCheck(range, + cgid, + RangeForOverlapCheck.REFERENCE_MARK_KIND, + name)); } - return xs; + return result; } /** @@ -458,7 +394,7 @@ public List citationRanges(XTextDocument doc) * footnote marks does not depend on how do we mark or * structure those ranges. */ - public List footnoteMarkRanges(XTextDocument doc) + private List footnoteMarkRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { @@ -467,14 +403,13 @@ public List footnoteMarkRanges(XTextDocument doc) // Could use RangeSet if we had that. RangeKeyedMap seen = new RangeKeyedMap<>(); - List xs = new ArrayList<>(); + List result = new ArrayList<>(); List citRanges = citationRanges(doc); for (RangeForOverlapCheck base : citRanges) { - XTextRange r = base.range; - Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(r); + Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(base.range); if (footnoteMarkRange.isEmpty()) { // not in footnote @@ -484,13 +419,13 @@ public List footnoteMarkRanges(XTextDocument doc) boolean seenContains = seen.containsKey(footnoteMarkRange.get()); if (!seenContains) { seen.put(footnoteMarkRange.get(), true); - xs.add(new RangeForOverlapCheck(footnoteMarkRange.get(), - base.i, // cgid :: identifies of citation group - RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + base.format())); + result.add(new RangeForOverlapCheck(footnoteMarkRange.get(), + base.i, // cgid :: identifies of citation group + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + base.format())); } } - return xs; + return result; } /** @@ -498,13 +433,12 @@ public List footnoteMarkRanges(XTextDocument doc) * @param reportAtMost Limit number of overlaps reported (0 for no limit) * */ - public void checkRangeOverlaps(XTextDocument doc, - boolean requireSeparation, - int reportAtMost) + public VoidResult checkRangeOverlaps(XTextDocument doc, + boolean requireSeparation, + int reportAtMost) throws NoDocumentException, - WrappedTargetException, - JabRefException { + WrappedTargetException { final boolean debugPartitions = false; @@ -538,7 +472,9 @@ public void checkRangeOverlaps(XTextDocument doc, break; } } - throw new JabRefException("Found overlapping or touching ranges", msg); + return VoidResult.Error(new JabRefException("Found overlapping or touching ranges", msg)); + } else { + return VoidResult.OK(); } } @@ -580,8 +516,7 @@ public List getCitationEntries(XTextDocument doc) throws UnknownPropertyException, WrappedTargetException, - NoDocumentException, - CreationException { + NoDocumentException { return this.backend.getCitationEntries(doc, citationGroups); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index e65d83d36a8..da6c357f929 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -61,8 +61,7 @@ public static String getCursorStringWithContext(XTextCursor cursor, boolean htmlMarkup) throws WrappedTargetException, - NoDocumentException, - CreationException { + NoDocumentException { String citPart = cursor.getString(); diff --git a/src/main/java/org/jabref/logic/openoffice/Result.java b/src/main/java/org/jabref/logic/openoffice/Result.java new file mode 100644 index 00000000000..a4a46e13b8f --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/Result.java @@ -0,0 +1,84 @@ +package org.jabref.logic.openoffice; + +import java.util.Optional; +import java.util.function.Consumer; + +/* + * error cannot be null + * result cannot be null + * If Void is not allowed for R, use VoidResult instead. + */ +public class Result { + private final Optional result; + private final Optional error; + + private Result(Optional result, Optional error) { + this.result = result; + this.error = error; + } + + public static Result OK(R result) { + return new Result(Optional.of(result), Optional.empty()); + } + + public static Result Error(E error) { + return new Result(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 RuntimeException("Cannot get from error"); + } + return result.orElse(null); + } + + /* + * Throw away the error part. + */ + public Optional getOptional() { + return result; + } + + public E getError() { + return error.get(); + } + + public Result ifError(Consumer fun) { + if (isError()) { + fun.accept(getError()); + } + return this; + } + + public Result ifPresent(Consumer fun) { + if (isPresent()) { + fun.accept(get()); + } + return this; + } + + public Result setIfPresent(Settable out) { + if (isPresent()) { + out.set(get()); + } + return this; + } + +} + diff --git a/src/main/java/org/jabref/logic/openoffice/Settable.java b/src/main/java/org/jabref/logic/openoffice/Settable.java new file mode 100644 index 00000000000..e10db2e9538 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/Settable.java @@ -0,0 +1,26 @@ +package org.jabref.logic.openoffice; + +import java.util.Optional; + +public class Settable { + private Optional value; + public Settable() { + value = Optional.empty(); + } + + public boolean isEmpty() { + return value.isEmpty(); + } + + public boolean isPresent() { + return value.isPresent(); + } + + public T get() { + return value.get(); + } + + public void set(T value) { + this.value = Optional.of(value); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBase.java b/src/main/java/org/jabref/logic/openoffice/StorageBase.java index eef0fb29c12..04668f9d33a 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBase.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBase.java @@ -32,8 +32,7 @@ public Optional getMarkRange(XTextDocument doc) public Optional getRawCursor(XTextDocument doc) throws NoDocumentException, - WrappedTargetException, - CreationException; + WrappedTargetException; /** * Get a cursor for filling in text. diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index 79f991e5b2f..005e7c11125 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -190,8 +190,7 @@ public Optional getMarkRange(XTextDocument doc) public Optional getRawCursor(XTextDocument doc) throws NoDocumentException, - WrappedTargetException, - CreationException { + WrappedTargetException { String name = this.getName(); Optional full = Optional.empty(); diff --git a/src/main/java/org/jabref/logic/openoffice/VoidResult.java b/src/main/java/org/jabref/logic/openoffice/VoidResult.java new file mode 100644 index 00000000000..69148a21307 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/VoidResult.java @@ -0,0 +1,43 @@ +package org.jabref.logic.openoffice; + +import java.util.Optional; +import java.util.function.Consumer; + +/* + * error cannot be null + */ +public class VoidResult { + private final Optional error; + + private VoidResult(Optional error) { + this.error = error; + } + + public static VoidResult OK() { + return new VoidResult(Optional.empty()); + } + + public static VoidResult Error(E error) { + return new VoidResult(Optional.of(error)); + } + + public boolean isError() { + return error.isPresent(); + } + + public boolean isOK() { + return !isError(); + } + + public E getError() { + return error.get(); + } + + public VoidResult ifError(Consumer fun) { + if (isError()) { + fun.accept(getError()); + } + return this; + } +} + diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index bc84278239f..06a3a00cbfa 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1544,7 +1544,6 @@ No\ bibliography\ entries\ are\ selected\ for\ citation.=No bibliography entries No\ bibliography\ style\ is\ selected\ for\ citation.=No bibliography style is selected for citation. No\ database=No database No\ entries\ selected\ for\ citation=No entries selected for citation -No\ style\ for\ citation=No style for citation Open\ one\ before\ citing.=Open one before citing. Please\ select\ one.=Please select one. Select\ one\ before\ citing.=Select one before citing. @@ -2339,6 +2338,8 @@ The\ %0\ paragraph\ style\ '%1'\ is\ a\ display\ name\ for\ '%2'.=The %0 paragra The\ %0\ paragraph\ style\ '%1'\ is\ missing\ from\ the\ document=The %0 paragraph style '%1' is missing from the document +Error\ while\ checking\ if\ Writer\ is\ recording\ changes\ or\ has\ recorded\ changes.=Error while checking if Writer is recording changes or has recorded changes. + Cannot\ work\ with\ [Edit]/[Track\ Changes]/[Record]\ turned\ on.=Cannot work with [Edit]/[Track Changes]/[Record] turned on. Changes\ by\ JabRef\ could\ result\ in\ unexpected\ interactions\ with\ recorded\ changes.=Changes by JabRef could result in unexpected interactions with recorded changes. From 2d087361407287c42336c2c3231f1eff43ec9947 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 14 May 2021 23:19:07 +0200 Subject: [PATCH 0711/1068] added OOError, moving stuff from OOBibBase to logic. Build fails with Wrong URL: https://docs.jabref.org/general/entryeditor ==> expected: <200> but was: <404> --- .../ManageCitationsDialogViewModel.java | 2 +- .../org/jabref/gui/openoffice/OOBibBase.java | 1165 ++++++----------- .../gui/openoffice/OOBibBaseConnect.java | 20 +- .../org/jabref/gui/openoffice/OOError.java | 134 ++ .../gui/openoffice/OpenOfficePanel.java | 324 ++--- .../org/jabref/logic/oostyle/OOBibStyle.java | 20 +- .../org/jabref/logic/oostyle/OOProcess.java | 7 +- .../openoffice/ConnectionLostException.java | 4 +- .../jabref/logic/openoffice/EditInsert.java | 159 +++ .../logic/openoffice/ManageCitations.java | 39 + .../logic/openoffice/NoDocumentException.java | 7 +- .../openoffice/NoDocumentFoundException.java | 12 + .../openoffice/OOFormattedTextIntoOO.java | 49 +- .../openoffice/OOFormattedTextIntoOOV1.java | 910 ------------- .../org/jabref/logic/openoffice/OOUtil.java | 3 - .../org/jabref/logic/openoffice/Result.java | 9 +- .../org/jabref/logic/openoffice/Settable.java | 26 - .../UndefinedCharacterFormatException.java | 19 - .../UndefinedParagraphFormatException.java | 18 - .../org/jabref/logic/openoffice/UnoStyle.java | 34 +- .../org/jabref/logic/openoffice/Update.java | 68 + .../logic/openoffice/UpdateBibliography.java | 149 +++ .../openoffice/UpdateCitationMarkers.java | 176 +++ .../jabref/logic/openoffice/VoidResult.java | 9 + src/main/resources/l10n/JabRef_en.properties | 36 +- 25 files changed, 1419 insertions(+), 1980 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/OOError.java rename src/main/java/org/jabref/{gui => logic}/openoffice/ConnectionLostException.java (62%) create mode 100644 src/main/java/org/jabref/logic/openoffice/EditInsert.java create mode 100644 src/main/java/org/jabref/logic/openoffice/ManageCitations.java create mode 100644 src/main/java/org/jabref/logic/openoffice/NoDocumentFoundException.java delete mode 100644 src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java delete mode 100644 src/main/java/org/jabref/logic/openoffice/Settable.java delete mode 100644 src/main/java/org/jabref/logic/openoffice/UndefinedCharacterFormatException.java delete mode 100644 src/main/java/org/jabref/logic/openoffice/UndefinedParagraphFormatException.java create mode 100644 src/main/java/org/jabref/logic/openoffice/Update.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 53f74179ca0..c2b997732db 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -30,7 +30,7 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, public void storeSettings() { List ciationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); - ooBase.applyCitationEntries(ciationEntries); + ooBase.guiActionApplyCitationEntries(ciationEntries); } public ListProperty citationsProperty() { diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b43b907377e..207960ab5b3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -3,12 +3,13 @@ import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.function.Supplier; import java.util.stream.Collectors; import org.jabref.gui.DialogService; @@ -16,31 +17,26 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.Citation; import org.jabref.logic.oostyle.CitationGroup; -import org.jabref.logic.oostyle.CitationGroups; -import org.jabref.logic.oostyle.CitationMarkerEntry; -import org.jabref.logic.oostyle.CitationMarkerEntryImpl; import org.jabref.logic.oostyle.CitedKey; import org.jabref.logic.oostyle.CitedKeys; import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.logic.oostyle.OOFormat; -import org.jabref.logic.oostyle.OOFormatBibliography; -import org.jabref.logic.oostyle.OOProcess; +import org.jabref.logic.openoffice.ConnectionLostException; import org.jabref.logic.openoffice.CreationException; +import org.jabref.logic.openoffice.EditInsert; +import org.jabref.logic.openoffice.ManageCitations; import org.jabref.logic.openoffice.NoDocumentException; -import org.jabref.logic.openoffice.OOFormattedTextIntoOO; +import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.Result; -import org.jabref.logic.openoffice.UndefinedCharacterFormatException; -import org.jabref.logic.openoffice.UndefinedParagraphFormatException; -import org.jabref.logic.openoffice.UnoBookmark; import org.jabref.logic.openoffice.UnoCrossRef; import org.jabref.logic.openoffice.UnoCursor; import org.jabref.logic.openoffice.UnoRedlines; import org.jabref.logic.openoffice.UnoScreenRefresh; import org.jabref.logic.openoffice.UnoStyle; import org.jabref.logic.openoffice.UnoTextRange; -import org.jabref.logic.openoffice.UnoTextSection; import org.jabref.logic.openoffice.UnoUndo; +import org.jabref.logic.openoffice.Update; +import org.jabref.logic.openoffice.UpdateCitationMarkers; import org.jabref.logic.openoffice.VoidResult; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; @@ -48,7 +44,6 @@ import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; -import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; @@ -63,7 +58,6 @@ import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; -import com.sun.star.text.XTextSection; import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -74,14 +68,14 @@ */ class OOBibBase { - private static final String BIB_SECTION_NAME = "JR_bib"; - private static final String BIB_SECTION_END_NAME = "JR_bib_end"; - - private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); /* variables */ private final DialogService dialogService; + + /* + * Shall we add "Cited on pages: ..." to resolved bibliography entries? + */ private final boolean alwaysAddCitedOnPages; private final OOBibBaseConnect connection; @@ -96,15 +90,27 @@ public OOBibBase(Path loPath, DialogService dialogService) this.dialogService = dialogService; this.connection = new OOBibBaseConnect(loPath, dialogService); - this.alwaysAddCitedOnPages = true; + this.alwaysAddCitedOnPages = false; } - public void selectDocument() - throws - NoDocumentException, - NoSuchElementException, - WrappedTargetException { - this.connection.selectDocument(); + public void guiActionSelectDocument(boolean autoSelectForSingle) { + try { + + this.connection.selectDocument(autoSelectForSingle); + + } catch (NoDocumentFoundException ex) { + OOError.from(ex).showErrorDialog(dialogService); + } catch (WrappedTargetException + | IndexOutOfBoundsException + | NoSuchElementException ex) { + LOGGER.warn("Problem connecting", ex); + dialogService.showErrorDialogAndWait(ex); + } + + if (this.isConnectedToDocument()) { + dialogService.notify(Localization.lang("Connected to document") + ": " + + this.getCurrentDocumentTitle().orElse("")); + } } /** @@ -128,19 +134,10 @@ public boolean isDocumentConnectionMissing() { /** * Either return an XTextDocument or return JabRefException. */ - public Result getXTextDocument() { + public Result getXTextDocument() { return this.connection.getXTextDocument(); } - public XTextDocument getXTextDocumentOrThrow() - throws JabRefException { - Result res = this.getXTextDocument(); - if (res.isEmpty()) { - throw res.getError(); - } - return res.get(); - } - /** * The title of the current document, or Optional.empty() */ @@ -154,15 +151,44 @@ public Optional getCurrentDocumentTitle() { * * ****************************/ - void showDialog(String title, JabRefException ex) { - dialogService.showErrorDialogAndWait(title, ex.getLocalizedMessage()); + void showDialog(OOError ex) { + ex.showErrorDialog(dialogService); + } + + void showDialog(String title, OOError ex) { + ex.setTitle(title).showErrorDialog(dialogService); + } + + VoidResult collectResults(String title, List> results) { + String msg = (results.stream() + .filter(e -> e.isError()) + .map(e -> e.getError().getLocalizedMessage()) + .collect(Collectors.joining("\n\n"))); + if (msg.isEmpty()) { + return VoidResult.OK(); + } else { + return VoidResult.Error(new OOError(title, msg)); + } } - boolean testDialog(String title, VoidResult res) { - return res.ifError(e -> showDialog(title, e)).isError(); + boolean testDialog(VoidResult res) { + return res.ifError(ex -> ex.showErrorDialog(dialogService)).isError(); } - private Optional getOrDialog(String title, Result res) { + boolean testDialog(String title, VoidResult res) { + return res.ifError(e -> showDialog(e.setTitle(title))).isError(); + } + + boolean testDialog(String title, List> results) { + return testDialog(title, collectResults(title, results)); + } + + boolean testDialog(String title, VoidResult... results) { + List> rs = Arrays.asList(results); + return testDialog(collectResults(title, rs)); + } + + private Optional getOrDialog(String title, Result res) { if (res.isOK()) { return res.getOptional(); } @@ -170,28 +196,39 @@ private Optional getOrDialog(String title, Result res return Optional.empty(); } - public Optional> getCitationEntries() { + /* + * + * ManageCitationsDialogView + * + */ + public Optional> guiActionGetCitationEntries() { + final Optional> FAIL = Optional.empty(); final String title = Localization.lang("Problem collecting citations"); + + Result odoc = getXTextDocument(); + if (testDialog(title, odoc.asVoidResult())) { + return FAIL; + } + XTextDocument doc = odoc.get(); + + if (testDialog(title, checkIfOpenOfficeIsRecordingChanges2(doc))) { + LOGGER.warn(title); + return FAIL; + } + try { - Optional odoc = getOrDialog(title, getXTextDocument()); - if (odoc.isEmpty() - || testDialog(title, checkIfOpenOfficeIsRecordingChanges2(odoc.get()))) { - LOGGER.warn(title); - return Optional.empty(); - } - XTextDocument doc = odoc.get(); - OOFrontend fr = new OOFrontend(doc); - return Optional.of(fr.getCitationEntries(doc)); + return Optional.of(ManageCitations.getCitationEntries(doc)); } catch (NoDocumentException ex) { - OpenOfficePanel.showNoDocumentErrorMessage(dialogService); - return Optional.empty(); + OOError.from(ex).showErrorDialog(dialogService); + return FAIL; } catch (UnknownPropertyException | WrappedTargetException ex) { LOGGER.warn(title, ex); - return Optional.empty(); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); + return FAIL; } } @@ -220,146 +257,33 @@ public Optional> getCitationEntries() { * citation from the text). * */ - public void applyCitationEntries(List citationEntries) { + public void guiActionApplyCitationEntries(List citationEntries) { final String title = Localization.lang("Problem modifying citation"); + Optional odoc = getOrDialog(title, getXTextDocument()); + if (odoc.isEmpty()) { + return; + } + XTextDocument doc = odoc.get(); + try { - Optional odoc = getOrDialog(title, getXTextDocument()); - if (odoc.isEmpty()) { - return; - } - XTextDocument doc = odoc.get(); - OOFrontend fr = new OOFrontend(doc); - fr.applyCitationEntries(doc, citationEntries); + ManageCitations.applyCitationEntries(doc, citationEntries); + + } catch (NoDocumentException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | PropertyVetoException | IllegalTypeException - | NoDocumentException | WrappedTargetException | IllegalArgumentException ex) { LOGGER.warn(title, ex); - dialogService.showErrorDialogAndWait(title, ex); - } - } - - private static void fillCitationMarkInCursor(XTextDocument doc, - XTextCursor cursor, - OOFormattedText citationText, - boolean withText, - OOBibStyle style) - throws - UnknownPropertyException, - WrappedTargetException, - PropertyVetoException, - IllegalArgumentException, - UndefinedCharacterFormatException, - NoSuchElementException, - CreationException { - - Objects.requireNonNull(cursor); - Objects.requireNonNull(citationText); - Objects.requireNonNull(style); - - if (withText) { - OOFormattedText citationText2 = OOFormat.setLocaleNone(citationText); - if (style.isFormatCitations()) { - String charStyle = style.getCitationCharacterFormat(); - citationText2 = OOFormat.setCharStyle(citationText2, charStyle); - } - // inject a ZERO_WIDTH_SPACE to hold the initial character format - final String ZERO_WIDTH_SPACE = "\u200b"; - citationText2 = OOFormattedText.fromString(ZERO_WIDTH_SPACE + citationText2.asString()); - OOFormattedTextIntoOO.write(doc, cursor, citationText2); - } else { - cursor.setString(""); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } } - /** - * Inserts a citation group in the document: creates and fills it. - * - * @param citationKeys BibTeX keys of - * @param pageInfosForCitations - * @param citationType - * - * @param citationText Text for the citation. A citation mark or - * placeholder if not yet available. - * - * @param position Location to insert at. - * @param withText If false, citationText is not shown. - * @param style - * @param insertSpaceAfter A space inserted after the reference - * mark makes it easier to separate from the text - * coming after. But is not wanted when we recreate a - * reference mark. - */ - private void createAndFillCitationGroup(OOFrontend fr, - XTextDocument doc, - List citationKeys, - List pageInfosForCitations, - InTextCitationType citationType, - OOFormattedText citationText, - XTextCursor position, - boolean withText, - OOBibStyle style, - boolean insertSpaceAfter) - throws - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, - PropertyVetoException, - WrappedTargetException, - PropertyVetoException, - IllegalArgumentException, - UndefinedCharacterFormatException, - CreationException, - NoDocumentException, - IllegalTypeException, - NoSuchElementException { - - Objects.requireNonNull(pageInfosForCitations); - if (pageInfosForCitations.size() != citationKeys.size()) { - throw new RuntimeException("pageInfosForCitations.size != citationKeys.size"); - } - CitationGroupID cgid = fr.createCitationGroup(doc, - citationKeys, - pageInfosForCitations, - citationType, - position, - insertSpaceAfter, - !withText /* withoutBrackets */); - - if (withText) { - XTextCursor c2 = fr.getFillCursorForCitationGroup(doc, cgid); - - fillCitationMarkInCursor(doc, c2, citationText, withText, style); - - fr.cleanFillCursorForCitationGroup(doc, cgid); - } - position.collapseToEnd(); - } - - /** - * In insertEntry we receive BibEntry values from the GUI. - * - * In the document we store citations by their citation key. - * - * If the citation key is missing, the best we can do is to notify - * the user. Or the programmer, that we cannot accept such input. - * - */ - private static String insertEntryGetCitationKey(BibEntry entry) { - Optional key = entry.getCitationKey(); - if (key.isEmpty()) { - throw new RuntimeException("insertEntryGetCitationKey:" - + " cannot cite entries without citation key"); - } - return key.get(); - } - /** * * Creates a citation group from {@code entries} at the cursor, @@ -416,34 +340,34 @@ private static String insertEntryGetCitationKey(BibEntry entry) { * * */ - public void insertEntry(List entries, - BibDatabase database, - List allBases, - OOBibStyle style, - boolean inParenthesis, - boolean withText, - String pageInfo, - boolean sync) { + public void guiActionInsertEntry(List entries, + BibDatabase database, + List allBases, + OOBibStyle style, + boolean inParenthesis, + boolean withText, + String pageInfo, + boolean sync) { final String title = "Could not insert entry"; - if (testDialog(title, styleIsRequired(style))) { + + Result odoc = getXTextDocument(); + if (testDialog(title, odoc.asVoidResult(), styleIsRequired(style))) { return; } if (entries == null || entries.size() == 0) { - // String title = "No bibliography entries selected"; - String msg = (Localization.lang("No bibliography entries are selected for citation.") - + "\n" - + Localization.lang("Select some before citing.")); - showDialog(title, new JabRefException(title, msg)); + OOError.noEntriesSelectedForCitation().showErrorDialog(dialogService); + return; } - final int nEntries = entries.size(); - Optional odoc = getOrDialog(title, getXTextDocument()); - if (odoc.isEmpty()) { + XTextDocument doc = odoc.get(); + + if (testDialog(title, + checkStylesExistInTheDocument(style, doc), + checkIfOpenOfficeIsRecordingChanges2(doc))) { return; } - XTextDocument doc = odoc.get(); boolean useUndoContext = true; @@ -452,16 +376,6 @@ public void insertEntry(List entries, UnoUndo.enterUndoContext(doc, "Insert citation"); } - try { - checkStylesExistInTheDocument(style, doc); - checkIfOpenOfficeIsRecordingChanges(doc); - } catch (JabRefException ex) { - dialogService.showErrorDialogAndWait( - Localization.lang("JabRefException"), - ex.getLocalizedMessage()); - return; - } - OOFrontend fr = new OOFrontend(doc); XTextCursor cursor; @@ -474,8 +388,8 @@ public void insertEntry(List entries, if (cursor == null) { showDialog(title, - new JabRefException("Could not get the cursor", - Localization.lang("Could not get the cursor."))); + new OOError(Localization.lang("Could not get the cursor."), + Localization.lang("Could not get the cursor."))); return; } @@ -489,128 +403,47 @@ public void insertEntry(List entries, + " to the location for the new citation.") + "\n" + Localization.lang("I cannot insert to the cursors current location."); - showDialog(title, new JabRefException(msg, ex)); + showDialog(title, new OOError(title, msg, ex)); return; } - List citationKeys = - entries.stream() - .map(OOBibBase::insertEntryGetCitationKey) - .collect(Collectors.toList()); - - InTextCitationType citationType = OOProcess.citationTypeFromOptions(withText, inParenthesis); - - // JabRef53 style pageInfo list - List pageInfosForCitations = - OOStyleDataModelVersion.fakePageInfosForCitations(pageInfo, nEntries); - - List citationMarkerEntries = new ArrayList<>(entries.size()); - for (int i = 0; i < nEntries; i++) { - // Using the same database for each entry. - // Probably the GUI limits selection to a single database. - CitationMarkerEntry cm = - new CitationMarkerEntryImpl(citationKeys.get(i), - Optional.ofNullable(entries.get(i)), - Optional.ofNullable(database), - Optional.empty(), // uniqueLetter - Optional.ofNullable(pageInfosForCitations.get(i)), - false /* isFirstAppearanceOfSource */); - citationMarkerEntries.add(cm); - } - - // The text we insert - OOFormattedText citeText = - (style.isNumberEntries() - ? OOFormattedText.fromString("[-]") // A dash only. Only refresh later. - : style.getCitationMarker(citationMarkerEntries, + EditInsert.insertCitationGroup(doc, + fr, + cursor, + entries, + database, + allBases, + style, inParenthesis, - OOBibStyle.NonUniqueCitationMarker.FORGIVEN)); - - if ("".equals(OOFormattedText.toString(citeText))) { - citeText = OOFormattedText.fromString("[?]"); - } - - createAndFillCitationGroup(fr, - doc, - citationKeys, - pageInfosForCitations, - citationType, - citeText, - cursor, - withText, - style, - true /* insertSpaceAfter */); - - // Remember this position: we will come back here in the - // end. - XTextRange position = cursor.getEnd(); - - if (sync) { - // To account for numbering and for uniqueLetters, we - // must refresh the cite markers: - OOFrontend fr2 = new OOFrontend(doc); - fr2.imposeGlobalOrder(doc); - OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr2.citationGroups, allBases, style); - try { - UnoScreenRefresh.lockControllers(doc); - applyNewCitationMarkers(doc, - fr2, - x.citMarkers, - style); - // Insert it at the current position: - rebuildBibTextSection(doc, - style, - fr2, - x.getBibliography(), - this.alwaysAddCitedOnPages); - } finally { - UnoScreenRefresh.unlockControllers(doc); - } + withText, + pageInfo, + sync, + this.alwaysAddCitedOnPages); - /* - * Problem: insertEntry in bibliography - * Reference is destroyed when we want to get there. - */ - // Go back to the relevant position: - try { - cursor.gotoRange(position, false); - } catch (com.sun.star.uno.RuntimeException ex) { - LOGGER.warn("OOBibBase.insertEntry:" - + " Could not go back to end of in-text citation", ex); - } - } } catch (NoDocumentException ex) { - OpenOfficePanel.showNoDocumentErrorMessage(dialogService); + OOError.from(ex).showErrorDialog(dialogService); return; } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is // loaded before connection, and therefore cannot directly reference // or catch a DisposedException (which is in a OO JAR file). // throw new ConnectionLostException(ex.getMessage()); - OpenOfficePanel.showConnectionLostErrorMessage(dialogService); - return; - } catch (UndefinedCharacterFormatException ex) { - OpenOfficePanel.reportUndefinedCharacterFormat(dialogService, ex); - return; - } catch (UndefinedParagraphFormatException ex) { - OpenOfficePanel.reportUndefinedParagraphFormat(dialogService, ex); + OOError.from(new ConnectionLostException("DisposedException")).showErrorDialog(dialogService); return; } catch (JabRefException ex) { - dialogService.showErrorDialogAndWait( - Localization.lang("JabRefException"), - ex.getLocalizedMessage()); + OOError.from(ex).showErrorDialog(dialogService); return; - } catch (com.sun.star.lang.IllegalArgumentException - | UnknownPropertyException - | PropertyVetoException - | CreationException - | NoSuchElementException - | WrappedTargetException - | IllegalTypeException - | PropertyExistException - | NotRemoveableException ex) { + } catch (// com.sun.star.lang.IllegalArgumentException + CreationException + | IllegalTypeException + | NoSuchElementException + | NotRemoveableException + | PropertyExistException + | PropertyVetoException + | UnknownPropertyException + | WrappedTargetException ex) { LOGGER.warn("Could not insert entry", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); return; } finally { if (useUndoContext) { @@ -619,204 +452,6 @@ public void insertEntry(List entries, } } - /* ************************************************** - * - * modifies both storage and presentation, but should only affect presentation - * - * **************************************************/ - - /** - * Visit each reference mark in referenceMarkNames, overwrite its - * text content. - * - * After each fillCitationMarkInCursor call check if we lost the - * OOBibBase.BIB_SECTION_NAME bookmark and recreate it if we did. - * - * @param fr - * - * @param citMarkers Corresponding text for each reference mark, - * that replaces the old text. - * - * @param style Bibliography style to use. - * - */ - private void applyNewCitationMarkers(XTextDocument doc, - OOFrontend fr, - Map citMarkers, - OOBibStyle style) - throws - NoDocumentException, - UndefinedCharacterFormatException, - UnknownPropertyException, - CreationException, - WrappedTargetException, - PropertyVetoException, - NoSuchElementException, - JabRefException { - - checkStylesExistInTheDocument(style, doc); - - CitationGroups cgs = fr.citationGroups; - final boolean hadBibSection = (UnoBookmark.getAnchor(doc, OOBibBase.BIB_SECTION_NAME) - .isPresent()); - - for (Map.Entry kv : citMarkers.entrySet()) { - - CitationGroupID cgid = kv.getKey(); - Objects.requireNonNull(cgid); - - OOFormattedText citationText = kv.getValue(); - Objects.requireNonNull(citationText); - - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - - boolean withText = (cg.citationType != InTextCitationType.INVISIBLE_CIT); - - if (withText) { - - XTextCursor cursor = fr.getFillCursorForCitationGroup(doc, cgid); - - fillCitationMarkInCursor(doc, cursor, citationText, withText, style); - - fr.cleanFillCursorForCitationGroup(doc, cgid); - } - - if (hadBibSection - && (UnoBookmark.getAnchor(doc, OOBibBase.BIB_SECTION_NAME) - .isEmpty())) { - // Overwriting text already there is too harsh. - // I am making it an error, to see if we ever get here. - throw new RuntimeException("OOBibBase.applyNewCitationMarkers:" - + " just overwrote the bibliography section marker. Sorry."); - } - } - } - - /* ************************************************** - * - * Bibliography: needs uniqueLetters or numbers - * - * **************************************************/ - - /** - * Rebuilds the bibliography. - * - * Note: assumes fresh `jabRefReferenceMarkNamesSortedByPosition` - * if `style.isSortByPosition()` - */ - private void rebuildBibTextSection(XTextDocument doc, - OOBibStyle style, - OOFrontend fr, - CitedKeys bibliography, - boolean alwaysAddCitedOnPages) - throws - NoSuchElementException, - WrappedTargetException, - IllegalArgumentException, - CreationException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - NoDocumentException { - - clearBibTextSectionContent2(doc); - - populateBibTextSection(doc, - fr, - bibliography, - style, - alwaysAddCitedOnPages); - } - - /** - * Insert a paragraph break and create a text section for the bibliography. - * - * Only called from `clearBibTextSectionContent2` - */ - private void createBibTextSection2(XTextDocument doc) - throws - IllegalArgumentException, - CreationException { - - // Always creating at the end of the document. - // Alternatively, we could receive a cursor. - XTextCursor textCursor = doc.getText().createTextCursor(); - textCursor.gotoEnd(false); - UnoTextSection.create(doc, - OOBibBase.BIB_SECTION_NAME, - textCursor, - false); - } - - /** - * Find and clear the text section OOBibBase.BIB_SECTION_NAME to "", - * or create it. - * - * Only called from: `rebuildBibTextSection` - * - */ - private void clearBibTextSectionContent2(XTextDocument doc) - throws - WrappedTargetException, - IllegalArgumentException, - CreationException, - NoDocumentException { - - Optional sectionRange = UnoTextSection.getAnchor(doc, OOBibBase.BIB_SECTION_NAME); - if (sectionRange.isEmpty()) { - createBibTextSection2(doc); - return; - } else { - // Clear it - XTextCursor cursor = doc.getText().createTextCursorByRange(sectionRange.get()); - cursor.setString(""); - } - } - - /** - * Only called from: `rebuildBibTextSection` - * - * Assumes the section named `OOBibBase.BIB_SECTION_NAME` exists. - */ - private void populateBibTextSection(XTextDocument doc, - OOFrontend fr, - CitedKeys bibliography, - OOBibStyle style, - boolean alwaysAddCitedOnPages) - throws - NoSuchElementException, - NoDocumentException, - WrappedTargetException, - PropertyVetoException, - UnknownPropertyException, - UndefinedParagraphFormatException, - IllegalArgumentException, - CreationException { - - XTextSection section = (UnoTextSection.getByName(doc, OOBibBase.BIB_SECTION_NAME) - .orElseThrow(RuntimeException::new)); - - XTextCursor cursor = doc.getText().createTextCursorByRange(section.getAnchor()); - - // emit the title of the bibliography - OOFormattedTextIntoOO.removeDirectFormatting(cursor); - OOFormattedText bibliographyText = OOFormatBibliography.formatBibliography(fr.citationGroups, - bibliography, - style, - alwaysAddCitedOnPages); - OOFormattedTextIntoOO.write(doc, cursor, bibliographyText); - cursor.collapseToEnd(); - - // remove the inital empty paragraph from the section. - XTextCursor initialParagraph = doc.getText().createTextCursorByRange(section.getAnchor()); - initialParagraph.collapseToStart(); - initialParagraph.goRight((short) 1, true); - initialParagraph.setString(""); - - UnoBookmark.create(doc, OOBibBase.BIB_SECTION_END_NAME, cursor, true); - cursor.collapseToEnd(); - } - /* ************************* * * GUI level @@ -839,7 +474,6 @@ public void combineCiteMarkers(List databases, NoSuchElementException, NotRemoveableException, IllegalArgumentException, - UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, PropertyExistException, @@ -850,7 +484,12 @@ public void combineCiteMarkers(List databases, InvalidStateException { final String title = "Could not merge citations"; - if (testDialog(title, styleIsRequired(style))) { + + Result odoc = getXTextDocument(); + if (testDialog(title, + odoc.asVoidResult(), + styleIsRequired(style), + databaseIsRequired(databases, OOError::noDataBaseIsOpen))) { return; } @@ -859,10 +498,13 @@ public void combineCiteMarkers(List databases, final boolean useLockControllers = true; - XTextDocument doc = this.getXTextDocumentOrThrow(); + XTextDocument doc = odoc.get(); - checkStylesExistInTheDocument(style, doc); - checkIfOpenOfficeIsRecordingChanges(doc); + if (testDialog(title, + checkStylesExistInTheDocument(style, doc), + checkIfOpenOfficeIsRecordingChanges2(doc))) { + return; + } OOFrontend fr = new OOFrontend(doc); @@ -1129,16 +771,16 @@ public void combineCiteMarkers(List databases, * be) */ boolean insertSpaceAfter = false; - createAndFillCitationGroup(fr, - doc, - citationKeys, - pageInfosForCitations, - citationType, // InTextCitationType.AUTHORYEAR_PAR - OOFormattedText.fromString("tmp"), - textCursor, - true, // withText - style, - insertSpaceAfter); + UpdateCitationMarkers.createAndFillCitationGroup(fr, + doc, + citationKeys, + pageInfosForCitations, + citationType, + OOFormattedText.fromString("tmp"), + textCursor, + true, // withText + style, + insertSpaceAfter); } // for gi madeModifications = (joinableGroups.size() > 0); @@ -1152,26 +794,14 @@ public void combineCiteMarkers(List databases, if (madeModifications) { UnoCrossRef.refresh(doc); OOFrontend fr2 = new OOFrontend(doc); - fr2.imposeGlobalOrder(doc); - OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr2.citationGroups, - databases, - style); - try { - if (useLockControllers) { - UnoScreenRefresh.lockControllers(doc); - } - applyNewCitationMarkers(doc, - fr2, - x.citMarkers, - style); - // bibliography is not refreshed - } finally { - if (useLockControllers) { - UnoScreenRefresh.unlockControllers(doc); - } - } + Update.updateDocument(doc, + fr2, + databases, + style, + false, /* doUpdateBibliography */ + this.alwaysAddCitedOnPages); } + } finally { UnoUndo.leaveUndoContext(doc); } @@ -1190,7 +820,6 @@ public void unCombineCiteMarkers(List databases, WrappedTargetException, NoSuchElementException, IllegalArgumentException, - UndefinedCharacterFormatException, UnknownPropertyException, NotRemoveableException, PropertyVetoException, @@ -1201,19 +830,28 @@ public void unCombineCiteMarkers(List databases, JabRefException, InvalidStateException { - final String title = "Could not separate citations"; - if (testDialog(title, styleIsRequired(style))) { + final String title = "Separate citations failed"; + + Result odoc = getXTextDocument(); + if (testDialog(title, + odoc.asVoidResult(), + styleIsRequired(style), + databaseIsRequired(databases, OOError::noDataBaseIsOpen))) { return; } + Objects.requireNonNull(databases); Objects.requireNonNull(style); final boolean useLockControllers = true; - XTextDocument doc = this.getXTextDocumentOrThrow(); + XTextDocument doc = odoc.get(); - checkStylesExistInTheDocument(style, doc); - checkIfOpenOfficeIsRecordingChanges(doc); + if (testDialog(title, + checkStylesExistInTheDocument(style, doc), + checkIfOpenOfficeIsRecordingChanges2(doc))) { + return; + } OOFrontend fr = new OOFrontend(doc); @@ -1260,23 +898,22 @@ public void unCombineCiteMarkers(List databases, // Insert mark for each key final int last = keys.size() - 1; for (int i = 0; i < keys.size(); i++) { - // Note: by using createAndFillCitationGroup (and not something - // that accepts List, we lose the extra - // info stored in the citations. - // We just reread below. - boolean insertSpaceAfter = (i != last); - boolean withText = cg.citationType != InTextCitationType.INVISIBLE_CIT; // true - createAndFillCitationGroup(fr, - doc, - keys.subList(i, i + 1), // citationKeys, - pageInfosForCitations.subList(i, i + 1), // pageInfos, - InTextCitationType.AUTHORYEAR_PAR, // citationType, - OOFormattedText.fromString("tmp"), - textCursor, - withText, - style, - insertSpaceAfter); + boolean withText = cg.citationType != InTextCitationType.INVISIBLE_CIT; + List citationKeys1 = keys.subList(i, i + 1); + List pageInfos1 = pageInfosForCitations.subList(i, i + 1); + InTextCitationType citationType1 = InTextCitationType.AUTHORYEAR_PAR; + OOFormattedText citationText1 = OOFormattedText.fromString("tmp"); + UpdateCitationMarkers.createAndFillCitationGroup(fr, + doc, + citationKeys1, + pageInfos1, + citationType1, + citationText1, + textCursor, + withText, + style, + insertSpaceAfter); textCursor.collapseToEnd(); } @@ -1292,34 +929,27 @@ public void unCombineCiteMarkers(List databases, if (madeModifications) { UnoCrossRef.refresh(doc); OOFrontend fr2 = new OOFrontend(doc); - fr2.imposeGlobalOrder(doc); - OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr2.citationGroups, databases, style); - try { - if (useLockControllers) { - UnoScreenRefresh.lockControllers(doc); - } - applyNewCitationMarkers(doc, fr2, x.citMarkers, style); - // bibliography is not refreshed - } finally { - if (useLockControllers) { - UnoScreenRefresh.unlockControllers(doc); - } - } + Update.updateDocument(doc, + fr2, + databases, + style, + false, /* doUpdateBibliography */ + this.alwaysAddCitedOnPages); } + } finally { UnoUndo.leaveUndoContext(doc); } } - static class ExportCitedHelperResult { + static class GenerateDatabaseResult { /** - * null: not done; isempty: no unresolved + * null: not done; isEmpty: no unresolved */ List unresolvedKeys; BibDatabase newDatabase; - ExportCitedHelperResult(List unresolvedKeys, - BibDatabase newDatabase) { + GenerateDatabaseResult(List unresolvedKeys, + BibDatabase newDatabase) { this.unresolvedKeys = unresolvedKeys; this.newDatabase = newDatabase; } @@ -1329,13 +959,16 @@ static class ExportCitedHelperResult { * GUI action for "Export cited" * * Does not refresh the bibliography. + * + * @param returnPartialResult If there are some unresolved keys, + * shall we return an otherwise nonempty result, or Optional.empty()? */ - public ExportCitedHelperResult exportCitedHelper(List databases) + public Optional exportCitedHelper(List databases, + boolean returnPartialResult) throws WrappedTargetException, NoSuchElementException, NoDocumentException, - UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, IOException, @@ -1343,14 +976,65 @@ public ExportCitedHelperResult exportCitedHelper(List databases) InvalidStateException, JabRefException { - XTextDocument doc = this.getXTextDocumentOrThrow(); + final Optional FAIL = Optional.empty(); + final String title = Localization.lang("Unable to generate new library"); + + Result odoc = getXTextDocument(); + if (testDialog(title, + odoc.asVoidResult(), + databaseIsRequired(databases, OOError::noDataBaseIsOpenForExport))) { + return FAIL; + } + + XTextDocument doc = odoc.get(); try { - UnoUndo.enterUndoContext(doc, "Changes during \"Export cited\""); - return this.generateDatabase(databases, doc); - } finally { - UnoUndo.leaveUndoContext(doc); + + GenerateDatabaseResult result; + try { + UnoUndo.enterUndoContext(doc, "Changes during \"Export cited\""); + result = this.generateDatabase(databases, doc); + } finally { + // There should be no changes, thus no Undo entry + // in LibreOffice + UnoUndo.leaveUndoContext(doc); + } + + if (!result.newDatabase.hasEntries()) { + dialogService.showErrorDialogAndWait( + Localization.lang("Unable to generate new library"), + Localization.lang("Your OpenOffice/LibreOffice document references" + + " no citation keys" + + " which could also be found in your current library.")); + return FAIL; + } + + List unresolvedKeys = result.unresolvedKeys; + if (!unresolvedKeys.isEmpty()) { + dialogService.showErrorDialogAndWait( + Localization.lang("Unable to generate new library"), + Localization.lang("Your OpenOffice/LibreOffice document references" + + " at least %0 citation keys" + + " which could not be found in your current library." + + " Some of these are %1.", + String.valueOf(unresolvedKeys.size()), + String.join(", ", unresolvedKeys))); + if (returnPartialResult) { + return Optional.of(result.newDatabase); + } else { + return FAIL; + } + } + return Optional.of(result.newDatabase); + } catch (NoDocumentException ex) { + OOError.from(ex).showErrorDialog(dialogService); + } catch (UnknownPropertyException + | NoSuchElementException + | WrappedTargetException ex) { + LOGGER.warn("Problem generating new database.", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } + return FAIL; } /** @@ -1365,8 +1049,7 @@ public ExportCitedHelperResult exportCitedHelper(List databases) * if the referenced entry is found, it is included in the result. * If it is not found, it is silently ignored. */ - private ExportCitedHelperResult generateDatabase(List databases, - XTextDocument doc) + private GenerateDatabaseResult generateDatabase(List databases, XTextDocument doc) throws NoSuchElementException, WrappedTargetException, @@ -1414,7 +1097,7 @@ private ExportCitedHelperResult generateDatabase(List databases, } resultDatabase.insertEntries(entriesToInsert); - return new ExportCitedHelperResult(unresolvedKeys, resultDatabase); + return new GenerateDatabaseResult(unresolvedKeys, resultDatabase); } /* @@ -1448,7 +1131,7 @@ private static void checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) } } - private static VoidResult checkIfOpenOfficeIsRecordingChanges2(XTextDocument doc) { + private static VoidResult checkIfOpenOfficeIsRecordingChanges2(XTextDocument doc) { String title = Localization.lang("Recording and/or Recorded changes"); try { @@ -1470,144 +1153,161 @@ private static VoidResult checkIfOpenOfficeIsRecordingChanges2( msg += "\n"; msg += Localization.lang("Use [Edit]/[Track Changes]/[Manage] to resolve them first."); } - return VoidResult.Error(new JabRefException(title, msg)); + return VoidResult.Error(new OOError(title, msg)); } } catch (UnknownPropertyException | WrappedTargetException ex) { String msg = Localization.lang("Error while checking if Writer" + " is recording changes or has recorded changes."); - return VoidResult.Error(new JabRefException(title, msg, ex)); + return VoidResult.Error(new OOError(title, msg, ex)); } return VoidResult.OK(); } /* * Called from GUI. + * @return true on error, false if OK. */ - public void checkIfOpenOfficeIsRecordingChanges() - throws - UnknownPropertyException, - WrappedTargetException, - PropertyVetoException, - JabRefException, - NoDocumentException { - XTextDocument doc = this.getXTextDocumentOrThrow(); - checkIfOpenOfficeIsRecordingChanges(doc); + public boolean guiCheckIfOpenOfficeIsRecordingChanges(String title) { + final boolean FAIL = true; + final boolean PASS = false; + Optional odoc = getOrDialog(title, getXTextDocument()); + if (odoc.isEmpty()) { + return FAIL; + } + XTextDocument doc = odoc.get(); + if (testDialog(title, checkIfOpenOfficeIsRecordingChanges2(doc))) { + return FAIL; + } + return PASS; + } + + public boolean guiCheckIfConnectedToDocument(String title) { + final boolean FAIL = true; + final boolean PASS = false; + if (!isConnectedToDocument()) { + String msg = Localization.lang("Not connected to any Writer document." + + " Please make sure a document is open," + + " and use the 'Select Writer document' button" + + " to connect to it."); + dialogService.showErrorDialogAndWait(title, msg); + return FAIL; + } + return PASS; } - VoidResult styleIsRequired(OOBibStyle style) { + VoidResult styleIsRequired(OOBibStyle style) { if (style == null) { - return VoidResult.Error( - new JabRefException("This operation requires a style", - Localization.lang("This operation requires a style.") - + "\n" - + Localization.lang("Please select one."))); + return VoidResult.Error(OOError.noValidStyleSelected()); + } else { + return VoidResult.OK(); + } + } + + VoidResult databaseIsRequired(List databases, + Supplier fun) { + if (databases == null || databases.isEmpty()) { + return VoidResult.Error(fun.get()); } else { return VoidResult.OK(); } } - public void checkParagraphStyleExistsInTheDocument(String styleName, - XTextDocument doc, - String labelInJstyleFile, - String pathToStyleFile) + /* + * Checks existence and also checks if it is not an internal name. + */ + public VoidResult checkStyleExistsInTheDocument(String familyName, + String styleName, + XTextDocument doc, + String labelInJstyleFile, + String pathToStyleFile) throws - JabRefException, NoSuchElementException, WrappedTargetException { - Optional internalName = UnoStyle.getInternalNameOfParagraphStyle(doc, styleName); + Optional internalName = UnoStyle.getInternalNameOfStyle(doc, familyName, styleName); if (internalName.isEmpty()) { String msg = - Localization.lang("The %0 paragraph style '%1'" - + " is missing from the document", + switch (familyName) { + case UnoStyle.PARAGRAPH_STYLES -> + Localization.lang("The %0 paragraph style '%1' is missing from the document", labelInJstyleFile, - styleName) + styleName); + case UnoStyle.CHARACTER_STYLES -> + Localization.lang("The %0 character style '%1' is missing from the document", + labelInJstyleFile, + styleName); + default -> + throw new RuntimeException("Expected " + UnoStyle.CHARACTER_STYLES + + " or " + UnoStyle.PARAGRAPH_STYLES + + " for familyName"); + } + "\n" + Localization.lang("Please create it in the document or change in the file:") + "\n" + pathToStyleFile; - throw new JabRefException(msg); + return VoidResult.Error(new OOError("StyleIsNotKnown", msg)); } if (!internalName.get().equals(styleName)) { String msg = - Localization.lang("The %0 paragraph style '%1'" - + " is a display name for '%2'.", + switch (familyName) { + case UnoStyle.PARAGRAPH_STYLES -> + Localization.lang("The %0 paragraph style '%1' is a display name for '%2'.", labelInJstyleFile, styleName, - internalName.get()) - + "\n" - + Localization.lang("Please use the latter in the style file below" - + " to avoid localization problems.") - + "\n" - + pathToStyleFile; - throw new JabRefException(msg); - } - } - - public void checkCharacterStyleExistsInTheDocument(String styleName, - XTextDocument doc, - String labelInJstyleFile, - String pathToStyleFile) - throws - JabRefException, - NoSuchElementException, - WrappedTargetException { - - Optional internalName = UnoStyle.getInternalNameOfCharacterStyle(doc, styleName); - - if (internalName.isEmpty()) { - String msg = - Localization.lang("The %0 character style '%1'" - + " is missing from the document", - labelInJstyleFile, - styleName) - + "\n" - + Localization.lang("Please create it in the document or change in the file:") - + "\n" + pathToStyleFile; - throw new JabRefException(msg); - } - - if (!internalName.get().equals(styleName)) { - String msg = - Localization.lang("The %0 character style '%1'" - + " is a display name for '%2'.", + internalName.get()); + case UnoStyle.CHARACTER_STYLES -> + Localization.lang("The %0 character style '%1' is a display name for '%2'.", labelInJstyleFile, styleName, - internalName.get()) + internalName.get()); + default -> + throw new RuntimeException("Expected " + UnoStyle.CHARACTER_STYLES + + " or " + UnoStyle.PARAGRAPH_STYLES + + " for familyName"); + } + "\n" + Localization.lang("Please use the latter in the style file below" + " to avoid localization problems.") + "\n" + pathToStyleFile; - throw new JabRefException(msg); + return VoidResult.Error(new OOError("StyleNameIsNotInternal", msg)); } + return VoidResult.OK(); } - public void checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) - throws - JabRefException, - NoSuchElementException, - WrappedTargetException { + public VoidResult checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) { String pathToStyleFile = style.getPath(); - checkParagraphStyleExistsInTheDocument(style.getReferenceHeaderParagraphFormat(), - doc, - "ReferenceHeaderParagraphFormat", - pathToStyleFile); - - checkParagraphStyleExistsInTheDocument(style.getReferenceParagraphFormat(), - doc, - "ReferenceParagraphFormat", - pathToStyleFile); - if (style.isFormatCitations()) { - checkCharacterStyleExistsInTheDocument(style.getCitationCharacterFormat(), - doc, - "CitationCharacterFormat", - pathToStyleFile); + List> results = new ArrayList<>(); + try { + results.add(checkStyleExistsInTheDocument(UnoStyle.PARAGRAPH_STYLES, + style.getReferenceHeaderParagraphFormat(), + doc, + "ReferenceHeaderParagraphFormat", + pathToStyleFile)); + results.add(checkStyleExistsInTheDocument(UnoStyle.PARAGRAPH_STYLES, + style.getReferenceParagraphFormat(), + doc, + "ReferenceParagraphFormat", + pathToStyleFile)); + if (style.isFormatCitations()) { + results.add(checkStyleExistsInTheDocument(UnoStyle.CHARACTER_STYLES, + style.getCitationCharacterFormat(), + doc, + "CitationCharacterFormat", + pathToStyleFile)); + } + } catch (NoSuchElementException + | WrappedTargetException ex) { + results.add(VoidResult.Error(new OOError("Other error in checkStyleExistsInTheDocument", + ex.getMessage(), + ex))); } + + return collectResults("checkStyleExistsInTheDocument failed", results); } /** @@ -1617,81 +1317,67 @@ public void checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) * @param style Style. * */ - public void updateDocumentActionHelper(List databases, OOBibStyle style) { + public void guiActionUpdateDocument(List databases, OOBibStyle style) { final String title = Localization.lang("Unable to synchronize bibliography"); try { - Optional odoc = getOrDialog(title, getXTextDocument()); - if (odoc.isEmpty() - || testDialog(title, styleIsRequired(style))) { + Result odoc = getXTextDocument(); + if (testDialog(title, List.of(odoc.asVoidResult(), styleIsRequired(style)))) { return; } XTextDocument doc = odoc.get(); - checkStylesExistInTheDocument(style, doc); - checkIfOpenOfficeIsRecordingChanges(doc); - - try { - UnoUndo.enterUndoContext(doc, "Refresh bibliography"); + if (testDialog(title, List.of(styleIsRequired(style), + checkStylesExistInTheDocument(style, doc)))) { + return; + } - OOFrontend fr = new OOFrontend(doc); + checkIfOpenOfficeIsRecordingChanges(doc); - // Check Range overlaps - boolean requireSeparation = false; - int maxReportedOverlaps = 10; - if (testDialog(title, fr.checkRangeOverlaps(doc, + OOFrontend fr = new OOFrontend(doc); + // Check Range overlaps + boolean requireSeparation = false; + int maxReportedOverlaps = 10; + VoidResult ee = (fr.checkRangeOverlaps(doc, requireSeparation, - maxReportedOverlaps))) { - return; - } + maxReportedOverlaps) + .mapError(OOError::fromJabRefException)); + if (testDialog(title, ee)) { + return; + } - final boolean useLockControllers = true; - fr.imposeGlobalOrder(doc); - OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); - try { - if (useLockControllers) { - UnoScreenRefresh.lockControllers(doc); - } - applyNewCitationMarkers(doc, fr, x.citMarkers, style); - rebuildBibTextSection(doc, - style, - fr, - x.getBibliography(), - this.alwaysAddCitedOnPages); - List unresolvedKeys = x.getUnresolvedKeys(); - if (!unresolvedKeys.isEmpty()) { - String msg = Localization.lang("Your OpenOffice/LibreOffice document" - + " references the citation key '%0'," - + " which could not be found" - + " in your current library.", - unresolvedKeys.get(0)); - dialogService.showErrorDialogAndWait(title, msg); - return; - } - } finally { - if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { - UnoScreenRefresh.unlockControllers(doc); - } - } + List unresolvedKeys; + try { + UnoUndo.enterUndoContext(doc, "Refresh bibliography"); + boolean doUpdateBibliography = true; + unresolvedKeys = Update.updateDocument(doc, + fr, + databases, + style, + doUpdateBibliography, + this.alwaysAddCitedOnPages); } finally { UnoUndo.leaveUndoContext(doc); } + + if (!unresolvedKeys.isEmpty()) { + String msg = Localization.lang( + "Your OpenOffice/LibreOffice document references the citation key '%0'," + + " which could not be found in your current library.", + unresolvedKeys.get(0)); + dialogService.showErrorDialogAndWait(title, msg); + return; + } + } catch (JabRefException ex) { - dialogService.showErrorDialogAndWait( - Localization.lang("JabRefException"), - ex.getLocalizedMessage()); - } catch (UndefinedCharacterFormatException ex) { - OpenOfficePanel.reportUndefinedCharacterFormat(dialogService, ex); - } catch (UndefinedParagraphFormatException ex) { - OpenOfficePanel.reportUndefinedParagraphFormat(dialogService, ex); + OOError.from(ex).showErrorDialog(dialogService); } catch (ConnectionLostException ex) { - OpenOfficePanel.showConnectionLostErrorMessage(dialogService); + OOError.from(ex).showErrorDialog(dialogService); } catch (NoDocumentException ex) { - OpenOfficePanel.showNoDocumentErrorMessage(dialogService); + OOError.from(ex).showErrorDialog(dialogService); } catch (com.sun.star.lang.IllegalArgumentException | PropertyVetoException | UnknownPropertyException @@ -1699,6 +1385,7 @@ public void updateDocumentActionHelper(List databases, OOBibStyle s | NoSuchElementException | CreationException ex) { LOGGER.warn("Could not update bibliography", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } } diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 13ddc505139..fe50f4eb30b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -7,10 +7,10 @@ import java.util.stream.Collectors; import org.jabref.gui.DialogService; -import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.NoDocumentException; +import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.Result; import org.jabref.logic.openoffice.UnoCast; import org.jabref.logic.openoffice.UnoTextDocument; @@ -156,7 +156,7 @@ public String toString() { * * If there is a single document to choose from, selects that. * If there are more than one, shows selection dialog. - * If there are none, throws NoDocumentException + * If there are none, throws NoDocumentFoundException * * After successful selection connects to the selected document * and extracts some frequently used parts (starting points for @@ -166,17 +166,17 @@ public String toString() { * document and parts extracted. * */ - public void selectDocument() + public void selectDocument(boolean autoSelectForSingle) throws - NoDocumentException, + NoDocumentFoundException, NoSuchElementException, WrappedTargetException { XTextDocument selected; List textDocumentList = getTextDocuments(this.xDesktop); if (textDocumentList.isEmpty()) { - throw new NoDocumentException("No Writer documents found"); - } else if (textDocumentList.size() == 1) { + throw new NoDocumentFoundException("No Writer documents found"); + } else if (textDocumentList.size() == 1 && autoSelectForSingle) { selected = textDocumentList.get(0); // Get the only one } else { // Bring up a dialog selected = OOBibBaseConnect.selectDocumentDialog(textDocumentList, @@ -239,13 +239,9 @@ public XTextDocument getXTextDocumentOrThrow() return this.xTextDocument; } - public Result getXTextDocument() { + public Result getXTextDocument() { if (isDocumentConnectionMissing()) { - final String msg = Localization.lang("Not connected to any Writer document." - + " Please make sure a document is open," - + " and use the 'Select Writer document' button" - + " to connect to it."); - return Result.Error(new JabRefException("Not connected to document", msg)); + return Result.Error(OOError.from(new NoDocumentException())); } return Result.OK(this.xTextDocument); } diff --git a/src/main/java/org/jabref/gui/openoffice/OOError.java b/src/main/java/org/jabref/gui/openoffice/OOError.java new file mode 100644 index 00000000000..c3f3dcbeeea --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/OOError.java @@ -0,0 +1,134 @@ +package org.jabref.gui.openoffice; + +import org.jabref.gui.DialogService; +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.logic.openoffice.ConnectionLostException; +import org.jabref.logic.openoffice.NoDocumentException; +import org.jabref.logic.openoffice.NoDocumentFoundException; + +class OOError extends JabRefException { + + private String localizedTitle; + + public OOError(String title, String localizedMessage) { + super(localizedMessage, localizedMessage); + this.localizedTitle = title; + } + + public OOError(String title, String localizedMessage, Throwable cause) { + super(localizedMessage, localizedMessage, cause); + this.localizedTitle = title; + } + + public String getTitle() { + return localizedTitle; + } + + public OOError setTitle(String title) { + localizedTitle = title; + return this; + } + + public void showErrorDialog(DialogService dialogService) { + dialogService.showErrorDialogAndWait(getTitle(), getLocalizedMessage()); + } + + public static OOError fromMisc(Exception ex) { + return new OOError( + "Exception", + ex.getMessage(), + ex); + } + + // For JabRefException + public static OOError from(JabRefException ex) { + return new OOError( + Localization.lang("JabRefException"), + ex.getLocalizedMessage(), + ex); + } + + public static OOError fromJabRefException(JabRefException ex) { + return from(ex); + } + + // For ConnectionLostException + public static OOError from(ConnectionLostException ex) { + return new OOError( + Localization.lang("Connection lost"), + Localization.lang("Connection to OpenOffice/LibreOffice has been lost." + + " Please make sure OpenOffice/LibreOffice is running," + + " and try to reconnect."), + ex); + } + + public static void + showConnectionLostErrorMessage(DialogService dialogService, ConnectionLostException ex) { + OOError.from(ex).showErrorDialog(dialogService); + } + + // For NoDocumentException + public static OOError from(NoDocumentException ex) { + return new OOError( + Localization.lang("Not connected to document"), + Localization.lang("Not connected to any Writer document." + + " Please make sure a document is open," + + " and use the 'Select Writer document' button" + + " to connect to it."), + ex); + } + + // For NoDocumentFoundException + public static OOError from(NoDocumentFoundException ex) { + return new OOError( + Localization.lang("No Writer documents found"), + Localization.lang("Could not connect to any Writer document." + + " Please make sure a document is open" + + " before using the 'Select Writer document' button" + + " to connect to it."), + ex); + } + + // noDataBaseIsOpenForCiting + public static OOError noDataBaseIsOpenForCiting() { + return new OOError( + Localization.lang("No database"), + Localization.lang("No bibliography database is open for citation.") + + "\n" + + Localization.lang("Open one before citing.")); + } + + // noDataBaseIsOpenForExport + public static OOError noDataBaseIsOpenForExport() { + return new OOError( + Localization.lang("No database is open"), + Localization.lang("We need a database to export from. Open one.")); + } + + // noDataBaseIsOpenForExport + public static OOError noDataBaseIsOpen() { + return new OOError( + Localization.lang("No database is open"), + Localization.lang("This operation requires a bibliography database.")); + } + + // noValidStyleSelected + public static OOError noValidStyleSelected() { + return new OOError(Localization.lang("No valid style file defined"), + Localization.lang("No bibliography style is selected for citation.") + + "\n" + + Localization.lang("Select one before citing.") + + "\n" + + Localization.lang("You must select either a valid style file," + + " or use one of the default styles.")); + } + + // noEntriesSelectedForCitation + public static OOError noEntriesSelectedForCitation() { + return new OOError(Localization.lang("No entries selected for citation"), + Localization.lang("No bibliography entries are selected for citation.") + + "\n" + + Localization.lang("Select some before citing.")); + } +} diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 9220c3f13c7..019d0ca50a9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -46,12 +46,11 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.StyleLoader; +import org.jabref.logic.openoffice.ConnectionLostException; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; -import org.jabref.logic.openoffice.UndefinedCharacterFormatException; -import org.jabref.logic.openoffice.UndefinedParagraphFormatException; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; @@ -145,23 +144,40 @@ public Node getContent() { return vbox; } + /* Note: the style may still be null on return. + * + * Return true is failed and dialog is already shown. + */ + private boolean getOrUpdateTheStyle(String title) { + final boolean FAIL = true; + final boolean PASS = false; + + if (style == null) { + style = loader.getUsedStyle(); + } else { + try { + style.ensureUpToDate(); + } catch (IOException ex) { + LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", ex); + String msg = (Localization.lang("Unable to reload style file") + + "'" + style.getPath() + "'" + + "\n" + ex.getMessage()); + new OOError(title, msg, ex).showErrorDialog(dialogService); + return FAIL; + } + } + return PASS; + } + private void initPanel() { connect.setOnAction(e -> connectAutomatically()); manualConnect.setOnAction(e -> connectManually()); selectDocument.setTooltip(new Tooltip(Localization.lang("Select which open Writer document to work on"))); - selectDocument.setOnAction(e -> { - try { - ooBase.selectDocument(); - dialogService.notify(Localization.lang("Connected to document") + ": " - + ooBase.getCurrentDocumentTitle().orElse("")); - } catch (WrappedTargetException | IndexOutOfBoundsException | - NoSuchElementException | NoDocumentException ex) { - LOGGER.warn("Problem connecting", ex); - dialogService.showErrorDialogAndWait(ex); - } + selectDocument.setOnAction(e -> { + ooBase.guiActionSelectDocument(false); }); setStyleFile.setMaxWidth(Double.MAX_VALUE); @@ -194,51 +210,54 @@ private void initPanel() { update.setTooltip(new Tooltip(Localization.lang("Ensure that the bibliography is up-to-date"))); update.setOnAction(event -> { - try { - if (style == null) { - style = loader.getUsedStyle(); - } else { - style.ensureUpToDate(); - } + String title = Localization.lang("Could not update bibliography"); + if (getOrUpdateTheStyle(title)) { + return; + } + if (style == null) { + OOError.noValidStyleSelected() + .setTitle(title) + .showErrorDialog(dialogService); + return; + } - List databases = getBaseList(); - ooBase.updateDocumentActionHelper(databases, style); + List databases = getBaseList(); + try { + ooBase.guiActionUpdateDocument(databases, style); } catch (ConnectionLostException ex) { - showConnectionLostErrorMessage(dialogService); - } catch (IOException ex) { - LOGGER.warn("Problem with style file", ex); - dialogService.showErrorDialogAndWait(Localization.lang("No valid style file defined"), - Localization.lang("You must select either a valid style file, or use one of the default styles.")); + OOError.from(ex).showErrorDialog(dialogService); } catch (com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Could not update bibliography", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } }); merge.setMaxWidth(Double.MAX_VALUE); merge.setTooltip(new Tooltip(Localization.lang("Combine pairs of citations that are separated by spaces only"))); merge.setOnAction(e -> { + final String title = Localization.lang("Problem combining cite markers"); + // check usedStylesExistInDocument try { ooBase.combineCiteMarkers(getBaseList(), style); } catch (JabRefException ex) { - dialogService.showErrorDialogAndWait( - Localization.lang("JabRefException"), - ex.getLocalizedMessage()); - } catch (UndefinedCharacterFormatException ex) { - reportUndefinedCharacterFormat(dialogService, ex); + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(dialogService); + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | NotRemoveableException | IllegalTypeException | InvalidStateException | PropertyExistException ex) { LOGGER.warn("Problem combining cite markers", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } }); unmerge.setMaxWidth(Double.MAX_VALUE); unmerge.setTooltip(new Tooltip(Localization.lang("Separate merged citations"))); unmerge.setOnAction(e -> { + final String title = Localization.lang("Problem during separating cite markers"); + // check usedStylesExistInDocument try { ooBase.unCombineCiteMarkers(getBaseList(), style); } catch (JabRefException ex) { @@ -246,14 +265,13 @@ private void initPanel() { Localization.lang("JabRefException"), ex.getLocalizedMessage()); } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(dialogService); - } catch (UndefinedCharacterFormatException ex) { - reportUndefinedCharacterFormat(dialogService, ex); + OOError.from(ex).showErrorDialog(dialogService); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | CreationException | NoSuchElementException | WrappedTargetException | IOException | PropertyExistException | IllegalTypeException | NotRemoveableException | InvalidStateException ex) { - LOGGER.warn("Problem uncombining cite markers", ex); + LOGGER.warn("Problem during separating cite markers", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } }); @@ -263,7 +281,7 @@ private void initPanel() { settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { - Optional> citations = ooBase.getCitationEntries(); + Optional> citations = ooBase.guiActionGetCitationEntries(); if (citations.isPresent()) { dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase, citations.get())); @@ -273,16 +291,7 @@ private void initPanel() { exportCitations.setMaxWidth(Double.MAX_VALUE); exportCitations.setOnAction(event -> exportEntries()); - selectDocument.setDisable(true); - pushEntries.setDisable(true); - pushEntriesInt.setDisable(true); - pushEntriesEmpty.setDisable(true); - pushEntriesAdvanced.setDisable(true); - update.setDisable(true); - merge.setDisable(true); - unmerge.setDisable(true); - manageCitations.setDisable(true); - exportCitations.setDisable(true); + updateButtonAvailability(); HBox hbox = new HBox(); hbox.getChildren().addAll(connect, manualConnect, selectDocument, update, help); @@ -302,44 +311,29 @@ private void initPanel() { } private void exportEntries() { + final String title = Localization.lang("Problem generating new database."); try { - if (style == null) { - style = loader.getUsedStyle(); - } else { - style.ensureUpToDate(); - } - List databases = getBaseList(); if (databases.isEmpty()) { - dialogService.showErrorDialogAndWait( - Localization.lang("No database is open"), - Localization.lang("We need a database to export from. Open one.")); + OOError.noDataBaseIsOpenForExport().showErrorDialog(dialogService); return; } - - OOBibBase.ExportCitedHelperResult r = ooBase.exportCitedHelper(databases); - List unresolvedKeys = r.unresolvedKeys; - BibDatabase newDatabase = r.newDatabase; - if (!unresolvedKeys.isEmpty()) { - - dialogService.showErrorDialogAndWait(Localization.lang("Unable to generate new library"), - Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", - unresolvedKeys.get(0))); + boolean returnPartialResult = false; + Optional newDatabase = ooBase.exportCitedHelper(databases, returnPartialResult); + if (newDatabase.isPresent()) { + BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase.get()); + this.frame.addTab(databaseContext, true); } - - BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase); - this.frame.addTab(databaseContext, true); } catch (JabRefException ex) { - dialogService.showErrorDialogAndWait( - Localization.lang("JabRefException"), - ex.getLocalizedMessage()); + OOError.from(ex).showErrorDialog(dialogService); } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(dialogService); + OOError.from(ex).showErrorDialog(dialogService); } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | - UndefinedCharacterFormatException | NoSuchElementException | WrappedTargetException | IOException | + NoSuchElementException | WrappedTargetException | IOException | InvalidStateException | - CreationException e) { - LOGGER.warn("Problem generating new database.", e); + CreationException ex) { + LOGGER.warn("Problem generating new database.", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } } @@ -420,6 +414,32 @@ private void connectManually() { } } + private void updateButtonAvailability() { + boolean isConnected = (ooBase != null); + boolean isConnectedToDocument = isConnected && !ooBase.isDocumentConnectionMissing(); + + // For these, we need to watch something + boolean hasStyle = true; // (style != null); + boolean hasDatabase = true; // !getBaseList().isEmpty(); + boolean hasSelectedBibEntry = true; + + selectDocument.setDisable(!(isConnected)); + pushEntries.setDisable(!(isConnectedToDocument && hasStyle && hasDatabase)); + + boolean canCite = isConnectedToDocument && hasStyle && hasSelectedBibEntry; + pushEntriesInt.setDisable(!canCite); + pushEntriesEmpty.setDisable(!canCite); + pushEntriesAdvanced.setDisable(!canCite); + + boolean canRefreshDocument = isConnectedToDocument && hasStyle; + update.setDisable(!canRefreshDocument); + merge.setDisable(!canRefreshDocument); + unmerge.setDisable(!canRefreshDocument); + manageCitations.setDisable(!canRefreshDocument); + + exportCitations.setDisable(!(isConnectedToDocument && hasDatabase)); + } + private void connect() { ooPrefs = preferencesService.getOpenOfficePreferences(); @@ -437,29 +457,12 @@ protected OOBibBase call() throws Exception { connectTask.setOnSucceeded(value -> { ooBase = connectTask.getValue(); - try { - ooBase.selectDocument(); - } catch (NoSuchElementException | WrappedTargetException | NoDocumentException ex) { - dialogService.showErrorDialogAndWait(Localization.lang("Error connecting to Writer document"), Localization.lang("You need to open Writer with a document before connecting"), ex); - LOGGER.error("Error connecting to writer document", ex); - } - - if (ooBase.isConnectedToDocument()) { - dialogService.notify(Localization.lang("Connected to document") + ": " + ooBase.getCurrentDocumentTitle().orElse("")); - } + ooBase.guiActionSelectDocument(true); // Enable actions that depend on Connect: - selectDocument.setDisable(false); - pushEntries.setDisable(false); - pushEntriesInt.setDisable(false); - pushEntriesEmpty.setDisable(false); - pushEntriesAdvanced.setDisable(false); - update.setDisable(false); - merge.setDisable(false); - unmerge.setDisable(false); - manageCitations.setDisable(false); - exportCitations.setDisable(false); + updateButtonAvailability(); }); + connectTask.setOnFailed(value -> { Throwable ex = connectTask.getException(); if (ex instanceof UnsatisfiedLinkError) { @@ -472,9 +475,9 @@ protected OOBibBase call() throws Exception { dialogService.showErrorDialogAndWait(Localization.lang("Could not connect to running OpenOffice/LibreOffice."), Localization.lang("Could not connect to running OpenOffice/LibreOffice.") - + "\n" - + Localization.lang("Make sure you have installed OpenOffice/LibreOffice with Java support.") + "\n" - + Localization.lang("If connecting manually, please verify program and library paths.") + "\n" + "\n" + Localization.lang("Error message:"), + + "\n" + + Localization.lang("Make sure you have installed OpenOffice/LibreOffice with Java support.") + "\n" + + Localization.lang("If connecting manually, please verify program and library paths.") + "\n" + "\n" + Localization.lang("Error message:"), ex); } else { dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), ex); @@ -491,25 +494,44 @@ private OOBibBase createBibBase(Path loPath) throws IOException, InvocationTarge } private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addPageInfo) { - if (!ooBase.isConnectedToDocument()) { - dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"), Localization.lang("Not connected to any Writer document. Please" + " make sure a document is open, and use the 'Select Writer document' button to connect to it.")); + final String title = Localization.lang("Error pushing entries"); + if (ooBase.guiCheckIfConnectedToDocument(title) + || ooBase.guiCheckIfOpenOfficeIsRecordingChanges(title)) { return; } - try { - ooBase.checkIfOpenOfficeIsRecordingChanges(); - } catch (JabRefException ex) { - dialogService.showErrorDialogAndWait( - Localization.lang("JabRefException"), - ex.getLocalizedMessage()); + LibraryTab libraryTab = frame.getCurrentLibraryTab(); + if (libraryTab == null) { + OOError.noDataBaseIsOpenForCiting() + .setTitle(title) + .showErrorDialog(dialogService); return; - } catch (NoDocumentException ex) { - showNoDocumentErrorMessage(dialogService); + } + + final BibDatabase database = libraryTab.getDatabase(); + if (database == null) { + OOError.noDataBaseIsOpenForCiting() + .setTitle(title) + .showErrorDialog(dialogService); + return; + } + + List entries = libraryTab.getSelectedEntries(); + if (entries.isEmpty()) { + OOError.noEntriesSelectedForCitation() + .setTitle(title) + .showErrorDialog(dialogService); + return; + } + + if (getOrUpdateTheStyle(title)) { + return; + } + if (style == null) { + OOError.noValidStyleSelected() + .setTitle(title) + .showErrorDialog(dialogService); return; - } catch (UnknownPropertyException - | PropertyVetoException - | WrappedTargetException ex) { - LOGGER.warn("Problem during checkIfOpenOfficeIsRecordingChanges", ex); } Boolean inParenthesis = inParenthesisIn; @@ -527,62 +549,18 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP } } - LibraryTab libraryTab = frame.getCurrentLibraryTab(); - if (libraryTab != null) { - final BibDatabase database = libraryTab.getDatabase(); - if (database == null) { - dialogService.showErrorDialogAndWait( - Localization.lang("No database"), - Localization.lang( - "No bibliography database is open for citation.") - + "\n" - + Localization.lang("Open one before citing.")); - return; - } - List entries = libraryTab.getSelectedEntries(); - if (entries.isEmpty()) { - dialogService.showErrorDialogAndWait( - Localization.lang("No entries selected for citation"), - Localization.lang( - "No bibliography entries are selected for citation.") - + "\n" - + Localization.lang("Select some before citing.")); - return; - } - if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { + if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { + try { - try { - if (style == null) { - style = loader.getUsedStyle(); - if (style == null) { - dialogService.showErrorDialogAndWait( - Localization.lang("No valid style file defined"), - Localization.lang( - "No bibliography style is selected for citation.") - + "\n" - + Localization.lang("Select one before citing.") - + "\n" - + Localization.lang("You must select either a valid style file, or use one of the default styles.")); - return; - } - } - ooBase.insertEntry(entries, database, getBaseList(), style, inParenthesis, withText, pageInfo, + ooBase.guiActionInsertEntry(entries, database, getBaseList(), style, inParenthesis, withText, pageInfo, ooPrefs.getSyncWhenCiting()); } catch (ConnectionLostException ex) { - showConnectionLostErrorMessage(dialogService); + OOError.from(ex).showErrorDialog(dialogService); } catch (com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Could not insert entry", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } } - } else { // libraryTab == null - dialogService.showErrorDialogAndWait( - Localization.lang("No database"), - Localization.lang( - "No bibliography database is open for citation.") - + "\n" - + Localization.lang("Open one before citing.")); - return; - } } /** @@ -637,32 +615,6 @@ private boolean checkThatEntriesHaveKeys(List entries) { } } - public static void showConnectionLostErrorMessage(DialogService dialogService) { - dialogService.showErrorDialogAndWait(Localization.lang("Connection lost"), - Localization.lang("Connection to OpenOffice/LibreOffice has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); - } - - public static void showNoDocumentErrorMessage(DialogService dialogService) { - dialogService.showErrorDialogAndWait(Localization.lang("Connection to document lost"), - Localization.lang("Connection to OpenOffice/LibreOffice document has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); - } - - public static void reportUndefinedParagraphFormat(DialogService dialogService, UndefinedParagraphFormatException ex) { - dialogService.showErrorDialogAndWait(Localization.lang("Undefined paragraph format"), - Localization.lang("Your style file specifies the paragraph format '%0', " - + "which is undefined in your current OpenOffice/LibreOffice document.", - ex.getFormatName()) + "\n" + Localization.lang("The paragraph format is controlled by the property 'ReferenceParagraphFormat' or 'ReferenceHeaderParagraphFormat' in the style file.")); - } - - public static void reportUndefinedCharacterFormat(DialogService dialogService, UndefinedCharacterFormatException ex) { - dialogService.showErrorDialogAndWait(Localization.lang("Undefined character format"), - Localization.lang("Your style file specifies the character format '%0', " - + "which is undefined in your current OpenOffice/LibreOffice document.", - ex.getFormatName()) + "\n" + Localization.lang("The character format is controlled by the citation property 'CitationCharacterFormat' in the style file.") - - ); - } - private ContextMenu createSettingsPopup() { ContextMenu contextMenu = new ContextMenu(); diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 47589fed991..998958c4a1c 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -1038,7 +1038,10 @@ public enum NonUniqueCitationMarker { * for freshly inserted citations without * going throw the uniquefication process. * - * @return The formatted citation. + * @return The formatted citation. The result does not include + * the standard wrappers: + * OOFormat.setLocaleNone() and OOFormat.setCharStyle(). + * These are added by decorateCitationMarker() */ public OOFormattedText getCitationMarker(List citationMarkerEntries, boolean inParenthesis, @@ -1049,6 +1052,21 @@ public OOFormattedText getCitationMarker(List citationMarke nonUniqueCitationMarkerHandling); } + /** + * Add setLocaleNone and optionally setCharStyle(CitationCharacterFormat) around + * citationText. Called in fillCitationMarkInCursor, so these are + * also applied to "Unresolved()" entries and numeric styles. + */ + public OOFormattedText decorateCitationMarker(OOFormattedText citationText) { + OOBibStyle style = this; + OOFormattedText citationText2 = OOFormat.setLocaleNone(citationText); + if (style.isFormatCitations()) { + String charStyle = style.getCitationCharacterFormat(); + citationText2 = OOFormat.setCharStyle(citationText2, charStyle); + } + return citationText2; + } + /* * * Property getters diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index e1d6b01625b..530fc20a8b7 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -385,10 +385,9 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole /* * All entries are resolved. */ - OOFormattedText citMarker = - style.getCitationMarker(citationMarkerEntries, - inParenthesis, - strictlyUnique); + OOFormattedText citMarker = style.getCitationMarker(citationMarkerEntries, + inParenthesis, + strictlyUnique); citMarkers.put(cgid, citMarker); } } diff --git a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java b/src/main/java/org/jabref/logic/openoffice/ConnectionLostException.java similarity index 62% rename from src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java rename to src/main/java/org/jabref/logic/openoffice/ConnectionLostException.java index 36fc16e5e3f..3f13bd74b4b 100644 --- a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java +++ b/src/main/java/org/jabref/logic/openoffice/ConnectionLostException.java @@ -1,9 +1,9 @@ -package org.jabref.gui.openoffice; +package org.jabref.logic.openoffice; /** * This exception is used to indicate that connection to OpenOffice has been lost. */ -class ConnectionLostException extends RuntimeException { +public class ConnectionLostException extends RuntimeException { public ConnectionLostException(String s) { super(s); diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java new file mode 100644 index 00000000000..a1f25ba58ac --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -0,0 +1,159 @@ +package org.jabref.logic.openoffice; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.oostyle.CitationMarkerEntry; +import org.jabref.logic.oostyle.CitationMarkerEntryImpl; +import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.oostyle.OOProcess; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOStyleDataModelVersion; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EditInsert { + + private static final Logger LOGGER = LoggerFactory.getLogger(EditInsert.class); + + /** + * In insertEntry we receive BibEntry values from the GUI. + * + * In the document we store citations by their citation key. + * + * If the citation key is missing, the best we can do is to notify + * the user. Or the programmer, that we cannot accept such input. + * + */ + private static String insertEntryGetCitationKey(BibEntry entry) { + Optional key = entry.getCitationKey(); + if (key.isEmpty()) { + throw new RuntimeException("insertEntryGetCitationKey:" + + " cannot cite entries without citation key"); + } + return key.get(); + } + + /* + * @param cursor Where to insert. + */ + public static void insertCitationGroup(XTextDocument doc, + OOFrontend fr, + XTextCursor cursor, + List entries, + BibDatabase database, + List allBases, + OOBibStyle style, + boolean inParenthesis, + boolean withText, + String pageInfo, + boolean sync, + boolean alwaysAddCitedOnPages) + throws + UnknownPropertyException, + NoDocumentException, + NotRemoveableException, + WrappedTargetException, + PropertyVetoException, + PropertyExistException, + NoSuchElementException, + CreationException, + IllegalTypeException, + JabRefException { + List citationKeys = + entries.stream() + .map(EditInsert::insertEntryGetCitationKey) + .collect(Collectors.toList()); + + InTextCitationType citationType = OOProcess.citationTypeFromOptions(withText, inParenthesis); + + final int nEntries = entries.size(); + // JabRef53 style pageInfo list + List pageInfosForCitations = + OOStyleDataModelVersion.fakePageInfosForCitations(pageInfo, nEntries); + + List citationMarkerEntries = new ArrayList<>(nEntries); + for (int i = 0; i < nEntries; i++) { + // Using the same database for each entry. + // Probably the GUI limits selection to a single database. + CitationMarkerEntry cm = + new CitationMarkerEntryImpl(citationKeys.get(i), + Optional.ofNullable(entries.get(i)), + Optional.ofNullable(database), + Optional.empty(), // uniqueLetter + Optional.ofNullable(pageInfosForCitations.get(i)), + false /* isFirstAppearanceOfSource */); + citationMarkerEntries.add(cm); + } + + // The text we insert + OOFormattedText citeText = + (style.isNumberEntries() + ? OOFormattedText.fromString("[-]") // A dash only. Only refresh later. + : style.getCitationMarker(citationMarkerEntries, + inParenthesis, + OOBibStyle.NonUniqueCitationMarker.FORGIVEN)); + + if ("".equals(OOFormattedText.toString(citeText))) { + citeText = OOFormattedText.fromString("[?]"); + } + + UpdateCitationMarkers.createAndFillCitationGroup(fr, + doc, + citationKeys, + pageInfosForCitations, + citationType, + citeText, + cursor, + withText, + style, + true /* insertSpaceAfter */); + + // Remember this position: we will come back here in the + // end. + XTextRange position = cursor.getEnd(); + + if (sync) { + // To account for numbering and for uniqueLetters, we + // must refresh the cite markers: + OOFrontend fr2 = new OOFrontend(doc); + + Update.updateDocument(doc, + fr2, + allBases, + style, + true, /* doUpdateBibliography */ + alwaysAddCitedOnPages); + + /* + * Problem: insertEntry in bibliography + * Reference is destroyed when we want to get there. + */ + // Go back to the relevant position: + try { + cursor.gotoRange(position, false); + } catch (com.sun.star.uno.RuntimeException ex) { + LOGGER.warn("insertCitationGroup:" + + " Could not go back to end of in-text citation", ex); + } + } + + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/ManageCitations.java b/src/main/java/org/jabref/logic/openoffice/ManageCitations.java new file mode 100644 index 00000000000..76e8f4cdd0b --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/ManageCitations.java @@ -0,0 +1,39 @@ +package org.jabref.logic.openoffice; + +import java.util.List; + +import org.jabref.model.openoffice.CitationEntry; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextDocument; + +public class ManageCitations { + + public static List getCitationEntries(XTextDocument doc) + throws + NoDocumentException, + UnknownPropertyException, + WrappedTargetException { + OOFrontend fr = new OOFrontend(doc); + return fr.getCitationEntries(doc); + } + + public static void applyCitationEntries(XTextDocument doc, List citationEntries) + throws + NoDocumentException, + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + PropertyVetoException, + IllegalTypeException, + WrappedTargetException, + IllegalArgumentException { + OOFrontend fr = new OOFrontend(doc); + fr.applyCitationEntries(doc, citationEntries); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/NoDocumentException.java b/src/main/java/org/jabref/logic/openoffice/NoDocumentException.java index 28d6ba7aced..a4edf3c661b 100644 --- a/src/main/java/org/jabref/logic/openoffice/NoDocumentException.java +++ b/src/main/java/org/jabref/logic/openoffice/NoDocumentException.java @@ -1,13 +1,12 @@ package org.jabref.logic.openoffice; -/** - * Exception used to indicate that the plugin attempted to set a character format that is - * not defined in the current OpenOffice document. - */ public class NoDocumentException extends Exception { public NoDocumentException(String message) { super(message); } + public NoDocumentException() { + super("Not connected to a document"); + } } diff --git a/src/main/java/org/jabref/logic/openoffice/NoDocumentFoundException.java b/src/main/java/org/jabref/logic/openoffice/NoDocumentFoundException.java new file mode 100644 index 00000000000..2759a9931aa --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/NoDocumentFoundException.java @@ -0,0 +1,12 @@ +package org.jabref.logic.openoffice; + +public class NoDocumentFoundException extends Exception { + + public NoDocumentFoundException(String message) { + super(message); + } + + public NoDocumentFoundException() { + super("No Writer documents found"); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index 8c23ca0db89..e073d925f24 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -516,20 +516,19 @@ public static void write(XTextDocument doc, NoSuchElementException, CreationException { - final boolean useSetString = true; + final boolean debugThisFun = false; String lText = OOFormattedText.toString(ootext); - // System.out.println(lText); + if (debugThisFun) { + System.out.println(lText); + } XText text = position.getText(); XTextCursor cursor = text.createTextCursorByRange(position); cursor.collapseToEnd(); MyPropertyStack formatStack = new MyPropertyStack(cursor); - - // Stack formatters = new Stack<>(); - Stack expectEnd = new Stack<>(); // We need to extract formatting. Use a simple regexp search iteration: @@ -539,11 +538,7 @@ public static void write(XTextDocument doc, String currentSubstring = lText.substring(piv, m.start()); if (!currentSubstring.isEmpty()) { - if (useSetString) { - cursor.setString(currentSubstring); - } else { - text.insertString(cursor, currentSubstring, true); - } + cursor.setString(currentSubstring); } formatStack.apply(cursor); cursor.collapseToEnd(); @@ -603,14 +598,16 @@ public static void write(XTextDocument doc, //

if (value != null && !value.equals("")) { // LOGGER.warn(String.format("oo:ParaStyleName=\"%s\" found", value)); - try { - setParagraphStyle(cursor, value); - } catch (UndefinedParagraphFormatException ex) { - LOGGER.warn(String.format("oo:ParaStyleName=\"%s\" failed with" - + " UndefinedParagraphFormatException", value)); + if (setParagraphStyle(cursor, value)) { + if (debugThisFun) { + // Presumably tested already: + LOGGER.warn(String.format("oo:ParaStyleName=\"%s\" failed", value)); + } } } else { - LOGGER.warn(String.format("oo:ParaStyleName inherited")); + if (debugThisFun) { + LOGGER.warn(String.format("oo:ParaStyleName inherited")); + } } break; default: @@ -695,11 +692,7 @@ public static void write(XTextDocument doc, } if (piv < lText.length()) { - if (useSetString) { - cursor.setString(lText.substring(piv)); - } else { - text.insertString(cursor, lText.substring(piv), true); - } + cursor.setString(lText.substring(piv)); } formatStack.apply(cursor); cursor.collapseToEnd(); @@ -934,19 +927,23 @@ private static List> SuperScript(MyPropertyStack formatStac formatStack); } - public static void setParagraphStyle(XTextCursor cursor, - String parStyle) - throws - UndefinedParagraphFormatException { + /* + * @return true on failure + */ + public static boolean setParagraphStyle(XTextCursor cursor, String parStyle) { + final boolean FAIL = true; + final boolean PASS = false; + XParagraphCursor parCursor = UnoCast.unoQI(XParagraphCursor.class, cursor); XPropertySet props = UnoCast.unoQI(XPropertySet.class, parCursor); try { props.setPropertyValue(PARA_STYLE_NAME, parStyle); + return PASS; } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | WrappedTargetException ex) { - throw new UndefinedParagraphFormatException(parStyle); + return FAIL; } } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java deleted file mode 100644 index b32c5f73bd1..00000000000 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOOV1.java +++ /dev/null @@ -1,910 +0,0 @@ -package org.jabref.logic.openoffice; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.Stack; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.model.oostyle.OOFormattedText; - -import com.sun.star.awt.FontSlant; -import com.sun.star.awt.FontStrikeout; -import com.sun.star.awt.FontUnderline; -import com.sun.star.awt.FontWeight; -import com.sun.star.beans.Property; -import com.sun.star.beans.PropertyAttribute; -import com.sun.star.beans.PropertyState; -import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.beans.XMultiPropertyStates; -import com.sun.star.beans.XPropertySet; -import com.sun.star.beans.XPropertySetInfo; -import com.sun.star.beans.XPropertyState; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.lang.Locale; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.style.CaseMap; -import com.sun.star.text.XParagraphCursor; -import com.sun.star.text.XText; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextDocument; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Interpret OOFormattedText into an OpenOffice or LibreOffice writer - * document. - * - * On the question of what should it understand: apart from what - * it can do now, probably whatever a CSL style with HTML output - * emits. - * - * Seems slow with approx 40 citations. - * - * Idea: - * - * - Use setString, not insertString. This removes character formats, - * probably no need for workaround about setPropertyToDefault. - * - Calculate current set of character properties in java. - * - Use interface allowing to set multiple properties in a single call. - * - */ -@AllowedToUseAwt("Requires AWT for changing document properties") -public class OOFormattedTextIntoOOV1 { - - private static final Logger LOGGER = LoggerFactory.getLogger(OOFormattedTextIntoOO.class); - - /** - * "ParaStyleName" is an OpenOffice Property name. - */ - private static final String PARA_STYLE_NAME = "ParaStyleName"; - - /* - * Character property names used in multiple locations below. - */ - private static final String CHAR_ESCAPEMENT_HEIGHT = "CharEscapementHeight"; - private static final String CHAR_ESCAPEMENT = "CharEscapement"; - private static final String CHAR_STYLE_NAME = "CharStyleName"; - private static final String CHAR_UNDERLINE = "CharUnderline"; - private static final String CHAR_STRIKEOUT = "CharStrikeout"; - - /* - * SUPERSCRIPT_VALUE and SUPERSCRIPT_HEIGHT are percents of the normal character height - */ - private static final short CHAR_ESCAPEMENT_VALUE_DEFAULT = (short) 0; - private static final short SUPERSCRIPT_VALUE = (short) 33; - private static final short SUBSCRIPT_VALUE = (short) -10; - private static final byte CHAR_ESCAPEMENT_HEIGHT_DEFAULT = (byte) 100; - private static final byte SUPERSCRIPT_HEIGHT = (byte) 58; - private static final byte SUBSCRIPT_HEIGHT = (byte) 58; - - private static final String TAG_NAME_REGEXP = - "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|span|oo:referenceToPageNumberOfReferenceMark)"; - private static final String ATTRIBUTE_NAME_REGEXP = - "(?:oo:ParaStyleName|oo:CharStyleName|lang|style|target)"; - private static final String ATTRIBUTE_VALUE_REGEXP = "\"([^\"]*)\""; - private static final Pattern HTML_TAG = - Pattern.compile("<(/" + TAG_NAME_REGEXP + ")>" - + "|" - + "<(" + TAG_NAME_REGEXP + ")" - + "((?:\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP + ")*)" - + ">"); - private static final Pattern ATTRIBUTE_PATTERN = - Pattern.compile("\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP); - - private OOFormattedTextIntoOOV1() { - // Just to hide the public constructor - } - - /** - * Insert a text with formatting indicated by HTML-like tags, into - * a text at the position given by a cursor. - * - * Limitation: understands no entities. It does not receive any either, unless - * the user provides it. - * - * To limit the damage {@code TAG_NAME_REGEXP} and {@code ATTRIBUTE_NAME_REGEXP} - * explicitly lists the values we care about. - * - * Notable changes w.r.t insertOOFormattedTextAtCurrentLocation: - * - * - new tags: - * - * - <span lang="zxx"> - * - earlier was applied from code - * - * - <span oo:CharStyleName="CharStylename"> - * - earlier was applied from code, for "CitationCharacterFormat" - * - * - <p> start new paragraph - * - earlier was applied from code - * - * - <p oo:ParaStyleName="ParStyleName"> : start new paragraph and apply ParStyleName - * - earlier was applied from code - * - * - <tt> - * - earlier: known, but ignored - * - now: equivalent to <span oo:CharStyleName="Example"> - * - <oo:referenceToPageNumberOfReferenceMark> (self-closing) - * - * - closing tags try to properly restore state instead of dictating - * an "off" state. - * - * - The practical consequence: the user can format - * citation marks (it is enough to format its start) and the - * properties not dictated by the style are preserved. - * - * A comparable example: a style with - * ReferenceParagraphFormat="JR_bibentry" - * JR_bibentry in LibreOffice, paragraph style prescribes "bold" font. - * LAYOUT only mentions bold around year. - * Which parts of the bibliography entries should come out as bold? - * - * @param position The cursor giving the insert location. Not modified. - * @param ootext The marked-up text to insert. - */ - public static void write(XTextDocument doc, - XTextCursor position, - OOFormattedText ootext) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, - CreationException { - - String lText = OOFormattedText.toString(ootext); - - System.out.println(lText); - - XText text = position.getText(); - XTextCursor cursor = text.createTextCursorByRange(position); - cursor.collapseToEnd(); - - Stack formatters = new Stack<>(); - Stack expectEnd = new Stack<>(); - - // We need to extract formatting. Use a simple regexp search iteration: - int piv = 0; - Matcher m = HTML_TAG.matcher(lText); - while (m.find()) { - - String currentSubstring = lText.substring(piv, m.start()); - if (!currentSubstring.isEmpty()) { - text.insertString(cursor, currentSubstring, true); - } - formatTextInCursor(cursor, formatters); - cursor.collapseToEnd(); - - String fullTag = m.group(); - String endTagName = m.group(1); - String startTagName = m.group(2); - String attributeListPart = m.group(3); - boolean isStartTag = (endTagName == null) || "".equals(endTagName); - String tagName = isStartTag ? startTagName : endTagName; - Objects.requireNonNull(tagName); - - List> attributes = parseAttributes(attributeListPart); - - // Handle tags: - switch (tagName) { - case "b": - formatters.push(setCharWeight(FontWeight.BOLD)); - expectEnd.push("/" + tagName); - break; - case "i": - case "em": - formatters.push(setCharPosture(FontSlant.ITALIC)); - expectEnd.push("/" + tagName); - break; - case "smallcaps": - formatters.push(setCharCaseMap(CaseMap.SMALLCAPS)); - expectEnd.push("/" + tagName); - break; - case "sup": - formatters.push(SuperScript()); - expectEnd.push("/" + tagName); - break; - case "sub": - formatters.push(SubScript()); - expectEnd.push("/" + tagName); - break; - case "u": - formatters.push(setCharUnderline(FontUnderline.SINGLE)); - expectEnd.push("/" + tagName); - break; - case "s": - formatters.push(setCharStrikeout(FontStrikeout.SINGLE)); - expectEnd.push("/" + tagName); - break; - case "/p": - // nop - break; - case "p": - OOUtil.insertParagraphBreak(text, cursor); - cursor.collapseToEnd(); - for (Pair kv : attributes) { - String key = kv.a; - String value = kv.b; - switch (key) { - case "oo:ParaStyleName": - //

- if (value != null && !value.equals("")) { - try { - setParagraphStyle(cursor, value); - } catch (UndefinedParagraphFormatException ex) { - // ignore silently - } - } - break; - default: - LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); - break; - } - } - break; - case "oo:referenceToPageNumberOfReferenceMark": - for (Pair kv : attributes) { - String key = kv.a; - String value = kv.b; - switch (key) { - case "target": - UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); - break; - default: - LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); - break; - } - } - break; - case "tt": - // Note: "Example" names a character style in LibreOffice. - formatters.push(setCharStyleName("Example")); - expectEnd.push("/" + tagName); - break; - case "span": - Formatters fs = new Formatters(); - for (Pair kv : attributes) { - String key = kv.a; - String value = kv.b; - switch (key) { - case "oo:CharStyleName": - // - fs.add(setCharStyleName(value)); - break; - case "lang": - // - // - fs.add(setCharLocale(value)); - break; - case "style": - // In general we may need to parse value - if (value.equals("font-variant: small-caps")) { - fs.add(setCharCaseMap(CaseMap.SMALLCAPS)); - break; - } - LOGGER.warn(String.format("Unexpected value %s for attribute '%s' for <%s>", - value, key, tagName)); - break; - default: - LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); - break; - } - } - formatters.push(fs); - expectEnd.push("/" + tagName); - break; - case "/b": - case "/i": - case "/em": - case "/tt": - case "/smallcaps": - case "/sup": - case "/sub": - case "/u": - case "/s": - case "/span": - formatters.pop().applyEnd(cursor); - String expected = expectEnd.pop(); - if (!tagName.equals(expected)) { - LOGGER.warn(String.format("expected '<%s>', found '<%s>'", expected, tagName)); - } - break; - } - - piv = m.end(); - } - - if (piv < lText.length()) { - text.insertString(cursor, lText.substring(piv), true); - } - formatTextInCursor(cursor, formatters); - cursor.collapseToEnd(); - - if (!expectEnd.empty()) { - String rest = ""; - for (String s : expectEnd) { - rest = String.format("<%s>", s) + rest; - } - LOGGER.warn(String.format("insertOOFormattedTextAtCurrentLocation2:" - + " expectEnd stack is not empty at the end: %s%n", - rest)); - } - } - - /** - * Purpose: in some cases we do not want to inherit direct - * formatting from the context. - * - * In particular, when filling the bibliography title and body. - */ - public static void removeDirectFormatting(XTextCursor cursor) { - - XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); - - /* - * Now that we have setAllPropertiesToDefault, check which properties - * are not set to default and try to correct what we can and seem necessary. - * - * Note: tested with LibreOffice : 6.4.6.2 - */ - - XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); - - try { - // Special handling - propertySet.setPropertyValue(CHAR_STYLE_NAME, "Standard"); - // propertySet.setPropertyValue("CharCaseMap", CaseMap.NONE); - propertyState.setPropertyToDefault("CharCaseMap"); - } catch (UnknownPropertyException | - PropertyVetoException | - IllegalArgumentException | - WrappedTargetException ex) { - LOGGER.warn("exception caught", ex); - } - - mpss.setAllPropertiesToDefault(); - - // Only report those we do not yet know about - final Set knownToFail = Set.of("ListAutoFormat", - "ListId", - "NumberingIsNumber", - "NumberingLevel", - "NumberingRules", - "NumberingStartValue", - "ParaChapterNumberingLevel", - "ParaIsNumberingRestart", - "ParaStyleName"); - - // query again, just in case it matters - propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - XPropertySetInfo psi = propertySet.getPropertySetInfo(); - - // check the result - for (Property p : psi.getProperties()) { - if ((p.Attributes & PropertyAttribute.READONLY) != 0) { - continue; - } - try { - if (isPropertyDefault(cursor, p.Name)) { - continue; - } - } catch (UnknownPropertyException ex) { - throw new RuntimeException("Unexpected UnknownPropertyException"); - } - if (knownToFail.contains(p.Name)) { - continue; - } - LOGGER.warn(String.format("OOFormattedTextIntoOO.removeDirectFormatting failed on '%s'", - p.Name)); - } - } - - private static List> parseAttributes(String s) { - List> res = new ArrayList<>(); - if (s == null) { - return res; - } - Matcher m = ATTRIBUTE_PATTERN.matcher(s); - while (m.find()) { - String key = m.group(1); - String value = m.group(2); - res.add(new Pair(key, value)); - } - return res; - } - - /** - * Remove direct formatting of propertyName from propertySet. - * - * Observation: while - * XPropertyState.setPropertyToDefault(propertyName) does reset - * the property, it also has a side effect (probably bug in LO - * 6.4.6.2) that it also resets other properties. - * - * For example setPropertyToDefault("CharWeight") also removes "CharColor" - * - * Workaround: - * (https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=105117) - * - * Use setPropertyValue with either result from - * getPropertyValue to restore the earlier state or with - * result from getPropertyDefault. - * - * In either case the property "CharStyleName" has to be handled - * specially, by mapping the received value "" to "Standard". - * Hopefully other properties will not need special handling. - * - * Well, they do. Some properties interact: setting one to - * non-default also sets the other to non-default. Fortunately - * these interactions appear meaningful. For example setting - * "CharCrossedOut" to non-default also modifies "CharStrikeout". - * For the strategy applied here (remove all, then restore all - * except the one we wanted to default) it means we have to avoid - * restoring those that would, as a side-effect set to non-default - * what we promised to set to default. I did not investigate - * potential asymmetries of these interactions, the code below implements - * symmetric behaviour. This means that for example for - * propertyName == "CharCrossedOut" we do not restore - * "CharStrikeout", although the problematic behaviour observed was - * that restoring "CharCrossedOut" changes "CharStrikeout" from its default. - * - */ - private static void setPropertyToDefault(XTextCursor cursor, String propertyName) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - - if (false) { - // This is what should "simply work". - // However it loses e.g. font color when propertyName is "CharWeight". - XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); - propertyState.setPropertyToDefault(propertyName); - } else if (false) { - - // Despite the name getPropertyDefault, storing - // its result by setPropertyValue is NOT (always) equivalent - // to setPropertyToDefault(). - // - // setPropertyToDefault() should remove direct ("hard") - // formatting. - // - // setPropertyValue(getPropertyDefault()) can only do that - // if getPropertyDefault provides a value with the meaning - // "use whatever comes from the level above". - // - // If the value from getPropertyDefault dictates any - // concrete value for the property and "whatever comes - // from the level above" happens to be a different value, - // then the two behaviours yield different results. - - XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); - Object value = propertyState.getPropertyDefault(propertyName); - XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - propertySet.setPropertyValue(propertyName, value); - } else { - - // Try to remove all, then add all directly formatted again, - // except the one we are removing. And those that would override - // what we try to achieve. - - /* https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Formatting - * at the bottom lists interdependent sets: - * - * Those marked [-] we probably will not touch, [X] handled, [?] maybe will touch. - * - * - [-] ParaRightMargin, ParaLeftMargin, ParaFirstLineIndent, ParaIsAutoFirstLineIndent - * - [-] ParaTopMargin, ParaBottomMargin - * - [-] ParaGraphicURL/Filter/Location, ParaBackColor, ParaBackTransparent - * - [-] ParaIsHyphenation, ParaHyphenationMaxLeadingChars/MaxTrailingChars/MaxHyphens - * - [-] Left/Right/Top/BottomBorder, Left/Right/Top/BottomBorderDistance, BorderDistance - * - [-] DropCapFormat, DropCapWholeWord, DropCapCharStyleName - * - [-] PageDescName, PageNumberOffset, PageStyleName - * - * - [-] CharCombineIsOn, CharCombinePrefix, CharCombineSuffix - * - [-] RubyText, RubyAdjust, RubyCharStyleName, RubyIsAbove - * - * - [X] CharStrikeOut, CharCrossedOut - * - [X] CharEscapement, CharAutoEscapement, CharEscapementHeight - * - [X] CharUnderline, CharUnderlineColor, CharUnderlineHasColor - * - * - [?] CharFontName, CharFontStyleName, CharFontFamily, CharFontPitch - * - [?] HyperLinkURL/Name/Target, UnvisitedCharStyleName, VisitedCharStyleName - * - */ - - // CharStrikeout and CharCrossedOut interact: if we default one, - // we default the other as well. - Set charStrikeOutSet = Set.of(CHAR_STRIKEOUT, - "CharCrossedOut"); - Set charEscapementSet = Set.of("CharAutoEscapement", - CHAR_ESCAPEMENT, - CHAR_ESCAPEMENT_HEIGHT); - Set charUnderlineSet = Set.of(CHAR_UNDERLINE, - "CharUnderlineColor", - "CharUnderlineHasColor"); - - Set namesToDefault = new HashSet<>(); - if (charStrikeOutSet.contains(propertyName)) { - namesToDefault = charStrikeOutSet; - } else if (charEscapementSet.contains(propertyName)) { - namesToDefault = charEscapementSet; - } else if (charUnderlineSet.contains(propertyName)) { - namesToDefault = charUnderlineSet; - } else { - namesToDefault.add(propertyName); - } - XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - XPropertySetInfo psi = propertySet.getPropertySetInfo(); - - // Remember those we shall we restore later - Map ds = new HashMap<>(); - for (Property p : psi.getProperties()) { - boolean noRestore = (namesToDefault.contains(p.Name) - || ((p.Attributes & PropertyAttribute.READONLY) != 0) - || (isPropertyDefault(cursor, p.Name))); - if (noRestore) { - continue; - } - ds.put(p.Name, propertySet.getPropertyValue(p.Name)); - } - - // Remove all - removeDirectFormatting(cursor); - - boolean failed = false; - if (!isPropertyDefault(cursor, propertyName)) { - LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault:" - + " removeDirectFormatting failed to reset '%s'", - propertyName)); - failed = true; - } - - // Restore those saved - for (Map.Entry e : ds.entrySet()) { - propertySet.setPropertyValue(e.getKey(), e.getValue()); - if (!failed && !isPropertyDefault(cursor, propertyName)) { - LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault('%s')" - + " setPropertyValue('%s') caused loss of default state", - propertyName, e.getKey())); - failed = true; - } - } - - if (!failed && !isPropertyDefault(cursor, propertyName)) { - LOGGER.warn(String.format("OOFormattedTextIntoOO.setPropertyToDefault('%s') failed", - propertyName)); - } - - } - } - - /** - * We rely on property values being either DIRECT_VALUE or - * DEFAULT_VALUE (not AMBIGUOUS_VALUE). If the cursor covers a homogeneous region, - * or is collapsed, then this is true. - */ - private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) - throws - UnknownPropertyException { - XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); - PropertyState pst = propertyState.getPropertyState(propertyName); - if (pst == PropertyState.AMBIGUOUS_VALUE) { - throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE" - + " (expected properties for a homogeneous cursor)"); - } - return pst == PropertyState.DEFAULT_VALUE; - } - - /** - * @return Optional.empty() if the property is not directly formatted. - */ - private static Optional getPropertyValue(XTextCursor cursor, String propertyName) - throws - UnknownPropertyException, - WrappedTargetException { - if (isPropertyDefault(cursor, propertyName)) { - return Optional.empty(); - } else { - XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - return Optional.of(propertySet.getPropertyValue(propertyName)); - } - } - - /** - * @param value Optional.empty() means instruction to remove direct formatting. - */ - private static void setPropertyValue(XTextCursor cursor, String propertyName, Optional value) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException { - XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - if (value.isPresent()) { - propertySet.setPropertyValue(propertyName, value.get()); - } else { - setPropertyToDefault(cursor, propertyName); - } - } - - /** - * At each tag we adjust the current stack of formatters-to-apply - * stack, then run it. - */ - private interface Formatter { - /** - * Note: apply may be called multiple times, but should pick up old value only - * at its first call. - */ - public void apply(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException; - - /** - * Closing tags call applyEnd directly, so applyEnd is only called once. - * - * It should restore the state to that seen by the first call to apply. - * - */ - public void applyEnd(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException; - } - - /** - * Apply Formatters on the stack. - * - * @param cursor Marks the text to format - * @param formatters Formatters to apply (normally extracted from OOFormattedText) - */ - private static void formatTextInCursor(XTextCursor cursor, - Stack formatters) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - - for (Formatter f : formatters) { - f.apply(cursor); - } - } - - private static class Formatters implements Formatter { - List parts; - public Formatters() { - parts = new ArrayList<>(); - } - - public void add(Formatter f) { - parts.add(f); - } - - @Override - public void apply(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - for (Formatter f : parts) { - f.apply(cursor); - } - } - - @Override - public void applyEnd(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - for (int i = parts.size() - 1; i >= 0; i--) { - Formatter f = parts.get(i); - f.applyEnd(cursor); - } - } - } - - private static class SimpleFormatter implements Formatter { - final String propertyName; - Optional myValue; - Optional oldValue; - boolean started; - - SimpleFormatter(String propertyName, Optional value) { - this.propertyName = propertyName; - this.myValue = value; - this.oldValue = Optional.empty(); - this.started = false; - } - - @Override - public void apply(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - - if (!started) { - oldValue = getPropertyValue(cursor, propertyName).map(e -> (T) e); - XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); - started = true; - } - - setPropertyValue(cursor, propertyName, myValue); - } - - @Override - public void applyEnd(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - setPropertyValue(cursor, propertyName, oldValue); - } - } - - private static Formatter setCharWeight(float value) { - return new SimpleFormatter("CharWeight", Optional.of(value)); - } - - private static Formatter setCharPosture(FontSlant value) { - return new SimpleFormatter("CharPosture", Optional.of(value)); - } - - private static Formatter setCharCaseMap(short value) { - return new SimpleFormatter("CharCaseMap", Optional.of(value)); - } - - // com.sun.star.awt.FontUnderline - private static Formatter setCharUnderline(short value) { - return new SimpleFormatter(CHAR_UNDERLINE, Optional.of(value)); - } - - // com.sun.star.awt.FontStrikeout - private static Formatter setCharStrikeout(short value) { - return new SimpleFormatter(CHAR_STRIKEOUT, Optional.of(value)); - } - - // CharStyleName - private static Formatter setCharStyleName(String value) { - return new SimpleFormatter(CHAR_STYLE_NAME, Optional.ofNullable(value)); - } - - // Locale - private static Formatter setCharLocale(Locale value) { - return new SimpleFormatter("CharLocale", Optional.of(value)); - } - - /** - * Locale from string encoding: language, language-country or language-country-variant - */ - private static Formatter setCharLocale(String value) { - if (value == null || "".equals(value)) { - throw new RuntimeException("setCharLocale \"\" or null"); - } - String[] parts = value.split("-"); - String language = (parts.length > 0) ? parts[0] : ""; - String country = (parts.length > 1) ? parts[1] : ""; - String variant = (parts.length > 2) ? parts[2] : ""; - Locale l = new Locale(language, country, variant); - return setCharLocale(l); - } - - /* - * SuperScript and SubScript - */ - private static class CharEscapement implements Formatter { - Optional myValue; - Optional myHeight; - boolean relative; - - Optional oldValue; - Optional oldHeight; - boolean started; - - /** - * @param relative Make value and height relative to oldHeight and oldValue. - * Needed for e^{x_i} e^{x^2} (i.e. sup or sub within sup or sup) - * - */ - CharEscapement(Optional value, Optional height, boolean relative) { - this.myValue = value; - this.myHeight = height; - this.relative = relative; - this.oldValue = Optional.empty(); - this.oldHeight = Optional.empty(); - this.started = false; - } - - @Override - public void apply(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - if (!started) { - oldValue = getPropertyValue(cursor, CHAR_ESCAPEMENT).map(e -> (short) e); - oldHeight = getPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT).map(e -> (byte) e); - started = true; - } - if (relative && (myValue.isPresent() || myHeight.isPresent())) { - double oh = oldHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * 0.01; - double xHeight = myHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * oh; - double ov = oldValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT); - double xValue = myValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT) * oh + ov; - setPropertyValue(cursor, CHAR_ESCAPEMENT, Optional.of((short) Math.round(xValue))); - setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, Optional.of((byte) Math.round(xHeight))); - } else { - setPropertyValue(cursor, CHAR_ESCAPEMENT, myValue); - setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, myHeight); - } - } - - @Override - public void applyEnd(XTextCursor cursor) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - setPropertyValue(cursor, CHAR_ESCAPEMENT, oldValue); - setPropertyValue(cursor, CHAR_ESCAPEMENT_HEIGHT, oldHeight); - } - } - - private static Formatter SubScript() { - return new CharEscapement(Optional.of(SUBSCRIPT_VALUE), Optional.of(SUBSCRIPT_HEIGHT), true); - } - - private static Formatter SuperScript() { - return new CharEscapement(Optional.of(SUPERSCRIPT_VALUE), Optional.of(SUPERSCRIPT_HEIGHT), true); - } - - public static void setParagraphStyle(XTextCursor cursor, - String parStyle) - throws - UndefinedParagraphFormatException { - XParagraphCursor parCursor = UnoCast.unoQI(XParagraphCursor.class, cursor); - XPropertySet props = UnoCast.unoQI(XPropertySet.class, parCursor); - try { - props.setPropertyValue(PARA_STYLE_NAME, parStyle); - } catch (UnknownPropertyException - | PropertyVetoException - | IllegalArgumentException - | WrappedTargetException ex) { - throw new UndefinedParagraphFormatException(parStyle); - } - } - -} diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index da6c357f929..415cf2a40bf 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -1,7 +1,5 @@ package org.jabref.logic.openoffice; -// import org.jabref.architecture.AllowedToUseAwt; - import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; @@ -15,7 +13,6 @@ /** * Utility methods for processing OO Writer documents. */ -// @AllowedToUseAwt("Requires AWT for changing document properties") public class OOUtil { private static final Logger LOGGER = LoggerFactory.getLogger(OOUtil.class); diff --git a/src/main/java/org/jabref/logic/openoffice/Result.java b/src/main/java/org/jabref/logic/openoffice/Result.java index a4a46e13b8f..f466544c9ac 100644 --- a/src/main/java/org/jabref/logic/openoffice/Result.java +++ b/src/main/java/org/jabref/logic/openoffice/Result.java @@ -73,11 +73,12 @@ public Result ifPresent(Consumer fun) { return this; } - public Result setIfPresent(Settable out) { - if (isPresent()) { - out.set(get()); + public VoidResult asVoidResult() { + if (isError()) { + return VoidResult.Error(getError()); + } else { + return VoidResult.OK(); } - return this; } } diff --git a/src/main/java/org/jabref/logic/openoffice/Settable.java b/src/main/java/org/jabref/logic/openoffice/Settable.java deleted file mode 100644 index e10db2e9538..00000000000 --- a/src/main/java/org/jabref/logic/openoffice/Settable.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.jabref.logic.openoffice; - -import java.util.Optional; - -public class Settable { - private Optional value; - public Settable() { - value = Optional.empty(); - } - - public boolean isEmpty() { - return value.isEmpty(); - } - - public boolean isPresent() { - return value.isPresent(); - } - - public T get() { - return value.get(); - } - - public void set(T value) { - this.value = Optional.of(value); - } -} diff --git a/src/main/java/org/jabref/logic/openoffice/UndefinedCharacterFormatException.java b/src/main/java/org/jabref/logic/openoffice/UndefinedCharacterFormatException.java deleted file mode 100644 index 62e969646ef..00000000000 --- a/src/main/java/org/jabref/logic/openoffice/UndefinedCharacterFormatException.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.jabref.logic.openoffice; - -/** - * Exception used to indicate that the plugin attempted to set a character format that is - * not defined in the current OpenOffice document. - */ -public class UndefinedCharacterFormatException extends Exception { - - private final String formatName; - - public UndefinedCharacterFormatException(String formatName) { - super(); - this.formatName = formatName; - } - - public String getFormatName() { - return formatName; - } -} diff --git a/src/main/java/org/jabref/logic/openoffice/UndefinedParagraphFormatException.java b/src/main/java/org/jabref/logic/openoffice/UndefinedParagraphFormatException.java deleted file mode 100644 index 361f8d44f54..00000000000 --- a/src/main/java/org/jabref/logic/openoffice/UndefinedParagraphFormatException.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.jabref.logic.openoffice; - -/** - * Exception used to indicate that the plugin attempted to set a paragraph format that is not defined in the current OpenOffice document. - */ -public class UndefinedParagraphFormatException extends Exception { - - private final String formatName; - - public UndefinedParagraphFormatException(String formatName) { - super(); - this.formatName = formatName; - } - - public String getFormatName() { - return formatName; - } -} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoStyle.java b/src/main/java/org/jabref/logic/openoffice/UnoStyle.java index d6518d33f25..96f67e4dbe0 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoStyle.java @@ -15,18 +15,26 @@ */ public class UnoStyle { + public static final String CHARACTER_STYLES = "CharacterStyles"; + public static final String PARAGRAPH_STYLES = "ParagraphStyles"; + private UnoStyle() { } private static Optional getStyleFromFamily(XTextDocument doc, String familyName, String styleName) throws - NoSuchElementException, WrappedTargetException { XStyleFamiliesSupplier fss = UnoCast.unoQI(XStyleFamiliesSupplier.class, doc); XNameAccess fs = UnoCast.unoQI(XNameAccess.class, fss.getStyleFamilies()); - XNameContainer xFamily = UnoCast.unoQI(XNameContainer.class, fs.getByName(familyName)); + XNameContainer xFamily; + try { + xFamily = UnoCast.unoQI(XNameContainer.class, fs.getByName(familyName)); + } catch (NoSuchElementException ex) { + String msg = String.format("Style family name '%s' is not recognized", familyName); + throw new RuntimeException(msg, ex); + } try { Object s = xFamily.getByName(styleName); @@ -39,31 +47,33 @@ private static Optional getStyleFromFamily(XTextDocument doc, public static Optional getParagraphStyle(XTextDocument doc, String styleName) throws - NoSuchElementException, WrappedTargetException { - return getStyleFromFamily(doc, "ParagraphStyles", styleName); + return getStyleFromFamily(doc, PARAGRAPH_STYLES, styleName); } public static Optional getCharacterStyle(XTextDocument doc, String styleName) throws - NoSuchElementException, WrappedTargetException { - return getStyleFromFamily(doc, "CharacterStyles", styleName); + return getStyleFromFamily(doc, CHARACTER_STYLES, styleName); } - public static Optional getInternalNameOfParagraphStyle(XTextDocument doc, String name) + public static Optional getInternalNameOfStyle(XTextDocument doc, String familyName, + String name) throws - NoSuchElementException, WrappedTargetException { - return (getParagraphStyle(doc, name) + return (getStyleFromFamily(doc, familyName, name) .map(e -> e.getName())); } + public static Optional getInternalNameOfParagraphStyle(XTextDocument doc, String name) + throws + WrappedTargetException { + return getInternalNameOfStyle(doc, PARAGRAPH_STYLES, name); + } + public static Optional getInternalNameOfCharacterStyle(XTextDocument doc, String name) throws - NoSuchElementException, WrappedTargetException { - return (getCharacterStyle(doc, name) - .map(e -> e.getName())); + return getInternalNameOfStyle(doc, CHARACTER_STYLES, name); } } diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java new file mode 100644 index 00000000000..a54b42f9184 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -0,0 +1,68 @@ +package org.jabref.logic.openoffice; + +import java.util.List; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.oostyle.OOProcess; +import org.jabref.model.database.BibDatabase; + +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextDocument; + +/* + * Update document: citation marks and bibliography + */ +public class Update { + + /* + * @return unresolvedKeys + */ + public static List updateDocument(XTextDocument doc, + OOFrontend fr, + List databases, + OOBibStyle style, + boolean doUpdateBibliography, + boolean alwaysAddCitedOnPages) + throws + JabRefException, + ConnectionLostException, + NoDocumentException, + com.sun.star.lang.IllegalArgumentException, + PropertyVetoException, + UnknownPropertyException, + WrappedTargetException, + NoSuchElementException, + CreationException { + + final boolean useLockControllers = true; + + fr.imposeGlobalOrder(doc); + OOProcess.ProduceCitationMarkersResult x = + OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); + + try { + if (useLockControllers) { + UnoScreenRefresh.lockControllers(doc); + } + + UpdateCitationMarkers.applyNewCitationMarkers(doc, fr, x.citMarkers, style); + + if (doUpdateBibliography) { + UpdateBibliography.rebuildBibTextSection(doc, + style, + fr, + x.getBibliography(), + alwaysAddCitedOnPages); + } + return x.getUnresolvedKeys(); + } finally { + if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { + UnoScreenRefresh.unlockControllers(doc); + } + } + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java new file mode 100644 index 00000000000..2dadab8d478 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -0,0 +1,149 @@ +package org.jabref.logic.openoffice; + +import java.util.Optional; + +import org.jabref.logic.oostyle.CitedKeys; +import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.oostyle.OOFormatBibliography; +import org.jabref.model.oostyle.OOFormattedText; + +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; +import com.sun.star.text.XTextSection; + +/* + * Update document: citation marks and bibliography + */ +public class UpdateBibliography { + + private static final String BIB_SECTION_NAME = "JR_bib"; + private static final String BIB_SECTION_END_NAME = "JR_bib_end"; + /* ************************************************** + * + * Bibliography: needs uniqueLetters or numbers + * + * **************************************************/ + + /** + * Rebuilds the bibliography. + * + * Note: assumes fresh `jabRefReferenceMarkNamesSortedByPosition` + * if `style.isSortByPosition()` + */ + static void rebuildBibTextSection(XTextDocument doc, + OOBibStyle style, + OOFrontend fr, + CitedKeys bibliography, + boolean alwaysAddCitedOnPages) + throws + NoSuchElementException, + WrappedTargetException, + IllegalArgumentException, + CreationException, + PropertyVetoException, + UnknownPropertyException, + NoDocumentException { + + clearBibTextSectionContent2(doc); + + populateBibTextSection(doc, + fr, + bibliography, + style, + alwaysAddCitedOnPages); + } + + /** + * Insert a paragraph break and create a text section for the bibliography. + * + * Only called from `clearBibTextSectionContent2` + */ + private static void createBibTextSection2(XTextDocument doc) + throws + IllegalArgumentException, + CreationException { + + // Always creating at the end of the document. + // Alternatively, we could receive a cursor. + XTextCursor textCursor = doc.getText().createTextCursor(); + textCursor.gotoEnd(false); + UnoTextSection.create(doc, + BIB_SECTION_NAME, + textCursor, + false); + } + + /** + * Find and clear the text section BIB_SECTION_NAME to "", + * or create it. + * + * Only called from: `rebuildBibTextSection` + * + */ + private static void clearBibTextSectionContent2(XTextDocument doc) + throws + WrappedTargetException, + IllegalArgumentException, + CreationException, + NoDocumentException { + + Optional sectionRange = UnoTextSection.getAnchor(doc, BIB_SECTION_NAME); + if (sectionRange.isEmpty()) { + createBibTextSection2(doc); + return; + } else { + // Clear it + XTextCursor cursor = doc.getText().createTextCursorByRange(sectionRange.get()); + cursor.setString(""); + } + } + + /** + * Only called from: `rebuildBibTextSection` + * + * Assumes the section named BIB_SECTION_NAME exists. + */ + private static void populateBibTextSection(XTextDocument doc, + OOFrontend fr, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) + throws + NoSuchElementException, + NoDocumentException, + WrappedTargetException, + PropertyVetoException, + UnknownPropertyException, + IllegalArgumentException, + CreationException { + + XTextSection section = (UnoTextSection.getByName(doc, BIB_SECTION_NAME) + .orElseThrow(RuntimeException::new)); + + XTextCursor cursor = doc.getText().createTextCursorByRange(section.getAnchor()); + + // emit the title of the bibliography + OOFormattedTextIntoOO.removeDirectFormatting(cursor); + OOFormattedText bibliographyText = OOFormatBibliography.formatBibliography(fr.citationGroups, + bibliography, + style, + alwaysAddCitedOnPages); + OOFormattedTextIntoOO.write(doc, cursor, bibliographyText); + cursor.collapseToEnd(); + + // remove the inital empty paragraph from the section. + XTextCursor initialParagraph = doc.getText().createTextCursorByRange(section.getAnchor()); + initialParagraph.collapseToStart(); + initialParagraph.goRight((short) 1, true); + initialParagraph.setString(""); + + UnoBookmark.create(doc, BIB_SECTION_END_NAME, cursor, true); + cursor.collapseToEnd(); + } + +} diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java new file mode 100644 index 00000000000..161b938ea33 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -0,0 +1,176 @@ +package org.jabref.logic.openoffice; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.oostyle.CitationGroup; +import org.jabref.logic.oostyle.CitationGroups; +import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OOFormattedText; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; + +/* + * Update document: citation marks and bibliography + */ +public class UpdateCitationMarkers { + /** + * Visit each reference mark in referenceMarkNames, overwrite its + * text content. + * + * After each fillCitationMarkInCursor call check if we lost the + * BIB_SECTION_NAME bookmark and recreate it if we did. + * + * @param fr + * + * @param citMarkers Corresponding text for each reference mark, + * that replaces the old text. + * + * @param style Bibliography style to use. + * + */ + static void applyNewCitationMarkers(XTextDocument doc, + OOFrontend fr, + Map citMarkers, + OOBibStyle style) + throws + NoDocumentException, + UnknownPropertyException, + CreationException, + WrappedTargetException, + PropertyVetoException, + NoSuchElementException, + JabRefException { + + // checkStylesExistInTheDocument(style, doc); + + CitationGroups cgs = fr.citationGroups; + + for (Map.Entry kv : citMarkers.entrySet()) { + + CitationGroupID cgid = kv.getKey(); + Objects.requireNonNull(cgid); + + OOFormattedText citationText = kv.getValue(); + Objects.requireNonNull(citationText); + + CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + + boolean withText = (cg.citationType != InTextCitationType.INVISIBLE_CIT); + + if (withText) { + + XTextCursor cursor = fr.getFillCursorForCitationGroup(doc, cgid); + + fillCitationMarkInCursor(doc, cursor, citationText, withText, style); + + fr.cleanFillCursorForCitationGroup(doc, cgid); + } + + } + } + + public static void fillCitationMarkInCursor(XTextDocument doc, + XTextCursor cursor, + OOFormattedText citationText, + boolean withText, + OOBibStyle style) + throws + UnknownPropertyException, + PropertyVetoException, + WrappedTargetException, + NoSuchElementException, + CreationException, + IllegalArgumentException { + + Objects.requireNonNull(cursor); + Objects.requireNonNull(citationText); + Objects.requireNonNull(style); + + if (withText) { + OOFormattedText citationText2 = style.decorateCitationMarker(citationText); + // inject a ZERO_WIDTH_SPACE to hold the initial character format + final String ZERO_WIDTH_SPACE = "\u200b"; + citationText2 = OOFormattedText.fromString(ZERO_WIDTH_SPACE + citationText2.asString()); + OOFormattedTextIntoOO.write(doc, cursor, citationText2); + } else { + cursor.setString(""); + } + } + + /** + * Inserts a citation group in the document: creates and fills it. + * + * @param citationKeys BibTeX keys of + * @param pageInfosForCitations + * @param citationType + * + * @param citationText Text for the citation. A citation mark or + * placeholder if not yet available. + * + * @param position Location to insert at. + * @param withText If false, citationText is not shown. + * @param style + * @param insertSpaceAfter A space inserted after the reference + * mark makes it easier to separate from the text + * coming after. But is not wanted when we recreate a + * reference mark. + */ + public static void createAndFillCitationGroup(OOFrontend fr, + XTextDocument doc, + List citationKeys, + List pageInfosForCitations, + InTextCitationType citationType, + OOFormattedText citationText, + XTextCursor position, + boolean withText, + OOBibStyle style, + boolean insertSpaceAfter) + throws + UnknownPropertyException, + NotRemoveableException, + PropertyExistException, + PropertyVetoException, + WrappedTargetException, + PropertyVetoException, + IllegalArgumentException, + CreationException, + NoDocumentException, + IllegalTypeException, + NoSuchElementException { + + Objects.requireNonNull(pageInfosForCitations); + if (pageInfosForCitations.size() != citationKeys.size()) { + throw new RuntimeException("pageInfosForCitations.size != citationKeys.size"); + } + CitationGroupID cgid = fr.createCitationGroup(doc, + citationKeys, + pageInfosForCitations, + citationType, + position, + insertSpaceAfter, + !withText /* withoutBrackets */); + + if (withText) { + XTextCursor c2 = fr.getFillCursorForCitationGroup(doc, cgid); + + UpdateCitationMarkers.fillCitationMarkInCursor(doc, c2, citationText, withText, style); + + fr.cleanFillCursorForCitationGroup(doc, cgid); + } + position.collapseToEnd(); + } + +} diff --git a/src/main/java/org/jabref/logic/openoffice/VoidResult.java b/src/main/java/org/jabref/logic/openoffice/VoidResult.java index 69148a21307..a95b1cc0e31 100644 --- a/src/main/java/org/jabref/logic/openoffice/VoidResult.java +++ b/src/main/java/org/jabref/logic/openoffice/VoidResult.java @@ -2,6 +2,7 @@ import java.util.Optional; import java.util.function.Consumer; +import java.util.function.Function; /* * error cannot be null @@ -39,5 +40,13 @@ public VoidResult ifError(Consumer fun) { } return this; } + + public VoidResult mapError(Function fun) { + if (isError()) { + return Error(fun.apply(getError())); + } else { + return OK(); + } + } } diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 06a3a00cbfa..9cd33e95d60 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1035,20 +1035,37 @@ Select\ Writer\ document=Select Writer document Sync\ OpenOffice/LibreOffice\ bibliography=Sync OpenOffice/LibreOffice bibliography Select\ which\ open\ Writer\ document\ to\ work\ on=Select which open Writer document to work on Connected\ to\ document=Connected to document + +Could\ not\ connect\ to\ any\ Writer\ document.\ Please\ make\ sure\ a\ document\ is\ open\ before\ using\ the\ 'Select\ Writer\ document'\ button\ to\ connect\ to\ it.=Could not connect to any Writer document. Please make sure a document is open before using the 'Select Writer document' button to connect to it. + +No\ Writer\ documents\ found=No Writer documents found + Insert\ a\ citation\ without\ text\ (the\ entry\ will\ appear\ in\ the\ reference\ list)=Insert a citation without text (the entry will appear in the reference list) Cite\ selected\ entries\ with\ extra\ information=Cite selected entries with extra information Ensure\ that\ the\ bibliography\ is\ up-to-date=Ensure that the bibliography is up-to-date Your\ OpenOffice/LibreOffice\ document\ references\ the\ citation\ key\ '%0',\ which\ could\ not\ be\ found\ in\ your\ current\ library.=Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library. +This\ operation\ requires\ a\ bibliography\ database.=This operation requires a bibliography database. + +Your\ OpenOffice/LibreOffice\ document\ references\ at\ least\ %0\ citation\ keys\ which\ could\ not\ be\ found\ in\ your\ current\ library.\ Some\ of\ these\ are\ %1.=Your OpenOffice/LibreOffice document references at least %0 citation keys which could not be found in your current library. Some of these are %1. + +Your\ OpenOffice/LibreOffice\ document\ references\ no\ citation\ keys\ which\ could\ also\ be\ found\ in\ your\ current\ library.=Your OpenOffice/LibreOffice document references no citation keys which could also be found in your current library. + Unable\ to\ synchronize\ bibliography=Unable to synchronize bibliography Combine\ pairs\ of\ citations\ that\ are\ separated\ by\ spaces\ only=Combine pairs of citations that are separated by spaces only Autodetection\ failed=Autodetection failed Please\ wait...=Please wait... Connection\ lost=Connection lost -Connection\ to\ document\ lost=Connection to document lost -The\ paragraph\ format\ is\ controlled\ by\ the\ property\ 'ReferenceParagraphFormat'\ or\ 'ReferenceHeaderParagraphFormat'\ in\ the\ style\ file.=The paragraph format is controlled by the property 'ReferenceParagraphFormat' or 'ReferenceHeaderParagraphFormat' in the style file. -The\ character\ format\ is\ controlled\ by\ the\ citation\ property\ 'CitationCharacterFormat'\ in\ the\ style\ file.=The character format is controlled by the citation property 'CitationCharacterFormat' in the style file. + +Could\ not\ update\ bibliography=Could not update bibliography +Not\ connected\ to\ document=Not connected to document +Problem\ combining\ cite\ markers=Problem combining cite markers +Problem\ generating\ new\ database.=Problem generating new database. +Unable\ to\ reload\ style\ file=Unable to reload style file + +Problem\ during\ separating\ cite\ markers=Problem during separating cite markers + Automatically\ sync\ bibliography\ when\ inserting\ citations=Automatically sync bibliography when inserting citations Look\ up\ BibTeX\ entries\ in\ the\ active\ tab\ only=Look up BibTeX entries in the active tab only Look\ up\ BibTeX\ entries\ in\ all\ open\ libraries=Look up BibTeX entries in all open libraries @@ -1145,7 +1162,7 @@ Toggle\ print\ status=Toggle print status Update\ keywords=Update keywords Write\ values\ of\ special\ fields\ as\ separate\ fields\ to\ BibTeX=Write values of special fields as separate fields to BibTeX Connection\ to\ OpenOffice/LibreOffice\ has\ been\ lost.\ Please\ make\ sure\ OpenOffice/LibreOffice\ is\ running,\ and\ try\ to\ reconnect.=Connection to OpenOffice/LibreOffice has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect. -Connection\ to\ OpenOffice/LibreOffice\ document\ has\ been\ lost.\ Please\ make\ sure\ OpenOffice/LibreOffice\ is\ running,\ and\ try\ to\ reconnect.=Connection to OpenOffice/LibreOffice document has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect. + JabRef\ will\ send\ at\ least\ one\ request\ per\ entry\ to\ a\ publisher.=JabRef will send at least one request per entry to a publisher. Correct\ the\ entry,\ and\ reopen\ editor\ to\ display/edit\ source.=Correct the entry, and reopen editor to display/edit source. Could\ not\ connect\ to\ running\ OpenOffice/LibreOffice.=Could not connect to running OpenOffice/LibreOffice. @@ -1159,8 +1176,6 @@ To\ disable\ the\ memory\ stick\ mode\ rename\ or\ remove\ the\ jabref.xml\ file Unable\ to\ connect.\ One\ possible\ reason\ is\ that\ JabRef\ and\ OpenOffice/LibreOffice\ are\ not\ both\ running\ in\ either\ 32\ bit\ mode\ or\ 64\ bit\ mode.=Unable to connect. One possible reason is that JabRef and OpenOffice/LibreOffice are not both running in either 32 bit mode or 64 bit mode. Delimiter(s)=Delimiter(s) When\ downloading\ files,\ or\ moving\ linked\ files\ to\ the\ file\ directory,\ prefer\ the\ BIB\ file\ location\ rather\ than\ the\ file\ directory\ set\ above=When downloading files, or moving linked files to the file directory, prefer the BIB file location rather than the file directory set above -Your\ style\ file\ specifies\ the\ character\ format\ '%0',\ which\ is\ undefined\ in\ your\ current\ OpenOffice/LibreOffice\ document.=Your style file specifies the character format '%0', which is undefined in your current OpenOffice/LibreOffice document. -Your\ style\ file\ specifies\ the\ paragraph\ format\ '%0',\ which\ is\ undefined\ in\ your\ current\ OpenOffice/LibreOffice\ document.=Your style file specifies the paragraph format '%0', which is undefined in your current OpenOffice/LibreOffice document. Searching...=Searching... Please\ enter\ a\ search\ string=Please enter a search string @@ -1545,10 +1560,10 @@ No\ bibliography\ style\ is\ selected\ for\ citation.=No bibliography style is s No\ database=No database No\ entries\ selected\ for\ citation=No entries selected for citation Open\ one\ before\ citing.=Open one before citing. -Please\ select\ one.=Please select one. + Select\ one\ before\ citing.=Select one before citing. Select\ some\ before\ citing.=Select some before citing. -This\ operation\ requires\ a\ style.=This operation requires a style. + Found\ identical\ ranges=Found identical ranges Found\ overlapping\ ranges=Found overlapping ranges Found\ touching\ ranges=Found touching ranges @@ -1821,9 +1836,6 @@ Could\ not\ connect\ to\ Vim\ server.\ Make\ sure\ that\ Vim\ is\ running\ with\ Could\ not\ connect\ to\ a\ running\ gnuserv\ process.\ Make\ sure\ that\ Emacs\ or\ XEmacs\ is\ running,\ and\ that\ the\ server\ has\ been\ started\ (by\ running\ the\ command\ 'server-start'/'gnuserv-start').=Could not connect to a running gnuserv process. Make sure that Emacs or XEmacs is running, and that the server has been started (by running the command 'server-start'/'gnuserv-start'). Error\ pushing\ entries=Error pushing entries -Undefined\ character\ format=Undefined character format -Undefined\ paragraph\ format=Undefined paragraph format - Edit\ Preamble=Edit Preamble Markings=Markings Use\ selected\ instance=Use selected instance @@ -2309,8 +2321,6 @@ Separate\ merged\ citations=Separate merged citations Separate\ citations=Separate citations Unprotect\ terms=Unprotect terms -Error\ connecting\ to\ Writer\ document=Error connecting to Writer document -You\ need\ to\ open\ Writer\ with\ a\ document\ before\ connecting=You need to open Writer with a document before connecting Generate\ a\ new\ key\ for\ imported\ entries\ (overwriting\ their\ default)=Generate a new key for imported entries (overwriting their default) Import\ settings=Import settings From 647da468b1aa9d5837437fd860cea4df85944b84 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 00:06:25 +0200 Subject: [PATCH 0712/1068] temporarily disable HelpFileTest --- src/test/java/org/jabref/logic/help/HelpFileTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/test/java/org/jabref/logic/help/HelpFileTest.java b/src/test/java/org/jabref/logic/help/HelpFileTest.java index 006c0383d0e..6c7f6ab85b8 100644 --- a/src/test/java/org/jabref/logic/help/HelpFileTest.java +++ b/src/test/java/org/jabref/logic/help/HelpFileTest.java @@ -8,11 +8,13 @@ import org.jabref.logic.net.URLDownload; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; +@Disabled("help links changed, waiting for upstream to update") class HelpFileTest { private final String jabrefHelp = "https://docs.jabref.org/"; From d0a92d6b1a72309b6f16f7a64c64d6d02c35f14d Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 00:50:23 +0200 Subject: [PATCH 0713/1068] add EditMerge.java --- .../org/jabref/gui/openoffice/OOBibBase.java | 342 +---------------- .../gui/openoffice/OpenOfficePanel.java | 2 +- .../jabref/logic/openoffice/EditMerge.java | 343 ++++++++++++++++++ 3 files changed, 362 insertions(+), 325 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/EditMerge.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 207960ab5b3..8fd860f1189 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -23,6 +23,7 @@ import org.jabref.logic.openoffice.ConnectionLostException; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.EditInsert; +import org.jabref.logic.openoffice.EditMerge; import org.jabref.logic.openoffice.ManageCitations; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.NoDocumentFoundException; @@ -33,7 +34,6 @@ import org.jabref.logic.openoffice.UnoRedlines; import org.jabref.logic.openoffice.UnoScreenRefresh; import org.jabref.logic.openoffice.UnoStyle; -import org.jabref.logic.openoffice.UnoTextRange; import org.jabref.logic.openoffice.UnoUndo; import org.jabref.logic.openoffice.Update; import org.jabref.logic.openoffice.UpdateCitationMarkers; @@ -188,14 +188,6 @@ boolean testDialog(String title, VoidResult... results) { return testDialog(collectResults(title, rs)); } - private Optional getOrDialog(String title, Result res) { - if (res.isOK()) { - return res.getOptional(); - } - showDialog(title, res.getError()); - return Optional.empty(); - } - /* * * ManageCitationsDialogView @@ -260,8 +252,9 @@ public Optional> guiActionGetCitationEntries() { public void guiActionApplyCitationEntries(List citationEntries) { final String title = Localization.lang("Problem modifying citation"); - Optional odoc = getOrDialog(title, getXTextDocument()); - if (odoc.isEmpty()) { + + Result odoc = getXTextDocument(); + if (testDialog(title, odoc.asVoidResult())) { return; } XTextDocument doc = odoc.get(); @@ -352,7 +345,10 @@ public void guiActionInsertEntry(List entries, final String title = "Could not insert entry"; Result odoc = getXTextDocument(); - if (testDialog(title, odoc.asVoidResult(), styleIsRequired(style))) { + if (testDialog(title, + odoc.asVoidResult(), + styleIsRequired(style), + databaseIsRequired(allBases, OOError::noDataBaseIsOpenForCiting))) { return; } @@ -452,22 +448,11 @@ public void guiActionInsertEntry(List entries, } } - /* ************************* - * - * GUI level - * - * *************************/ - - /* - * GUI: Manage citations - */ - /** * GUI action "Merge citations" * */ - public void combineCiteMarkers(List databases, - OOBibStyle style) + public void guiActionMergeCitationGroups(List databases, OOBibStyle style) throws IOException, WrappedTargetException, @@ -493,11 +478,6 @@ public void combineCiteMarkers(List databases, return; } - Objects.requireNonNull(databases); - Objects.requireNonNull(style); - - final boolean useLockControllers = true; - XTextDocument doc = odoc.get(); if (testDialog(title, @@ -511,306 +491,19 @@ public void combineCiteMarkers(List databases, try { UnoUndo.enterUndoContext(doc, "Merge citations"); - boolean madeModifications = false; - - List referenceMarkNames = - fr.getCitationGroupIDsSortedWithinPartitions(doc, - false /* mapFootnotesToFootnoteMarks */); - - final int nRefMarks = referenceMarkNames.size(); - - try { - - if (useLockControllers) { - UnoScreenRefresh.lockControllers(doc); - } - - /* - * joinableGroups collects lists of CitationGroup values - * that we think are joinable. - * - * joinableGroupsCursors provides the range for each group - */ - List> joinableGroups = new ArrayList<>(); - List joinableGroupsCursors = new ArrayList<>(); - - // Since we only join groups with identical citationTypes, we - // can get citationType from the first element of each - // joinableGroup. - - if (referenceMarkNames.size() > 0) { - // current group of CitationGroup values - List currentGroup = new ArrayList<>(); - XTextCursor currentGroupCursor = null; - XTextCursor cursorBetween = null; - CitationGroup prev = null; - XTextRange prevRange = null; - - for (CitationGroupID cgid : referenceMarkNames) { - CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); - - XTextRange currentRange = (fr - .getMarkRange(doc, cgid) - .orElseThrow(RuntimeException::new)); - - boolean addToGroup = true; - /* - * Decide if we add cg to the group - */ - - // Only combine (Author 2000) type citations - if (cg.citationType != InTextCitationType.AUTHORYEAR_PAR) { - addToGroup = false; - } - - // Even if we combine AUTHORYEAR_INTEXT citations, we - // would not mix them with AUTHORYEAR_PAR - if (addToGroup && (prev != null)) { - if (cg.citationType != prev.citationType) { - addToGroup = false; - } - } - - if (addToGroup && prev != null) { - Objects.requireNonNull(prevRange); - Objects.requireNonNull(currentRange); - if (!UnoTextRange.comparables(prevRange, currentRange)) { - addToGroup = false; - } else { - - int textOrder = UnoTextRange.compareStarts(prevRange, currentRange); - - if (textOrder != (-1)) { - String msg = - String.format("combineCiteMarkers:" - + " \"%s\" supposed to be followed by \"%s\"," - + " but %s", - prevRange.getString(), - currentRange.getString(), - ((textOrder == 0) - ? "they start at the same position" - : ("the start of the latter precedes" - + " the start of the first"))); - LOGGER.warn(msg); - addToGroup = false; - } - } - } - - if (addToGroup && (cursorBetween != null)) { - Objects.requireNonNull(currentGroupCursor); - // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() - if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { - String msg = ("combineCiteMarkers:" - + " cursorBetween.end != currentGroupCursor.end"); - throw new RuntimeException(msg); - } - - XTextRange rangeStart = currentRange.getStart(); - - boolean couldExpand = true; - - XTextCursor thisCharCursor = - (currentRange.getText() - .createTextCursorByRange(cursorBetween.getEnd())); - - while (couldExpand && - (UnoTextRange.compareEnds(cursorBetween, rangeStart) < 0)) { - couldExpand = cursorBetween.goRight((short) 1, true); - currentGroupCursor.goRight((short) 1, true); - // - thisCharCursor.goRight((short) 1, true); - String thisChar = thisCharCursor.getString(); - thisCharCursor.collapseToEnd(); - if (thisChar.isEmpty() - || thisChar.equals("\n") - || !thisChar.trim().isEmpty()) { - couldExpand = false; - } - if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { - String msg = ("combineCiteMarkers:" - + " cursorBetween.end != currentGroupCursor.end" - + " (during expand)"); - throw new RuntimeException(msg); - } - } // while - - if (!couldExpand) { - addToGroup = false; - } - } - - /* - * Even if we do not add it to an existing group, - * we might use it to start a new group. - * - * Can it start a new group? - */ - boolean canStartGroup = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); - - if (!addToGroup) { - // close currentGroup - if (currentGroup.size() > 1) { - joinableGroups.add(currentGroup); - joinableGroupsCursors.add(currentGroupCursor); - } - // Start a new, empty group - currentGroup = new ArrayList<>(); - currentGroupCursor = null; - cursorBetween = null; - prev = null; - prevRange = null; - } - - if (addToGroup || canStartGroup) { - // Add the current entry to a group. - currentGroup.add(cg); - // ... and start new cursorBetween - // Set up cursorBetween - // - XTextRange rangeEnd = currentRange.getEnd(); - cursorBetween = - currentRange.getText().createTextCursorByRange(rangeEnd); - // If new group, create currentGroupCursor - if (currentGroupCursor == null) { - currentGroupCursor = (currentRange.getText() - .createTextCursorByRange(currentRange.getStart())); - } - // include self in currentGroupCursor - currentGroupCursor.goRight((short) (currentRange.getString().length()), true); - - if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { - /* - * A problem discovered using this check: - * when viewing the document in - * two-pages-side-by-side mode, our visual - * firstAppearanceOrder follows the visual - * ordering on the screen. The problem - * this caused: it sees a citation on the - * 2nd line of the 1st page as appearing - * after one at the 1st line of 2nd - * page. Since we create cursorBetween at - * the end of range1Full (on 1st page), it - * is now BEFORE currentGroupCursor (on - * 2nd page). - */ - String msg = - "combineCiteMarkers: " - + "cursorBetween.end != currentGroupCursor.end" - + String.format(" (after %s)", - addToGroup ? "addToGroup" : "startGroup") - + (addToGroup - ? String.format(" comparisonResult: %d\n" - + "cursorBetween: '%s'\n" - + "currentRange: '%s'\n" - + "currentGroupCursor: '%s'\n", - UnoTextRange.compareEnds(cursorBetween, - currentGroupCursor), - cursorBetween.getString(), - currentRange.getString(), - currentGroupCursor.getString()) - : ""); - throw new RuntimeException(msg); - } - prev = cg; - prevRange = currentRange; - } - } // for cgid - - // close currentGroup - if (currentGroup.size() > 1) { - joinableGroups.add(currentGroup); - joinableGroupsCursors.add(currentGroupCursor); - } - } // if (referenceMarkNames.size() > 0) - - /* - * Now we can process the joinable groups - */ - for (int gi = 0; gi < joinableGroups.size(); gi++) { - - List joinableGroup = joinableGroups.get(gi); - /* - * Join those in joinableGroups.get(gi) - */ - - // - // Note: we are taking ownership of the citations (by - // adding to newGroupCitations, then removing - // the original CitationGroup values) - - List newGroupCitations = new ArrayList<>(); - for (CitationGroup rk : joinableGroup) { - newGroupCitations.addAll(rk.citationsInStorageOrder); - } - - InTextCitationType citationType = joinableGroup.get(0).citationType; - - // cgPageInfos belong to the CitationGroup (DataModel JabRef52), - // but it is not clear how should we handle them here. - // We delegate the problem to the backend. - List pageInfosForCitations = - fr.backend.combinePageInfos(joinableGroup); - - // Remove the old citation groups from the document. - for (int gj = 0; gj < joinableGroup.size(); gj++) { - fr.removeCitationGroups(joinableGroup, doc); - } - - XTextCursor textCursor = joinableGroupsCursors.get(gi); - // Also remove the spaces between. - textCursor.setString(""); - - List citationKeys = (newGroupCitations.stream() - .map(cit -> cit.citationKey) - .collect(Collectors.toList())); - - // Insert reference mark: - - /* insertSpaceAfter: no, it is already there (or could - * be) - */ - boolean insertSpaceAfter = false; - UpdateCitationMarkers.createAndFillCitationGroup(fr, - doc, - citationKeys, - pageInfosForCitations, - citationType, - OOFormattedText.fromString("tmp"), - textCursor, - true, // withText - style, - insertSpaceAfter); - } // for gi - - madeModifications = (joinableGroups.size() > 0); - - } finally { - if (useLockControllers) { - UnoScreenRefresh.unlockControllers(doc); - } - } - - if (madeModifications) { - UnoCrossRef.refresh(doc); - OOFrontend fr2 = new OOFrontend(doc); - Update.updateDocument(doc, - fr2, - databases, - style, - false, /* doUpdateBibliography */ - this.alwaysAddCitedOnPages); - } - + EditMerge.mergeCitationGroups(doc, + fr, + databases, + style); } finally { UnoUndo.leaveUndoContext(doc); } - } // combineCiteMarkers + } // MergeCitationGroups /** * GUI action "Separate citations". * - * Do the opposite of combineCiteMarkers. + * Do the opposite of MergeCitationGroups. * Combined markers are split, with a space inserted between. */ public void unCombineCiteMarkers(List databases, @@ -1170,11 +863,12 @@ private static VoidResult checkIfOpenOfficeIsRecordingChanges2(XTextDoc public boolean guiCheckIfOpenOfficeIsRecordingChanges(String title) { final boolean FAIL = true; final boolean PASS = false; - Optional odoc = getOrDialog(title, getXTextDocument()); - if (odoc.isEmpty()) { + Result odoc = getXTextDocument(); + if (testDialog(title, odoc.asVoidResult())) { return FAIL; } XTextDocument doc = odoc.get(); + if (testDialog(title, checkIfOpenOfficeIsRecordingChanges2(doc))) { return FAIL; } diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 019d0ca50a9..8a43f2475e2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -239,7 +239,7 @@ private void initPanel() { final String title = Localization.lang("Problem combining cite markers"); // check usedStylesExistInDocument try { - ooBase.combineCiteMarkers(getBaseList(), style); + ooBase.guiActionMergeCitationGroups(getBaseList(), style); } catch (JabRefException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (NoDocumentException ex) { diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java new file mode 100644 index 00000000000..688f544bcb3 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -0,0 +1,343 @@ +package org.jabref.logic.openoffice; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.oostyle.Citation; +import org.jabref.logic.oostyle.CitationGroup; +import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OOFormattedText; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; +import com.sun.star.util.InvalidStateException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EditMerge { + + private static final Logger LOGGER = LoggerFactory.getLogger(EditMerge.class); + + public static void mergeCitationGroups(XTextDocument doc, + OOFrontend fr, + List databases, + OOBibStyle style) + throws + CreationException, + IllegalArgumentException, + IllegalTypeException, + InvalidStateException, + JabRefException, + NoDocumentException, + NoSuchElementException, + NotRemoveableException, + PropertyExistException, + PropertyVetoException, + UnknownPropertyException, + WrappedTargetException { + + final boolean useLockControllers = true; + boolean madeModifications = false; + + List referenceMarkNames = + fr.getCitationGroupIDsSortedWithinPartitions(doc, + false /* mapFootnotesToFootnoteMarks */); + + final int nRefMarks = referenceMarkNames.size(); + + try { + + if (useLockControllers) { + UnoScreenRefresh.lockControllers(doc); + } + + /* + * joinableGroups collects lists of CitationGroup values + * that we think are joinable. + * + * joinableGroupsCursors provides the range for each group + */ + List> joinableGroups = new ArrayList<>(); + List joinableGroupsCursors = new ArrayList<>(); + + // Since we only join groups with identical citationTypes, we + // can get citationType from the first element of each + // joinableGroup. + + if (referenceMarkNames.size() > 0) { + // current group of CitationGroup values + List currentGroup = new ArrayList<>(); + XTextCursor currentGroupCursor = null; + XTextCursor cursorBetween = null; + CitationGroup prev = null; + XTextRange prevRange = null; + + for (CitationGroupID cgid : referenceMarkNames) { + CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); + + XTextRange currentRange = (fr + .getMarkRange(doc, cgid) + .orElseThrow(RuntimeException::new)); + + boolean addToGroup = true; + /* + * Decide if we add cg to the group + */ + + // Only combine (Author 2000) type citations + if (cg.citationType != InTextCitationType.AUTHORYEAR_PAR) { + addToGroup = false; + } + + // Even if we combine AUTHORYEAR_INTEXT citations, we + // would not mix them with AUTHORYEAR_PAR + if (addToGroup && (prev != null)) { + if (cg.citationType != prev.citationType) { + addToGroup = false; + } + } + + if (addToGroup && prev != null) { + Objects.requireNonNull(prevRange); + Objects.requireNonNull(currentRange); + if (!UnoTextRange.comparables(prevRange, currentRange)) { + addToGroup = false; + } else { + int textOrder = UnoTextRange.compareStarts(prevRange, currentRange); + if (textOrder != (-1)) { + String msg = + String.format("MergeCitationGroups:" + + " \"%s\" supposed to be followed by \"%s\"," + + " but %s", + prevRange.getString(), + currentRange.getString(), + ((textOrder == 0) + ? "they start at the same position" + : ("the start of the latter precedes" + + " the start of the first"))); + LOGGER.warn(msg); + addToGroup = false; + } + } + } + + if (addToGroup && (cursorBetween != null)) { + Objects.requireNonNull(currentGroupCursor); + // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() + if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { + String msg = ("MergeCitationGroups:" + + " cursorBetween.end != currentGroupCursor.end"); + throw new RuntimeException(msg); + } + + XTextRange rangeStart = currentRange.getStart(); + + boolean couldExpand = true; + + XTextCursor thisCharCursor = + (currentRange.getText() + .createTextCursorByRange(cursorBetween.getEnd())); + + while (couldExpand && + (UnoTextRange.compareEnds(cursorBetween, rangeStart) < 0)) { + couldExpand = cursorBetween.goRight((short) 1, true); + currentGroupCursor.goRight((short) 1, true); + // + thisCharCursor.goRight((short) 1, true); + String thisChar = thisCharCursor.getString(); + thisCharCursor.collapseToEnd(); + if (thisChar.isEmpty() + || thisChar.equals("\n") + || !thisChar.trim().isEmpty()) { + couldExpand = false; + } + if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { + String msg = ("MergeCitationGroups:" + + " cursorBetween.end != currentGroupCursor.end" + + " (during expand)"); + throw new RuntimeException(msg); + } + } // while + + if (!couldExpand) { + addToGroup = false; + } + } + + /* + * Even if we do not add it to an existing group, + * we might use it to start a new group. + * + * Can it start a new group? + */ + boolean canStartGroup = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); + + if (!addToGroup) { + // close currentGroup + if (currentGroup.size() > 1) { + joinableGroups.add(currentGroup); + joinableGroupsCursors.add(currentGroupCursor); + } + // Start a new, empty group + currentGroup = new ArrayList<>(); + currentGroupCursor = null; + cursorBetween = null; + prev = null; + prevRange = null; + } + + if (addToGroup || canStartGroup) { + // Add the current entry to a group. + currentGroup.add(cg); + // ... and start new cursorBetween + // Set up cursorBetween + // + XTextRange rangeEnd = currentRange.getEnd(); + cursorBetween = + currentRange.getText().createTextCursorByRange(rangeEnd); + // If new group, create currentGroupCursor + if (currentGroupCursor == null) { + currentGroupCursor = (currentRange.getText() + .createTextCursorByRange(currentRange.getStart())); + } + // include self in currentGroupCursor + currentGroupCursor.goRight((short) (currentRange.getString().length()), true); + + if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { + /* + * A problem discovered using this check: + * when viewing the document in + * two-pages-side-by-side mode, our visual + * firstAppearanceOrder follows the visual + * ordering on the screen. The problem + * this caused: it sees a citation on the + * 2nd line of the 1st page as appearing + * after one at the 1st line of 2nd + * page. Since we create cursorBetween at + * the end of range1Full (on 1st page), it + * is now BEFORE currentGroupCursor (on + * 2nd page). + */ + String msg = + "MergeCitationGroups: " + + "cursorBetween.end != currentGroupCursor.end" + + String.format(" (after %s)", + addToGroup ? "addToGroup" : "startGroup") + + (addToGroup + ? String.format(" comparisonResult: %d\n" + + "cursorBetween: '%s'\n" + + "currentRange: '%s'\n" + + "currentGroupCursor: '%s'\n", + UnoTextRange.compareEnds(cursorBetween, + currentGroupCursor), + cursorBetween.getString(), + currentRange.getString(), + currentGroupCursor.getString()) + : ""); + throw new RuntimeException(msg); + } + prev = cg; + prevRange = currentRange; + } + } // for cgid + + // close currentGroup + if (currentGroup.size() > 1) { + joinableGroups.add(currentGroup); + joinableGroupsCursors.add(currentGroupCursor); + } + } // if (referenceMarkNames.size() > 0) + + /* + * Now we can process the joinable groups + */ + for (int gi = 0; gi < joinableGroups.size(); gi++) { + + List joinableGroup = joinableGroups.get(gi); + /* + * Join those in joinableGroups.get(gi) + */ + + // + // Note: we are taking ownership of the citations (by + // adding to newGroupCitations, then removing + // the original CitationGroup values) + + List newGroupCitations = new ArrayList<>(); + for (CitationGroup rk : joinableGroup) { + newGroupCitations.addAll(rk.citationsInStorageOrder); + } + + InTextCitationType citationType = joinableGroup.get(0).citationType; + + // cgPageInfos belong to the CitationGroup (DataModel JabRef52), + // but it is not clear how should we handle them here. + // We delegate the problem to the backend. + List pageInfosForCitations = + fr.backend.combinePageInfos(joinableGroup); + + // Remove the old citation groups from the document. + for (int gj = 0; gj < joinableGroup.size(); gj++) { + fr.removeCitationGroups(joinableGroup, doc); + } + + XTextCursor textCursor = joinableGroupsCursors.get(gi); + // Also remove the spaces between. + textCursor.setString(""); + + List citationKeys = (newGroupCitations.stream() + .map(cit -> cit.citationKey) + .collect(Collectors.toList())); + + // Insert reference mark: + + /* insertSpaceAfter: no, it is already there (or could + * be) + */ + boolean insertSpaceAfter = false; + UpdateCitationMarkers.createAndFillCitationGroup(fr, + doc, + citationKeys, + pageInfosForCitations, + citationType, + OOFormattedText.fromString("tmp"), + textCursor, + true, // withText + style, + insertSpaceAfter); + } // for gi + + madeModifications = (joinableGroups.size() > 0); + + } finally { + if (useLockControllers) { + UnoScreenRefresh.unlockControllers(doc); + } + } + + if (madeModifications) { + UnoCrossRef.refresh(doc); + OOFrontend fr2 = new OOFrontend(doc); + Update.updateDocument(doc, + fr2, + databases, + style, + false, /* doUpdateBibliography */ + false); + } + } +} From f3873bfdb6510f0337bf4652b22d04af88387fa9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 09:50:29 +0200 Subject: [PATCH 0714/1068] refactor: move NonUniqueCitationMarker to model --- .../java/org/jabref/logic/oostyle/OOBibStyle.java | 12 +----------- .../logic/oostyle/OOBibStyleGetCitationMarker.java | 5 +++-- .../java/org/jabref/logic/oostyle/OOProcess.java | 4 ++-- .../org/jabref/logic/openoffice/EditInsert.java | 3 ++- .../model/oostyle/NonUniqueCitationMarker.java | 13 +++++++++++++ 5 files changed, 21 insertions(+), 16 deletions(-) create mode 100644 src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 998958c4a1c..7df048d2c0d 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -30,6 +30,7 @@ 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.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.slf4j.Logger; @@ -1001,17 +1002,6 @@ public OOFormattedText getNormalizedCitationMarker(CitationMarkerEntry ce) { return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, ce, Optional.empty()); } - /** - * What should getCitationMarker do if it discovers that - * uniqueLetters provided are not sufficient for unique presentation? - */ - public enum NonUniqueCitationMarker { - /** Give an insufficient representation anyway. */ - FORGIVEN, - /** Throw a RuntimeException */ - THROWS - } - /** * Format the marker for the in-text citation according to this * BIB style. Uniquefier letters are added as provided by the diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 2e9f4a43ded..20dc0efd683 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -12,6 +12,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; +import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.strings.StringUtil; @@ -567,7 +568,7 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, getCitationMarker(OOBibStyle style, List citationMarkerEntries, boolean inParenthesis, - OOBibStyle.NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { + NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { final int nEntries = citationMarkerEntries.size(); @@ -701,7 +702,7 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, && !k2.equals(k1)); if (uniqueLetterDoesNotMakeUnique && - nonUniqueCitationMarkerHandling == OOBibStyle.NonUniqueCitationMarker.THROWS) { + nonUniqueCitationMarkerHandling == NonUniqueCitationMarker.THROWS) { throw new RuntimeException("different citation keys," + " but same normalizedMarker and uniqueLetter"); } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 530fc20a8b7..91193da920c 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -17,6 +17,7 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.slf4j.Logger; @@ -361,8 +362,7 @@ public static InTextCitationType citationTypeFromOptions(boolean withText, boole // not needed anymore. final boolean inParenthesis = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); - final OOBibStyle.NonUniqueCitationMarker strictlyUnique = - OOBibStyle.NonUniqueCitationMarker.THROWS; + final NonUniqueCitationMarker strictlyUnique = NonUniqueCitationMarker.THROWS; if (hasUnresolved) { /* * Some entries are unresolved. diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index a1f25ba58ac..d2991447c29 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -13,6 +13,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; @@ -109,7 +110,7 @@ public static void insertCitationGroup(XTextDocument doc, ? OOFormattedText.fromString("[-]") // A dash only. Only refresh later. : style.getCitationMarker(citationMarkerEntries, inParenthesis, - OOBibStyle.NonUniqueCitationMarker.FORGIVEN)); + NonUniqueCitationMarker.FORGIVEN)); if ("".equals(OOFormattedText.toString(citeText))) { citeText = OOFormattedText.fromString("[?]"); diff --git a/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java b/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java new file mode 100644 index 00000000000..ddfea3aaa64 --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java @@ -0,0 +1,13 @@ +package org.jabref.model.oostyle; + +/** + * What should getCitationMarker do if it discovers that + * uniqueLetters provided are not sufficient for unique presentation? + */ +public enum NonUniqueCitationMarker { + /** Give an insufficient representation anyway. */ + FORGIVEN, + /** Throw a RuntimeException */ + THROWS +} + From c6272bed9caa1fd308862be58e7ab5726f394b51 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 09:54:12 +0200 Subject: [PATCH 0715/1068] format --- .../org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 20dc0efd683..4ac8ef72ee5 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -29,8 +29,7 @@ class OOBibStyleGetCitationMarker { * @param number The number of the author to return. * @return The author name, or an empty String if inapplicable. */ - private static String getAuthorLastName(AuthorList al, - int number) { + private static String getAuthorLastName(AuthorList al, int number) { StringBuilder sb = new StringBuilder(); if (al.getNumberOfAuthors() > number) { From 959662bb466dacae5fe9877e93a7cc99782acc1b Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 11:05:59 +0200 Subject: [PATCH 0716/1068] use InTextCitationType to encode citation type, not pair of booleans --- .../org/jabref/gui/openoffice/OOBibBase.java | 22 ++++------- .../gui/openoffice/OpenOfficePanel.java | 39 ++++++++++++++----- .../org/jabref/logic/oostyle/OOProcess.java | 17 -------- .../jabref/logic/openoffice/Backend52.java | 8 +--- .../jabref/logic/openoffice/EditInsert.java | 9 +---- .../jabref/logic/openoffice/EditMerge.java | 1 - .../jabref/logic/openoffice/OOFrontend.java | 10 +---- .../openoffice/UpdateCitationMarkers.java | 7 ++-- .../model/oostyle/InTextCitationType.java | 11 ++++++ 9 files changed, 58 insertions(+), 66 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 8fd860f1189..f3b97abfffd 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -303,12 +303,11 @@ public void guiActionApplyCitationEntries(List citationEntries) { * * @param style The bibliography style we are using. * - * @param inParenthesis Indicates whether it is an in-text - * citation or a citation in parenthesis. - * This is not relevant if - * numbered citations are used. - * @param withText Indicates whether this should be a visible - * citation (true) or an empty (invisible) citation (false). + * @param citationType Indicates whether it is an in-text + * citation, a citation in parenthesis or + * an invisible citation. + * The in-text/in-parenthesis distionction is not relevant if + * numbered citations are used. * * @param pageInfo A single page-info for these entries. Stored in custom property * with the same name as the reference mark. @@ -337,8 +336,7 @@ public void guiActionInsertEntry(List entries, BibDatabase database, List allBases, OOBibStyle style, - boolean inParenthesis, - boolean withText, + InTextCitationType citationType, String pageInfo, boolean sync) { @@ -410,8 +408,7 @@ public void guiActionInsertEntry(List entries, database, allBases, style, - inParenthesis, - withText, + citationType, pageInfo, sync, this.alwaysAddCitedOnPages); @@ -592,19 +589,16 @@ public void unCombineCiteMarkers(List databases, final int last = keys.size() - 1; for (int i = 0; i < keys.size(); i++) { boolean insertSpaceAfter = (i != last); - boolean withText = cg.citationType != InTextCitationType.INVISIBLE_CIT; List citationKeys1 = keys.subList(i, i + 1); List pageInfos1 = pageInfosForCitations.subList(i, i + 1); - InTextCitationType citationType1 = InTextCitationType.AUTHORYEAR_PAR; OOFormattedText citationText1 = OOFormattedText.fromString("tmp"); UpdateCitationMarkers.createAndFillCitationGroup(fr, doc, citationKeys1, pageInfos1, - citationType1, + cg.citationType, citationText1, textCursor, - withText, style, insertSpaceAfter); textCursor.collapseToEnd(); diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 8a43f2475e2..e62683961e7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -54,6 +54,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.openoffice.CitationEntry; import org.jabref.preferences.PreferencesService; @@ -195,16 +196,16 @@ private void initPanel() { }); pushEntries.setTooltip(new Tooltip(Localization.lang("Cite selected entries between parenthesis"))); - pushEntries.setOnAction(e -> pushEntries(true, true, false)); + pushEntries.setOnAction(e -> pushEntries(InTextCitationType.AUTHORYEAR_PAR, false)); pushEntries.setMaxWidth(Double.MAX_VALUE); pushEntriesInt.setTooltip(new Tooltip(Localization.lang("Cite selected entries with in-text citation"))); - pushEntriesInt.setOnAction(e -> pushEntries(false, true, false)); + pushEntriesInt.setOnAction(e -> pushEntries(InTextCitationType.AUTHORYEAR_INTEXT, false)); pushEntriesInt.setMaxWidth(Double.MAX_VALUE); pushEntriesEmpty.setTooltip(new Tooltip(Localization.lang("Insert a citation without text (the entry will appear in the reference list)"))); - pushEntriesEmpty.setOnAction(e -> pushEntries(false, false, false)); + pushEntriesEmpty.setOnAction(e -> pushEntries(InTextCitationType.INVISIBLE_CIT, false)); pushEntriesEmpty.setMaxWidth(Double.MAX_VALUE); pushEntriesAdvanced.setTooltip(new Tooltip(Localization.lang("Cite selected entries with extra information"))); - pushEntriesAdvanced.setOnAction(e -> pushEntries(false, true, true)); + pushEntriesAdvanced.setOnAction(e -> pushEntries(InTextCitationType.AUTHORYEAR_INTEXT, true)); pushEntriesAdvanced.setMaxWidth(Double.MAX_VALUE); update.setTooltip(new Tooltip(Localization.lang("Ensure that the bibliography is up-to-date"))); @@ -493,7 +494,24 @@ private OOBibBase createBibBase(Path loPath) throws IOException, InvocationTarge return new OOBibBase(loPath, dialogService); } - private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addPageInfo) { + /** + * Given the withText and inParenthesis options, + * return the corresponding citationType. + * + * @param withText False means invisible citation (no text). + * @param inParenthesis True means "(Au and Thor 2000)". + * False means "Au and Thor (2000)". + */ + private static InTextCitationType citationTypeFromOptions(boolean withText, boolean inParenthesis) { + if (!withText) { + return InTextCitationType.INVISIBLE_CIT; + } + return (inParenthesis + ? InTextCitationType.AUTHORYEAR_PAR + : InTextCitationType.AUTHORYEAR_INTEXT); + } + + private void pushEntries(InTextCitationType citationType, boolean addPageInfo) { final String title = Localization.lang("Error pushing entries"); if (ooBase.guiCheckIfConnectedToDocument(title) || ooBase.guiCheckIfOpenOfficeIsRecordingChanges(title)) { @@ -534,7 +552,9 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP return; } - Boolean inParenthesis = inParenthesisIn; + Boolean inParenthesis = citationType.inParenthesis(); + boolean withText = citationType.withText(); + String pageInfo = null; if (addPageInfo) { @@ -551,9 +571,10 @@ private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addP if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { try { - - ooBase.guiActionInsertEntry(entries, database, getBaseList(), style, inParenthesis, withText, pageInfo, - ooPrefs.getSyncWhenCiting()); + ooBase.guiActionInsertEntry(entries, database, getBaseList(), style, + citationTypeFromOptions(withText, inParenthesis), + pageInfo, + ooPrefs.getSyncWhenCiting()); } catch (ConnectionLostException ex) { OOError.from(ex).showErrorDialog(dialogService); } catch (com.sun.star.lang.IllegalArgumentException ex) { diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 91193da920c..486463949e4 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -182,23 +182,6 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, * * **************************************/ - /** - * Given the withText and inParenthesis options, - * return the corresponding citationType. - * - * @param withText False means invisible citation (no text). - * @param inParenthesis True means "(Au and Thor 2000)". - * False means "Au and Thor (2000)". - */ - public static InTextCitationType citationTypeFromOptions(boolean withText, boolean inParenthesis) { - if (!withText) { - return InTextCitationType.INVISIBLE_CIT; - } - return (inParenthesis - ? InTextCitationType.AUTHORYEAR_PAR - : InTextCitationType.AUTHORYEAR_INTEXT); - } - /** * Produce citation markers for the case when the citation * markers are the citation keys themselves, separated by commas. diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 46aad42d008..5d0cfc0ac34 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -189,18 +189,13 @@ static Optional normalizePageInfoToOptional(OOFormattedText o) * @param insertSpaceAfter We insert a space after the mark, that * carries on format of characters from * the original position. - * - * @param withoutBrackets Force empty reference mark (no brackets). - * For use with INVISIBLE_CIT. - * */ public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, List pageInfosForCitations, InTextCitationType citationType, XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) + boolean insertSpaceAfter) throws CreationException, NoDocumentException, @@ -250,6 +245,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, /* * Apply to document */ + boolean withoutBrackets = (citationType == InTextCitationType.INVISIBLE_CIT); StorageBase.NamedRange storedRange = this.citationStorageManager.create(doc, refMarkName, position, insertSpaceAfter, withoutBrackets); diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index d2991447c29..d4aeee2be59 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -9,7 +9,6 @@ import org.jabref.logic.oostyle.CitationMarkerEntry; import org.jabref.logic.oostyle.CitationMarkerEntryImpl; import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.logic.oostyle.OOProcess; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.InTextCitationType; @@ -62,8 +61,7 @@ public static void insertCitationGroup(XTextDocument doc, BibDatabase database, List allBases, OOBibStyle style, - boolean inParenthesis, - boolean withText, + InTextCitationType citationType, String pageInfo, boolean sync, boolean alwaysAddCitedOnPages) @@ -83,8 +81,6 @@ public static void insertCitationGroup(XTextDocument doc, .map(EditInsert::insertEntryGetCitationKey) .collect(Collectors.toList()); - InTextCitationType citationType = OOProcess.citationTypeFromOptions(withText, inParenthesis); - final int nEntries = entries.size(); // JabRef53 style pageInfo list List pageInfosForCitations = @@ -109,7 +105,7 @@ public static void insertCitationGroup(XTextDocument doc, (style.isNumberEntries() ? OOFormattedText.fromString("[-]") // A dash only. Only refresh later. : style.getCitationMarker(citationMarkerEntries, - inParenthesis, + citationType.inParenthesis(), NonUniqueCitationMarker.FORGIVEN)); if ("".equals(OOFormattedText.toString(citeText))) { @@ -123,7 +119,6 @@ public static void insertCitationGroup(XTextDocument doc, citationType, citeText, cursor, - withText, style, true /* insertSpaceAfter */); diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 688f544bcb3..668fe4f36ce 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -316,7 +316,6 @@ public static void mergeCitationGroups(XTextDocument doc, citationType, OOFormattedText.fromString("tmp"), textCursor, - true, // withText style, insertSpaceAfter); } // for gi diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index ddfaf084afe..2c31830c09c 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -247,18 +247,13 @@ public Optional healthReport(XTextDocument doc) * @param insertSpaceAfter If true, we insert a space after the mark, that * carries on format of characters from * the original position. - * - * @param withoutBrackets Force empty reference mark (no brackets). - * For use with INVISIBLE_CIT. - * */ public CitationGroupID createCitationGroup(XTextDocument doc, List citationKeys, List pageInfosForCitations, InTextCitationType citationType, XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) + boolean insertSpaceAfter) throws CreationException, NoDocumentException, @@ -277,8 +272,7 @@ public CitationGroupID createCitationGroup(XTextDocument doc, pageInfosForCitations, citationType, position, - insertSpaceAfter, - withoutBrackets); + insertSpaceAfter); this.citationGroups.afterCreateCitationGroup(cg); return cg.cgid; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 161b938ea33..46f81b6ea71 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -121,7 +121,6 @@ public static void fillCitationMarkInCursor(XTextDocument doc, * placeholder if not yet available. * * @param position Location to insert at. - * @param withText If false, citationText is not shown. * @param style * @param insertSpaceAfter A space inserted after the reference * mark makes it easier to separate from the text @@ -135,7 +134,6 @@ public static void createAndFillCitationGroup(OOFrontend fr, InTextCitationType citationType, OOFormattedText citationText, XTextCursor position, - boolean withText, OOBibStyle style, boolean insertSpaceAfter) throws @@ -160,8 +158,9 @@ public static void createAndFillCitationGroup(OOFrontend fr, pageInfosForCitations, citationType, position, - insertSpaceAfter, - !withText /* withoutBrackets */); + insertSpaceAfter); + + final boolean withText = citationType.withText(); if (withText) { XTextCursor c2 = fr.getFillCursorForCitationGroup(doc, cgid); diff --git a/src/main/java/org/jabref/model/oostyle/InTextCitationType.java b/src/main/java/org/jabref/model/oostyle/InTextCitationType.java index 060d54082c2..8b6423c27ca 100644 --- a/src/main/java/org/jabref/model/oostyle/InTextCitationType.java +++ b/src/main/java/org/jabref/model/oostyle/InTextCitationType.java @@ -7,6 +7,17 @@ public enum InTextCitationType { 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); + } } From 296c02cbca1375442f0c02ade09f011abd192245 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 16:10:15 +0200 Subject: [PATCH 0717/1068] NonUniqueCitationMarker in model, add EditInsert.SyncOptions --- .../org/jabref/gui/openoffice/OOBibBase.java | 529 +++++++++--------- .../org/jabref/gui/openoffice/OOError.java | 8 + .../gui/openoffice/OpenOfficePanel.java | 29 +- .../jabref/logic/openoffice/EditInsert.java | 159 +++--- src/main/resources/l10n/JabRef_en.properties | 4 + .../jabref/logic/oostyle/OOBibStyleTest.java | 49 +- 6 files changed, 407 insertions(+), 371 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index f3b97abfffd..5113c6df4bc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -73,6 +73,12 @@ class OOBibBase { /* variables */ private final DialogService dialogService; + /* + * After inserting a citation, if ooPrefs.getSyncWhenCiting() returns true, + * shall we also update the bibliography? + */ + private final boolean refreshBibliographyDuringSyncWhenCiting; + /* * Shall we add "Cited on pages: ..." to resolved bibliography entries? */ @@ -90,6 +96,8 @@ public OOBibBase(Path loPath, DialogService dialogService) this.dialogService = dialogService; this.connection = new OOBibBaseConnect(loPath, dialogService); + + this.refreshBibliographyDuringSyncWhenCiting = false; this.alwaysAddCitedOnPages = false; } @@ -188,6 +196,229 @@ boolean testDialog(String title, VoidResult... results) { return testDialog(collectResults(title, rs)); } + /* + * Get the cursor positioned by the user for inserting text. + */ + Result getUserCursorForTextInsertion(XTextDocument doc, String title) { + + XTextCursor cursor; + // Get the cursor positioned by the user. + try { + cursor = UnoCursor.getViewCursor(doc).orElse(null); + } catch (RuntimeException ex) { + return Result.Error(new OOError(title, + Localization.lang("Could not get the cursor."), + ex)); + } + + // Check for crippled XTextViewCursor + Objects.requireNonNull(cursor); + try { + cursor.getStart(); + } catch (com.sun.star.uno.RuntimeException ex) { + String msg = + Localization.lang("Please move the cursor" + + " to the location for the new citation.") + + "\n" + + Localization.lang("I cannot insert to the cursors current location."); + return Result.Error(new OOError(title, msg, ex)); + } + return Result.OK(cursor); + } + + /* + * Tests for preconditions. + */ + + private static VoidResult checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) { + + String title = Localization.lang("Recording and/or Recorded changes"); + try { + boolean recordingChanges = UnoRedlines.getRecordChanges(doc); + int nRedlines = UnoRedlines.countRedlines(doc); + if (recordingChanges || nRedlines > 0) { + String msg = ""; + if (recordingChanges) { + msg += Localization.lang("Cannot work with" + + " [Edit]/[Track Changes]/[Record] turned on."); + } + if (nRedlines > 0) { + if (recordingChanges) { + msg += "\n"; + } + msg += Localization.lang("Changes by JabRef" + + " could result in unexpected interactions with" + + " recorded changes."); + msg += "\n"; + msg += Localization.lang("Use [Edit]/[Track Changes]/[Manage] to resolve them first."); + } + return VoidResult.Error(new OOError(title, msg)); + } + } catch (UnknownPropertyException | WrappedTargetException ex) { + String msg = Localization.lang("Error while checking if Writer" + + " is recording changes or has recorded changes."); + return VoidResult.Error(new OOError(title, msg, ex)); + } + return VoidResult.OK(); + } + + /* + * Called from GUI. + * @return true on error, false if OK. + */ + public boolean guiCheckIfOpenOfficeIsRecordingChanges(String title) { + final boolean FAIL = true; + final boolean PASS = false; + Result odoc = getXTextDocument(); + if (testDialog(title, odoc.asVoidResult())) { + return FAIL; + } + XTextDocument doc = odoc.get(); + + if (testDialog(title, checkIfOpenOfficeIsRecordingChanges(doc))) { + return FAIL; + } + return PASS; + } + + public boolean guiCheckIfConnectedToDocument(String title) { + final boolean FAIL = true; + final boolean PASS = false; + if (!isConnectedToDocument()) { + String msg = Localization.lang("Not connected to any Writer document." + + " Please make sure a document is open," + + " and use the 'Select Writer document' button" + + " to connect to it."); + dialogService.showErrorDialogAndWait(title, msg); + return FAIL; + } + return PASS; + } + + VoidResult styleIsRequired(OOBibStyle style) { + if (style == null) { + return VoidResult.Error(OOError.noValidStyleSelected()); + } else { + return VoidResult.OK(); + } + } + + VoidResult databaseIsRequired(List databases, + Supplier fun) { + if (databases == null || databases.isEmpty()) { + return VoidResult.Error(fun.get()); + } else { + return VoidResult.OK(); + } + } + + VoidResult selectedBibEntryIsRequired(List entries, + Supplier fun) { + if (entries == null || entries.isEmpty()) { + return VoidResult.Error(fun.get()); + } else { + return VoidResult.OK(); + } + } + + /* + * Checks existence and also checks if it is not an internal name. + */ + public VoidResult checkStyleExistsInTheDocument(String familyName, + String styleName, + XTextDocument doc, + String labelInJstyleFile, + String pathToStyleFile) + throws + NoSuchElementException, + WrappedTargetException { + + Optional internalName = UnoStyle.getInternalNameOfStyle(doc, familyName, styleName); + + if (internalName.isEmpty()) { + String msg = + switch (familyName) { + case UnoStyle.PARAGRAPH_STYLES -> + Localization.lang("The %0 paragraph style '%1' is missing from the document", + labelInJstyleFile, + styleName); + case UnoStyle.CHARACTER_STYLES -> + Localization.lang("The %0 character style '%1' is missing from the document", + labelInJstyleFile, + styleName); + default -> + throw new RuntimeException("Expected " + UnoStyle.CHARACTER_STYLES + + " or " + UnoStyle.PARAGRAPH_STYLES + + " for familyName"); + } + + "\n" + + Localization.lang("Please create it in the document or change in the file:") + + "\n" + + pathToStyleFile; + return VoidResult.Error(new OOError("StyleIsNotKnown", msg)); + } + + if (!internalName.get().equals(styleName)) { + String msg = + switch (familyName) { + case UnoStyle.PARAGRAPH_STYLES -> + Localization.lang("The %0 paragraph style '%1' is a display name for '%2'.", + labelInJstyleFile, + styleName, + internalName.get()); + case UnoStyle.CHARACTER_STYLES -> + Localization.lang("The %0 character style '%1' is a display name for '%2'.", + labelInJstyleFile, + styleName, + internalName.get()); + default -> + throw new RuntimeException("Expected " + UnoStyle.CHARACTER_STYLES + + " or " + UnoStyle.PARAGRAPH_STYLES + + " for familyName"); + } + + "\n" + + Localization.lang("Please use the latter in the style file below" + + " to avoid localization problems.") + + "\n" + + pathToStyleFile; + return VoidResult.Error(new OOError("StyleNameIsNotInternal", msg)); + } + return VoidResult.OK(); + } + + public VoidResult checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) { + + String pathToStyleFile = style.getPath(); + + List> results = new ArrayList<>(); + try { + results.add(checkStyleExistsInTheDocument(UnoStyle.PARAGRAPH_STYLES, + style.getReferenceHeaderParagraphFormat(), + doc, + "ReferenceHeaderParagraphFormat", + pathToStyleFile)); + results.add(checkStyleExistsInTheDocument(UnoStyle.PARAGRAPH_STYLES, + style.getReferenceParagraphFormat(), + doc, + "ReferenceParagraphFormat", + pathToStyleFile)); + if (style.isFormatCitations()) { + results.add(checkStyleExistsInTheDocument(UnoStyle.CHARACTER_STYLES, + style.getCitationCharacterFormat(), + doc, + "CitationCharacterFormat", + pathToStyleFile)); + } + } catch (NoSuchElementException + | WrappedTargetException ex) { + results.add(VoidResult.Error(new OOError("Other error in checkStyleExistsInTheDocument", + ex.getMessage(), + ex))); + } + + return collectResults("checkStyleExistsInTheDocument failed", results); + } + /* * * ManageCitationsDialogView @@ -204,7 +435,7 @@ public Optional> guiActionGetCitationEntries() { } XTextDocument doc = odoc.get(); - if (testDialog(title, checkIfOpenOfficeIsRecordingChanges2(doc))) { + if (testDialog(title, checkIfOpenOfficeIsRecordingChanges(doc))) { LOGGER.warn(title); return FAIL; } @@ -298,9 +529,6 @@ public void guiActionApplyCitationEntries(List citationEntries) { * @param database The database the entries belong to (all of them). * Used when creating the citation mark. * - * @param allBases Used if sync is true. The list of all databases - * we may need to refresh the document. - * * @param style The bibliography style we are using. * * @param citationType Indicates whether it is an in-text @@ -327,18 +555,19 @@ public void guiActionApplyCitationEntries(List citationEntries) { * \citealp[pp.~21--23]{smith2003}} * """ * - * @param sync Indicates whether the reference list and in-text citations + * @param syncOptions Indicates whether in-text citations * should be refreshed in the document. + * Optional.empty() indicates no refresh. + * Otherwise provides options for refreshing the reference list. * * */ public void guiActionInsertEntry(List entries, BibDatabase database, - List allBases, OOBibStyle style, InTextCitationType citationType, String pageInfo, - boolean sync) { + Optional syncOptions) { final String title = "Could not insert entry"; @@ -346,23 +575,31 @@ public void guiActionInsertEntry(List entries, if (testDialog(title, odoc.asVoidResult(), styleIsRequired(style), - databaseIsRequired(allBases, OOError::noDataBaseIsOpenForCiting))) { - return; - } - - if (entries == null || entries.size() == 0) { - OOError.noEntriesSelectedForCitation().showErrorDialog(dialogService); + selectedBibEntryIsRequired(entries, OOError::noEntriesSelectedForCitation))) { return; } XTextDocument doc = odoc.get(); + Result cursor = getUserCursorForTextInsertion(doc, title); if (testDialog(title, + cursor.asVoidResult(), checkStylesExistInTheDocument(style, doc), - checkIfOpenOfficeIsRecordingChanges2(doc))) { + checkIfOpenOfficeIsRecordingChanges(doc))) { return; } + syncOptions + .map(e -> e.setUpdateBibliography(this.refreshBibliographyDuringSyncWhenCiting)) + .map(e -> e.setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages)); + + if (syncOptions.isPresent()) { + if (testDialog(databaseIsRequired(syncOptions.get().databases, + OOError::noDataBaseIsOpenForSyncingAfterCitation))) { + return; + } + } + boolean useUndoContext = true; try { @@ -372,46 +609,15 @@ public void guiActionInsertEntry(List entries, OOFrontend fr = new OOFrontend(doc); - XTextCursor cursor; - // Get the cursor positioned by the user. - try { - cursor = UnoCursor.getViewCursor(doc).orElse(null); - } catch (RuntimeException ex) { - cursor = null; - } - - if (cursor == null) { - showDialog(title, - new OOError(Localization.lang("Could not get the cursor."), - Localization.lang("Could not get the cursor."))); - return; - } - - // Check for crippled XTextViewCursor - Objects.requireNonNull(cursor); - try { - cursor.getStart(); - } catch (com.sun.star.uno.RuntimeException ex) { - String msg = - Localization.lang("Please move the cursor" - + " to the location for the new citation.") - + "\n" - + Localization.lang("I cannot insert to the cursors current location."); - showDialog(title, new OOError(title, msg, ex)); - return; - } - EditInsert.insertCitationGroup(doc, fr, - cursor, + cursor.get(), entries, database, - allBases, style, citationType, pageInfo, - sync, - this.alwaysAddCitedOnPages); + syncOptions); } catch (NoDocumentException ex) { OOError.from(ex).showErrorDialog(dialogService); @@ -479,7 +685,7 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle if (testDialog(title, checkStylesExistInTheDocument(style, doc), - checkIfOpenOfficeIsRecordingChanges2(doc))) { + checkIfOpenOfficeIsRecordingChanges(doc))) { return; } @@ -530,16 +736,13 @@ public void unCombineCiteMarkers(List databases, return; } - Objects.requireNonNull(databases); - Objects.requireNonNull(style); - final boolean useLockControllers = true; XTextDocument doc = odoc.get(); if (testDialog(title, checkStylesExistInTheDocument(style, doc), - checkIfOpenOfficeIsRecordingChanges2(doc))) { + checkIfOpenOfficeIsRecordingChanges(doc))) { return; } @@ -787,217 +990,6 @@ private GenerateDatabaseResult generateDatabase(List databases, XTe return new GenerateDatabaseResult(unresolvedKeys, resultDatabase); } - /* - * Throw JabRefException if recording changes or the document contains - * recorded changes. - */ - private static void checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) - throws - UnknownPropertyException, - WrappedTargetException, - JabRefException { - boolean recordingChanges = UnoRedlines.getRecordChanges(doc); - int nRedlines = UnoRedlines.countRedlines(doc); - if (recordingChanges || nRedlines > 0) { - String msg = ""; - if (recordingChanges) { - msg += Localization.lang("Cannot work with [Edit]/[Track Changes]/[Record] turned on."); - } - if (nRedlines > 0) { - if (recordingChanges) { - msg += "\n"; - } - msg += Localization.lang("Changes by JabRef" - + " could result in unexpected interactions with" - + " recorded changes."); - msg += "\n"; - msg += Localization.lang("Use [Edit]/[Track Changes]/[Manage] to resolve them first."); - } - String title = Localization.lang("Recording and/or Recorded changes"); - throw new JabRefException(title, msg); - } - } - - private static VoidResult checkIfOpenOfficeIsRecordingChanges2(XTextDocument doc) { - - String title = Localization.lang("Recording and/or Recorded changes"); - try { - boolean recordingChanges = UnoRedlines.getRecordChanges(doc); - int nRedlines = UnoRedlines.countRedlines(doc); - if (recordingChanges || nRedlines > 0) { - String msg = ""; - if (recordingChanges) { - msg += Localization.lang("Cannot work with" - + " [Edit]/[Track Changes]/[Record] turned on."); - } - if (nRedlines > 0) { - if (recordingChanges) { - msg += "\n"; - } - msg += Localization.lang("Changes by JabRef" - + " could result in unexpected interactions with" - + " recorded changes."); - msg += "\n"; - msg += Localization.lang("Use [Edit]/[Track Changes]/[Manage] to resolve them first."); - } - return VoidResult.Error(new OOError(title, msg)); - } - } catch (UnknownPropertyException | WrappedTargetException ex) { - String msg = Localization.lang("Error while checking if Writer" - + " is recording changes or has recorded changes."); - return VoidResult.Error(new OOError(title, msg, ex)); - } - return VoidResult.OK(); - } - - /* - * Called from GUI. - * @return true on error, false if OK. - */ - public boolean guiCheckIfOpenOfficeIsRecordingChanges(String title) { - final boolean FAIL = true; - final boolean PASS = false; - Result odoc = getXTextDocument(); - if (testDialog(title, odoc.asVoidResult())) { - return FAIL; - } - XTextDocument doc = odoc.get(); - - if (testDialog(title, checkIfOpenOfficeIsRecordingChanges2(doc))) { - return FAIL; - } - return PASS; - } - - public boolean guiCheckIfConnectedToDocument(String title) { - final boolean FAIL = true; - final boolean PASS = false; - if (!isConnectedToDocument()) { - String msg = Localization.lang("Not connected to any Writer document." - + " Please make sure a document is open," - + " and use the 'Select Writer document' button" - + " to connect to it."); - dialogService.showErrorDialogAndWait(title, msg); - return FAIL; - } - return PASS; - } - - VoidResult styleIsRequired(OOBibStyle style) { - if (style == null) { - return VoidResult.Error(OOError.noValidStyleSelected()); - } else { - return VoidResult.OK(); - } - } - - VoidResult databaseIsRequired(List databases, - Supplier fun) { - if (databases == null || databases.isEmpty()) { - return VoidResult.Error(fun.get()); - } else { - return VoidResult.OK(); - } - } - - /* - * Checks existence and also checks if it is not an internal name. - */ - public VoidResult checkStyleExistsInTheDocument(String familyName, - String styleName, - XTextDocument doc, - String labelInJstyleFile, - String pathToStyleFile) - throws - NoSuchElementException, - WrappedTargetException { - - Optional internalName = UnoStyle.getInternalNameOfStyle(doc, familyName, styleName); - - if (internalName.isEmpty()) { - String msg = - switch (familyName) { - case UnoStyle.PARAGRAPH_STYLES -> - Localization.lang("The %0 paragraph style '%1' is missing from the document", - labelInJstyleFile, - styleName); - case UnoStyle.CHARACTER_STYLES -> - Localization.lang("The %0 character style '%1' is missing from the document", - labelInJstyleFile, - styleName); - default -> - throw new RuntimeException("Expected " + UnoStyle.CHARACTER_STYLES - + " or " + UnoStyle.PARAGRAPH_STYLES - + " for familyName"); - } - + "\n" - + Localization.lang("Please create it in the document or change in the file:") - + "\n" - + pathToStyleFile; - return VoidResult.Error(new OOError("StyleIsNotKnown", msg)); - } - - if (!internalName.get().equals(styleName)) { - String msg = - switch (familyName) { - case UnoStyle.PARAGRAPH_STYLES -> - Localization.lang("The %0 paragraph style '%1' is a display name for '%2'.", - labelInJstyleFile, - styleName, - internalName.get()); - case UnoStyle.CHARACTER_STYLES -> - Localization.lang("The %0 character style '%1' is a display name for '%2'.", - labelInJstyleFile, - styleName, - internalName.get()); - default -> - throw new RuntimeException("Expected " + UnoStyle.CHARACTER_STYLES - + " or " + UnoStyle.PARAGRAPH_STYLES - + " for familyName"); - } - + "\n" - + Localization.lang("Please use the latter in the style file below" - + " to avoid localization problems.") - + "\n" - + pathToStyleFile; - return VoidResult.Error(new OOError("StyleNameIsNotInternal", msg)); - } - return VoidResult.OK(); - } - - public VoidResult checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) { - - String pathToStyleFile = style.getPath(); - - List> results = new ArrayList<>(); - try { - results.add(checkStyleExistsInTheDocument(UnoStyle.PARAGRAPH_STYLES, - style.getReferenceHeaderParagraphFormat(), - doc, - "ReferenceHeaderParagraphFormat", - pathToStyleFile)); - results.add(checkStyleExistsInTheDocument(UnoStyle.PARAGRAPH_STYLES, - style.getReferenceParagraphFormat(), - doc, - "ReferenceParagraphFormat", - pathToStyleFile)); - if (style.isFormatCitations()) { - results.add(checkStyleExistsInTheDocument(UnoStyle.CHARACTER_STYLES, - style.getCitationCharacterFormat(), - doc, - "CitationCharacterFormat", - pathToStyleFile)); - } - } catch (NoSuchElementException - | WrappedTargetException ex) { - results.add(VoidResult.Error(new OOError("Other error in checkStyleExistsInTheDocument", - ex.getMessage(), - ex))); - } - - return collectResults("checkStyleExistsInTheDocument failed", results); - } - /** * GUI action, refreshes citation markers and bibliography. * @@ -1012,19 +1004,20 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl try { Result odoc = getXTextDocument(); - if (testDialog(title, List.of(odoc.asVoidResult(), styleIsRequired(style)))) { + if (testDialog(title, + odoc.asVoidResult(), + styleIsRequired(style))) { return; } XTextDocument doc = odoc.get(); - if (testDialog(title, List.of(styleIsRequired(style), - checkStylesExistInTheDocument(style, doc)))) { + if (testDialog(title, + checkStylesExistInTheDocument(style, doc), + checkIfOpenOfficeIsRecordingChanges(doc))) { return; } - checkIfOpenOfficeIsRecordingChanges(doc); - OOFrontend fr = new OOFrontend(doc); // Check Range overlaps boolean requireSeparation = false; diff --git a/src/main/java/org/jabref/gui/openoffice/OOError.java b/src/main/java/org/jabref/gui/openoffice/OOError.java index c3f3dcbeeea..d5002cc9b10 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOError.java +++ b/src/main/java/org/jabref/gui/openoffice/OOError.java @@ -99,6 +99,14 @@ public static OOError noDataBaseIsOpenForCiting() { + Localization.lang("Open one before citing.")); } + public static OOError noDataBaseIsOpenForSyncingAfterCitation() { + return new OOError( + Localization.lang("No database"), + Localization.lang("No database is open for updating citation markers after citing.") + + "\n" + + Localization.lang("Open one before citing.")); + } + // noDataBaseIsOpenForExport public static OOError noDataBaseIsOpenForExport() { return new OOError( diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index e62683961e7..2bf521bad05 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -48,6 +48,7 @@ import org.jabref.logic.oostyle.StyleLoader; import org.jabref.logic.openoffice.ConnectionLostException; import org.jabref.logic.openoffice.CreationException; +import org.jabref.logic.openoffice.EditInsert; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; @@ -571,17 +572,25 @@ private void pushEntries(InTextCitationType citationType, boolean addPageInfo) { if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { try { - ooBase.guiActionInsertEntry(entries, database, getBaseList(), style, - citationTypeFromOptions(withText, inParenthesis), - pageInfo, - ooPrefs.getSyncWhenCiting()); - } catch (ConnectionLostException ex) { - OOError.from(ex).showErrorDialog(dialogService); - } catch (com.sun.star.lang.IllegalArgumentException ex) { - LOGGER.warn("Could not insert entry", ex); - OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); - } + Optional syncOptions = + (ooPrefs.getSyncWhenCiting() + ? Optional.of(new EditInsert.SyncOptions(getBaseList())) + : Optional.empty()); + + ooBase.guiActionInsertEntry(entries, + database, + style, + citationTypeFromOptions(withText, inParenthesis), + pageInfo, + syncOptions); + + } catch (ConnectionLostException ex) { + OOError.from(ex).showErrorDialog(dialogService); + } catch (com.sun.star.lang.IllegalArgumentException ex) { + LOGGER.warn("Could not insert entry", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } + } } /** diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index d4aeee2be59..58b6afd2455 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -51,6 +51,29 @@ private static String insertEntryGetCitationKey(BibEntry entry) { return key.get(); } + public static class SyncOptions { + + public final List databases; + boolean updateBibliography; + boolean alwaysAddCitedOnPages; + + public SyncOptions(List databases) { + this.databases = databases; + this.updateBibliography = false; + this.alwaysAddCitedOnPages = false; + } + + public SyncOptions setUpdateBibliography(boolean value) { + this.updateBibliography = value; + return this; + } + + public SyncOptions setAlwaysAddCitedOnPages(boolean value) { + this.alwaysAddCitedOnPages = value; + return this; + } + } + /* * @param cursor Where to insert. */ @@ -59,12 +82,10 @@ public static void insertCitationGroup(XTextDocument doc, XTextCursor cursor, List entries, BibDatabase database, - List allBases, OOBibStyle style, InTextCitationType citationType, String pageInfo, - boolean sync, - boolean alwaysAddCitedOnPages) + Optional sync) throws UnknownPropertyException, NoDocumentException, @@ -76,80 +97,80 @@ public static void insertCitationGroup(XTextDocument doc, CreationException, IllegalTypeException, JabRefException { - List citationKeys = - entries.stream() - .map(EditInsert::insertEntryGetCitationKey) - .collect(Collectors.toList()); - - final int nEntries = entries.size(); - // JabRef53 style pageInfo list - List pageInfosForCitations = - OOStyleDataModelVersion.fakePageInfosForCitations(pageInfo, nEntries); - - List citationMarkerEntries = new ArrayList<>(nEntries); - for (int i = 0; i < nEntries; i++) { - // Using the same database for each entry. - // Probably the GUI limits selection to a single database. - CitationMarkerEntry cm = - new CitationMarkerEntryImpl(citationKeys.get(i), - Optional.ofNullable(entries.get(i)), - Optional.ofNullable(database), - Optional.empty(), // uniqueLetter - Optional.ofNullable(pageInfosForCitations.get(i)), - false /* isFirstAppearanceOfSource */); - citationMarkerEntries.add(cm); - } - // The text we insert - OOFormattedText citeText = - (style.isNumberEntries() - ? OOFormattedText.fromString("[-]") // A dash only. Only refresh later. - : style.getCitationMarker(citationMarkerEntries, - citationType.inParenthesis(), - NonUniqueCitationMarker.FORGIVEN)); + List citationKeys = + entries.stream() + .map(EditInsert::insertEntryGetCitationKey) + .collect(Collectors.toList()); + + final int nEntries = entries.size(); + // JabRef53 style pageInfo list + List pageInfosForCitations = + OOStyleDataModelVersion.fakePageInfosForCitations(pageInfo, nEntries); + + List citationMarkerEntries = new ArrayList<>(nEntries); + for (int i = 0; i < nEntries; i++) { + // Using the same database for each entry. + // Probably the GUI limits selection to a single database. + CitationMarkerEntry cm = + new CitationMarkerEntryImpl(citationKeys.get(i), + Optional.ofNullable(entries.get(i)), + Optional.ofNullable(database), + Optional.empty(), // uniqueLetter + Optional.ofNullable(pageInfosForCitations.get(i)), + false /* isFirstAppearanceOfSource */); + citationMarkerEntries.add(cm); + } - if ("".equals(OOFormattedText.toString(citeText))) { - citeText = OOFormattedText.fromString("[?]"); - } + // The text we insert + OOFormattedText citeText = + (style.isNumberEntries() + ? OOFormattedText.fromString("[-]") // A dash only. Only refresh later. + : style.getCitationMarker(citationMarkerEntries, + citationType.inParenthesis(), + NonUniqueCitationMarker.FORGIVEN)); - UpdateCitationMarkers.createAndFillCitationGroup(fr, - doc, - citationKeys, - pageInfosForCitations, - citationType, - citeText, - cursor, - style, - true /* insertSpaceAfter */); + if ("".equals(OOFormattedText.toString(citeText))) { + citeText = OOFormattedText.fromString("[?]"); + } + UpdateCitationMarkers.createAndFillCitationGroup(fr, + doc, + citationKeys, + pageInfosForCitations, + citationType, + citeText, + cursor, + style, + true /* insertSpaceAfter */); + + if (sync.isPresent()) { // Remember this position: we will come back here in the // end. XTextRange position = cursor.getEnd(); - if (sync) { - // To account for numbering and for uniqueLetters, we - // must refresh the cite markers: - OOFrontend fr2 = new OOFrontend(doc); - - Update.updateDocument(doc, - fr2, - allBases, - style, - true, /* doUpdateBibliography */ - alwaysAddCitedOnPages); - - /* - * Problem: insertEntry in bibliography - * Reference is destroyed when we want to get there. - */ - // Go back to the relevant position: - try { - cursor.gotoRange(position, false); - } catch (com.sun.star.uno.RuntimeException ex) { - LOGGER.warn("insertCitationGroup:" - + " Could not go back to end of in-text citation", ex); - } + // To account for numbering and for uniqueLetters, we + // must refresh the cite markers: + OOFrontend fr2 = new OOFrontend(doc); + + Update.updateDocument(doc, + fr2, + sync.get().databases, + style, + sync.get().updateBibliography, + sync.get().alwaysAddCitedOnPages); + + /* + * Problem: insertEntry in bibliography + * Reference is destroyed when we want to get there. + */ + // Go back to the relevant position: + try { + cursor.gotoRange(position, false); + } catch (com.sun.star.uno.RuntimeException ex) { + LOGGER.warn("insertCitationGroup:" + + " Could not go back to end of in-text citation", ex); } - + } } } diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 9cd33e95d60..5f07ecd84f4 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1555,9 +1555,13 @@ Unable\ to\ generate\ new\ library=Unable to generate new library Could\ not\ get\ the\ cursor.=Could not get the cursor. JabRefException=JabRefException No\ bibliography\ database\ is\ open\ for\ citation.=No bibliography database is open for citation. + +No\ database\ is\ open\ for\ updating\ citation\ markers\ after\ citing.=No database is open for updating citation markers after citing. + No\ bibliography\ entries\ are\ selected\ for\ citation.=No bibliography entries are selected for citation. No\ bibliography\ style\ is\ selected\ for\ citation.=No bibliography style is selected for citation. No\ database=No database + No\ entries\ selected\ for\ citation=No entries selected for citation Open\ one\ before\ citing.=Open one before citing. diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 29b87185ffe..6d1c5a5b3fc 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -21,6 +21,7 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; +import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.junit.jupiter.api.BeforeEach; @@ -315,12 +316,12 @@ void testGetCitationMarker() throws IOException { assertEquals("[Boström et al., 2006]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Boström et al. [2006]", style.getCitationMarker(citationMarkerEntries, false, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); /* * Currently there is no way override for getMaxAuthors(), except @@ -333,7 +334,7 @@ void testGetCitationMarker() throws IOException { assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -410,13 +411,13 @@ void testGetCitationMarkerJoinFirst() throws IOException { +"; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Boström, Wäyrynen, Bodén, Beznosov & Kruchten [2006a,b]" + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten [2006c]", style.getCitationMarker(citationMarkerEntries, false, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the first is isFirstAppearanceOfSource. @@ -438,7 +439,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { +"; Boström et al., 2006c]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the second is isFirstAppearanceOfSource. @@ -462,7 +463,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström et al., 2006c]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the neither is isFirstAppearanceOfSource. @@ -484,7 +485,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a,b,c]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: different entries with identical non-null pageInfo: not joined. @@ -506,7 +507,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström et al., 2006c; p1]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: same entries with identical non-null pageInfo: collapsed. @@ -527,7 +528,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a; p1]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: same entries with different pageInfo: kept separate. // Empty ("") and null pageInfos considered equal her, collapsed. @@ -551,7 +552,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström et al., 2006a]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } } @@ -641,7 +642,7 @@ void testInstitutionAuthorMarker() throws IOException { assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -666,7 +667,7 @@ void testVonAuthorMarker() throws IOException { assertEquals("[von Beta, 2016]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -689,7 +690,7 @@ void testNullAuthorMarker() throws IOException { assertEquals("[, 2016]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -712,7 +713,7 @@ void testNullYearMarker() throws IOException { assertEquals("[von Beta, ]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -733,7 +734,7 @@ void testEmptyEntryMarker() throws IOException { assertEquals("[, ]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS) + NonUniqueCitationMarker.THROWS) .asString()); } @@ -788,7 +789,7 @@ void testGetCitationMarkerUniquefiers() throws IOException { try { style.getCitationMarker(citationMarkerEntriesA, false, - OOBibStyle.NonUniqueCitationMarker.THROWS); + NonUniqueCitationMarker.THROWS); } catch (RuntimeException ex) { doesItThrow = true; } @@ -798,12 +799,12 @@ void testGetCitationMarkerUniquefiers() throws IOException { assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", style.getCitationMarker(citationMarkerEntriesA, true, - OOBibStyle.NonUniqueCitationMarker.FORGIVEN).asString()); + NonUniqueCitationMarker.FORGIVEN).asString()); assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", style.getCitationMarker(citationMarkerEntriesA, false, - OOBibStyle.NonUniqueCitationMarker.FORGIVEN).asString()); + NonUniqueCitationMarker.FORGIVEN).asString()); // With uniquefiers @@ -820,12 +821,12 @@ void testGetCitationMarkerUniquefiers() throws IOException { assertEquals("[Beta, 2000a,b; Epsilon, 2001]", style.getCitationMarker(citationMarkerEntriesB, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Beta [2000a,b]; Epsilon [2001]", style.getCitationMarker(citationMarkerEntriesB, false, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } @@ -869,12 +870,12 @@ void testGetCitationMarkerUniquefiersThreeSameAuthor() throws IOException { assertEquals("[Beta, 2000a,b,c]", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Beta [2000a,b,c]", style.getCitationMarker(citationMarkerEntries, false, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -937,7 +938,7 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { assertEquals("von Beta, Epsilon, & Tau, 2016", style.getCitationMarker(citationMarkerEntries, true, - OOBibStyle.NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).asString()); } @Test From 332a06355b4ada6e12c7f7663d5956966dcc9bbd Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 16:13:01 +0200 Subject: [PATCH 0718/1068] undo: temporarily disable HelpFileTest --- src/test/java/org/jabref/logic/help/HelpFileTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/org/jabref/logic/help/HelpFileTest.java b/src/test/java/org/jabref/logic/help/HelpFileTest.java index 6c7f6ab85b8..006c0383d0e 100644 --- a/src/test/java/org/jabref/logic/help/HelpFileTest.java +++ b/src/test/java/org/jabref/logic/help/HelpFileTest.java @@ -8,13 +8,11 @@ import org.jabref.logic.net.URLDownload; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertEquals; -@Disabled("help links changed, waiting for upstream to update") class HelpFileTest { private final String jabrefHelp = "https://docs.jabref.org/"; From 925211663ddcf29af67f27954ce3ffe599db6b76 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 17:31:28 +0200 Subject: [PATCH 0719/1068] guiActionSeparateCitations, does not throw --- .../org/jabref/gui/openoffice/OOBibBase.java | 259 +++++------------- .../gui/openoffice/OpenOfficePanel.java | 39 +-- .../jabref/logic/openoffice/EditMerge.java | 2 +- .../jabref/logic/openoffice/EditSeparate.java | 125 +++++++++ .../org/jabref/logic/openoffice/Update.java | 8 +- 5 files changed, 202 insertions(+), 231 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/EditSeparate.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5113c6df4bc..69a0b465cd9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -15,8 +15,6 @@ import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.oostyle.Citation; -import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.CitedKey; import org.jabref.logic.oostyle.CitedKeys; import org.jabref.logic.oostyle.OOBibStyle; @@ -24,26 +22,22 @@ import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.EditInsert; import org.jabref.logic.openoffice.EditMerge; +import org.jabref.logic.openoffice.EditSeparate; import org.jabref.logic.openoffice.ManageCitations; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.Result; -import org.jabref.logic.openoffice.UnoCrossRef; import org.jabref.logic.openoffice.UnoCursor; import org.jabref.logic.openoffice.UnoRedlines; -import org.jabref.logic.openoffice.UnoScreenRefresh; import org.jabref.logic.openoffice.UnoStyle; import org.jabref.logic.openoffice.UnoUndo; import org.jabref.logic.openoffice.Update; -import org.jabref.logic.openoffice.UpdateCitationMarkers; import org.jabref.logic.openoffice.VoidResult; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; -import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; -import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.openoffice.CitationEntry; import com.sun.star.beans.IllegalTypeException; @@ -57,7 +51,6 @@ import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; -import com.sun.star.text.XTextRange; import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -153,11 +146,11 @@ public Optional getCurrentDocumentTitle() { return this.connection.getCurrentDocumentTitle(); } - /* **************************** + /* ****************************************************** * - * Misc + * Tools to collect and show precondition test results * - * ****************************/ + * ******************************************************/ void showDialog(OOError ex) { ex.showErrorDialog(dialogService); @@ -197,7 +190,9 @@ boolean testDialog(String title, VoidResult... results) { } /* + * * Get the cursor positioned by the user for inserting text. + * */ Result getUserCursorForTextInsertion(XTextDocument doc, String title) { @@ -227,7 +222,9 @@ Result getUserCursorForTextInsertion(XTextDocument doc, St } /* + * * Tests for preconditions. + * */ private static VoidResult checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) { @@ -262,39 +259,6 @@ private static VoidResult checkIfOpenOfficeIsRecordingChanges(XTextDocu return VoidResult.OK(); } - /* - * Called from GUI. - * @return true on error, false if OK. - */ - public boolean guiCheckIfOpenOfficeIsRecordingChanges(String title) { - final boolean FAIL = true; - final boolean PASS = false; - Result odoc = getXTextDocument(); - if (testDialog(title, odoc.asVoidResult())) { - return FAIL; - } - XTextDocument doc = odoc.get(); - - if (testDialog(title, checkIfOpenOfficeIsRecordingChanges(doc))) { - return FAIL; - } - return PASS; - } - - public boolean guiCheckIfConnectedToDocument(String title) { - final boolean FAIL = true; - final boolean PASS = false; - if (!isConnectedToDocument()) { - String msg = Localization.lang("Not connected to any Writer document." - + " Please make sure a document is open," - + " and use the 'Select Writer document' button" - + " to connect to it."); - dialogService.showErrorDialogAndWait(title, msg); - return FAIL; - } - return PASS; - } - VoidResult styleIsRequired(OOBibStyle style) { if (style == null) { return VoidResult.Error(OOError.noValidStyleSelected()); @@ -324,11 +288,11 @@ VoidResult selectedBibEntryIsRequired(List entries, /* * Checks existence and also checks if it is not an internal name. */ - public VoidResult checkStyleExistsInTheDocument(String familyName, - String styleName, - XTextDocument doc, - String labelInJstyleFile, - String pathToStyleFile) + private VoidResult checkStyleExistsInTheDocument(String familyName, + String styleName, + XTextDocument doc, + String labelInJstyleFile, + String pathToStyleFile) throws NoSuchElementException, WrappedTargetException { @@ -502,7 +466,7 @@ public void guiActionApplyCitationEntries(List citationEntries) { | PropertyVetoException | IllegalTypeException | WrappedTargetException - | IllegalArgumentException ex) { + | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn(title, ex); OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } @@ -569,7 +533,7 @@ public void guiActionInsertEntry(List entries, String pageInfo, Optional syncOptions) { - final String title = "Could not insert entry"; + final String title = "Could not insert citation"; Result odoc = getXTextDocument(); if (testDialog(title, @@ -600,12 +564,8 @@ public void guiActionInsertEntry(List entries, } } - boolean useUndoContext = true; - try { - if (useUndoContext) { - UnoUndo.enterUndoContext(doc, "Insert citation"); - } + UnoUndo.enterUndoContext(doc, "Insert citation"); OOFrontend fr = new OOFrontend(doc); @@ -620,7 +580,7 @@ public void guiActionInsertEntry(List entries, syncOptions); } catch (NoDocumentException ex) { - OOError.from(ex).showErrorDialog(dialogService); + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); return; } catch (DisposedException ex) { // We need to catch this one here because the OpenOfficePanel class is @@ -630,24 +590,21 @@ public void guiActionInsertEntry(List entries, OOError.from(new ConnectionLostException("DisposedException")).showErrorDialog(dialogService); return; } catch (JabRefException ex) { - OOError.from(ex).showErrorDialog(dialogService); + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); return; - } catch (// com.sun.star.lang.IllegalArgumentException - CreationException - | IllegalTypeException - | NoSuchElementException - | NotRemoveableException - | PropertyExistException - | PropertyVetoException - | UnknownPropertyException - | WrappedTargetException ex) { + } catch (CreationException + | IllegalTypeException + | NoSuchElementException + | NotRemoveableException + | PropertyExistException + | PropertyVetoException + | UnknownPropertyException + | WrappedTargetException ex) { LOGGER.warn("Could not insert entry", ex); OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); return; } finally { - if (useUndoContext) { - UnoUndo.leaveUndoContext(doc); - } + UnoUndo.leaveUndoContext(doc); } } @@ -655,23 +612,9 @@ public void guiActionInsertEntry(List entries, * GUI action "Merge citations" * */ - public void guiActionMergeCitationGroups(List databases, OOBibStyle style) - throws - IOException, - WrappedTargetException, - NoSuchElementException, - NotRemoveableException, - IllegalArgumentException, - UnknownPropertyException, - PropertyVetoException, - PropertyExistException, - IllegalTypeException, - CreationException, - NoDocumentException, - JabRefException, - InvalidStateException { + public void guiActionMergeCitationGroups(List databases, OOBibStyle style) { - final String title = "Could not merge citations"; + final String title = Localization.lang("Problem combining cite markers"); Result odoc = getXTextDocument(); if (testDialog(title, @@ -689,15 +632,31 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle return; } - OOFrontend fr = new OOFrontend(doc); - try { UnoUndo.enterUndoContext(doc, "Merge citations"); + OOFrontend fr = new OOFrontend(doc); EditMerge.mergeCitationGroups(doc, fr, databases, style); + + } catch (NoDocumentException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); + } catch (JabRefException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); + } catch (CreationException + | IllegalTypeException + | InvalidStateException + | NoSuchElementException + | NotRemoveableException + | PropertyExistException + | PropertyVetoException + | UnknownPropertyException + | WrappedTargetException + | com.sun.star.lang.IllegalArgumentException ex) { + LOGGER.warn("Problem combining cite markers", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } finally { UnoUndo.leaveUndoContext(doc); } @@ -709,24 +668,9 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle * Do the opposite of MergeCitationGroups. * Combined markers are split, with a space inserted between. */ - public void unCombineCiteMarkers(List databases, - OOBibStyle style) - throws - IOException, - WrappedTargetException, - NoSuchElementException, - IllegalArgumentException, - UnknownPropertyException, - NotRemoveableException, - PropertyVetoException, - PropertyExistException, - IllegalTypeException, - CreationException, - NoDocumentException, - JabRefException, - InvalidStateException { + public void guiActionSeparateCitations(List databases, OOBibStyle style) { - final String title = "Separate citations failed"; + final String title = Localization.lang("Problem during separating cite markers"); Result odoc = getXTextDocument(); if (testDialog(title, @@ -736,8 +680,6 @@ public void unCombineCiteMarkers(List databases, return; } - final boolean useLockControllers = true; - XTextDocument doc = odoc.get(); if (testDialog(title, @@ -746,87 +688,28 @@ public void unCombineCiteMarkers(List databases, return; } - OOFrontend fr = new OOFrontend(doc); - try { UnoUndo.enterUndoContext(doc, "Separate citations"); - boolean madeModifications = false; - - // {@code names} does not need to be sorted. - List names = - new ArrayList<>(fr.citationGroups.getCitationGroupIDsUnordered()); - - try { - if (useLockControllers) { - UnoScreenRefresh.lockControllers(doc); - } - - int pivot = 0; - - while (pivot < (names.size())) { - CitationGroupID cgid = names.get(pivot); - CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); - XTextRange range1 = (fr - .getMarkRange(doc, cgid) - .orElseThrow(RuntimeException::new)); - XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); - - // Note: JabRef52 returns cg.pageInfo for the last citation. - List pageInfosForCitations = - cg.getPageInfosForCitationsInStorageOrder(); - List cits = cg.citationsInStorageOrder; - if (cits.size() <= 1) { - pivot++; - continue; - } - - List keys = - cits.stream().map(cit -> cit.citationKey).collect(Collectors.toList()); - - fr.removeCitationGroup(cg, doc); - - // Now we own the content of cits - - // Insert mark for each key - final int last = keys.size() - 1; - for (int i = 0; i < keys.size(); i++) { - boolean insertSpaceAfter = (i != last); - List citationKeys1 = keys.subList(i, i + 1); - List pageInfos1 = pageInfosForCitations.subList(i, i + 1); - OOFormattedText citationText1 = OOFormattedText.fromString("tmp"); - UpdateCitationMarkers.createAndFillCitationGroup(fr, - doc, - citationKeys1, - pageInfos1, - cg.citationType, - citationText1, - textCursor, - style, - insertSpaceAfter); - textCursor.collapseToEnd(); - } - - madeModifications = true; - pivot++; - } - } finally { - if (useLockControllers) { - UnoScreenRefresh.unlockControllers(doc); - } - } - - if (madeModifications) { - UnoCrossRef.refresh(doc); - OOFrontend fr2 = new OOFrontend(doc); - Update.updateDocument(doc, - fr2, - databases, - style, - false, /* doUpdateBibliography */ - this.alwaysAddCitedOnPages); - } + OOFrontend fr = new OOFrontend(doc); + EditSeparate.separateCitations(doc, fr, databases, style); + } catch (NoDocumentException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); + } catch (JabRefException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); + } catch (CreationException + | IllegalTypeException + | InvalidStateException + | NoSuchElementException + | NotRemoveableException + | PropertyExistException + | PropertyVetoException + | UnknownPropertyException + | WrappedTargetException + | com.sun.star.lang.IllegalArgumentException ex) { + LOGGER.warn("Problem during separating cite markers", ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } finally { UnoUndo.leaveUndoContext(doc); } @@ -1044,7 +927,7 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl UnoUndo.leaveUndoContext(doc); } - if (!unresolvedKeys.isEmpty()) { + if (!unresolvedKeys.isEmpty()) { String msg = Localization.lang( "Your OpenOffice/LibreOffice document references the citation key '%0'," + " which could not be found in your current library.", @@ -1059,12 +942,12 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl OOError.from(ex).showErrorDialog(dialogService); } catch (NoDocumentException ex) { OOError.from(ex).showErrorDialog(dialogService); - } catch (com.sun.star.lang.IllegalArgumentException + } catch (CreationException + | NoSuchElementException | PropertyVetoException | UnknownPropertyException | WrappedTargetException - | NoSuchElementException - | CreationException ex) { + | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Could not update bibliography", ex); OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 2bf521bad05..ed53d716edc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -59,9 +59,6 @@ import org.jabref.model.openoffice.CitationEntry; import org.jabref.preferences.PreferencesService; -import com.sun.star.beans.IllegalTypeException; -import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.comp.helper.BootstrapException; @@ -238,43 +235,13 @@ private void initPanel() { merge.setMaxWidth(Double.MAX_VALUE); merge.setTooltip(new Tooltip(Localization.lang("Combine pairs of citations that are separated by spaces only"))); merge.setOnAction(e -> { - final String title = Localization.lang("Problem combining cite markers"); - // check usedStylesExistInDocument - try { ooBase.guiActionMergeCitationGroups(getBaseList(), style); - } catch (JabRefException ex) { - OOError.from(ex).setTitle(title).showErrorDialog(dialogService); - } catch (NoDocumentException ex) { - OOError.from(ex).setTitle(title).showErrorDialog(dialogService); - } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | - CreationException | NoSuchElementException | WrappedTargetException | IOException | - NotRemoveableException | IllegalTypeException | InvalidStateException | - PropertyExistException ex) { - LOGGER.warn("Problem combining cite markers", ex); - OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); - } }); unmerge.setMaxWidth(Double.MAX_VALUE); unmerge.setTooltip(new Tooltip(Localization.lang("Separate merged citations"))); unmerge.setOnAction(e -> { - final String title = Localization.lang("Problem during separating cite markers"); - // check usedStylesExistInDocument - try { - ooBase.unCombineCiteMarkers(getBaseList(), style); - } catch (JabRefException ex) { - dialogService.showErrorDialogAndWait( - Localization.lang("JabRefException"), - ex.getLocalizedMessage()); - } catch (NoDocumentException ex) { - OOError.from(ex).showErrorDialog(dialogService); - } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | - CreationException | NoSuchElementException | WrappedTargetException | IOException | - PropertyExistException | IllegalTypeException | NotRemoveableException | - InvalidStateException ex) { - LOGGER.warn("Problem during separating cite markers", ex); - OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); - } + ooBase.guiActionSeparateCitations(getBaseList(), style); }); ContextMenu settingsMenu = createSettingsPopup(); @@ -514,10 +481,6 @@ private static InTextCitationType citationTypeFromOptions(boolean withText, bool private void pushEntries(InTextCitationType citationType, boolean addPageInfo) { final String title = Localization.lang("Error pushing entries"); - if (ooBase.guiCheckIfConnectedToDocument(title) - || ooBase.guiCheckIfOpenOfficeIsRecordingChanges(title)) { - return; - } LibraryTab libraryTab = frame.getCurrentLibraryTab(); if (libraryTab == null) { diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 668fe4f36ce..83efc56c4b7 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -336,7 +336,7 @@ public static void mergeCitationGroups(XTextDocument doc, databases, style, false, /* doUpdateBibliography */ - false); + false /* alwaysAddCitedOnPages */); } } } diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java new file mode 100644 index 00000000000..9cd12df5c1c --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -0,0 +1,125 @@ +package org.jabref.logic.openoffice; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.oostyle.Citation; +import org.jabref.logic.oostyle.CitationGroup; +import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.OOFormattedText; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; +import com.sun.star.util.InvalidStateException; + +public class EditSeparate { + + public static void separateCitations(XTextDocument doc, + OOFrontend fr, + List databases, + OOBibStyle style) + throws + CreationException, + IllegalTypeException, + InvalidStateException, + JabRefException, + NoDocumentException, + NoSuchElementException, + NotRemoveableException, + PropertyExistException, + PropertyVetoException, + UnknownPropertyException, + WrappedTargetException, + com.sun.star.lang.IllegalArgumentException { + + boolean madeModifications = false; + + // {@code names} does not need to be sorted. + List names = + new ArrayList<>(fr.citationGroups.getCitationGroupIDsUnordered()); + + final boolean useLockControllers = true; + try { + if (useLockControllers) { + UnoScreenRefresh.lockControllers(doc); + } + + int pivot = 0; + + while (pivot < (names.size())) { + CitationGroupID cgid = names.get(pivot); + CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); + XTextRange range1 = (fr + .getMarkRange(doc, cgid) + .orElseThrow(RuntimeException::new)); + XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); + + // Note: JabRef52 returns cg.pageInfo for the last citation. + List pageInfosForCitations = + cg.getPageInfosForCitationsInStorageOrder(); + + List cits = cg.citationsInStorageOrder; + if (cits.size() <= 1) { + pivot++; + continue; + } + + List keys = + cits.stream().map(cit -> cit.citationKey).collect(Collectors.toList()); + + fr.removeCitationGroup(cg, doc); + + // Now we own the content of cits + + // Insert mark for each key + final int last = keys.size() - 1; + for (int i = 0; i < keys.size(); i++) { + boolean insertSpaceAfter = (i != last); + List citationKeys1 = keys.subList(i, i + 1); + List pageInfos1 = pageInfosForCitations.subList(i, i + 1); + OOFormattedText citationText1 = OOFormattedText.fromString("tmp"); + UpdateCitationMarkers.createAndFillCitationGroup(fr, + doc, + citationKeys1, + pageInfos1, + cg.citationType, + citationText1, + textCursor, + style, + insertSpaceAfter); + textCursor.collapseToEnd(); + } + + madeModifications = true; + pivot++; + } + } finally { + if (useLockControllers) { + UnoScreenRefresh.unlockControllers(doc); + } + } + + if (madeModifications) { + UnoCrossRef.refresh(doc); + OOFrontend fr2 = new OOFrontend(doc); + Update.updateDocument(doc, + fr2, + databases, + style, + false, /* doUpdateBibliography */ + false /* alwaysAddCitedOnPages */); + } + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index a54b42f9184..52ade44b6f4 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -28,15 +28,15 @@ public static List updateDocument(XTextDocument doc, boolean doUpdateBibliography, boolean alwaysAddCitedOnPages) throws - JabRefException, ConnectionLostException, + CreationException, + JabRefException, NoDocumentException, - com.sun.star.lang.IllegalArgumentException, + NoSuchElementException, PropertyVetoException, UnknownPropertyException, WrappedTargetException, - NoSuchElementException, - CreationException { + com.sun.star.lang.IllegalArgumentException { final boolean useLockControllers = true; From 4f578f9327974f0211e158624f6ae78f774283b7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 17:51:42 +0200 Subject: [PATCH 0720/1068] refactor: ExportCited.java --- .../org/jabref/gui/openoffice/OOBibBase.java | 90 +---------------- .../jabref/logic/openoffice/ExportCited.java | 96 +++++++++++++++++++ 2 files changed, 101 insertions(+), 85 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/ExportCited.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 69a0b465cd9..61873d4776a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -4,25 +4,22 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; -import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.oostyle.CitedKey; -import org.jabref.logic.oostyle.CitedKeys; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.openoffice.ConnectionLostException; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.EditInsert; import org.jabref.logic.openoffice.EditMerge; import org.jabref.logic.openoffice.EditSeparate; +import org.jabref.logic.openoffice.ExportCited; import org.jabref.logic.openoffice.ManageCitations; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.NoDocumentFoundException; @@ -36,7 +33,6 @@ import org.jabref.logic.openoffice.VoidResult; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.StandardField; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.openoffice.CitationEntry; @@ -715,19 +711,6 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s } } - static class GenerateDatabaseResult { - /** - * null: not done; isEmpty: no unresolved - */ - List unresolvedKeys; - BibDatabase newDatabase; - GenerateDatabaseResult(List unresolvedKeys, - BibDatabase newDatabase) { - this.unresolvedKeys = unresolvedKeys; - this.newDatabase = newDatabase; - } - } - /** * GUI action for "Export cited" * @@ -763,13 +746,13 @@ public Optional exportCitedHelper(List databases, try { - GenerateDatabaseResult result; + ExportCited.GenerateDatabaseResult result; try { UnoUndo.enterUndoContext(doc, "Changes during \"Export cited\""); - result = this.generateDatabase(databases, doc); + result = ExportCited.generateDatabase(doc, databases); } finally { - // There should be no changes, thus no Undo entry - // in LibreOffice + // There should be no changes, thus no Undo entry should appear + // in LibreOffice. UnoUndo.leaveUndoContext(doc); } @@ -810,69 +793,6 @@ public Optional exportCitedHelper(List databases, return FAIL; } - /** - * Used from GUI: "Export cited" - * - * @param databases The databases to look up the citation keys in the document from. - * @return A new database, with cloned entries. - * - * If a key is not found, it is added to result.unresolvedKeys - * - * Cross references (in StandardField.CROSSREF) are followed (not recursively): - * if the referenced entry is found, it is included in the result. - * If it is not found, it is silently ignored. - */ - private GenerateDatabaseResult generateDatabase(List databases, XTextDocument doc) - throws - NoSuchElementException, - WrappedTargetException, - NoDocumentException, - UnknownPropertyException { - - OOFrontend fr = new OOFrontend(doc); - CitedKeys cks = fr.citationGroups.getCitedKeysUnordered(); - cks.lookupInDatabases(databases); - - List unresolvedKeys = new ArrayList<>(); - BibDatabase resultDatabase = new BibDatabase(); - - List entriesToInsert = new ArrayList<>(); - Set seen = new HashSet<>(); // Only add crossReference once. - - for (CitedKey ck : cks.values()) { - if (ck.db.isEmpty()) { - unresolvedKeys.add(ck.citationKey); - continue; - } else { - BibEntry entry = ck.db.get().entry; - BibDatabase loopDatabase = ck.db.get().database; - - // If entry found - BibEntry clonedEntry = (BibEntry) entry.clone(); - - // Insert a copy of the entry - entriesToInsert.add(clonedEntry); - - // Check if the cloned entry has a cross-reference field - clonedEntry - .getField(StandardField.CROSSREF) - .ifPresent(crossReference -> { - boolean isNew = !seen.contains(crossReference); - if (isNew) { - // Add it if it is in the current library - loopDatabase - .getEntryByCitationKey(crossReference) - .ifPresent(entriesToInsert::add); - seen.add(crossReference); - } - }); - } - } - - resultDatabase.insertEntries(entriesToInsert); - return new GenerateDatabaseResult(unresolvedKeys, resultDatabase); - } - /** * GUI action, refreshes citation markers and bibliography. * diff --git a/src/main/java/org/jabref/logic/openoffice/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/ExportCited.java new file mode 100644 index 00000000000..5e8ccb09184 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/ExportCited.java @@ -0,0 +1,96 @@ +package org.jabref.logic.openoffice; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.jabref.logic.oostyle.CitedKey; +import org.jabref.logic.oostyle.CitedKeys; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.StandardField; + +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextDocument; + +public class ExportCited { + + public static class GenerateDatabaseResult { + /** + * null: not done; isEmpty: no unresolved + */ + public final List unresolvedKeys; + public final BibDatabase newDatabase; + + GenerateDatabaseResult(List unresolvedKeys, BibDatabase newDatabase) { + this.unresolvedKeys = unresolvedKeys; + this.newDatabase = newDatabase; + } + } + + /** + * + * @param databases The databases to look up the citation keys in the document from. + * @return A new database, with cloned entries. + * + * If a key is not found, it is added to result.unresolvedKeys + * + * Cross references (in StandardField.CROSSREF) are followed (not recursively): + * if the referenced entry is found, it is included in the result. + * If it is not found, it is silently ignored. + */ + public static GenerateDatabaseResult generateDatabase(XTextDocument doc, List databases) + throws + NoSuchElementException, + WrappedTargetException, + NoDocumentException, + UnknownPropertyException { + + OOFrontend fr = new OOFrontend(doc); + CitedKeys cks = fr.citationGroups.getCitedKeysUnordered(); + cks.lookupInDatabases(databases); + + List unresolvedKeys = new ArrayList<>(); + BibDatabase resultDatabase = new BibDatabase(); + + List entriesToInsert = new ArrayList<>(); + Set seen = new HashSet<>(); // Only add crossReference once. + + for (CitedKey ck : cks.values()) { + if (ck.db.isEmpty()) { + unresolvedKeys.add(ck.citationKey); + continue; + } else { + BibEntry entry = ck.db.get().entry; + BibDatabase loopDatabase = ck.db.get().database; + + // If entry found + BibEntry clonedEntry = (BibEntry) entry.clone(); + + // Insert a copy of the entry + entriesToInsert.add(clonedEntry); + + // Check if the cloned entry has a cross-reference field + clonedEntry + .getField(StandardField.CROSSREF) + .ifPresent(crossReference -> { + boolean isNew = !seen.contains(crossReference); + if (isNew) { + // Add it if it is in the current library + loopDatabase + .getEntryByCitationKey(crossReference) + .ifPresent(entriesToInsert::add); + seen.add(crossReference); + } + }); + } + } + + resultDatabase.insertEntries(entriesToInsert); + return new GenerateDatabaseResult(unresolvedKeys, resultDatabase); + } + +} From c930afe9d030dd4caf2657cf6c7ecf1680acf797 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 18:06:21 +0200 Subject: [PATCH 0721/1068] UpdateBibliography : remove old bookmark before creating new --- .../jabref/logic/openoffice/UnoBookmark.java | 22 ++++++++++++ .../org/jabref/logic/openoffice/Update.java | 2 +- .../logic/openoffice/UpdateBibliography.java | 35 +++++++------------ 3 files changed, 36 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java index 61c5c89e1c2..ef42e6b4a95 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java @@ -2,12 +2,14 @@ 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.IllegalArgumentException; 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; @@ -73,4 +75,24 @@ public static XNamed create(XTextDocument doc, String name, XTextRange range, bo range, absorb); } + + /** + * Remove the named bookmark if it exists. + */ + public static void remove(XTextDocument doc, String name) + throws + NoDocumentException, + NoSuchElementException, + WrappedTargetException { + + XNameAccess marks = UnoBookmark.getNameAccess(doc); + + if (marks.hasByName(name)) { + Optional mark = UnoNameAccess.getTextContentByName(marks, name); + if (mark.isEmpty()) { + return; + } + doc.getText().removeTextContent(mark.get()); + } + } } diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index 52ade44b6f4..cf91b5a13b2 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -53,9 +53,9 @@ public static List updateDocument(XTextDocument doc, if (doUpdateBibliography) { UpdateBibliography.rebuildBibTextSection(doc, - style, fr, x.getBibliography(), + style, alwaysAddCitedOnPages); } return x.getUnresolvedKeys(); diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java index 2dadab8d478..11300ec3a76 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -23,22 +23,14 @@ public class UpdateBibliography { private static final String BIB_SECTION_NAME = "JR_bib"; private static final String BIB_SECTION_END_NAME = "JR_bib_end"; - /* ************************************************** - * - * Bibliography: needs uniqueLetters or numbers - * - * **************************************************/ /** * Rebuilds the bibliography. - * - * Note: assumes fresh `jabRefReferenceMarkNamesSortedByPosition` - * if `style.isSortByPosition()` */ static void rebuildBibTextSection(XTextDocument doc, - OOBibStyle style, OOFrontend fr, CitedKeys bibliography, + OOBibStyle style, boolean alwaysAddCitedOnPages) throws NoSuchElementException, @@ -65,17 +57,14 @@ static void rebuildBibTextSection(XTextDocument doc, */ private static void createBibTextSection2(XTextDocument doc) throws - IllegalArgumentException, - CreationException { + CreationException, + IllegalArgumentException { // Always creating at the end of the document. // Alternatively, we could receive a cursor. XTextCursor textCursor = doc.getText().createTextCursor(); textCursor.gotoEnd(false); - UnoTextSection.create(doc, - BIB_SECTION_NAME, - textCursor, - false); + UnoTextSection.create(doc, BIB_SECTION_NAME, textCursor, false); } /** @@ -87,10 +76,10 @@ private static void createBibTextSection2(XTextDocument doc) */ private static void clearBibTextSectionContent2(XTextDocument doc) throws - WrappedTargetException, - IllegalArgumentException, CreationException, - NoDocumentException { + IllegalArgumentException, + NoDocumentException, + WrappedTargetException { Optional sectionRange = UnoTextSection.getAnchor(doc, BIB_SECTION_NAME); if (sectionRange.isEmpty()) { @@ -114,13 +103,13 @@ private static void populateBibTextSection(XTextDocument doc, OOBibStyle style, boolean alwaysAddCitedOnPages) throws - NoSuchElementException, + CreationException, + IllegalArgumentException, NoDocumentException, - WrappedTargetException, + NoSuchElementException, PropertyVetoException, UnknownPropertyException, - IllegalArgumentException, - CreationException { + WrappedTargetException { XTextSection section = (UnoTextSection.getByName(doc, BIB_SECTION_NAME) .orElseThrow(RuntimeException::new)); @@ -142,7 +131,9 @@ private static void populateBibTextSection(XTextDocument doc, initialParagraph.goRight((short) 1, true); initialParagraph.setString(""); + UnoBookmark.remove(doc, BIB_SECTION_END_NAME); UnoBookmark.create(doc, BIB_SECTION_END_NAME, cursor, true); + cursor.collapseToEnd(); } From 99a552e145ed11605e85a263140b07c24bcb38f8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 18:55:27 +0200 Subject: [PATCH 0722/1068] guiAction* methods do not throw --- .../org/jabref/gui/openoffice/OOBibBase.java | 20 +--- .../gui/openoffice/OpenOfficePanel.java | 105 +++++------------- .../jabref/logic/openoffice/ExportCited.java | 6 +- 3 files changed, 37 insertions(+), 94 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 61873d4776a..b78d38e67dd 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -1,6 +1,5 @@ package org.jabref.gui.openoffice; -import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; @@ -720,17 +719,7 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s * shall we return an otherwise nonempty result, or Optional.empty()? */ public Optional exportCitedHelper(List databases, - boolean returnPartialResult) - throws - WrappedTargetException, - NoSuchElementException, - NoDocumentException, - UnknownPropertyException, - PropertyVetoException, - IOException, - CreationException, - InvalidStateException, - JabRefException { + boolean returnPartialResult) { final Optional FAIL = Optional.empty(); final String title = Localization.lang("Unable to generate new library"); @@ -784,9 +773,10 @@ public Optional exportCitedHelper(List databases, return Optional.of(result.newDatabase); } catch (NoDocumentException ex) { OOError.from(ex).showErrorDialog(dialogService); - } catch (UnknownPropertyException - | NoSuchElementException - | WrappedTargetException ex) { + } catch (NoSuchElementException + | UnknownPropertyException + | WrappedTargetException + | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Problem generating new database.", ex); OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index ed53d716edc..0bd9e471848 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -39,17 +39,14 @@ import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.gui.util.TaskExecutor; -import org.jabref.logic.JabRefException; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.help.HelpFile; import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.StyleLoader; -import org.jabref.logic.openoffice.ConnectionLostException; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.EditInsert; -import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; import org.jabref.model.database.BibDatabase; @@ -59,12 +56,7 @@ import org.jabref.model.openoffice.CitationEntry; import org.jabref.preferences.PreferencesService; -import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; import com.sun.star.comp.helper.BootstrapException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -145,7 +137,7 @@ public Node getContent() { /* Note: the style may still be null on return. * - * Return true is failed and dialog is already shown. + * Return true if failed. In this case the dialog is already shown. */ private boolean getOrUpdateTheStyle(String title) { final boolean FAIL = true; @@ -213,23 +205,8 @@ private void initPanel() { if (getOrUpdateTheStyle(title)) { return; } - if (style == null) { - OOError.noValidStyleSelected() - .setTitle(title) - .showErrorDialog(dialogService); - return; - } - List databases = getBaseList(); - - try { - ooBase.guiActionUpdateDocument(databases, style); - } catch (ConnectionLostException ex) { - OOError.from(ex).showErrorDialog(dialogService); - } catch (com.sun.star.lang.IllegalArgumentException ex) { - LOGGER.warn("Could not update bibliography", ex); - OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); - } + ooBase.guiActionUpdateDocument(databases, style); }); merge.setMaxWidth(Double.MAX_VALUE); @@ -281,28 +258,12 @@ private void initPanel() { private void exportEntries() { final String title = Localization.lang("Problem generating new database."); - try { - List databases = getBaseList(); - if (databases.isEmpty()) { - OOError.noDataBaseIsOpenForExport().showErrorDialog(dialogService); - return; - } - boolean returnPartialResult = false; - Optional newDatabase = ooBase.exportCitedHelper(databases, returnPartialResult); - if (newDatabase.isPresent()) { - BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase.get()); - this.frame.addTab(databaseContext, true); - } - } catch (JabRefException ex) { - OOError.from(ex).showErrorDialog(dialogService); - } catch (NoDocumentException ex) { - OOError.from(ex).showErrorDialog(dialogService); - } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | - NoSuchElementException | WrappedTargetException | IOException | - InvalidStateException | - CreationException ex) { - LOGGER.warn("Problem generating new database.", ex); - OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); + List databases = getBaseList(); + boolean returnPartialResult = false; + Optional newDatabase = ooBase.exportCitedHelper(databases, returnPartialResult); + if (newDatabase.isPresent()) { + BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase.get()); + this.frame.addTab(databaseContext, true); } } @@ -509,18 +470,11 @@ private void pushEntries(InTextCitationType citationType, boolean addPageInfo) { if (getOrUpdateTheStyle(title)) { return; } - if (style == null) { - OOError.noValidStyleSelected() - .setTitle(title) - .showErrorDialog(dialogService); - return; - } - - Boolean inParenthesis = citationType.inParenthesis(); - boolean withText = citationType.withText(); String pageInfo = null; if (addPageInfo) { + Boolean inParenthesis = citationType.inParenthesis(); + boolean withText = citationType.withText(); Optional citeDialogViewModel = dialogService.showCustomDialogAndWait(new AdvancedCiteDialogView()); if (citeDialogViewModel.isPresent()) { @@ -530,30 +484,29 @@ private void pushEntries(InTextCitationType citationType, boolean addPageInfo) { pageInfo = model.pageInfoProperty().getValue(); } inParenthesis = model.citeInParProperty().getValue(); + citationType = citationTypeFromOptions(withText, inParenthesis); + } else { + // user canceled + return; } } - if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { - try { - Optional syncOptions = - (ooPrefs.getSyncWhenCiting() - ? Optional.of(new EditInsert.SyncOptions(getBaseList())) - : Optional.empty()); - - ooBase.guiActionInsertEntry(entries, - database, - style, - citationTypeFromOptions(withText, inParenthesis), - pageInfo, - syncOptions); - - } catch (ConnectionLostException ex) { - OOError.from(ex).showErrorDialog(dialogService); - } catch (com.sun.star.lang.IllegalArgumentException ex) { - LOGGER.warn("Could not insert entry", ex); - OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); - } + if (!checkThatEntriesHaveKeys(entries)) { + // Not all entries have keys and key generation was declined. + return; } + + Optional syncOptions = + (ooPrefs.getSyncWhenCiting() + ? Optional.of(new EditInsert.SyncOptions(getBaseList())) + : Optional.empty()); + + ooBase.guiActionInsertEntry(entries, + database, + style, + citationType, + pageInfo, + syncOptions); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/ExportCited.java index 5e8ccb09184..349e35205db 100644 --- a/src/main/java/org/jabref/logic/openoffice/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/ExportCited.java @@ -44,10 +44,10 @@ public static class GenerateDatabaseResult { */ public static GenerateDatabaseResult generateDatabase(XTextDocument doc, List databases) throws - NoSuchElementException, - WrappedTargetException, NoDocumentException, - UnknownPropertyException { + NoSuchElementException, + UnknownPropertyException, + WrappedTargetException { OOFrontend fr = new OOFrontend(doc); CitedKeys cks = fr.citationGroups.getCitedKeysUnordered(); From 0639b2c06def3c1dbf32613fc2137545201d434b Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 19:36:14 +0200 Subject: [PATCH 0723/1068] Seems DisposedException it must be caught as com.sun.star.lang.DisposedException Despite the attempt to turn it into a NoDocumentException in UnoReferenceMark.getNameAccess(doc) --- src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java index 4a2031d8dc2..ae85ce44575 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java @@ -34,6 +34,8 @@ public static boolean isDocumentConnectionMissing(XTextDocument doc) { UnoReferenceMark.getNameAccess(doc); } catch (NoDocumentException ex) { missing = true; + } catch (com.sun.star.lang.DisposedException ex) { + missing = true; } } return missing; From 84020c93067e8647cd8227167cb1200cd7de919e Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 21:13:11 +0200 Subject: [PATCH 0724/1068] Experiment with ManageCitationsDialogView.close() --- .../openoffice/ManageCitationsDialogView.java | 53 ++++++++++++++++--- .../ManageCitationsDialogViewModel.java | 14 +++-- .../gui/openoffice/OpenOfficePanel.java | 7 +-- 3 files changed, 57 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index 508b238ac90..a4bab43b9fa 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -1,12 +1,13 @@ package org.jabref.gui.openoffice; -import java.util.List; - import javax.inject.Inject; +import javafx.application.Platform; +import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.ButtonType; +import javafx.scene.control.DialogEvent; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellEditEvent; import javafx.scene.control.TableView; @@ -19,7 +20,6 @@ import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.strings.StringUtil; import com.airhacks.afterburner.views.ViewLoader; @@ -33,7 +33,6 @@ public class ManageCitationsDialogView extends BaseDialog { private static final String HTML_BOLD_START_TAG = ""; private final OOBibBase ooBase; - private final List citations; @FXML private TableView citationsTableView; @FXML private TableColumn citation; @@ -43,9 +42,8 @@ public class ManageCitationsDialogView extends BaseDialog { private ManageCitationsDialogViewModel viewModel; - public ManageCitationsDialogView(OOBibBase ooBase, List citations) { + public ManageCitationsDialogView(OOBibBase ooBase) { this.ooBase = ooBase; - this.citations = citations; ViewLoader.view(this) .load() @@ -64,7 +62,48 @@ public ManageCitationsDialogView(OOBibBase ooBase, List citations @FXML private void initialize() throws NoSuchElementException, WrappedTargetException, UnknownPropertyException, JabRefException { - viewModel = new ManageCitationsDialogViewModel(ooBase, citations, dialogService); + viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); + if (viewModel.citationEntries.isEmpty()) { + dialogService.showErrorDialogAndWait("citationEntries is empty, now trying this.close()"); + + final int variant = 4; + switch (variant) { + case 1: + // vvv This is not effective. The dialog still comes up. + this.close(); + break; + case 2: + // vvv This is not effective. The dialog still comes up. + ManageCitationsDialogView thisDialog = this; + this.setOnShowing​(new EventHandler() { + @Override + public void handle(DialogEvent arg0) { + thisDialog.close(); + } + }); + break; + case 3: + // vvv This is not effective. The dialog still comes up. + ManageCitationsDialogView thisDialog = this; + this.setOnShown(new EventHandler() { + @Override + public void handle(DialogEvent arg0) { + thisDialog.close(); + } + }); + break; + case 4: + // vvv This lets the window to be shown for + // a fraction of a second, then closes it. + ManageCitationsDialogView thisDialog = this; + Platform.runLater(new Runnable() { + @Override public void run() { + thisDialog.close(); + } + }); + break; + } + } citation.setCellValueFactory(cellData -> cellData.getValue().citationProperty()); new ValueTableCellFactory().withGraphic(this::getText).install(citation); diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index c2b997732db..32acaa54ca6 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -1,6 +1,7 @@ package org.jabref.gui.openoffice; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; import javafx.beans.property.ListProperty; @@ -12,17 +13,22 @@ public class ManageCitationsDialogViewModel { + Optional> citationEntries; + private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList()); private final OOBibBase ooBase; private final DialogService dialogService; - public ManageCitationsDialogViewModel(OOBibBase ooBase, - List citationEntries, - DialogService dialogService) { + public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) { this.ooBase = ooBase; this.dialogService = dialogService; - for (CitationEntry entry : citationEntries) { + this.citationEntries = ooBase.guiActionGetCitationEntries(); + if (citationEntries.isEmpty()) { + return; + } + + for (CitationEntry entry : citationEntries.get()) { CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); } diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 0bd9e471848..b7360ceb246 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -53,7 +53,6 @@ import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.InTextCitationType; -import org.jabref.model.openoffice.CitationEntry; import org.jabref.preferences.PreferencesService; import com.sun.star.comp.helper.BootstrapException; @@ -227,11 +226,7 @@ private void initPanel() { settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { - Optional> citations = ooBase.guiActionGetCitationEntries(); - if (citations.isPresent()) { - dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase, - citations.get())); - } + dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); }); exportCitations.setMaxWidth(Double.MAX_VALUE); From 3ace48b485bc77f32fdb8ebd4eb75409e97caf11 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 15 May 2021 23:29:29 +0200 Subject: [PATCH 0725/1068] Experiment with ManageCitationsDialogView.close() : variant 4 with SimpleObjectProperty; --- .../openoffice/ManageCitationsDialogView.java | 58 ++++--------------- .../ManageCitationsDialogViewModel.java | 10 ++-- 2 files changed, 17 insertions(+), 51 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index a4bab43b9fa..a605dded0d0 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -3,11 +3,9 @@ import javax.inject.Inject; import javafx.application.Platform; -import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.ButtonType; -import javafx.scene.control.DialogEvent; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellEditEvent; import javafx.scene.control.TableView; @@ -18,14 +16,10 @@ import org.jabref.gui.DialogService; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.ValueTableCellFactory; -import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.model.strings.StringUtil; import com.airhacks.afterburner.views.ViewLoader; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.lang.WrappedTargetException; public class ManageCitationsDialogView extends BaseDialog { @@ -60,49 +54,19 @@ public ManageCitationsDialogView(OOBibBase ooBase) { } @FXML - private void initialize() throws NoSuchElementException, WrappedTargetException, UnknownPropertyException, JabRefException { + private void initialize() { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); - if (viewModel.citationEntries.isEmpty()) { - dialogService.showErrorDialogAndWait("citationEntries is empty, now trying this.close()"); - - final int variant = 4; - switch (variant) { - case 1: - // vvv This is not effective. The dialog still comes up. - this.close(); - break; - case 2: - // vvv This is not effective. The dialog still comes up. - ManageCitationsDialogView thisDialog = this; - this.setOnShowing​(new EventHandler() { - @Override - public void handle(DialogEvent arg0) { - thisDialog.close(); - } - }); - break; - case 3: - // vvv This is not effective. The dialog still comes up. - ManageCitationsDialogView thisDialog = this; - this.setOnShown(new EventHandler() { - @Override - public void handle(DialogEvent arg0) { - thisDialog.close(); - } - }); - break; - case 4: - // vvv This lets the window to be shown for - // a fraction of a second, then closes it. - ManageCitationsDialogView thisDialog = this; - Platform.runLater(new Runnable() { - @Override public void run() { - thisDialog.close(); - } - }); - break; - } + + if (viewModel.citationEntries.getValue().isEmpty()) { + // Close the window if ooBase.guiActionGetCitationEntries(); + // returned Optional.empty(); + ManageCitationsDialogView thisDialog = this; + Platform.runLater(new Runnable() { + @Override public void run() { + thisDialog.close(); + } + }); } citation.setCellValueFactory(cellData -> cellData.getValue().citationProperty()); diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 32acaa54ca6..a7eb825b41f 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -6,6 +6,7 @@ import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; +import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import org.jabref.gui.DialogService; @@ -13,7 +14,7 @@ public class ManageCitationsDialogViewModel { - Optional> citationEntries; + SimpleObjectProperty>> citationEntries; private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList()); private final OOBibBase ooBase; @@ -23,12 +24,13 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogServ this.ooBase = ooBase; this.dialogService = dialogService; - this.citationEntries = ooBase.guiActionGetCitationEntries(); - if (citationEntries.isEmpty()) { + this.citationEntries = new SimpleObjectProperty<>(); + this.citationEntries.setValue(ooBase.guiActionGetCitationEntries()); + if (citationEntries.getValue().isEmpty()) { return; } - for (CitationEntry entry : citationEntries.get()) { + for (CitationEntry entry : citationEntries.getValue().get()) { CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); } From cac5131d317aaa9a455543495c5475dd19eadd37 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 00:08:15 +0200 Subject: [PATCH 0726/1068] Experiment with ManageCitationsDialogView.close(): just set and query state flag --- .../openoffice/ManageCitationsDialogView.java | 19 +++++++------------ .../ManageCitationsDialogViewModel.java | 12 +++++------- .../gui/openoffice/OpenOfficePanel.java | 5 ++++- 3 files changed, 16 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index a605dded0d0..588381cea3e 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -2,7 +2,6 @@ import javax.inject.Inject; -import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.ButtonType; @@ -58,17 +57,6 @@ private void initialize() { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); - if (viewModel.citationEntries.getValue().isEmpty()) { - // Close the window if ooBase.guiActionGetCitationEntries(); - // returned Optional.empty(); - ManageCitationsDialogView thisDialog = this; - Platform.runLater(new Runnable() { - @Override public void run() { - thisDialog.close(); - } - }); - } - citation.setCellValueFactory(cellData -> cellData.getValue().citationProperty()); new ValueTableCellFactory().withGraphic(this::getText).install(citation); @@ -99,4 +87,11 @@ private Node getText(String citationContext) { FlowPane flow = new FlowPane(startText, inBetweenText, endText); return flow; } + + public boolean isOkToShowThisDialog() { + if (viewModel == null || viewModel.failedToGetCitationEntries) { + return false; + } + return true; + } } diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index a7eb825b41f..3736cb3243c 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -6,7 +6,6 @@ import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; -import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import org.jabref.gui.DialogService; @@ -14,8 +13,7 @@ public class ManageCitationsDialogViewModel { - SimpleObjectProperty>> citationEntries; - + public final boolean failedToGetCitationEntries; private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList()); private final OOBibBase ooBase; private final DialogService dialogService; @@ -24,13 +22,13 @@ public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogServ this.ooBase = ooBase; this.dialogService = dialogService; - this.citationEntries = new SimpleObjectProperty<>(); - this.citationEntries.setValue(ooBase.guiActionGetCitationEntries()); - if (citationEntries.getValue().isEmpty()) { + Optional> citationEntries = ooBase.guiActionGetCitationEntries(); + this.failedToGetCitationEntries = citationEntries.isEmpty(); + if (citationEntries.isEmpty()) { return; } - for (CitationEntry entry : citationEntries.getValue().get()) { + for (CitationEntry entry : citationEntries.get()) { CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); } diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index b7360ceb246..6ef0d6902f9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -226,7 +226,10 @@ private void initPanel() { settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { - dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); + ManageCitationsDialogView dialog = new ManageCitationsDialogView(ooBase); + if (dialog.isOkToShowThisDialog()) { + dialogService.showCustomDialogAndWait(dialog); + } }); exportCitations.setMaxWidth(Double.MAX_VALUE); From 95495df8191244660ac55dbc89a3b5e63d4ffaad Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 10:01:43 +0200 Subject: [PATCH 0727/1068] restore crazy indentation --- .../java/org/jabref/gui/openoffice/OpenOfficePanel.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 6ef0d6902f9..7ad23fb5446 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -403,10 +403,10 @@ protected OOBibBase call() throws Exception { dialogService.showErrorDialogAndWait(Localization.lang("Could not connect to running OpenOffice/LibreOffice."), Localization.lang("Could not connect to running OpenOffice/LibreOffice.") - + "\n" - + Localization.lang("Make sure you have installed OpenOffice/LibreOffice with Java support.") + "\n" - + Localization.lang("If connecting manually, please verify program and library paths.") + "\n" + "\n" + Localization.lang("Error message:"), - ex); + + "\n" + + Localization.lang("Make sure you have installed OpenOffice/LibreOffice with Java support.") + "\n" + + Localization.lang("If connecting manually, please verify program and library paths.") + "\n" + "\n" + Localization.lang("Error message:"), + ex); + "\n" } else { dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), ex); } From afcd2e3a37ebfd9333058d133af95c9cace8a921 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 10:40:17 +0200 Subject: [PATCH 0728/1068] review Result.java --- .../org/jabref/logic/openoffice/Result.java | 66 +++++++++++++++---- 1 file changed, 54 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Result.java b/src/main/java/org/jabref/logic/openoffice/Result.java index f466544c9ac..1aa0462cfc1 100644 --- a/src/main/java/org/jabref/logic/openoffice/Result.java +++ b/src/main/java/org/jabref/logic/openoffice/Result.java @@ -6,25 +6,44 @@ /* * error cannot be null * result cannot be null - * If Void is not allowed for R, use VoidResult instead. + * + * Void is not allowed for R, use VoidResult instead. + * + * Out of `isPresent()` and `isError()` exactly one is true. */ public class Result { private final Optional result; private final Optional error; + /** + * Exactly one of the arguments should be Optional.empty() + * + * @param result + * @param error + */ private Result(Optional result, Optional error) { this.result = result; this.error = error; } + /** + * @param result Null is not allowed. + */ public static Result OK(R result) { return new Result(Optional.of(result), Optional.empty()); } + /** + * @param error Null is not allowed. + */ public static Result Error(E error) { return new Result(Optional.empty(), Optional.of(error)); } + /* + * Test state + */ + public boolean isPresent() { return result.isPresent(); } @@ -41,22 +60,30 @@ public boolean isOK() { return !isError(); } + /* + * getters + */ + public R get() { if (isError()) { throw new RuntimeException("Cannot get from error"); } - return result.orElse(null); + return result.get(); + } + + public E getError() { + return error.get(); } /* - * Throw away the error part. + * Conditionals */ - public Optional getOptional() { - return result; - } - public E getError() { - return error.get(); + public Result ifPresent(Consumer fun) { + if (isPresent()) { + fun.accept(get()); + } + return this; } public Result ifError(Consumer fun) { @@ -66,13 +93,28 @@ public Result ifError(Consumer fun) { return this; } - public Result ifPresent(Consumer fun) { - if (isPresent()) { - fun.accept(get()); + public Result mapError(Function fun) { + if (isError()) { + return Error(fun.apply(getError())); + } else { + return OK(get()); } - return this; } + public Result map(Function fun) { + if (isError()) { + return Error(getError()); + } else { + return OK(fun.apply(get())); + } + } + + /** Throw away the error part. */ + public Optional getOptional() { + return result; + } + + /** Throw away the result part. */ public VoidResult asVoidResult() { if (isError()) { return VoidResult.Error(getError()); From 991127437a845865d48f5bb94c7c188f3bd52dda Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 10:48:53 +0200 Subject: [PATCH 0729/1068] restore crazy indentation: correction --- src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 7ad23fb5446..2bd57cd7b9a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -406,7 +406,7 @@ protected OOBibBase call() throws Exception { + "\n" + Localization.lang("Make sure you have installed OpenOffice/LibreOffice with Java support.") + "\n" + Localization.lang("If connecting manually, please verify program and library paths.") + "\n" + "\n" + Localization.lang("Error message:"), - ex); + "\n" + ex); } else { dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), ex); } From 997717c3e20e055c178670e14042f5f80edf70d8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 10:51:49 +0200 Subject: [PATCH 0730/1068] Result.java : map needs Function --- src/main/java/org/jabref/logic/openoffice/Result.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/jabref/logic/openoffice/Result.java b/src/main/java/org/jabref/logic/openoffice/Result.java index 1aa0462cfc1..2c31ae5f971 100644 --- a/src/main/java/org/jabref/logic/openoffice/Result.java +++ b/src/main/java/org/jabref/logic/openoffice/Result.java @@ -2,6 +2,7 @@ import java.util.Optional; import java.util.function.Consumer; +import java.util.function.Function; /* * error cannot be null From 5f1a34c980d71321e4aaa7d1bbed0ea09c8a0067 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 11:14:53 +0200 Subject: [PATCH 0731/1068] move Pair to model --- src/main/java/org/jabref/logic/oostyle/Citation.java | 2 +- .../org/jabref/logic/oostyle/CitationGroups.java | 2 +- .../logic/openoffice/OOFormattedTextIntoOO.java | 1 + .../java/org/jabref/logic/openoffice/Result.java | 12 ++++++------ .../org/jabref/{logic => model}/openoffice/Pair.java | 2 +- 5 files changed, 10 insertions(+), 9 deletions(-) rename src/main/java/org/jabref/{logic => model}/openoffice/Pair.java (80%) diff --git a/src/main/java/org/jabref/logic/oostyle/Citation.java b/src/main/java/org/jabref/logic/oostyle/Citation.java index 821e2c50807..e66f5a54439 100644 --- a/src/main/java/org/jabref/logic/oostyle/Citation.java +++ b/src/main/java/org/jabref/logic/oostyle/Citation.java @@ -2,10 +2,10 @@ import java.util.Optional; -import org.jabref.logic.openoffice.Pair; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.openoffice.Pair; public class Citation implements CitationSort.ComparableCitation { diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java index 468033c8130..12eab101707 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroups.java @@ -9,12 +9,12 @@ import java.util.Set; import java.util.function.Consumer; -import org.jabref.logic.openoffice.Pair; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.openoffice.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index e073d925f24..106d79b1f4a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -14,6 +14,7 @@ import org.jabref.architecture.AllowedToUseAwt; import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.openoffice.Pair; import com.sun.star.awt.FontSlant; import com.sun.star.awt.FontStrikeout; diff --git a/src/main/java/org/jabref/logic/openoffice/Result.java b/src/main/java/org/jabref/logic/openoffice/Result.java index 2c31ae5f971..6f9f7427c46 100644 --- a/src/main/java/org/jabref/logic/openoffice/Result.java +++ b/src/main/java/org/jabref/logic/openoffice/Result.java @@ -94,19 +94,19 @@ public Result ifError(Consumer fun) { return this; } - public Result mapError(Function fun) { + public Result map(Function fun) { if (isError()) { - return Error(fun.apply(getError())); + return Error(getError()); } else { - return OK(get()); + return OK(fun.apply(get())); } } - public Result map(Function fun) { + public Result mapError(Function fun) { if (isError()) { - return Error(getError()); + return Error(fun.apply(getError())); } else { - return OK(fun.apply(get())); + return OK(get()); } } diff --git a/src/main/java/org/jabref/logic/openoffice/Pair.java b/src/main/java/org/jabref/model/openoffice/Pair.java similarity index 80% rename from src/main/java/org/jabref/logic/openoffice/Pair.java rename to src/main/java/org/jabref/model/openoffice/Pair.java index b4c2a7bab90..de53f6d2965 100644 --- a/src/main/java/org/jabref/logic/openoffice/Pair.java +++ b/src/main/java/org/jabref/model/openoffice/Pair.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.model.openoffice; public class Pair { public final A a; From 1fe9e1df14bea0c488b328947300e8e5af2794b2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 12:07:00 +0200 Subject: [PATCH 0732/1068] moved VoidResult to model --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 1 + src/main/java/org/jabref/logic/openoffice/Result.java | 2 ++ .../java/org/jabref/{logic => model}/openoffice/VoidResult.java | 2 +- 4 files changed, 5 insertions(+), 2 deletions(-) rename src/main/java/org/jabref/{logic => model}/openoffice/VoidResult.java (96%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index b78d38e67dd..36d01cac4d2 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -29,11 +29,11 @@ import org.jabref.logic.openoffice.UnoStyle; import org.jabref.logic.openoffice.UnoUndo; import org.jabref.logic.openoffice.Update; -import org.jabref.logic.openoffice.VoidResult; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.VoidResult; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 2c31830c09c..bcb7ec5a667 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -18,6 +18,7 @@ import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.VoidResult; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/Result.java b/src/main/java/org/jabref/logic/openoffice/Result.java index 6f9f7427c46..24cf9cf8a9e 100644 --- a/src/main/java/org/jabref/logic/openoffice/Result.java +++ b/src/main/java/org/jabref/logic/openoffice/Result.java @@ -4,6 +4,8 @@ import java.util.function.Consumer; import java.util.function.Function; +import org.jabref.model.openoffice.VoidResult; + /* * error cannot be null * result cannot be null diff --git a/src/main/java/org/jabref/logic/openoffice/VoidResult.java b/src/main/java/org/jabref/model/openoffice/VoidResult.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/VoidResult.java rename to src/main/java/org/jabref/model/openoffice/VoidResult.java index a95b1cc0e31..b7add91332e 100644 --- a/src/main/java/org/jabref/logic/openoffice/VoidResult.java +++ b/src/main/java/org/jabref/model/openoffice/VoidResult.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.model.openoffice; import java.util.Optional; import java.util.function.Consumer; From 1ce9d832453dc906206d2aac0ad9849202650a71 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 12:11:36 +0200 Subject: [PATCH 0733/1068] moved Result.java to model --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java | 2 +- .../java/org/jabref/{logic => model}/openoffice/Result.java | 4 +--- 3 files changed, 3 insertions(+), 5 deletions(-) rename src/main/java/org/jabref/{logic => model}/openoffice/Result.java (96%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 36d01cac4d2..ca6e91efce5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -23,7 +23,6 @@ import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.OOFrontend; -import org.jabref.logic.openoffice.Result; import org.jabref.logic.openoffice.UnoCursor; import org.jabref.logic.openoffice.UnoRedlines; import org.jabref.logic.openoffice.UnoStyle; @@ -33,6 +32,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.Result; import org.jabref.model.openoffice.VoidResult; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index fe50f4eb30b..3b8bde37453 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -11,9 +11,9 @@ import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.NoDocumentFoundException; -import org.jabref.logic.openoffice.Result; import org.jabref.logic.openoffice.UnoCast; import org.jabref.logic.openoffice.UnoTextDocument; +import org.jabref.model.openoffice.Result; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; diff --git a/src/main/java/org/jabref/logic/openoffice/Result.java b/src/main/java/org/jabref/model/openoffice/Result.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/Result.java rename to src/main/java/org/jabref/model/openoffice/Result.java index 24cf9cf8a9e..e55c39fd1f6 100644 --- a/src/main/java/org/jabref/logic/openoffice/Result.java +++ b/src/main/java/org/jabref/model/openoffice/Result.java @@ -1,11 +1,9 @@ -package org.jabref.logic.openoffice; +package org.jabref.model.openoffice; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; -import org.jabref.model.openoffice.VoidResult; - /* * error cannot be null * result cannot be null From d32d2815afebd880c849ad6db7971ef0636563c3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 12:34:52 +0200 Subject: [PATCH 0734/1068] drop ConnectionLostException, catch DisposedException --- .../org/jabref/gui/openoffice/OOBibBase.java | 36 ++++++++++++------- .../org/jabref/gui/openoffice/OOError.java | 12 +++---- .../openoffice/ConnectionLostException.java | 11 ------ .../org/jabref/logic/openoffice/Update.java | 1 - 4 files changed, 27 insertions(+), 33 deletions(-) delete mode 100644 src/main/java/org/jabref/logic/openoffice/ConnectionLostException.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index ca6e91efce5..930ac5777a9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -13,7 +13,6 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.logic.openoffice.ConnectionLostException; import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.EditInsert; import org.jabref.logic.openoffice.EditMerge; @@ -90,17 +89,21 @@ public OOBibBase(Path loPath, DialogService dialogService) } public void guiActionSelectDocument(boolean autoSelectForSingle) { + final String title = Localization.lang("Problem connecting"); + try { this.connection.selectDocument(autoSelectForSingle); } catch (NoDocumentFoundException ex) { OOError.from(ex).showErrorDialog(dialogService); + } catch (DisposedException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (WrappedTargetException | IndexOutOfBoundsException | NoSuchElementException ex) { LOGGER.warn("Problem connecting", ex); - dialogService.showErrorDialogAndWait(ex); + OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } if (this.isConnectedToDocument()) { @@ -404,7 +407,10 @@ public Optional> guiActionGetCitationEntries() { return Optional.of(ManageCitations.getCitationEntries(doc)); } catch (NoDocumentException ex) { - OOError.from(ex).showErrorDialog(dialogService); + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); + return FAIL; + } catch (DisposedException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); return FAIL; } catch (UnknownPropertyException | WrappedTargetException ex) { @@ -455,6 +461,8 @@ public void guiActionApplyCitationEntries(List citationEntries) { } catch (NoDocumentException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); + } catch (DisposedException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException @@ -578,11 +586,7 @@ public void guiActionInsertEntry(List entries, OOError.from(ex).setTitle(title).showErrorDialog(dialogService); return; } catch (DisposedException ex) { - // We need to catch this one here because the OpenOfficePanel class is - // loaded before connection, and therefore cannot directly reference - // or catch a DisposedException (which is in a OO JAR file). - // throw new ConnectionLostException(ex.getMessage()); - OOError.from(new ConnectionLostException("DisposedException")).showErrorDialog(dialogService); + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); return; } catch (JabRefException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); @@ -638,6 +642,8 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle } catch (NoDocumentException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); + } catch (DisposedException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (JabRefException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (CreationException @@ -691,6 +697,8 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s } catch (NoDocumentException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); + } catch (DisposedException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (JabRefException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (CreationException @@ -772,7 +780,9 @@ public Optional exportCitedHelper(List databases, } return Optional.of(result.newDatabase); } catch (NoDocumentException ex) { - OOError.from(ex).showErrorDialog(dialogService); + OOError.from(ex).showErrorDialog(dialogService); + } catch (DisposedException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (NoSuchElementException | UnknownPropertyException | WrappedTargetException @@ -847,11 +857,11 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl } } catch (JabRefException ex) { - OOError.from(ex).showErrorDialog(dialogService); - } catch (ConnectionLostException ex) { - OOError.from(ex).showErrorDialog(dialogService); + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (NoDocumentException ex) { - OOError.from(ex).showErrorDialog(dialogService); + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); + } catch (DisposedException ex) { + OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (CreationException | NoSuchElementException | PropertyVetoException diff --git a/src/main/java/org/jabref/gui/openoffice/OOError.java b/src/main/java/org/jabref/gui/openoffice/OOError.java index d5002cc9b10..b7875b081da 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOError.java +++ b/src/main/java/org/jabref/gui/openoffice/OOError.java @@ -3,10 +3,11 @@ import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.openoffice.ConnectionLostException; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.NoDocumentFoundException; +import com.sun.star.lang.DisposedException; + class OOError extends JabRefException { private String localizedTitle; @@ -53,8 +54,8 @@ public static OOError fromJabRefException(JabRefException ex) { return from(ex); } - // For ConnectionLostException - public static OOError from(ConnectionLostException ex) { + // For DisposedException + public static OOError from(DisposedException ex) { return new OOError( Localization.lang("Connection lost"), Localization.lang("Connection to OpenOffice/LibreOffice has been lost." @@ -63,11 +64,6 @@ public static OOError from(ConnectionLostException ex) { ex); } - public static void - showConnectionLostErrorMessage(DialogService dialogService, ConnectionLostException ex) { - OOError.from(ex).showErrorDialog(dialogService); - } - // For NoDocumentException public static OOError from(NoDocumentException ex) { return new OOError( diff --git a/src/main/java/org/jabref/logic/openoffice/ConnectionLostException.java b/src/main/java/org/jabref/logic/openoffice/ConnectionLostException.java deleted file mode 100644 index 3f13bd74b4b..00000000000 --- a/src/main/java/org/jabref/logic/openoffice/ConnectionLostException.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.jabref.logic.openoffice; - -/** - * This exception is used to indicate that connection to OpenOffice has been lost. - */ -public class ConnectionLostException extends RuntimeException { - - public ConnectionLostException(String s) { - super(s); - } -} diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index cf91b5a13b2..5753e0beaf8 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -28,7 +28,6 @@ public static List updateDocument(XTextDocument doc, boolean doUpdateBibliography, boolean alwaysAddCitedOnPages) throws - ConnectionLostException, CreationException, JabRefException, NoDocumentException, From 608cd7cdee1da8a75e88ffc5f2fe05ccb7fafd37 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 13:15:21 +0200 Subject: [PATCH 0735/1068] doc CreationException.java --- .../java/org/jabref/logic/openoffice/CreationException.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/CreationException.java b/src/main/java/org/jabref/logic/openoffice/CreationException.java index d688afa5ae0..2b55b4496be 100644 --- a/src/main/java/org/jabref/logic/openoffice/CreationException.java +++ b/src/main/java/org/jabref/logic/openoffice/CreationException.java @@ -1,8 +1,10 @@ package org.jabref.logic.openoffice; /** - * Exception used to indicate that the plugin attempted to set a character format that is - * not defined in the current OpenOffice document. + * Exception used to indicate failure in either + * + * XMultiServiceFactory.createInstance() + * XMultiComponentFactory.createInstanceWithContext() */ public class CreationException extends Exception { From 3af113eebd921d721b4de2fd7fcd9f9db69d982f Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 13:49:18 +0200 Subject: [PATCH 0736/1068] renamed RangeForOverlapCheck.i to idWithinKind --- .../java/org/jabref/logic/openoffice/OOFrontend.java | 2 +- .../logic/openoffice/RangeForOverlapCheck.java | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index bcb7ec5a667..ba7fab37ab5 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -415,7 +415,7 @@ private List footnoteMarkRanges(XTextDocument doc) if (!seenContains) { seen.put(footnoteMarkRange.get(), true); result.add(new RangeForOverlapCheck(footnoteMarkRange.get(), - base.i, // cgid :: identifies of citation group + base.idWithinKind, RangeForOverlapCheck.FOOTNOTE_MARK_KIND, "FootnoteMark for " + base.format())); } diff --git a/src/main/java/org/jabref/logic/openoffice/RangeForOverlapCheck.java b/src/main/java/org/jabref/logic/openoffice/RangeForOverlapCheck.java index 2e639afdde5..d14d2c13d95 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeForOverlapCheck.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeForOverlapCheck.java @@ -11,9 +11,9 @@ * checking, we need a {@code description} that can be understood * by the user. * - * To be able to refer back to more extended data, we might need - * to identify its {@code kind}, and index ({@code i}) in the - * corresponding tables. + * To be able to refer back to more extended data, we might need to + * identify its {@code kind}, and its index in the corresponding + * tables or other identifier within its kind ({@code idWithinKind}) * */ public class RangeForOverlapCheck { @@ -22,13 +22,13 @@ public class RangeForOverlapCheck { public final XTextRange range; public final int kind; - public final T i; // TODO: rename to content if identifier or cgid + public final T idWithinKind; private final String description; - public RangeForOverlapCheck(XTextRange range, T i, int kind, String description) { + public RangeForOverlapCheck(XTextRange range, T idWithinKind, int kind, String description) { this.range = range; this.kind = kind; - this.i = i; + this.idWithinKind = idWithinKind; this.description = description; } From dfaed4ff7975c9ead1e7e8aa473dbf19c5e16dff Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 14:00:08 +0200 Subject: [PATCH 0737/1068] format --- src/main/java/org/jabref/logic/openoffice/OOUtil.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 415cf2a40bf..28bc0bc7f4a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -26,8 +26,7 @@ public static void insertParagraphBreak(XText text, XTextCursor cursor) text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); } - public static void insertTextAtCurrentLocation(XTextCursor cursor, - String string) + public static void insertTextAtCurrentLocation(XTextCursor cursor, String string) throws UnknownPropertyException, PropertyVetoException, From 78c20f27baf240a778bc26084200c219fb854368 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 14:07:02 +0200 Subject: [PATCH 0738/1068] use more descriptive names in RangeKeyedMap.java --- .../logic/openoffice/RangeKeyedMap.java | 41 ++++++++++--------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java index 832ba13ed8e..cb12e588f80 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java @@ -16,10 +16,10 @@ * (of type V) * * Since XTextRange values are only comparable if they share the same - * r.getText(), we group them by these. + * range.getText(), we group them by these. * * Within such groups (partitions) we may define comparison, here - * based on (r.getStart(),r.getEnd()), thus equality means identical + * based on (range.getStart(),range.getEnd()), thus equality means identical * ranges. * * For finding overlapping ranges this class proved insufficient, @@ -28,27 +28,28 @@ * */ public class RangeKeyedMap { - private final Map> xxs; + + private final Map> partitions; public RangeKeyedMap() { - this.xxs = new HashMap<>(); + this.partitions = new HashMap<>(); } - public boolean containsKey(XTextRange r) { - Objects.requireNonNull(r); - XText partitionKey = r.getText(); - if (!xxs.containsKey(partitionKey)) { + public boolean containsKey(XTextRange range) { + Objects.requireNonNull(range); + XText partitionKey = range.getText(); + if (!partitions.containsKey(partitionKey)) { return false; } - return xxs.get(partitionKey).containsKey(r); + return partitions.get(partitionKey).containsKey(range); } - public V get(XTextRange r) { - TreeMap xs = xxs.get(r.getText()); - if (xs == null) { + public V get(XTextRange range) { + TreeMap partition = partitions.get(range.getText()); + if (partition == null) { return null; } - return xs.get(r); + return partition.get(range); } private static int comparator(XTextRange a, XTextRange b) { @@ -59,19 +60,19 @@ private static int comparator(XTextRange a, XTextRange b) { return UnoTextRange.compareEnds(a, b); } - public V put(XTextRange r, V value) { - TreeMap xs = xxs.get(r.getText()); - if (xs == null) { - xs = new TreeMap<>(RangeKeyedMap::comparator); - xxs.put(r.getText(), xs); + public V put(XTextRange range, V value) { + TreeMap partition = partitions.get(range.getText()); + if (partition == null) { + partition = new TreeMap<>(RangeKeyedMap::comparator); + partitions.put(range.getText(), partition); } - return xs.put(r, value); + return partition.put(range, value); } /** * @return A list of the partitions. */ public List> partitionValues() { - return new ArrayList(xxs.values()); + return new ArrayList(partitions.values()); } } From 4ba7243b7dd78ddaafb6500078f41eb401ba9f1e Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 14:22:24 +0200 Subject: [PATCH 0739/1068] use more descriptive names in RangeKeyedMapList.java --- .../jabref/logic/openoffice/OOFrontend.java | 2 +- .../logic/openoffice/RangeKeyedMapList.java | 78 +++++++++---------- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index ba7fab37ab5..3f198ba2586 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -453,7 +453,7 @@ public VoidResult checkRangeOverlaps(XTextDocument doc, String msg = ""; for (RangeKeyedMapList.RangeOverlap e : ovs) { String l = (": " - + (e.vs.stream() + + (e.valuesForOverlappingRanges.stream() .map(v -> String.format("'%s'", v.format())) .collect(Collectors.joining(", "))) + "\n"); diff --git a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java index d39abb67335..1432c2e8121 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java @@ -7,28 +7,28 @@ import com.sun.star.text.XTextRange; public class RangeKeyedMapList { - RangeKeyedMap> xxs; + RangeKeyedMap> partitions; public RangeKeyedMapList() { - this.xxs = new RangeKeyedMap<>(); + this.partitions = new RangeKeyedMap<>(); } - public boolean containsKey(XTextRange r) { - return xxs.containsKey(r); + public boolean containsKey(XTextRange range) { + return partitions.containsKey(range); } - public List get(XTextRange r) { - return xxs.get(r); + public List get(XTextRange range) { + return partitions.get(range); } - public void add(XTextRange r, V value) { - List vs = xxs.get(r); - if (vs == null) { - vs = new ArrayList<>(); - vs.add(value); - xxs.put(r, vs); + public void add(XTextRange range, V value) { + List values = partitions.get(range); + if (values == null) { + values = new ArrayList<>(); + values.add(value); + partitions.put(range, values); } else { - vs.add(value); + values.add(value); } } @@ -36,7 +36,7 @@ public void add(XTextRange r, V value) { * @return A list of the partitions. */ public List>> partitionValues() { - return this.xxs.partitionValues(); + return this.partitions.partitionValues(); } /** @@ -68,11 +68,11 @@ public enum OverlapKind { */ public class RangeOverlap { public final OverlapKind kind; - public final List vs; + public final List valuesForOverlappingRanges; - public RangeOverlap(OverlapKind kind, List vs) { + public RangeOverlap(OverlapKind kind, List valuesForOverlappingRanges) { this.kind = kind; - this.vs = vs; + this.valuesForOverlappingRanges = valuesForOverlappingRanges; } } @@ -86,36 +86,36 @@ public RangeOverlap(OverlapKind kind, List vs) { * Zero or negative {@code atMost} means no limit. */ public List findOverlappingRanges(int atMost, boolean includeTouching) { - List res = new ArrayList<>(); - for (TreeMap> xs : xxs.partitionValues()) { - List oxs = new ArrayList<>(xs.keySet()); - for (int i = 0; i < oxs.size(); i++) { - XTextRange a = oxs.get(i); - List avs = xs.get(a); - if (avs.size() > 1) { - res.add(new RangeOverlap(OverlapKind.EQUAL_RANGE, avs)); - if (atMost > 0 && res.size() >= atMost) { - return res; + List result = new ArrayList<>(); + for (TreeMap> partition : partitions.partitionValues()) { + List orderedRanges = new ArrayList<>(partition.keySet()); + for (int i = 0; i < orderedRanges.size(); i++) { + XTextRange aRange = orderedRanges.get(i); + List aValues = partition.get(aRange); + if (aValues.size() > 1) { + result.add(new RangeOverlap(OverlapKind.EQUAL_RANGE, aValues)); + if (atMost > 0 && result.size() >= atMost) { + return result; } } - if ((i + 1) < oxs.size()) { - XTextRange b = oxs.get(i + 1); - int cmp = UnoTextRange.compareStarts(a.getEnd(), b.getStart()); + if ((i + 1) < orderedRanges.size()) { + XTextRange bRange = orderedRanges.get(i + 1); + int cmp = UnoTextRange.compareStarts(aRange.getEnd(), bRange.getStart()); if (cmp > 0 || (includeTouching && (cmp == 0))) { // found overlap or touch - List bvs = xs.get(b); - List vs = new ArrayList<>(); - vs.add(avs.get(0)); - vs.add(bvs.get(0)); - res.add(new RangeOverlap((cmp == 0) ? OverlapKind.TOUCH : OverlapKind.OVERLAP, - vs)); + List bValues = partition.get(bRange); + List valuesForOverlappingRanges = new ArrayList<>(); + valuesForOverlappingRanges.add(aValues.get(0)); + valuesForOverlappingRanges.add(bValues.get(0)); + result.add(new RangeOverlap((cmp == 0) ? OverlapKind.TOUCH : OverlapKind.OVERLAP, + valuesForOverlappingRanges)); } - if (atMost > 0 && res.size() >= atMost) { - return res; + if (atMost > 0 && result.size() >= atMost) { + return result; } } } } - return res; + return result; } } From e6beb4d19c0ebe593819ce16e4fb4eefa056819a Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 14:34:41 +0200 Subject: [PATCH 0740/1068] use more descriptive names --- .../org/jabref/logic/openoffice/OOFrontend.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 3f198ba2586..48f33633a1f 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -147,7 +147,7 @@ public Optional healthReport(XTextDocument doc) } // build final list - List> res = new ArrayList<>(); + List> result = new ArrayList<>(); for (TreeMap>> partition : rangeSorter.partitionValues()) { @@ -168,11 +168,11 @@ public Optional healthReport(XTextDocument doc) sortable.range = footnoteMarkRange.get(); } } - res.add(sortable); + result.add(sortable); } } } - return res.stream().map(e -> e).collect(Collectors.toList()); + return result.stream().map(e -> e).collect(Collectors.toList()); } /** @@ -400,11 +400,10 @@ private List footnoteMarkRanges(XTextDocument doc) List result = new ArrayList<>(); - List citRanges = citationRanges(doc); + for (RangeForOverlapCheck citationRange : citationRanges(doc)) { - for (RangeForOverlapCheck base : citRanges) { - - Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(base.range); + Optional footnoteMarkRange = + UnoTextRange.getFootnoteMarkRange(citationRange.range); if (footnoteMarkRange.isEmpty()) { // not in footnote @@ -415,9 +414,9 @@ private List footnoteMarkRanges(XTextDocument doc) if (!seenContains) { seen.put(footnoteMarkRange.get(), true); result.add(new RangeForOverlapCheck(footnoteMarkRange.get(), - base.idWithinKind, + citationRange.idWithinKind, RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + base.format())); + "FootnoteMark for " + citationRange.format())); } } return result; From 8f9762351b7e9d6bae8ffa82075969cbb4ed52da Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 18:20:52 +0200 Subject: [PATCH 0741/1068] add FunctionalTextViewCursor Getting a functional XTextViewCursor is now done in OOBibBase, so it can precheck. --- .../org/jabref/gui/openoffice/OOBibBase.java | 47 +++++- .../jabref/logic/openoffice/EditInsert.java | 11 +- .../jabref/logic/openoffice/EditMerge.java | 4 +- .../jabref/logic/openoffice/EditSeparate.java | 4 +- .../openoffice/FunctionalTextViewCursor.java | 149 ++++++++++++++++++ .../jabref/logic/openoffice/OOFrontend.java | 16 +- .../logic/openoffice/RangeSortVisual.java | 83 +--------- .../jabref/logic/openoffice/UnoCursor.java | 6 +- .../jabref/logic/openoffice/UnoSelection.java | 44 +++++- .../logic/openoffice/UnoTextDocument.java | 10 +- .../org/jabref/logic/openoffice/Update.java | 3 +- 11 files changed, 273 insertions(+), 104 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 930ac5777a9..c271c998ab8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -18,6 +18,7 @@ import org.jabref.logic.openoffice.EditMerge; import org.jabref.logic.openoffice.EditSeparate; import org.jabref.logic.openoffice.ExportCited; +import org.jabref.logic.openoffice.FunctionalTextViewCursor; import org.jabref.logic.openoffice.ManageCitations; import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.NoDocumentFoundException; @@ -219,6 +220,22 @@ Result getUserCursorForTextInsertion(XTextDocument doc, St return Result.OK(cursor); } + /** + * This may move the user cursor. + */ + Result getFunctionalTextViewCursor(XTextDocument doc, + String title) { + String messageOnFailureToObtain = + Localization.lang("Please move the cursor into the document text.") + + "\n" + + Localization.lang("To get the visual positions of your citations" + + " I need to move the cursor around," + + " but could not get it."); + Result result = + FunctionalTextViewCursor.get(doc, messageOnFailureToObtain); + return result.mapError(e -> OOError.from(e).setTitle(title)); + } + /* * * Tests for preconditions. @@ -549,6 +566,19 @@ public void guiActionInsertEntry(List entries, XTextDocument doc = odoc.get(); Result cursor = getUserCursorForTextInsertion(doc, title); + /* + * For sync we need a FunctionalTextViewCursor. + */ + Optional fcursorOpt = Optional.empty(); + + if (syncOptions.isPresent()) { + Result fcursor = getFunctionalTextViewCursor(doc, title); + if (testDialog(title, fcursor.asVoidResult())) { + return; + } + fcursorOpt = fcursor.getOptional(); + } + if (testDialog(title, cursor.asVoidResult(), checkStylesExistInTheDocument(style, doc), @@ -580,7 +610,8 @@ public void guiActionInsertEntry(List entries, style, citationType, pageInfo, - syncOptions); + syncOptions, + fcursorOpt); } catch (NoDocumentException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); @@ -625,7 +656,10 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle XTextDocument doc = odoc.get(); + Result fcursor = getFunctionalTextViewCursor(doc, title); + if (testDialog(title, + fcursor.asVoidResult(), checkStylesExistInTheDocument(style, doc), checkIfOpenOfficeIsRecordingChanges(doc))) { return; @@ -638,7 +672,8 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle EditMerge.mergeCitationGroups(doc, fr, databases, - style); + style, + fcursor.get()); } catch (NoDocumentException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); @@ -682,8 +717,10 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s } XTextDocument doc = odoc.get(); + Result fcursor = getFunctionalTextViewCursor(doc, title); if (testDialog(title, + fcursor.asVoidResult(), checkStylesExistInTheDocument(style, doc), checkIfOpenOfficeIsRecordingChanges(doc))) { return; @@ -693,7 +730,7 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s UnoUndo.enterUndoContext(doc, "Separate citations"); OOFrontend fr = new OOFrontend(doc); - EditSeparate.separateCitations(doc, fr, databases, style); + EditSeparate.separateCitations(doc, fr, databases, style, fcursor.get()); } catch (NoDocumentException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); @@ -815,7 +852,10 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl XTextDocument doc = odoc.get(); + Result fcursor = getFunctionalTextViewCursor(doc, title); + if (testDialog(title, + fcursor.asVoidResult(), checkStylesExistInTheDocument(style, doc), checkIfOpenOfficeIsRecordingChanges(doc))) { return; @@ -841,6 +881,7 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl fr, databases, style, + fcursor.get(), doUpdateBibliography, this.alwaysAddCitedOnPages); } finally { diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 58b6afd2455..da6ed416158 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -76,6 +76,13 @@ public SyncOptions setAlwaysAddCitedOnPages(boolean value) { /* * @param cursor Where to insert. + * + * @param sync If not empty, update citation markers and, + * depending on the embedded options, the + * bibliography. + * + * @param fcursor If sync.isPresent(), it must provide a + * FunctionalTextViewCursor. Otherwise not used. */ public static void insertCitationGroup(XTextDocument doc, OOFrontend fr, @@ -85,7 +92,8 @@ public static void insertCitationGroup(XTextDocument doc, OOBibStyle style, InTextCitationType citationType, String pageInfo, - Optional sync) + Optional sync, + Optional fcursor) throws UnknownPropertyException, NoDocumentException, @@ -157,6 +165,7 @@ public static void insertCitationGroup(XTextDocument doc, fr2, sync.get().databases, style, + fcursor.get(), sync.get().updateBibliography, sync.get().alwaysAddCitedOnPages); diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 83efc56c4b7..3d2c9e0cdc0 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -35,7 +35,8 @@ public class EditMerge { public static void mergeCitationGroups(XTextDocument doc, OOFrontend fr, List databases, - OOBibStyle style) + OOBibStyle style, + FunctionalTextViewCursor fcursor) throws CreationException, IllegalArgumentException, @@ -335,6 +336,7 @@ public static void mergeCitationGroups(XTextDocument doc, fr2, databases, style, + fcursor, false, /* doUpdateBibliography */ false /* alwaysAddCitedOnPages */); } diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 9cd12df5c1c..24f1d44d1e0 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -29,7 +29,8 @@ public class EditSeparate { public static void separateCitations(XTextDocument doc, OOFrontend fr, List databases, - OOBibStyle style) + OOBibStyle style, + FunctionalTextViewCursor fcursor) throws CreationException, IllegalTypeException, @@ -118,6 +119,7 @@ public static void separateCitations(XTextDocument doc, fr2, databases, style, + fcursor, false, /* doUpdateBibliography */ false /* alwaysAddCitedOnPages */); } diff --git a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java new file mode 100644 index 00000000000..f262bbab10c --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java @@ -0,0 +1,149 @@ +package org.jabref.logic.openoffice; + +import java.util.Arrays; +import java.util.Objects; + +import org.jabref.logic.JabRefException; +import org.jabref.model.openoffice.Result; + +import com.sun.star.lang.XServiceInfo; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; +import com.sun.star.text.XTextViewCursor; + +/* + * A problem with XTextViewCursor: if it is not in text, + * then we get a crippled version that does not support + * viewCursor.getStart() or viewCursor.gotoRange(range,false), + * and will throw an exception instead. + * + * Here we manipulate the cursor via getSelection and + * select (of XSelectionSupplier) to move it to the text. + * + * Seems to work when the user selected a frame or image. + * In these cases restoring the selection works, too. + * + * When the cursor is in a comment + * (referred to as "annotation" in OO API) then + * initialSelection is null, and select() + * does not help to get a function viewCursor. + * + * If get reports error, we have to ask the user + * to move the cursor into the document text. + */ +public class FunctionalTextViewCursor { + + /* + * The initial position of the cursor or null. + */ + private XTextRange initialPosition; + + /* + * The initial selection in the document or null. + */ + private XServiceInfo initialSelection; + + /* + * The view cursor, potentially moved from its original location. + */ + private XTextViewCursor viewCursor; + + /** + * The constructor may change the selection (and cursor position) to provide + * a functional XTextViewCursor. + * + * On failure the constructor restores the selection. On success, the caller must call + * instance.restore() after finished using the cursor. + */ + private FunctionalTextViewCursor(XTextRange initialPosition, + XServiceInfo initialSelection, + XTextViewCursor viewCursor) { + this.initialPosition = initialPosition; + this.initialSelection = initialSelection; + this.viewCursor = viewCursor; + } + + /* + * Get a functional XTextViewCursor or an error message. + * + * The cursor position may differ from the location + * provided by the user. + */ + public static Result get(XTextDocument doc, + String messageOnFailure) { + + Objects.requireNonNull(doc); + Objects.requireNonNull(messageOnFailure); + + XTextRange initialPosition = null; + XServiceInfo initialSelection = UnoSelection.getSelectionAsXServiceInfo(doc).orElse(null); + XTextViewCursor viewCursor = UnoCursor.getViewCursor(doc).orElse(null); + if (viewCursor != null) { + try { + initialPosition = UnoCursor.createTextCursorByRange(viewCursor); + viewCursor.getStart(); + return Result.OK(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); + } catch (com.sun.star.uno.RuntimeException ex) { + // bad cursor + viewCursor = null; + initialPosition = null; + } + } + + if (initialSelection == null) { + String errorMessage = ("Selection is not available:" + + " cannot provide a functional view cursor"); + return Result.Error(new JabRefException(errorMessage, messageOnFailure)); + } else if (!Arrays.stream(initialSelection.getSupportedServiceNames()) + .anyMatch("com.sun.star.text.TextRanges"::equals)) { + // initialSelection does not support TextRanges. + // We need to change it (and the viewCursor with it). + XTextRange newSelection = doc.getText().getStart(); + UnoSelection.select(doc, newSelection); + viewCursor = UnoCursor.getViewCursor(doc).orElse(null); + } + + if (viewCursor == null) { + restore(doc, initialPosition, initialSelection); + String errorMessage = "Could not get the view cursor"; + return Result.Error(new JabRefException(errorMessage, messageOnFailure)); + } + + try { + viewCursor.getStart(); + } catch (com.sun.star.uno.RuntimeException ex) { + restore(doc, initialPosition, initialSelection); + String errorMessage = "The view cursor failed the functionality test"; + return Result.Error(new JabRefException(errorMessage, messageOnFailure)); + } + + return Result.OK(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); + } + + public XTextViewCursor getViewCursor() { + return viewCursor; + } + + private static void restore(XTextDocument doc, + XTextRange initialPosition, + XServiceInfo initialSelection) { + + if (initialPosition != null) { + XTextViewCursor viewCursor = UnoCursor.getViewCursor(doc).orElse(null); + if (viewCursor != null) { + viewCursor.gotoRange(initialPosition, false); + return; + } + } + if (initialSelection != null) { + UnoSelection.select(doc, initialSelection); + } + } + + /* + * Restore initial state of selection (and thus viewCursor) + */ + public void restore(XTextDocument doc) { + FunctionalTextViewCursor.restore(doc, initialPosition, initialSelection); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 48f33633a1f..1022998951e 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -190,7 +190,9 @@ public Optional healthReport(XTextDocument doc) * */ private List - getVisuallySortedCitationGroupIDs(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) + getVisuallySortedCitationGroupIDs(XTextDocument doc, + boolean mapFootnotesToFootnoteMarks, + FunctionalTextViewCursor fcursor) throws WrappedTargetException, NoDocumentException, @@ -199,16 +201,10 @@ public Optional healthReport(XTextDocument doc) List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); - String messageOnFailureToObtainAFunctionalXTextViewCursor = - Localization.lang("Please move the cursor into the document text.") - + "\n" - + Localization.lang("To get the visual positions of your citations" - + " I need to move the cursor around," - + " but could not get it."); List> sorted = RangeSortVisual.visualSort(sortables, doc, - messageOnFailureToObtainAFunctionalXTextViewCursor); + fcursor); return (sorted.stream().map(e -> e.getContent()).collect(Collectors.toList())); } @@ -527,7 +523,7 @@ public void applyCitationEntries(XTextDocument doc, List citation this.backend.applyCitationEntries(doc, citationEntries); } - public void imposeGlobalOrder(XTextDocument doc) + public void imposeGlobalOrder(XTextDocument doc, FunctionalTextViewCursor fcursor) throws WrappedTargetException, NoDocumentException, @@ -535,7 +531,7 @@ public void imposeGlobalOrder(XTextDocument doc) boolean mapFootnotesToFootnoteMarks = true; List sortedCitationGroupIDs = - getVisuallySortedCitationGroupIDs(doc, mapFootnotesToFootnoteMarks); + getVisuallySortedCitationGroupIDs(doc, mapFootnotesToFootnoteMarks, fcursor); citationGroups.setGlobalOrder(sortedCitationGroupIDs); } } diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index e45bec419c1..14fa80d7cb8 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -1,17 +1,13 @@ package org.jabref.logic.openoffice; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.TreeSet; -import org.jabref.logic.JabRefException; - import com.sun.star.awt.Point; import com.sun.star.lang.WrappedTargetException; -import com.sun.star.lang.XServiceInfo; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextViewCursor; @@ -126,13 +122,6 @@ public int hashCode() { * Sort its input {@code vses} visually. * * Requires a functional {@code XTextViewCursor}. - * In case the user selected a frame, it can get one, - * but not if the cursor is in a comment. In the latter case - * it throws a JabRefException asking the user to move the cursor. - * - * @param messageOnFailureToObtainAFunctionalXTextViewCursor - * A localized message to the user, asking to move the cursor - * into the document. * * @return The input, sorted by the elements XTextRange and * getIndexInPosition. @@ -140,11 +129,10 @@ public int hashCode() { public static List> visualSort(List> vses, XTextDocument doc, - String messageOnFailureToObtainAFunctionalXTextViewCursor) + FunctionalTextViewCursor fcursor) throws WrappedTargetException, - NoDocumentException, - JabRefException { + NoDocumentException { final int inputSize = vses.size(); @@ -154,65 +142,7 @@ public int hashCode() { + " is probably useless"); } - /* - * A problem with XTextViewCursor: if it is not in text, - * then we get a crippled version that does not support - * viewCursor.getStart() or viewCursor.gotoRange(range,false), - * and will throw an exception instead. - * - * Our hope is that either we can move the cursor with a - * page- or scrolling-based method that does not throw, (see - * https://docs.libreoffice.org/sw/html/unotxvw_8cxx_source.html#l00896 - * ) or that we can manipulate the cursor via getSelection and - * select (of XSelectionSupplier). - * - * Here we implemented the second, selection-based method. - * Seems to work when the user selected a frame or image. - * In these cases restoring the selection works, too. - * - * Still, we have a problem when the cursor is in a comment - * (referred to as "annotation" in OO API): in this case - * initialSelection is null, and Documentconnection.select() - * does not help to get a function viewCursor. Having no - * better idea, we ask the user to move the cursor into the - * document. - */ - - /* - * Selection-based - */ - final boolean debugThisFun = false; - - XServiceInfo initialSelection = UnoSelection.getSelectionAsXServiceInfo(doc).orElse(null); - - if (initialSelection != null) { - if (Arrays.stream(initialSelection.getSupportedServiceNames()) - .anyMatch("com.sun.star.text.TextRanges"::equals)) { - // we are probably OK with the viewCursor - if (debugThisFun) { - LOGGER.info("visualSort: initialSelection supports TextRanges: no action needed."); - } - } else { - if (debugThisFun) { - LOGGER.info("visualSort: initialSelection does not support TextRanges." - + " We need to change the viewCursor."); - } - XTextRange newSelection = doc.getText().getStart(); - UnoSelection.select(doc, newSelection); - } - } else { - if (debugThisFun) { - LOGGER.info("visualSort: initialSelection is null: no idea what to do."); - } - } - - XTextViewCursor viewCursor = UnoCursor.getViewCursor(doc).orElse(null); - Objects.requireNonNull(viewCursor); - try { - viewCursor.getStart(); - } catch (com.sun.star.uno.RuntimeException ex) { - throw new JabRefException(messageOnFailureToObtainAFunctionalXTextViewCursor, ex); - } + XTextViewCursor viewCursor = fcursor.getViewCursor(); // find coordinates List positions = new ArrayList<>(vses.size()); @@ -222,12 +152,7 @@ public int hashCode() { viewCursor)); } - /* - * Restore initial state of selection (and thus viewCursor) - */ - if (initialSelection != null) { - UnoSelection.select(doc, initialSelection); - } + fcursor.restore(doc); if (positions.size() != inputSize) { throw new RuntimeException("visualSort: positions.size() != inputSize"); diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCursor.java b/src/main/java/org/jabref/logic/openoffice/UnoCursor.java index d495f5c8960..2d5d6443b01 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoCursor.java @@ -25,7 +25,7 @@ public static Optional getViewCursor(XTextDocument doc) { /** * Create a text cursor for a textContent. * - * @return null if mark is null, otherwise cursor. + * @return Optional.empty if mark is null, otherwise cursor. * */ public static Optional getTextCursorOfTextContentAnchor(XTextContent mark) { @@ -38,4 +38,8 @@ public static Optional getTextCursorOfTextContentAnchor(XTextConten } return Optional.of(markAnchor.getText().createTextCursorByRange(markAnchor)); } + + public static XTextCursor createTextCursorByRange(XTextRange r) { + return r.getText().createTextCursorByRange(r); + } } diff --git a/src/main/java/org/jabref/logic/openoffice/UnoSelection.java b/src/main/java/org/jabref/logic/openoffice/UnoSelection.java index ac5c2285d2c..a5fb4290d0f 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoSelection.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoSelection.java @@ -1,22 +1,40 @@ package org.jabref.logic.openoffice; +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 getSelectionSupplier(XTextDocument doc) { - return (Optional.ofNullable(doc) - .map(e -> UnoTextDocument.getCurrentController(e)) - .flatMap(e -> UnoCast.optUnoQI(XSelectionSupplier.class, e))); + if (doc == null) { + LOGGER.warn("UnoSelection.getSelectionSupplier: doc is null"); + return Optional.empty(); + } + Optional controller = UnoTextDocument.getCurrentController(doc); + if (controller.isEmpty()) { + LOGGER.warn("UnoSelection.getSelectionSupplier: getCurrentController(doc) returned empty"); + return Optional.empty(); + } + XSelectionSupplier supplier = UnoCast.unoQI(XSelectionSupplier.class, controller.get()); + if (supplier == null) { + LOGGER.warn("UnoSelection.getSelectionSupplier: unoQI(XSelectionSupplier) returned null"); + return Optional.empty(); + } + return Optional.of(supplier); } /** @@ -63,9 +81,22 @@ private static Optional getSelectionSupplier(XTextDocument d * "com.sun.star.text.TextGraphicObject" */ public static Optional getSelectionAsXServiceInfo(XTextDocument doc) { - return (getSelectionSupplier(doc) - .flatMap(e -> Optional.ofNullable(e.getSelection())) - .flatMap(e -> UnoCast.optUnoQI(XServiceInfo.class, e))); + Objects.requireNonNull(doc); + Optional 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(); + } + XServiceInfo result = UnoCast.unoQI(XServiceInfo.class, selection); + if (result == null) { + LOGGER.warn("unoQI(XServiceInfo) returned null"); + return Optional.empty(); + } + return Optional.of(result); } /** @@ -78,6 +109,7 @@ public static Optional getSelectionAsXServiceInfo(XTextDocument do * */ public static void select(XTextDocument doc, Object newSelection) { + Objects.requireNonNull(doc); getSelectionSupplier(doc).ifPresent(e -> e.select(newSelection)); } } diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java index ae85ce44575..6a1d8862400 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java @@ -42,7 +42,15 @@ public static boolean isDocumentConnectionMissing(XTextDocument doc) { } public static Optional getCurrentController(XTextDocument doc) { - return Optional.ofNullable(doc).flatMap(e -> Optional.ofNullable(e.getCurrentController())); + 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); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index 5753e0beaf8..1523997baa1 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -25,6 +25,7 @@ public static List updateDocument(XTextDocument doc, OOFrontend fr, List databases, OOBibStyle style, + FunctionalTextViewCursor fcursor, boolean doUpdateBibliography, boolean alwaysAddCitedOnPages) throws @@ -39,7 +40,7 @@ public static List updateDocument(XTextDocument doc, final boolean useLockControllers = true; - fr.imposeGlobalOrder(doc); + fr.imposeGlobalOrder(doc, fcursor); OOProcess.ProduceCitationMarkersResult x = OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); From 0225f89dc6521d0865a20814a9451f80f680909f Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 20:34:13 +0200 Subject: [PATCH 0742/1068] Only get fcursor after cursor was checked --- .../org/jabref/gui/openoffice/OOBibBase.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index c271c998ab8..5a172550624 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -221,7 +221,7 @@ Result getUserCursorForTextInsertion(XTextDocument doc, St } /** - * This may move the user cursor. + * This may move the view cursor. */ Result getFunctionalTextViewCursor(XTextDocument doc, String title) { @@ -566,6 +566,13 @@ public void guiActionInsertEntry(List entries, XTextDocument doc = odoc.get(); Result cursor = getUserCursorForTextInsertion(doc, title); + if (testDialog(title, + cursor.asVoidResult(), + checkStylesExistInTheDocument(style, doc), + checkIfOpenOfficeIsRecordingChanges(doc))) { + return; + } + /* * For sync we need a FunctionalTextViewCursor. */ @@ -579,13 +586,6 @@ public void guiActionInsertEntry(List entries, fcursorOpt = fcursor.getOptional(); } - if (testDialog(title, - cursor.asVoidResult(), - checkStylesExistInTheDocument(style, doc), - checkIfOpenOfficeIsRecordingChanges(doc))) { - return; - } - syncOptions .map(e -> e.setUpdateBibliography(this.refreshBibliographyDuringSyncWhenCiting)) .map(e -> e.setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages)); From 40fe0378f0a7e0a02d36610e243a0741bfb399ef Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 22:11:18 +0200 Subject: [PATCH 0743/1068] moved data types used in range overlap checking to model --- .../jabref/logic/openoffice/OOFrontend.java | 27 ++-- .../logic/openoffice/RangeKeyedMapList.java | 121 ------------------ .../logic/openoffice/RangeOverlapFinder.java | 60 +++++++++ .../jabref/logic/openoffice/UnoTextRange.java | 13 ++ .../openoffice/RangeForOverlapCheck.java | 2 +- .../openoffice/RangeKeyedMap.java | 22 +++- .../model/openoffice/RangeKeyedMapList.java | 57 +++++++++ .../jabref/model/openoffice/RangeOverlap.java | 19 +++ .../model/openoffice/RangeOverlapKind.java | 8 ++ 9 files changed, 191 insertions(+), 138 deletions(-) delete mode 100644 src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java create mode 100644 src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java rename src/main/java/org/jabref/{logic => model}/openoffice/RangeForOverlapCheck.java (96%) rename src/main/java/org/jabref/{logic => model}/openoffice/RangeKeyedMap.java (77%) create mode 100644 src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java create mode 100644 src/main/java/org/jabref/model/openoffice/RangeOverlap.java create mode 100644 src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 1022998951e..616b48bcf83 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -18,6 +18,10 @@ import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.RangeForOverlapCheck; +import org.jabref.model.openoffice.RangeKeyedMap; +import org.jabref.model.openoffice.RangeKeyedMapList; +import org.jabref.model.openoffice.RangeOverlap; import org.jabref.model.openoffice.VoidResult; import com.sun.star.beans.IllegalTypeException; @@ -350,12 +354,13 @@ public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroupID c * * result.size() == nRefMarks */ - private List citationRanges(XTextDocument doc) + private List> citationRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - List result = new ArrayList<>(citationGroups.numberOfCitationGroups()); + List> result = + new ArrayList<>(citationGroups.numberOfCitationGroups()); List cgids = new ArrayList<>(citationGroups.getCitationGroupIDsUnordered()); @@ -385,7 +390,7 @@ private List citationRanges(XTextDocument doc) * footnote marks does not depend on how do we mark or * structure those ranges. */ - private List footnoteMarkRanges(XTextDocument doc) + private List> footnoteMarkRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { @@ -394,9 +399,9 @@ private List footnoteMarkRanges(XTextDocument doc) // Could use RangeSet if we had that. RangeKeyedMap seen = new RangeKeyedMap<>(); - List result = new ArrayList<>(); + List> result = new ArrayList<>(); - for (RangeForOverlapCheck citationRange : citationRanges(doc)) { + for (RangeForOverlapCheck citationRange : citationRanges(doc)) { Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(citationRange.range); @@ -432,21 +437,21 @@ public VoidResult checkRangeOverlaps(XTextDocument doc, final boolean debugPartitions = false; - List xs = citationRanges(doc); + List> xs = citationRanges(doc); xs.addAll(footnoteMarkRanges(doc)); - RangeKeyedMapList xall = new RangeKeyedMapList<>(); - for (RangeForOverlapCheck x : xs) { + RangeKeyedMapList> xall = new RangeKeyedMapList<>(); + for (RangeForOverlapCheck x : xs) { XTextRange key = x.range; xall.add(key, x); } - List.RangeOverlap> ovs = - xall.findOverlappingRanges(reportAtMost, requireSeparation); + List>> ovs = + RangeOverlapFinder.findOverlappingRanges(xall, reportAtMost, requireSeparation); if (ovs.size() > 0) { String msg = ""; - for (RangeKeyedMapList.RangeOverlap e : ovs) { + for (RangeOverlap> e : ovs) { String l = (": " + (e.valuesForOverlappingRanges.stream() .map(v -> String.format("'%s'", v.format())) diff --git a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java deleted file mode 100644 index 1432c2e8121..00000000000 --- a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMapList.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.jabref.logic.openoffice; - -import java.util.ArrayList; -import java.util.List; -import java.util.TreeMap; - -import com.sun.star.text.XTextRange; - -public class RangeKeyedMapList { - RangeKeyedMap> partitions; - - public RangeKeyedMapList() { - this.partitions = new RangeKeyedMap<>(); - } - - public boolean containsKey(XTextRange range) { - return partitions.containsKey(range); - } - - public List get(XTextRange range) { - return partitions.get(range); - } - - public void add(XTextRange range, V value) { - List values = partitions.get(range); - if (values == null) { - values = new ArrayList<>(); - values.add(value); - partitions.put(range, values); - } else { - values.add(value); - } - } - - /** - * @return A list of the partitions. - */ - public List>> partitionValues() { - return this.partitions.partitionValues(); - } - - /** - * Lis of all values: partitions in arbitrary order, ranges are - * sorted within partitions, values under the same range are in - * the order they were added. - */ - public List flatListOfValues() { - List result = new ArrayList<>(); - for (TreeMap> partition : partitionValues()) { - for (List valuesUnderARange : partition.values()) { - result.addAll(valuesUnderARange); - } - } - return result; - } - - public enum OverlapKind { - TOUCH, - OVERLAP, - EQUAL_RANGE - } - - /** - * Used in reporting range overlaps. - * - * You probably want {@code V} to include information - * identifying the ranges. - */ - public class RangeOverlap { - public final OverlapKind kind; - public final List valuesForOverlappingRanges; - - public RangeOverlap(OverlapKind kind, List valuesForOverlappingRanges) { - this.kind = kind; - this.valuesForOverlappingRanges = valuesForOverlappingRanges; - } - } - - /** - * Report identical, overlapping or touching ranges. - * - * For overlapping and touching, only report consecutive ranges - * and only with a single sample of otherwise identical ranges. - * - * @param atMost Limit the number of records returneed to atMost. - * Zero or negative {@code atMost} means no limit. - */ - public List findOverlappingRanges(int atMost, boolean includeTouching) { - List result = new ArrayList<>(); - for (TreeMap> partition : partitions.partitionValues()) { - List orderedRanges = new ArrayList<>(partition.keySet()); - for (int i = 0; i < orderedRanges.size(); i++) { - XTextRange aRange = orderedRanges.get(i); - List aValues = partition.get(aRange); - if (aValues.size() > 1) { - result.add(new RangeOverlap(OverlapKind.EQUAL_RANGE, aValues)); - if (atMost > 0 && result.size() >= atMost) { - return result; - } - } - if ((i + 1) < orderedRanges.size()) { - XTextRange bRange = orderedRanges.get(i + 1); - int cmp = UnoTextRange.compareStarts(aRange.getEnd(), bRange.getStart()); - if (cmp > 0 || (includeTouching && (cmp == 0))) { - // found overlap or touch - List bValues = partition.get(bRange); - List valuesForOverlappingRanges = new ArrayList<>(); - valuesForOverlappingRanges.add(aValues.get(0)); - valuesForOverlappingRanges.add(bValues.get(0)); - result.add(new RangeOverlap((cmp == 0) ? OverlapKind.TOUCH : OverlapKind.OVERLAP, - valuesForOverlappingRanges)); - } - if (atMost > 0 && result.size() >= atMost) { - return result; - } - } - } - } - return result; - } -} diff --git a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java b/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java new file mode 100644 index 00000000000..f88a56997a9 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java @@ -0,0 +1,60 @@ +package org.jabref.logic.openoffice; + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeMap; + +import org.jabref.model.openoffice.RangeKeyedMapList; +import org.jabref.model.openoffice.RangeOverlap; +import org.jabref.model.openoffice.RangeOverlapKind; + +import com.sun.star.text.XTextRange; + +class RangeOverlapFinder { + /** + * Report identical, overlapping or touching ranges. + * + * For overlapping and touching, only report consecutive ranges + * and only with a single sample of otherwise identical ranges. + * + * @param atMost Limit the number of records returneed to atMost. + * Zero or negative {@code atMost} means no limit. + */ + public static List> findOverlappingRanges(RangeKeyedMapList input, + int atMost, + boolean includeTouching) { + List> result = new ArrayList<>(); + for (TreeMap> partition : input.partitions.partitionValues()) { + List orderedRanges = new ArrayList<>(partition.keySet()); + for (int i = 0; i < orderedRanges.size(); i++) { + XTextRange aRange = orderedRanges.get(i); + List aValues = partition.get(aRange); + if (aValues.size() > 1) { + result.add(new RangeOverlap(RangeOverlapKind.EQUAL_RANGE, aValues)); + if (atMost > 0 && result.size() >= atMost) { + return result; + } + } + if ((i + 1) < orderedRanges.size()) { + XTextRange bRange = orderedRanges.get(i + 1); + int cmp = UnoTextRange.compareStarts(aRange.getEnd(), bRange.getStart()); + if (cmp > 0 || (includeTouching && (cmp == 0))) { + // found overlap or touch + List bValues = partition.get(bRange); + List valuesForOverlappingRanges = new ArrayList<>(); + valuesForOverlappingRanges.add(aValues.get(0)); + valuesForOverlappingRanges.add(bValues.get(0)); + result.add(new RangeOverlap((cmp == 0) + ? RangeOverlapKind.TOUCH + : RangeOverlapKind.OVERLAP, + valuesForOverlappingRanges)); + } + if (atMost > 0 && result.size() >= atMost) { + return result; + } + } + } + } + return result; + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextRange.java b/src/main/java/org/jabref/logic/openoffice/UnoTextRange.java index 42995d7cb81..8cd0d4fefe0 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextRange.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextRange.java @@ -60,4 +60,17 @@ public static int compareEnds(XTextRange a, XTextRange b) { final XTextRangeCompare compare = UnoCast.unoQI(XTextRangeCompare.class, a.getText()); return (-1) * compare.compareRegionEnds(a, b); } + + public static int compareStartsThenEnds(XTextRange a, XTextRange b) { + if (!comparables(a, b)) { + throw new RuntimeException("compareStartsThenEnds: got incomparable regions"); + } + final XTextRangeCompare compare = UnoCast.unoQI(XTextRangeCompare.class, a.getText()); + int res = (-1) * compare.compareRegionStarts(a, b); + if (res != 0) { + return res; + } + return (-1) * compare.compareRegionEnds(a, b); + } + } diff --git a/src/main/java/org/jabref/logic/openoffice/RangeForOverlapCheck.java b/src/main/java/org/jabref/model/openoffice/RangeForOverlapCheck.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/RangeForOverlapCheck.java rename to src/main/java/org/jabref/model/openoffice/RangeForOverlapCheck.java index d14d2c13d95..8c15931422d 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeForOverlapCheck.java +++ b/src/main/java/org/jabref/model/openoffice/RangeForOverlapCheck.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.model.openoffice; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java similarity index 77% rename from src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java rename to src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java index cb12e588f80..c1da3c94b69 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeKeyedMap.java +++ b/src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.model.openoffice; import java.util.ArrayList; import java.util.HashMap; @@ -9,6 +9,8 @@ import com.sun.star.text.XText; import com.sun.star.text.XTextRange; +import com.sun.star.text.XTextRangeCompare; +import com.sun.star.uno.UnoRuntime; /** * Purpose: in order to check overlaps of XTextRange values, sort @@ -52,12 +54,22 @@ public V get(XTextRange range) { return partition.get(range); } + /* + * Same as UnoTextRange.compareStartsThenEnds in logic. + */ private static int comparator(XTextRange a, XTextRange b) { - int startOrder = UnoTextRange.compareStarts(a, b); - if (startOrder != 0) { - return startOrder; + if (a.getText() != b.getText()) { + throw new RuntimeException("comparator: got incomparable regions"); + } + + final XTextRangeCompare compare = + UnoRuntime.queryInterface(XTextRangeCompare.class, a.getText()); + + int cmpStart = (-1) * compare.compareRegionStarts(a, b); + if (cmpStart != 0) { + return cmpStart; } - return UnoTextRange.compareEnds(a, b); + return (-1) * compare.compareRegionEnds(a, b); } public V put(XTextRange range, V value) { diff --git a/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java new file mode 100644 index 00000000000..dfde0c37b2e --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java @@ -0,0 +1,57 @@ +package org.jabref.model.openoffice; + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeMap; + +import com.sun.star.text.XTextRange; + +public class RangeKeyedMapList { + public RangeKeyedMap> partitions; + + public RangeKeyedMapList() { + this.partitions = new RangeKeyedMap<>(); + } + + public boolean containsKey(XTextRange range) { + return partitions.containsKey(range); + } + + public List get(XTextRange range) { + return partitions.get(range); + } + + public void add(XTextRange range, V value) { + List values = partitions.get(range); + if (values == null) { + values = new ArrayList<>(); + values.add(value); + partitions.put(range, values); + } else { + values.add(value); + } + } + + /** + * @return A list of the partitions. + */ + public List>> partitionValues() { + return this.partitions.partitionValues(); + } + + /** + * Lis of all values: partitions in arbitrary order, ranges are + * sorted within partitions, values under the same range are in + * the order they were added. + */ + public List flatListOfValues() { + List result = new ArrayList<>(); + for (TreeMap> partition : partitionValues()) { + for (List valuesUnderARange : partition.values()) { + result.addAll(valuesUnderARange); + } + } + return result; + } + +} diff --git a/src/main/java/org/jabref/model/openoffice/RangeOverlap.java b/src/main/java/org/jabref/model/openoffice/RangeOverlap.java new file mode 100644 index 00000000000..05e8b4251b3 --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/RangeOverlap.java @@ -0,0 +1,19 @@ +package org.jabref.model.openoffice; + +import java.util.List; + +/** + * Used in reporting range overlaps. + * + * You probably want {@code V} to include information + * identifying the ranges. + */ +public class RangeOverlap { + public final RangeOverlapKind kind; + public final List valuesForOverlappingRanges; + + public RangeOverlap(RangeOverlapKind kind, List valuesForOverlappingRanges) { + this.kind = kind; + this.valuesForOverlappingRanges = valuesForOverlappingRanges; + } +} diff --git a/src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java b/src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java new file mode 100644 index 00000000000..79b1acac3fe --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java @@ -0,0 +1,8 @@ +package org.jabref.model.openoffice; + +public enum RangeOverlapKind { + TOUCH, + OVERLAP, + EQUAL_RANGE +} + From ebe12eb36cf3d4774071b328f971be14092251f1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 22:46:30 +0200 Subject: [PATCH 0744/1068] split RangeSort.java --- .../jabref/logic/openoffice/OOFrontend.java | 79 +++++++++---------- .../jabref/logic/openoffice/RangeSort.java | 54 ------------- .../logic/openoffice/RangeSortEntry.java | 35 ++++++++ .../logic/openoffice/RangeSortVisual.java | 12 +-- .../logic/openoffice/RangeSortable.java | 18 +++++ 5 files changed, 97 insertions(+), 101 deletions(-) delete mode 100644 src/main/java/org/jabref/logic/openoffice/RangeSort.java create mode 100644 src/main/java/org/jabref/logic/openoffice/RangeSortEntry.java create mode 100644 src/main/java/org/jabref/logic/openoffice/RangeSortable.java diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 616b48bcf83..bf04fa3e217 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -107,7 +107,7 @@ public Optional healthReport(XTextDocument doc) * mark. This is used for numbering the citations. * */ - private List> + private List> createVisualSortInput(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) throws NoDocumentException, @@ -115,12 +115,12 @@ public Optional healthReport(XTextDocument doc) List cgids = new ArrayList<>(citationGroups.getCitationGroupIDsUnordered()); - List sortables = new ArrayList<>(); + List sortables = new ArrayList<>(); for (CitationGroupID cgid : cgids) { XTextRange range = (this .getMarkRange(doc, cgid) .orElseThrow(RuntimeException::new)); - sortables.add(new RangeSort.RangeSortEntry(range, 0, cgid)); + sortables.add(new RangeSortEntry(range, 0, cgid)); } /* @@ -144,16 +144,16 @@ public Optional healthReport(XTextDocument doc) */ // Sort within partitions - RangeKeyedMapList> rangeSorter = + RangeKeyedMapList> rangeSorter = new RangeKeyedMapList<>(); - for (RangeSort.RangeSortEntry sortable : sortables) { + for (RangeSortEntry sortable : sortables) { rangeSorter.add(sortable.getRange(), sortable); } // build final list - List> result = new ArrayList<>(); + List> result = new ArrayList<>(); - for (TreeMap>> + for (TreeMap>> partition : rangeSorter.partitionValues()) { List orderedRanges = new ArrayList<>(partition.keySet()); @@ -161,8 +161,8 @@ public Optional healthReport(XTextDocument doc) int indexInPartition = 0; for (int i = 0; i < orderedRanges.size(); i++) { XTextRange aRange = orderedRanges.get(i); - List> sortablesAtARange = partition.get(aRange); - for (RangeSort.RangeSortEntry sortable : sortablesAtARange) { + List> sortablesAtARange = partition.get(aRange); + for (RangeSortEntry sortable : sortablesAtARange) { sortable.indexInPosition = indexInPartition++; if (mapFootnotesToFootnoteMarks) { Optional footnoteMarkRange = @@ -202,10 +202,10 @@ public Optional healthReport(XTextDocument doc) NoDocumentException, JabRefException { - List> sortables = + List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); - List> sorted = + List> sorted = RangeSortVisual.visualSort(sortables, doc, fcursor); @@ -228,7 +228,7 @@ public Optional healthReport(XTextDocument doc) WrappedTargetException { // This is like getVisuallySortedCitationGroupIDs, // but we skip the visualSort part. - List> sortables = + List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); return (sortables.stream().map(e -> e.getContent()).collect(Collectors.toList())); @@ -435,39 +435,36 @@ public VoidResult checkRangeOverlaps(XTextDocument doc, NoDocumentException, WrappedTargetException { - final boolean debugPartitions = false; + List> ranges = citationRanges(doc); + ranges.addAll(footnoteMarkRanges(doc)); - List> xs = citationRanges(doc); - xs.addAll(footnoteMarkRanges(doc)); - - RangeKeyedMapList> xall = new RangeKeyedMapList<>(); - for (RangeForOverlapCheck x : xs) { - XTextRange key = x.range; - xall.add(key, x); + RangeKeyedMapList> sorted = new RangeKeyedMapList<>(); + for (RangeForOverlapCheck aRange : ranges) { + sorted.add(aRange.range, aRange); } - List>> ovs = - RangeOverlapFinder.findOverlappingRanges(xall, reportAtMost, requireSeparation); - - if (ovs.size() > 0) { - String msg = ""; - for (RangeOverlap> e : ovs) { - String l = (": " - + (e.valuesForOverlappingRanges.stream() - .map(v -> String.format("'%s'", v.format())) - .collect(Collectors.joining(", "))) - + "\n"); - - switch (e.kind) { - case EQUAL_RANGE: msg = msg + Localization.lang("Found identical ranges") + l; - break; - case OVERLAP: msg = msg + Localization.lang("Found overlapping ranges") + l; - break; - case TOUCH: msg = msg + Localization.lang("Found touching ranges") + l; - break; - } + List>> overlaps = + RangeOverlapFinder.findOverlappingRanges(sorted, reportAtMost, requireSeparation); + + if (overlaps.size() > 0) { + StringBuilder msg = new StringBuilder(); + for (RangeOverlap> overlap : overlaps) { + String listOfRanges = (overlap.valuesForOverlappingRanges.stream() + .map(v -> String.format("'%s'", v.format())) + .collect(Collectors.joining(", "))); + + msg.append( + switch (overlap.kind) { + case EQUAL_RANGE -> Localization.lang("Found identical ranges"); + case OVERLAP -> Localization.lang("Found overlapping ranges"); + case TOUCH -> Localization.lang("Found touching ranges"); + }); + msg.append(": "); + msg.append(listOfRanges); + msg.append("\n"); } - return VoidResult.Error(new JabRefException("Found overlapping or touching ranges", msg)); + return VoidResult.Error(new JabRefException("Found overlapping or touching ranges", + msg.toString())); } else { return VoidResult.OK(); } diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSort.java b/src/main/java/org/jabref/logic/openoffice/RangeSort.java deleted file mode 100644 index c945e878059..00000000000 --- a/src/main/java/org/jabref/logic/openoffice/RangeSort.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.jabref.logic.openoffice; - -import com.sun.star.text.XTextRange; - -public class RangeSort { - - /** - * This is what {@code visualSort} needs in its input. - * - * But actually there is nothing visual in it. - * Maybe we could reuse it for other sorters. - * - */ - public interface RangeSortable { - public XTextRange getRange(); - - public int getIndexInPosition(); - - public T getContent(); - } - - /** - * A simple implementation of {@code RangeSortable} - */ - public static class RangeSortEntry implements RangeSortable { - public XTextRange range; - public int indexInPosition; - public T content; - - public RangeSortEntry(XTextRange range, - int indexInPosition, - T content) { - this.range = range; - this.indexInPosition = indexInPosition; - this.content = content; - } - - @Override - public XTextRange getRange() { - return range; - } - - @Override - public int getIndexInPosition() { - return indexInPosition; - } - - @Override - public T getContent() { - return content; - } - } - -} diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortEntry.java b/src/main/java/org/jabref/logic/openoffice/RangeSortEntry.java new file mode 100644 index 00000000000..e1e0fc0e368 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortEntry.java @@ -0,0 +1,35 @@ +package org.jabref.logic.openoffice; + +import com.sun.star.text.XTextRange; + +/** + * A simple implementation of {@code RangeSortable} + */ +public class RangeSortEntry implements RangeSortable { + public XTextRange range; + public int indexInPosition; + public T content; + + public RangeSortEntry(XTextRange range, + int indexInPosition, + T content) { + this.range = range; + this.indexInPosition = indexInPosition; + this.content = content; + } + + @Override + public XTextRange getRange() { + return range; + } + + @Override + public int getIndexInPosition() { + return indexInPosition; + } + + @Override + public T getContent() { + return content; + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index 14fa80d7cb8..83de2955d59 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -126,8 +126,8 @@ public int hashCode() { * @return The input, sorted by the elements XTextRange and * getIndexInPosition. */ - public static List> - visualSort(List> vses, + public static List> + visualSort(List> vses, XTextDocument doc, FunctionalTextViewCursor fcursor) throws @@ -147,7 +147,7 @@ public int hashCode() { // find coordinates List positions = new ArrayList<>(vses.size()); - for (RangeSort.RangeSortable v : vses) { + for (RangeSortable v : vses) { positions.add(findPositionOfTextRange(v.getRange(), viewCursor)); } @@ -159,7 +159,7 @@ public int hashCode() { } // order by position - Set>> set = new TreeSet<>(); + Set>> set = new TreeSet<>(); for (int i = 0; i < vses.size(); i++) { set.add(new ComparableMark<>(positions.get(i), vses.get(i).getIndexInPosition(), @@ -171,8 +171,8 @@ public int hashCode() { } // collect CitationGroupIDs in order - List> result = new ArrayList<>(set.size()); - for (ComparableMark> mark : set) { + List> result = new ArrayList<>(set.size()); + for (ComparableMark> mark : set) { result.add(mark.getContent()); } diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortable.java b/src/main/java/org/jabref/logic/openoffice/RangeSortable.java new file mode 100644 index 00000000000..50385c87b22 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortable.java @@ -0,0 +1,18 @@ +package org.jabref.logic.openoffice; + +import com.sun.star.text.XTextRange; + +/** + * This is what {@code visualSort} needs in its input. + * + * But actually there is nothing visual in it. + * Maybe we could reuse it for other sorters. + * + */ +public interface RangeSortable { + public XTextRange getRange(); + + public int getIndexInPosition(); + + public T getContent(); +} From d70e85c7ca8e6ad406c27be55b69b7725e7a7083 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 22:55:56 +0200 Subject: [PATCH 0745/1068] moved RangeSortEntry and RangeSortable to model --- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 2 ++ src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java | 2 ++ .../org/jabref/{logic => model}/openoffice/RangeSortEntry.java | 2 +- .../org/jabref/{logic => model}/openoffice/RangeSortable.java | 2 +- 4 files changed, 6 insertions(+), 2 deletions(-) rename src/main/java/org/jabref/{logic => model}/openoffice/RangeSortEntry.java (95%) rename src/main/java/org/jabref/{logic => model}/openoffice/RangeSortable.java (90%) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index bf04fa3e217..313ea91042e 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -22,6 +22,8 @@ import org.jabref.model.openoffice.RangeKeyedMap; import org.jabref.model.openoffice.RangeKeyedMapList; import org.jabref.model.openoffice.RangeOverlap; +import org.jabref.model.openoffice.RangeSortEntry; +import org.jabref.model.openoffice.RangeSortable; import org.jabref.model.openoffice.VoidResult; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index 83de2955d59..8fbfbac169c 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -6,6 +6,8 @@ import java.util.Set; import java.util.TreeSet; +import org.jabref.model.openoffice.RangeSortable; + import com.sun.star.awt.Point; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortEntry.java b/src/main/java/org/jabref/model/openoffice/RangeSortEntry.java similarity index 95% rename from src/main/java/org/jabref/logic/openoffice/RangeSortEntry.java rename to src/main/java/org/jabref/model/openoffice/RangeSortEntry.java index e1e0fc0e368..9141bbbaef3 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortEntry.java +++ b/src/main/java/org/jabref/model/openoffice/RangeSortEntry.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.model.openoffice; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortable.java b/src/main/java/org/jabref/model/openoffice/RangeSortable.java similarity index 90% rename from src/main/java/org/jabref/logic/openoffice/RangeSortable.java rename to src/main/java/org/jabref/model/openoffice/RangeSortable.java index 50385c87b22..d72736cb1c6 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortable.java +++ b/src/main/java/org/jabref/model/openoffice/RangeSortable.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.model.openoffice; import com.sun.star.text.XTextRange; From 6f8260e10fe1d052a25c0df2da8a35ab5d991649 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 16 May 2021 23:24:56 +0200 Subject: [PATCH 0746/1068] moved StorageBase.java to model --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- .../java/org/jabref/gui/openoffice/OOBibBaseConnect.java | 4 ++-- src/main/java/org/jabref/gui/openoffice/OOError.java | 2 +- .../java/org/jabref/gui/openoffice/OpenOfficePanel.java | 2 +- src/main/java/org/jabref/logic/oostyle/CitationGroup.java | 2 +- src/main/java/org/jabref/logic/openoffice/Backend52.java | 3 +++ src/main/java/org/jabref/logic/openoffice/Codec52.java | 4 +++- src/main/java/org/jabref/logic/openoffice/EditInsert.java | 2 ++ src/main/java/org/jabref/logic/openoffice/EditMerge.java | 2 ++ .../java/org/jabref/logic/openoffice/EditSeparate.java | 2 ++ .../java/org/jabref/logic/openoffice/ExportCited.java | 1 + .../java/org/jabref/logic/openoffice/ManageCitations.java | 1 + .../jabref/logic/openoffice/OOFormattedTextIntoOO.java | 1 + src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 2 ++ src/main/java/org/jabref/logic/openoffice/OOUtil.java | 2 ++ .../java/org/jabref/logic/openoffice/RangeSortVisual.java | 1 + .../org/jabref/logic/openoffice/StorageBaseRefMark.java | 4 ++++ .../java/org/jabref/logic/openoffice/UnoBookmark.java | 3 +++ .../java/org/jabref/logic/openoffice/UnoCrossRef.java | 2 ++ src/main/java/org/jabref/logic/openoffice/UnoNamed.java | 2 ++ .../org/jabref/logic/openoffice/UnoReferenceMark.java | 3 +++ .../java/org/jabref/logic/openoffice/UnoTextDocument.java | 2 ++ .../java/org/jabref/logic/openoffice/UnoTextSection.java | 3 +++ src/main/java/org/jabref/logic/openoffice/Update.java | 2 ++ .../org/jabref/logic/openoffice/UpdateBibliography.java | 2 ++ .../jabref/logic/openoffice/UpdateCitationMarkers.java | 2 ++ .../{logic => model}/openoffice/CreationException.java | 2 +- .../{logic => model}/openoffice/NoDocumentException.java | 2 +- .../jabref/{logic => model}/openoffice/StorageBase.java | 8 ++++---- 29 files changed, 58 insertions(+), 14 deletions(-) rename src/main/java/org/jabref/{logic => model}/openoffice/CreationException.java (88%) rename src/main/java/org/jabref/{logic => model}/openoffice/NoDocumentException.java (85%) rename src/main/java/org/jabref/{logic => model}/openoffice/StorageBase.java (94%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5a172550624..6649360ca15 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -13,14 +13,12 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.EditInsert; import org.jabref.logic.openoffice.EditMerge; import org.jabref.logic.openoffice.EditSeparate; import org.jabref.logic.openoffice.ExportCited; import org.jabref.logic.openoffice.FunctionalTextViewCursor; import org.jabref.logic.openoffice.ManageCitations; -import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.UnoCursor; @@ -32,6 +30,8 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.Result; import org.jabref.model.openoffice.VoidResult; diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 3b8bde37453..77b52311d3c 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -8,11 +8,11 @@ import org.jabref.gui.DialogService; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.openoffice.CreationException; -import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.UnoCast; import org.jabref.logic.openoffice.UnoTextDocument; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.Result; import com.sun.star.comp.helper.BootstrapException; diff --git a/src/main/java/org/jabref/gui/openoffice/OOError.java b/src/main/java/org/jabref/gui/openoffice/OOError.java index b7875b081da..ef0138d2d82 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOError.java +++ b/src/main/java/org/jabref/gui/openoffice/OOError.java @@ -3,8 +3,8 @@ import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.openoffice.NoDocumentException; import org.jabref.logic.openoffice.NoDocumentFoundException; +import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.lang.DisposedException; diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 2bd57cd7b9a..331263cb6bf 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -45,7 +45,6 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.StyleLoader; -import org.jabref.logic.openoffice.CreationException; import org.jabref.logic.openoffice.EditInsert; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; @@ -53,6 +52,7 @@ import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.openoffice.CreationException; import org.jabref.preferences.PreferencesService; import com.sun.star.comp.helper.BootstrapException; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java index 72962d96b63..179755baa03 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/logic/oostyle/CitationGroup.java @@ -8,12 +8,12 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import org.jabref.logic.openoffice.StorageBase; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; +import org.jabref.model.openoffice.StorageBase; /* * A CitationGroup describes a group of citations. diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 5d0cfc0ac34..b1433452f90 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -16,6 +16,9 @@ import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.StorageBase; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/Codec52.java index 4ab1611eefd..26d48ec27db 100644 --- a/src/main/java/org/jabref/logic/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/Codec52.java @@ -10,6 +10,7 @@ import java.util.stream.Collectors; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.openoffice.NoDocumentException; /** * How and what is encoded in a mark names. @@ -92,7 +93,8 @@ public static int InTextCitationTypeToInt(InTextCitationType i) { public static String getUniqueMarkName(Set usedNames, String bibtexKey, InTextCitationType citationType) - throws NoDocumentException { + throws + NoDocumentException { int i = 0; int j = InTextCitationTypeToInt(citationType); diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index da6ed416158..cac77a9b7cc 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -15,6 +15,8 @@ import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 3d2c9e0cdc0..51a4ad0797a 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -13,6 +13,8 @@ import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 24f1d44d1e0..be09a52d6ab 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -11,6 +11,8 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/ExportCited.java index 349e35205db..7e3de920b94 100644 --- a/src/main/java/org/jabref/logic/openoffice/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/ExportCited.java @@ -10,6 +10,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; +import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; diff --git a/src/main/java/org/jabref/logic/openoffice/ManageCitations.java b/src/main/java/org/jabref/logic/openoffice/ManageCitations.java index 76e8f4cdd0b..964e87d28f4 100644 --- a/src/main/java/org/jabref/logic/openoffice/ManageCitations.java +++ b/src/main/java/org/jabref/logic/openoffice/ManageCitations.java @@ -3,6 +3,7 @@ import java.util.List; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java index 106d79b1f4a..8160fb463e6 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java @@ -14,6 +14,7 @@ import org.jabref.architecture.AllowedToUseAwt; import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.Pair; import com.sun.star.awt.FontSlant; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 313ea91042e..9a2fcde23f2 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -18,6 +18,8 @@ import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.RangeForOverlapCheck; import org.jabref.model.openoffice.RangeKeyedMap; import org.jabref.model.openoffice.RangeKeyedMapList; diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 28bc0bc7f4a..1a09c083e49 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -1,5 +1,7 @@ package org.jabref.logic.openoffice; +import org.jabref.model.openoffice.NoDocumentException; + import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index 8fbfbac169c..a76a8645c35 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -6,6 +6,7 @@ import java.util.Set; import java.util.TreeSet; +import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.RangeSortable; import com.sun.star.awt.Point; diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index 005e7c11125..1426273147e 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -3,6 +3,10 @@ import java.util.List; import java.util.Optional; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.StorageBase; + import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XText; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java index ef42e6b4a95..287a59eef9d 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java @@ -2,6 +2,9 @@ import java.util.Optional; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; + import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java b/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java index 89ba5bd8b09..c7e8e09f1bb 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java @@ -1,5 +1,7 @@ package org.jabref.logic.openoffice; +import org.jabref.model.openoffice.CreationException; + import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertySet; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoNamed.java b/src/main/java/org/jabref/logic/openoffice/UnoNamed.java index 58bb9a3905b..bd6459fa192 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoNamed.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoNamed.java @@ -1,5 +1,7 @@ package org.jabref.logic.openoffice; +import org.jabref.model.openoffice.CreationException; + import com.sun.star.container.XNamed; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.text.XTextContent; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java index fb9458a5fd2..36c60d8f9d0 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java @@ -5,6 +5,9 @@ import java.util.List; import java.util.Optional; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; + import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java index 6a1d8862400..461b14fc26e 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java @@ -2,6 +2,8 @@ import java.util.Optional; +import org.jabref.model.openoffice.NoDocumentException; + import com.sun.star.beans.XPropertySet; import com.sun.star.document.XDocumentProperties; import com.sun.star.document.XDocumentPropertiesSupplier; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java index 02a9de1bb50..fe02ccafebe 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java @@ -2,6 +2,9 @@ import java.util.Optional; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; + import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index 1523997baa1..cd51124b2ea 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -6,6 +6,8 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOProcess; import org.jabref.model.database.BibDatabase; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java index 11300ec3a76..2c5043be455 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -6,6 +6,8 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOFormatBibliography; import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 46f81b6ea71..f0084691f5a 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -11,6 +11,8 @@ import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/CreationException.java b/src/main/java/org/jabref/model/openoffice/CreationException.java similarity index 88% rename from src/main/java/org/jabref/logic/openoffice/CreationException.java rename to src/main/java/org/jabref/model/openoffice/CreationException.java index 2b55b4496be..5900f99c935 100644 --- a/src/main/java/org/jabref/logic/openoffice/CreationException.java +++ b/src/main/java/org/jabref/model/openoffice/CreationException.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.model.openoffice; /** * Exception used to indicate failure in either diff --git a/src/main/java/org/jabref/logic/openoffice/NoDocumentException.java b/src/main/java/org/jabref/model/openoffice/NoDocumentException.java similarity index 85% rename from src/main/java/org/jabref/logic/openoffice/NoDocumentException.java rename to src/main/java/org/jabref/model/openoffice/NoDocumentException.java index a4edf3c661b..09cc216fd12 100644 --- a/src/main/java/org/jabref/logic/openoffice/NoDocumentException.java +++ b/src/main/java/org/jabref/model/openoffice/NoDocumentException.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.model.openoffice; public class NoDocumentException extends Exception { diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBase.java b/src/main/java/org/jabref/model/openoffice/StorageBase.java similarity index 94% rename from src/main/java/org/jabref/logic/openoffice/StorageBase.java rename to src/main/java/org/jabref/model/openoffice/StorageBase.java index 04668f9d33a..988f3a82a1b 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBase.java +++ b/src/main/java/org/jabref/model/openoffice/StorageBase.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.model.openoffice; import java.util.List; import java.util.Optional; @@ -11,11 +11,11 @@ public class StorageBase { - interface HasName { + public interface HasName { public String getName(); } - interface HasTextRange { + public interface HasTextRange { /** * @return Optional.empty if the mark is missing from the document. @@ -70,7 +70,7 @@ public interface NamedRange extends HasName, HasTextRange { // nothing new here } - interface NamedRangeManager { + public interface NamedRangeManager { public NamedRange create(XTextDocument doc, String markName, XTextCursor position, From 05aeca4c5d4c8723ba144b3f863d0ec9dba09296 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 00:04:00 +0200 Subject: [PATCH 0747/1068] moved CitationGroups.java et al to model --- .../org/jabref/logic/oostyle/OOBibStyle.java | 31 +------------- .../OOBibStyleGetNumCitationMarker.java | 3 +- .../logic/oostyle/OOFormatBibliography.java | 5 +++ .../org/jabref/logic/oostyle/OOProcess.java | 5 +++ .../jabref/logic/openoffice/Backend52.java | 6 +-- .../jabref/logic/openoffice/EditMerge.java | 4 +- .../jabref/logic/openoffice/EditSeparate.java | 4 +- .../jabref/logic/openoffice/ExportCited.java | 4 +- .../jabref/logic/openoffice/OOFrontend.java | 4 +- .../logic/openoffice/UpdateBibliography.java | 2 +- .../openoffice/UpdateCitationMarkers.java | 4 +- .../{logic => model}/oostyle/Citation.java | 4 +- .../oostyle/CitationGroup.java | 6 +-- .../oostyle/CitationGroups.java | 5 +-- .../oostyle/CitationPath.java | 4 +- .../oostyle/CitationSort.java | 41 +++++++++++++++---- .../{logic => model}/oostyle/CitedKey.java | 4 +- .../{logic => model}/oostyle/CitedKeys.java | 2 +- 18 files changed, 68 insertions(+), 70 deletions(-) rename src/main/java/org/jabref/{logic => model}/oostyle/Citation.java (93%) rename src/main/java/org/jabref/{logic => model}/oostyle/CitationGroup.java (96%) rename src/main/java/org/jabref/{logic => model}/oostyle/CitationGroups.java (98%) rename src/main/java/org/jabref/{logic => model}/oostyle/CitationPath.java (82%) rename src/main/java/org/jabref/{logic => model}/oostyle/CitationSort.java (59%) rename src/main/java/org/jabref/{logic => model}/oostyle/CitedKey.java (94%) rename src/main/java/org/jabref/{logic => model}/oostyle/CitedKeys.java (98%) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 7df048d2c0d..634f3e43a1a 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -30,6 +30,7 @@ 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.oostyle.CitationSort; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; @@ -940,15 +941,7 @@ public OOFormattedText getNumCitationMarkerForBibliography(int number) { } public static OOFormattedText regularizePageInfo(OOFormattedText p) { - if (p == null) { - return null; - } - String pt = OOFormattedText.toString(p).trim(); - if (pt.equals("")) { - return null; - } else { - return OOFormattedText.fromString(pt); - } + return OOFormattedText.fromString(CitationSort.regularizePageInfoToString(p)); } /** @@ -978,26 +971,6 @@ public static OOFormattedText regularizePageInfo(OOFormattedText p) { } } - /** - * Defines sort order for pageInfo strings. - * - * null comes before non-null - */ - public static int comparePageInfo(OOFormattedText a, OOFormattedText b) { - String aa = OOFormattedText.toString(regularizePageInfo(a)); - String bb = OOFormattedText.toString(regularizePageInfo(b)); - if (aa == null && bb == null) { - return 0; - } - if (aa == null) { - return -1; - } - if (bb == null) { - return +1; - } - return aa.compareTo(bb); - } - public OOFormattedText getNormalizedCitationMarker(CitationMarkerEntry ce) { return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, ce, Optional.empty()); } diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index c3966847ea1..635fe62029b 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.function.ToIntFunction; +import org.jabref.model.oostyle.CitationSort; import org.jabref.model.oostyle.OOFormattedText; class OOBibStyleGetNumCitationMarker { @@ -30,7 +31,7 @@ private static class NumberWithPageInfo { private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPageInfo b) { int res = Integer.compare(a.num, b.num); if (res == 0) { - res = OOBibStyle.comparePageInfo(a.pageInfo, b.pageInfo); + res = CitationSort.comparePageInfo(a.pageInfo, b.pageInfo); } return res; } diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index 01d95381366..7147c2945ff 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -10,7 +10,12 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.UnknownField; +import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroups; +import org.jabref.model.oostyle.CitationPath; +import org.jabref.model.oostyle.CitedKey; +import org.jabref.model.oostyle.CitedKeys; import org.jabref.model.oostyle.OOFormattedText; public class OOFormatBibliography { diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 486463949e4..dcffdbe2fc1 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -15,7 +15,12 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; +import org.jabref.model.oostyle.Citation; +import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroups; +import org.jabref.model.oostyle.CitedKey; +import org.jabref.model.oostyle.CitedKeys; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index b1433452f90..5da5e1e277d 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -8,10 +8,10 @@ import java.util.Set; import java.util.stream.Collectors; -import org.jabref.logic.oostyle.Citation; -import org.jabref.logic.oostyle.CitationGroup; -import org.jabref.logic.oostyle.CitationGroups; +import org.jabref.model.oostyle.Citation; +import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 51a4ad0797a..50c27eb8653 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -6,10 +6,10 @@ import java.util.stream.Collectors; import org.jabref.logic.JabRefException; -import org.jabref.logic.oostyle.Citation; -import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.database.BibDatabase; +import org.jabref.model.oostyle.Citation; +import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index be09a52d6ab..0c46198ea74 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -5,10 +5,10 @@ import java.util.stream.Collectors; import org.jabref.logic.JabRefException; -import org.jabref.logic.oostyle.Citation; -import org.jabref.logic.oostyle.CitationGroup; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.database.BibDatabase; +import org.jabref.model.oostyle.Citation; +import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.openoffice.CreationException; diff --git a/src/main/java/org/jabref/logic/openoffice/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/ExportCited.java index 7e3de920b94..78c09cc95df 100644 --- a/src/main/java/org/jabref/logic/openoffice/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/ExportCited.java @@ -5,11 +5,11 @@ import java.util.List; import java.util.Set; -import org.jabref.logic.oostyle.CitedKey; -import org.jabref.logic.oostyle.CitedKeys; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; +import org.jabref.model.oostyle.CitedKey; +import org.jabref.model.oostyle.CitedKeys; import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.beans.UnknownPropertyException; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 9a2fcde23f2..0ae671efca6 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -11,9 +11,9 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.oostyle.CitationGroup; -import org.jabref.logic.oostyle.CitationGroups; +import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java index 2c5043be455..0f71793f098 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -2,9 +2,9 @@ import java.util.Optional; -import org.jabref.logic.oostyle.CitedKeys; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOFormatBibliography; +import org.jabref.model.oostyle.CitedKeys; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index f0084691f5a..de8d086bdd7 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -5,10 +5,10 @@ import java.util.Objects; import org.jabref.logic.JabRefException; -import org.jabref.logic.oostyle.CitationGroup; -import org.jabref.logic.oostyle.CitationGroups; import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.openoffice.CreationException; diff --git a/src/main/java/org/jabref/logic/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java similarity index 93% rename from src/main/java/org/jabref/logic/oostyle/Citation.java rename to src/main/java/org/jabref/model/oostyle/Citation.java index e66f5a54439..1f6cdde6baf 100644 --- a/src/main/java/org/jabref/logic/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -1,10 +1,8 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; import java.util.Optional; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.CitationDatabaseLookup; -import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.openoffice.Pair; public class Citation implements CitationSort.ComparableCitation { diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java similarity index 96% rename from src/main/java/org/jabref/logic/oostyle/CitationGroup.java rename to src/main/java/org/jabref/model/oostyle/CitationGroup.java index 179755baa03..f3f05f4a82c 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; import java.util.ArrayList; import java.util.Collections; @@ -9,10 +9,6 @@ import java.util.stream.Stream; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.CitationGroupID; -import org.jabref.model.oostyle.InTextCitationType; -import org.jabref.model.oostyle.OOFormattedText; -import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.StorageBase; /* diff --git a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java similarity index 98% rename from src/main/java/org/jabref/logic/oostyle/CitationGroups.java rename to src/main/java/org/jabref/model/oostyle/CitationGroups.java index 12eab101707..783959897c7 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; import java.util.Comparator; import java.util.LinkedHashMap; @@ -11,9 +11,6 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.CitationDatabaseLookup; -import org.jabref.model.oostyle.CitationGroupID; -import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.openoffice.Pair; import org.slf4j.Logger; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationPath.java b/src/main/java/org/jabref/model/oostyle/CitationPath.java similarity index 82% rename from src/main/java/org/jabref/logic/oostyle/CitationPath.java rename to src/main/java/org/jabref/model/oostyle/CitationPath.java index 8bc1360447c..9678b30b279 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationPath.java +++ b/src/main/java/org/jabref/model/oostyle/CitationPath.java @@ -1,6 +1,4 @@ -package org.jabref.logic.oostyle; - -import org.jabref.model.oostyle.CitationGroupID; +package org.jabref.model.oostyle; /** * Identifies a citation with the citation group containing it and diff --git a/src/main/java/org/jabref/logic/oostyle/CitationSort.java b/src/main/java/org/jabref/model/oostyle/CitationSort.java similarity index 59% rename from src/main/java/org/jabref/logic/oostyle/CitationSort.java rename to src/main/java/org/jabref/model/oostyle/CitationSort.java index 5d0a06858bd..cd4c710c863 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationSort.java +++ b/src/main/java/org/jabref/model/oostyle/CitationSort.java @@ -1,14 +1,13 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; import java.util.Comparator; import java.util.Optional; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.OOFormattedText; -class CitationSort { +public class CitationSort { - interface ComparableCitation { + public interface ComparableCitation { public String getCitationKey(); @@ -17,7 +16,7 @@ interface ComparableCitation { public Optional getPageInfo(); } - static class CitationComparator implements Comparator { + public static class CitationComparator implements Comparator { Comparator entryComparator; boolean unresolvedComesFirst; @@ -50,11 +49,39 @@ public int compare(ComparableCitation a, ComparableCitation b) { } // Also consider pageInfo if (res == 0) { - OOBibStyle.comparePageInfo(a.getPageInfo().orElse(null), - b.getPageInfo().orElse(null)); + CitationSort.comparePageInfo(a.getPageInfo().orElse(null), + b.getPageInfo().orElse(null)); } return res; } } + public static String regularizePageInfoToString(OOFormattedText p) { + if (p == null) { + return null; + } + String pt = OOFormattedText.toString(p).trim(); + return (pt.equals("") ? null : pt); + } + + /** + * Defines sort order for pageInfo strings. + * + * null comes before non-null + */ + public static int comparePageInfo(OOFormattedText a, OOFormattedText b) { + + String aa = regularizePageInfoToString(a); + String bb = regularizePageInfoToString(b); + if (aa == null && bb == null) { + return 0; + } + if (aa == null) { + return -1; + } + if (bb == null) { + return +1; + } + return aa.compareTo(bb); + } } diff --git a/src/main/java/org/jabref/logic/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java similarity index 94% rename from src/main/java/org/jabref/logic/oostyle/CitedKey.java rename to src/main/java/org/jabref/model/oostyle/CitedKey.java index 09abf8af4a6..c7a72fe7d2d 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; import java.util.LinkedHashSet; import java.util.List; @@ -6,8 +6,6 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.CitationDatabaseLookup; -import org.jabref.model.oostyle.OOFormattedText; public class CitedKey implements CitationSort.ComparableCitation { public String citationKey; diff --git a/src/main/java/org/jabref/logic/oostyle/CitedKeys.java b/src/main/java/org/jabref/model/oostyle/CitedKeys.java similarity index 98% rename from src/main/java/org/jabref/logic/oostyle/CitedKeys.java rename to src/main/java/org/jabref/model/oostyle/CitedKeys.java index 47f2e3fb9f5..7e6199e6fcd 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKeys.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; import java.util.ArrayList; import java.util.Comparator; From 56fb8e89701fd2b6a52d1b9469fe2bc961f59041 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 00:09:48 +0200 Subject: [PATCH 0748/1068] moved CitationMarkerEntry to model --- src/main/java/org/jabref/logic/oostyle/OOBibStyle.java | 1 + .../org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java | 1 + src/main/java/org/jabref/logic/oostyle/OOProcess.java | 2 ++ src/main/java/org/jabref/logic/openoffice/EditInsert.java | 4 ++-- .../jabref/{logic => model}/oostyle/CitationMarkerEntry.java | 3 +-- .../{logic => model}/oostyle/CitationMarkerEntryImpl.java | 3 +-- 6 files changed, 8 insertions(+), 6 deletions(-) rename src/main/java/org/jabref/{logic => model}/oostyle/CitationMarkerEntry.java (95%) rename src/main/java/org/jabref/{logic => model}/oostyle/CitationMarkerEntryImpl.java (97%) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 634f3e43a1a..ada60df646c 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -30,6 +30,7 @@ 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.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationSort; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 4ac8ef72ee5..cd2915b6f30 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -12,6 +12,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; +import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.strings.StringUtil; diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index dcffdbe2fc1..7881e09b655 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -19,6 +19,8 @@ import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; +import org.jabref.model.oostyle.CitationMarkerEntry; +import org.jabref.model.oostyle.CitationMarkerEntryImpl; import org.jabref.model.oostyle.CitedKey; import org.jabref.model.oostyle.CitedKeys; import org.jabref.model.oostyle.InTextCitationType; diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index cac77a9b7cc..e35ae0f307e 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -6,11 +6,11 @@ import java.util.stream.Collectors; import org.jabref.logic.JabRefException; -import org.jabref.logic.oostyle.CitationMarkerEntry; -import org.jabref.logic.oostyle.CitationMarkerEntryImpl; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.CitationMarkerEntry; +import org.jabref.model.oostyle.CitationMarkerEntryImpl; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; diff --git a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java similarity index 95% rename from src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java rename to src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java index 3b52eaf9b94..81debf4bc31 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java @@ -1,10 +1,9 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; import java.util.Optional; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.OOFormattedText; /** * This is what we need for getCitationMarker to produce author-year diff --git a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java similarity index 97% rename from src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java rename to src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java index cb5537c01b1..ad36cd5c2dc 100644 --- a/src/main/java/org/jabref/logic/oostyle/CitationMarkerEntryImpl.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java @@ -1,11 +1,10 @@ -package org.jabref.logic.oostyle; +package org.jabref.model.oostyle; import java.util.Objects; import java.util.Optional; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.OOFormattedText; /** * Implement CitationMarkerEntry by containing the data needed. From d46e253ad51bce3b9e4d2f165e33038b0f5d3779 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 08:18:38 +0200 Subject: [PATCH 0749/1068] drop superfluous changes --- src/main/resources/l10n/JabRef_en.properties | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index cfa3a44067e..a00119959b2 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1022,7 +1022,6 @@ Problem\ modifying\ citation=Problem modifying citation Problem\ collecting\ citations=Problem collecting citations Citation=Citation Connecting...=Connecting... - Select\ style=Select style Journals=Journals Cite=Cite @@ -2372,4 +2371,3 @@ Convert\ timestamp\ field\ to\ field\ 'creationdate'=Convert timestamp field to Convert\ timestamp\ field\ to\ field\ 'modificationdate'=Convert timestamp field to field 'modificationdate' New\ entry\ by\ type=New entry by type - From d25534dde45ac267879538ad331a6085befdae7f Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 08:32:34 +0200 Subject: [PATCH 0750/1068] use longer names --- .../jabref/model/oostyle/CitationSort.java | 20 ++++++++----------- 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationSort.java b/src/main/java/org/jabref/model/oostyle/CitationSort.java index cd4c710c863..abb713a50a2 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationSort.java +++ b/src/main/java/org/jabref/model/oostyle/CitationSort.java @@ -21,31 +21,27 @@ public static class CitationComparator implements Comparator Comparator entryComparator; boolean unresolvedComesFirst; - CitationComparator(Comparator entryComparator, - boolean unresolvedComesFirst) { + CitationComparator(Comparator entryComparator, boolean unresolvedComesFirst) { this.entryComparator = entryComparator; this.unresolvedComesFirst = unresolvedComesFirst; } public int compare(ComparableCitation a, ComparableCitation b) { - Optional abe = a.getBibEntry(); - Optional bbe = b.getBibEntry(); + Optional aBibEntry = a.getBibEntry(); + Optional bBibEntry = b.getBibEntry(); final int mul = unresolvedComesFirst ? (+1) : (-1); int res = 0; - if (abe.isEmpty() && bbe.isEmpty()) { + if (aBibEntry.isEmpty() && bBibEntry.isEmpty()) { // Both are unresolved: compare them by citation key. - String ack = a.getCitationKey(); - String bck = b.getCitationKey(); - res = ack.compareTo(bck); - } else if (abe.isEmpty()) { + res = a.getCitationKey().compareTo(b.getCitationKey()); + } else if (aBibEntry.isEmpty()) { return -mul; - } else if (bbe.isEmpty()) { + } else if (bBibEntry.isEmpty()) { return mul; } else { // Proper comparison of entries - res = entryComparator.compare(abe.get(), - bbe.get()); + res = entryComparator.compare(aBibEntry.get(), bBibEntry.get()); } // Also consider pageInfo if (res == 0) { From e9422558a6a4aa67d3c039c1b6e094c120c02835 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 09:39:45 +0200 Subject: [PATCH 0751/1068] add missing localization message --- src/main/resources/l10n/JabRef_en.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index a00119959b2..2a060589c54 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1159,6 +1159,7 @@ Toggle\ quality\ assured=Toggle quality assured Toggle\ print\ status=Toggle print status Update\ keywords=Update keywords Write\ values\ of\ special\ fields\ as\ separate\ fields\ to\ BibTeX=Write values of special fields as separate fields to BibTeX +Problem\ connecting=Problem connecting Connection\ to\ OpenOffice/LibreOffice\ has\ been\ lost.\ Please\ make\ sure\ OpenOffice/LibreOffice\ is\ running,\ and\ try\ to\ reconnect.=Connection to OpenOffice/LibreOffice has been lost. Please make sure OpenOffice/LibreOffice is running, and try to reconnect. JabRef\ will\ send\ at\ least\ one\ request\ per\ entry\ to\ a\ publisher.=JabRef will send at least one request per entry to a publisher. From 925ff905759711871d124db8e73e18dbc4739881 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 09:51:22 +0200 Subject: [PATCH 0752/1068] use CitationDatabaseLookup.Result in CitationMarkerEntry --- .../oostyle/OOBibStyleGetCitationMarker.java | 40 +++----- .../org/jabref/logic/oostyle/OOProcess.java | 10 +- .../jabref/logic/openoffice/EditInsert.java | 8 +- .../org/jabref/model/oostyle/Citation.java | 4 + .../model/oostyle/CitationDatabaseLookup.java | 8 +- .../model/oostyle/CitationMarkerEntry.java | 18 +--- .../oostyle/CitationMarkerEntryImpl.java | 78 +++++---------- .../jabref/logic/oostyle/OOBibStyleTest.java | 98 ++++++++++++------- 8 files changed, 118 insertions(+), 146 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index cd2915b6f30..386e753e604 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -12,6 +12,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; +import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; @@ -292,16 +293,15 @@ private static String getCitationMarkerField(OOBibStyle style, } private static AuthorList getAuthorList(OOBibStyle style, - BibEntry entry, - BibDatabase database) { + CitationDatabaseLookup.Result db) { // The bibtex fields providing author names, e.g. "author" or // "editor". OrFields authorFieldNames = style.getAuthorFieldNames(); String authorListAsString = getCitationMarkerField(style, - entry, - database, + db.entry, + db.database, authorFieldNames); return AuthorList.parse(authorListAsString); } @@ -325,14 +325,13 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, ? style.getMaxAuthorsFirst() : style.getMaxAuthors()); - BibEntry bibEntry = ce.getBibEntry().orElse(null); - BibDatabase database = ce.getDatabase().orElse(null); - boolean isUnresolved = (bibEntry == null) || (database == null); - if (isUnresolved) { + if (ce.getDatabaseLookupResult().isEmpty()) { + // unresolved return 0; } - AuthorList authorList = getAuthorList(style, bibEntry, database); + AuthorList authorList = getAuthorList(style, + ce.getDatabaseLookupResult().get()); int nAuthors = authorList.getNumberOfAuthors(); if (maxAuthors == -1) { @@ -443,15 +442,13 @@ private static OOFormattedText getAuthorYearParenthesisMarker(OOBibStyle style, sb.append(citationSeparator); } - BibDatabase currentDatabase = ce.getDatabase().orElse(null); - BibEntry currentEntry = ce.getBibEntry().orElse(null); - - boolean isUnresolved = (currentEntry == null) || (currentDatabase == null); - - if (isUnresolved) { + if (ce.getDatabaseLookupResult().isEmpty()) { sb.append(String.format("Unresolved(%s)", ce.getCitationKey())); } else { + BibEntry currentEntry = ce.getDatabaseLookupResult().get().entry; + BibDatabase currentDatabase = ce.getDatabaseLookupResult().get().database; + int maxAuthors = (purpose == AuthorYearMarkerPurpose.NORMALIZED ? style.getMaxAuthors() : calculateNAuthorsToEmit(style, ce)); @@ -461,8 +458,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker(OOBibStyle style, } AuthorList authorList = getAuthorList(style, - currentEntry, - currentDatabase); + ce.getDatabaseLookupResult().get()); String authorString = formatAuthorList(style, authorList, maxAuthors, andString); sb.append(authorString); sb.append(yearSep); @@ -622,14 +618,8 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, String nm1 = OOFormattedText.toString(normalizedMarkers.get(i - 1)); String nm2 = OOFormattedText.toString(normalizedMarkers.get(i)); - BibEntry bibEntry1 = ce1.getBibEntry().orElse(null); - BibEntry bibEntry2 = ce2.getBibEntry().orElse(null); - - BibDatabase database1 = ce1.getDatabase().orElse(null); - BibDatabase database2 = ce2.getDatabase().orElse(null); - - boolean isUnresolved1 = (bibEntry1 == null) || (database1 == null); - boolean isUnresolved2 = (bibEntry2 == null) || (database2 == null); + boolean isUnresolved1 = ce1.getDatabaseLookupResult().isEmpty(); + boolean isUnresolved2 = ce2.getDatabaseLookupResult().isEmpty(); boolean startingNewGroup; boolean sameAsPrev; diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 7881e09b655..c5e673fec89 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -95,8 +95,7 @@ private static OOFormattedText normalizedCitationMarkerForNormalStyle(CitedKey c // for uniqueness checking purposes: // createNormalizedCitationMarker CitationMarkerEntry ce = new CitationMarkerEntryImpl(ck.citationKey, - ck.db.map(e -> e.entry), - ck.db.map(e -> e.database), + ck.db, Optional.empty(), // uniqueLetter Optional.empty(), // pageInfo false /* isFirstAppearanceOfSource */); @@ -333,13 +332,10 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, if (cit.db.isEmpty()) { hasUnresolved = true; } - Optional database = cit.db.map(e -> e.database); - Optional bibEntry = cit.db.map(e -> e.entry); CitationMarkerEntry cm = new CitationMarkerEntryImpl(currentKey, - bibEntry, - database, + cit.db, uniqueLetterForKey, Optional.ofNullable(pageInfosForCitations.get(j)), isFirst); @@ -361,7 +357,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, for (int j = 0; j < nCitedEntries; j++) { CitationMarkerEntry cm = citationMarkerEntries.get(j); - if (cm.getBibEntry().isPresent()) { + if (cm.getDatabaseLookupResult().isPresent()) { s = (s + style.getCitationMarker(citationMarkerEntries.subList(j, j + 1), inParenthesis, diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index e35ae0f307e..539c61b6eff 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -9,6 +9,7 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerEntryImpl; import org.jabref.model.oostyle.InTextCitationType; @@ -122,10 +123,13 @@ public static void insertCitationGroup(XTextDocument doc, for (int i = 0; i < nEntries; i++) { // Using the same database for each entry. // Probably the GUI limits selection to a single database. + Optional db = + Optional.of(new CitationDatabaseLookup.Result(entries.get(i), database)); CitationMarkerEntry cm = new CitationMarkerEntryImpl(citationKeys.get(i), - Optional.ofNullable(entries.get(i)), - Optional.ofNullable(database), + db, + // Optional.ofNullable(entries.get(i)), + // Optional.ofNullable(database), Optional.empty(), // uniqueLetter Optional.ofNullable(pageInfosForCitations.get(i)), false /* isFirstAppearanceOfSource */); diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 1f6cdde6baf..498c430a948 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -51,6 +51,10 @@ public Optional getBibEntry() { : Optional.empty()); } + public Optional getDatabaseLookupResult() { + return db; + } + public static void setDatabaseLookupResult(Pair> x) { Citation cit = x.a; cit.db = x.b; diff --git a/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java b/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java index 635dbd500c0..8e490b7ed2a 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java @@ -3,6 +3,7 @@ // import org.jabref.model.oostyle.CitationDatabaseLookup; import java.util.List; +import java.util.Objects; import java.util.Optional; import org.jabref.model.database.BibDatabase; @@ -13,14 +14,15 @@ public class CitationDatabaseLookup { public static class Result { public final BibEntry entry; public final BibDatabase database; - Result(BibEntry entry, BibDatabase database) { + public Result(BibEntry entry, BibDatabase database) { + Objects.requireNonNull(entry); + Objects.requireNonNull(database); this.entry = entry; this.database = database; } } - public static Optional lookup(List databases, - String key) { + public static Optional lookup(List databases, String key) { for (BibDatabase database : databases) { Optional entry = database.getEntryByCitationKey(key); if (entry.isPresent()) { diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java index 81debf4bc31..79313e42a2a 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java @@ -2,9 +2,6 @@ import java.util.Optional; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; - /** * This is what we need for getCitationMarker to produce author-year * citation markers. @@ -28,21 +25,12 @@ public interface CitationMarkerEntry { */ String getCitationKey(); - /** Bibliography entry looked up from databases. - * - * May be empty if not found. In this case getDatabase() - * should also return empty. - */ - Optional getBibEntry(); - - /** - * The database where BibEntry was found. - * May be empty, if not found (otherwise not). + /** Result of looking up citation key in databases. */ - Optional getDatabase(); + Optional getDatabaseLookupResult(); /** - * uniqueLetter or null if not needed. + * uniqueLetter or Optional.empty() if not needed. */ Optional getUniqueLetter(); diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java index ad36cd5c2dc..5d13148d5f2 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java @@ -3,9 +3,6 @@ import java.util.Objects; import java.util.Optional; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; - /** * Implement CitationMarkerEntry by containing the data needed. * @@ -14,67 +11,41 @@ */ public class CitationMarkerEntryImpl implements CitationMarkerEntry { final String citationKey; - final Optional bibEntry; - final Optional database; + final Optional db; final Optional uniqueLetter; final Optional pageInfo; final boolean isFirstAppearanceOfSource; public CitationMarkerEntryImpl(String citationKey, - Optional bibEntry, - Optional database, + Optional databaseLookupResult, Optional uniqueLetter, Optional pageInfo, boolean isFirstAppearanceOfSource) { Objects.requireNonNull(citationKey); this.citationKey = citationKey; - - if (bibEntry.isEmpty() && database.isPresent()) { - throw new RuntimeException("CitationMarkerEntryImpl:" - + " bibEntry is present, but database is not"); - } - - if (bibEntry.isPresent() && database.isEmpty()) { - throw new RuntimeException("CitationMarkerEntryImpl:" - + " bibEntry missing, but database is present"); - } - - this.bibEntry = bibEntry; - this.database = database; + this.db = databaseLookupResult; this.uniqueLetter = uniqueLetter; this.pageInfo = pageInfo; this.isFirstAppearanceOfSource = isFirstAppearanceOfSource; } - public CitationMarkerEntryImpl(String citationKey, - BibEntry bibEntryQ, - BibDatabase databaseQ, - String uniqueLetterQ, - String pageInfoQ, - boolean isFirstAppearanceOfSource) { - Objects.requireNonNull(citationKey); - this.citationKey = citationKey; - Optional bibEntry = Optional.ofNullable(bibEntryQ); - Optional database = Optional.ofNullable(databaseQ); - Optional uniqueLetter = Optional.ofNullable(uniqueLetterQ); - Optional pageInfo = - Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); - - if (bibEntry.isEmpty() && database.isPresent()) { - throw new RuntimeException("CitationMarkerEntryImpl:" - + " bibEntry is present, but database is not"); - } - if (bibEntry.isPresent() && database.isEmpty()) { - throw new RuntimeException("CitationMarkerEntryImpl:" - + " bibEntry missing, but database is present"); - } - - this.bibEntry = bibEntry; - this.database = database; - this.uniqueLetter = uniqueLetter; - this.pageInfo = pageInfo; - this.isFirstAppearanceOfSource = isFirstAppearanceOfSource; - } +// public CitationMarkerEntryImpl(String citationKey, +// BibEntry entry, +// BibDatabase database, +// String uniqueLetterQ, +// String pageInfoQ, +// boolean isFirstAppearanceOfSource) { +// Optional uniqueLetter = Optional.ofNullable(uniqueLetterQ); +// Optional pageInfo = +// Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); +// +// Objects.requireNonNull(citationKey); +// this.citationKey = citationKey; +// this.db = new CitationDatabaseLookup.Result(entry, database); +// this.uniqueLetter = uniqueLetter; +// this.pageInfo = pageInfo; +// this.isFirstAppearanceOfSource = isFirstAppearanceOfSource; +// } @Override public String getCitationKey() { @@ -82,13 +53,8 @@ public String getCitationKey() { } @Override - public Optional getBibEntry() { - return bibEntry; - } - - @Override - public Optional getDatabase() { - return database; + public Optional getDatabaseLookupResult() { + return db; } @Override diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 6d1c5a5b3fc..c4d1e7fb37a 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -11,6 +11,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -21,6 +23,9 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; +import org.jabref.model.oostyle.CitationDatabaseLookup; +import org.jabref.model.oostyle.CitationMarkerEntry; +import org.jabref.model.oostyle.CitationMarkerEntryImpl; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; @@ -288,6 +293,23 @@ void testGetCitProperty() throws IOException { assertTrue(journals.contains("Journal name 1")); } + private static CitationMarkerEntry makeCitationMarkerEntry(String citationKey, + BibEntry entry, + BibDatabase database, + String uniqueLetterQ, + String pageInfoQ, + boolean isFirstAppearanceOfSource) { + Optional uniqueLetter = Optional.ofNullable(uniqueLetterQ); + Optional pageInfo = + Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); + Objects.requireNonNull(citationKey); + return new CitationMarkerEntryImpl(citationKey, + Optional.of(new CitationDatabaseLookup.Result(entry, database)), + uniqueLetter, + pageInfo, + isFirstAppearanceOfSource); + } + @Test void testGetCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); @@ -303,7 +325,7 @@ void testGetCitationMarker() throws IOException { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm = - new CitationMarkerEntryImpl("Bostrom2006", entry, database, null, null, false); + makeCitationMarkerEntry("Bostrom2006", entry, database, null, null, false); citationMarkerEntries.add(cm); assertEquals(3, style.getMaxAuthors()); @@ -328,7 +350,7 @@ void testGetCitationMarker() throws IOException { * cm.isFirstAppearanceOfSource, which asks for getMaxAuthorsFirst() */ citationMarkerEntries.clear(); - cm = new CitationMarkerEntryImpl("Bostrom2006", entry, database, null, null, true); + cm = makeCitationMarkerEntry("Bostrom2006", entry, database, null, null, true); citationMarkerEntries.add(cm); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", @@ -398,13 +420,13 @@ void testGetCitationMarkerJoinFirst() throws IOException { if (true) { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", null, true); + makeCitationMarkerEntry("b1", entry1, database, "a", null, true); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = - new CitationMarkerEntryImpl("b2", entry2, database, "b", null, true); + makeCitationMarkerEntry("b2", entry2, database, "b", null, true); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = - new CitationMarkerEntryImpl("b3", entry3, database, "c", null, true); + makeCitationMarkerEntry("b3", entry3, database, "c", null, true); citationMarkerEntries.add(cm3); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" @@ -426,13 +448,13 @@ void testGetCitationMarkerJoinFirst() throws IOException { if (true) { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", null, true); + makeCitationMarkerEntry("b1", entry1, database, "a", null, true); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = - new CitationMarkerEntryImpl("b2", entry2, database, "b", null, false); + makeCitationMarkerEntry("b2", entry2, database, "b", null, false); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = - new CitationMarkerEntryImpl("b3", entry3, database, "c", null, false); + makeCitationMarkerEntry("b3", entry3, database, "c", null, false); citationMarkerEntries.add(cm3); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" @@ -449,13 +471,13 @@ void testGetCitationMarkerJoinFirst() throws IOException { if (true) { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", null, false); + makeCitationMarkerEntry("b1", entry1, database, "a", null, false); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = - new CitationMarkerEntryImpl("b2", entry2, database, "b", null, true); + makeCitationMarkerEntry("b2", entry2, database, "b", null, true); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = - new CitationMarkerEntryImpl("b3", entry3, database, "c", null, false); + makeCitationMarkerEntry("b3", entry3, database, "c", null, false); citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a" @@ -473,13 +495,13 @@ void testGetCitationMarkerJoinFirst() throws IOException { if (true) { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", null, false); + makeCitationMarkerEntry("b1", entry1, database, "a", null, false); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = - new CitationMarkerEntryImpl("b2", entry2, database, "b", null, false); + makeCitationMarkerEntry("b2", entry2, database, "b", null, false); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = - new CitationMarkerEntryImpl("b3", entry3, database, "c", null, false); + makeCitationMarkerEntry("b3", entry3, database, "c", null, false); citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a,b,c]", @@ -493,13 +515,13 @@ void testGetCitationMarkerJoinFirst() throws IOException { if (true) { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", "p1", false); + makeCitationMarkerEntry("b1", entry1, database, "a", "p1", false); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = - new CitationMarkerEntryImpl("b2", entry2, database, "b", "p1", false); + makeCitationMarkerEntry("b2", entry2, database, "b", "p1", false); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = - new CitationMarkerEntryImpl("b3", entry3, database, "c", "p1", false); + makeCitationMarkerEntry("b3", entry3, database, "c", "p1", false); citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a; p1" @@ -516,13 +538,13 @@ void testGetCitationMarkerJoinFirst() throws IOException { if (true) { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", "p1", false); + makeCitationMarkerEntry("b1", entry1, database, "a", "p1", false); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", "p1", false); + makeCitationMarkerEntry("b1", entry1, database, "a", "p1", false); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", "p1", false); + makeCitationMarkerEntry("b1", entry1, database, "a", "p1", false); citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a; p1]", @@ -535,16 +557,16 @@ void testGetCitationMarkerJoinFirst() throws IOException { if (true) { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm1 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", "p1", false); + makeCitationMarkerEntry("b1", entry1, database, "a", "p1", false); citationMarkerEntries.add(cm1); CitationMarkerEntry cm2 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", "p2", false); + makeCitationMarkerEntry("b1", entry1, database, "a", "p2", false); citationMarkerEntries.add(cm2); CitationMarkerEntry cm3 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", "", false); + makeCitationMarkerEntry("b1", entry1, database, "a", "", false); citationMarkerEntries.add(cm3); CitationMarkerEntry cm4 = - new CitationMarkerEntryImpl("b1", entry1, database, "a", null, false); + makeCitationMarkerEntry("b1", entry1, database, "a", null, false); citationMarkerEntries.add(cm4); assertEquals("[Boström et al., 2006a; p1" @@ -637,7 +659,7 @@ void testInstitutionAuthorMarker() throws IOException { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm = - new CitationMarkerEntryImpl("JabRef2016", entry, database, null, null, false); + makeCitationMarkerEntry("JabRef2016", entry, database, null, null, false); citationMarkerEntries.add(cm); assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(citationMarkerEntries, @@ -661,7 +683,7 @@ void testVonAuthorMarker() throws IOException { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm = - new CitationMarkerEntryImpl("vonBeta2016", entry, database, null, null, false); + makeCitationMarkerEntry("vonBeta2016", entry, database, null, null, false); citationMarkerEntries.add(cm); assertEquals("[von Beta, 2016]", @@ -684,7 +706,7 @@ void testNullAuthorMarker() throws IOException { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm = - new CitationMarkerEntryImpl("anon2016", entry, database, null, null, false); + makeCitationMarkerEntry("anon2016", entry, database, null, null, false); citationMarkerEntries.add(cm); assertEquals("[, 2016]", @@ -707,7 +729,7 @@ void testNullYearMarker() throws IOException { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm = - new CitationMarkerEntryImpl("vonBetaNNNN", entry, database, null, null, false); + makeCitationMarkerEntry("vonBetaNNNN", entry, database, null, null, false); citationMarkerEntries.add(cm); assertEquals("[von Beta, ]", @@ -729,7 +751,7 @@ void testEmptyEntryMarker() throws IOException { List citationMarkerEntries = new ArrayList<>(); CitationMarkerEntry cm = - new CitationMarkerEntryImpl("Empty", entry, database, null, null, false); + makeCitationMarkerEntry("Empty", entry, database, null, null, false); citationMarkerEntries.add(cm); assertEquals("[, ]", style.getCitationMarker(citationMarkerEntries, @@ -772,11 +794,11 @@ void testGetCitationMarkerUniquefiers() throws IOException { // This latter is used for providing a temporary citation mark // for newly inserted citations. CitationMarkerEntry cm1a = - new CitationMarkerEntryImpl("Beta2000a", entry1, database, null, null, false); + makeCitationMarkerEntry("Beta2000a", entry1, database, null, null, false); CitationMarkerEntry cm3a = - new CitationMarkerEntryImpl("Beta2000b", entry3, database, null, null, false); + makeCitationMarkerEntry("Beta2000b", entry3, database, null, null, false); CitationMarkerEntry cm2 = - new CitationMarkerEntryImpl("Epsilon2001", entry2, database, null, null, false); + makeCitationMarkerEntry("Epsilon2001", entry2, database, null, null, false); List citationMarkerEntriesA = new ArrayList<>(); citationMarkerEntriesA.add(cm1a); @@ -809,9 +831,9 @@ void testGetCitationMarkerUniquefiers() throws IOException { // With uniquefiers CitationMarkerEntry cm1b = - new CitationMarkerEntryImpl("Beta2000a", entry1, database, "a", null, false); + makeCitationMarkerEntry("Beta2000a", entry1, database, "a", null, false); CitationMarkerEntry cm3b = - new CitationMarkerEntryImpl("Beta2000b", entry3, database, "b", null, false); + makeCitationMarkerEntry("Beta2000b", entry3, database, "b", null, false); List citationMarkerEntriesB = new ArrayList<>(); citationMarkerEntriesB.add(cm1b); @@ -856,11 +878,11 @@ void testGetCitationMarkerUniquefiersThreeSameAuthor() throws IOException { database.insertEntry(entry3); CitationMarkerEntry cm1 = - new CitationMarkerEntryImpl("v1", entry1, database, "a", null, false); + makeCitationMarkerEntry("v1", entry1, database, "a", null, false); CitationMarkerEntry cm2 = - new CitationMarkerEntryImpl("v2", entry2, database, "b", null, false); + makeCitationMarkerEntry("v2", entry2, database, "b", null, false); CitationMarkerEntry cm3 = - new CitationMarkerEntryImpl("v3", entry3, database, "c", null, false); + makeCitationMarkerEntry("v3", entry3, database, "c", null, false); List citationMarkerEntries = new ArrayList<>(); citationMarkerEntries.add(cm1); @@ -933,7 +955,7 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { List citationMarkerEntries = new ArrayList<>(); citationMarkerEntries.add( - new CitationMarkerEntryImpl("Beta2016", entry, database, null, null, false)); + makeCitationMarkerEntry("Beta2016", entry, database, null, null, false)); assertEquals("von Beta, Epsilon, & Tau, 2016", style.getCitationMarker(citationMarkerEntries, From 8bcb609da6aaa9cd423ba1af46ee084481fc421e Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 10:14:58 +0200 Subject: [PATCH 0753/1068] mode use of CitationDatabaseLookup.Result db --- .../oostyle/OOBibStyleGetCitationMarker.java | 36 ++++++------------- 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 386e753e604..06ed61c8f9f 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -244,9 +244,6 @@ private static Optional getRawCitationMarkerField(BibEntry entr * Any number of backup fields can be used if the primary field is * empty. * - * @param entry The entry. - * @param database The database the entry belongs to. - * * @param fields A list of fields, to look up, using first nonempty hit. * * If backup fields are needed, separate field @@ -264,14 +261,12 @@ private static Optional getRawCitationMarkerField(BibEntry entr * */ private static String getCitationMarkerField(OOBibStyle style, - BibEntry entry, - BibDatabase database, + CitationDatabaseLookup.Result db, OrFields fields) { - Objects.requireNonNull(entry, "Entry cannot be null"); - Objects.requireNonNull(database, "database cannot be null"); + Objects.requireNonNull(db); Optional optionalFieldAndContent = - getRawCitationMarkerField(entry, database, fields); + getRawCitationMarkerField(db.entry, db.database, fields); if (optionalFieldAndContent.isEmpty()) { // No luck? Return an empty string: @@ -292,17 +287,13 @@ private static String getCitationMarkerField(OOBibStyle style, return result; } - private static AuthorList getAuthorList(OOBibStyle style, - CitationDatabaseLookup.Result db) { + private static AuthorList getAuthorList(OOBibStyle style, CitationDatabaseLookup.Result db) { // The bibtex fields providing author names, e.g. "author" or // "editor". OrFields authorFieldNames = style.getAuthorFieldNames(); - String authorListAsString = getCitationMarkerField(style, - db.entry, - db.database, - authorFieldNames); + String authorListAsString = getCitationMarkerField(style, db, authorFieldNames); return AuthorList.parse(authorListAsString); } @@ -318,8 +309,7 @@ private enum AuthorYearMarkerPurpose { * * If ce is unresolved, return 0. */ - private static int calculateNAuthorsToEmit(OOBibStyle style, - CitationMarkerEntry ce) { + private static int calculateNAuthorsToEmit(OOBibStyle style, CitationMarkerEntry ce) { int maxAuthors = (ce.getIsFirstAppearanceOfSource() ? style.getMaxAuthorsFirst() @@ -330,8 +320,7 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, return 0; } - AuthorList authorList = getAuthorList(style, - ce.getDatabaseLookupResult().get()); + AuthorList authorList = getAuthorList(style, ce.getDatabaseLookupResult().get()); int nAuthors = authorList.getNumberOfAuthors(); if (maxAuthors == -1) { @@ -446,8 +435,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker(OOBibStyle style, sb.append(String.format("Unresolved(%s)", ce.getCitationKey())); } else { - BibEntry currentEntry = ce.getDatabaseLookupResult().get().entry; - BibDatabase currentDatabase = ce.getDatabaseLookupResult().get().database; + final CitationDatabaseLookup.Result db = ce.getDatabaseLookupResult().get(); int maxAuthors = (purpose == AuthorYearMarkerPurpose.NORMALIZED ? style.getMaxAuthors() @@ -457,8 +445,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker(OOBibStyle style, maxAuthors = maxAuthorsOverride.get(); } - AuthorList authorList = getAuthorList(style, - ce.getDatabaseLookupResult().get()); + AuthorList authorList = getAuthorList(style, db); String authorString = formatAuthorList(style, authorList, maxAuthors, andString); sb.append(authorString); sb.append(yearSep); @@ -467,10 +454,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker(OOBibStyle style, sb.append(startBrace); } - String year = getCitationMarkerField(style, - currentEntry, - currentDatabase, - yearFieldNames); + String year = getCitationMarkerField(style, db, yearFieldNames); if (year != null) { sb.append(year); } From d9939a496b3f7a1cdf52203372ef1b9481965d15 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 18:48:55 +0200 Subject: [PATCH 0754/1068] do use Optional.empty isntead of null for pageInfos --- .../org/jabref/logic/oostyle/OOBibStyle.java | 25 ++- .../oostyle/OOBibStyleGetCitationMarker.java | 162 +++++++++--------- .../OOBibStyleGetNumCitationMarker.java | 34 ++-- .../org/jabref/logic/oostyle/OOProcess.java | 11 +- .../jabref/logic/openoffice/Backend52.java | 37 ++-- .../jabref/logic/openoffice/EditInsert.java | 4 +- .../jabref/logic/openoffice/EditMerge.java | 3 +- .../jabref/logic/openoffice/EditSeparate.java | 9 +- .../jabref/logic/openoffice/OOFrontend.java | 2 +- .../openoffice/UpdateCitationMarkers.java | 3 +- .../jabref/model/oostyle/CitationGroup.java | 12 +- .../jabref/model/oostyle/CitationSort.java | 40 ++++- .../jabref/model/oostyle/OOFormattedText.java | 24 +++ .../oostyle/OOStyleDataModelVersion.java | 13 +- .../jabref/logic/oostyle/OOBibStyleTest.java | 64 +++---- 15 files changed, 253 insertions(+), 190 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index ada60df646c..88bd3037391 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -444,7 +444,7 @@ public Layout getReferenceFormat(EntryType type) { */ public OOFormattedText getNumCitationMarker(List number, int minGroupingCount, - List pageInfosForCitations) { + List> pageInfosForCitations) { return OOBibStyleGetNumCitationMarker.getNumCitationMarker(this, number, minGroupingCount, @@ -941,21 +941,20 @@ public OOFormattedText getNumCitationMarkerForBibliography(int number) { number); } - public static OOFormattedText regularizePageInfo(OOFormattedText p) { - return OOFormattedText.fromString(CitationSort.regularizePageInfoToString(p)); - } - /** * Make sure that (1) we have exactly one entry for each - * citation, (2) each entry is either null or is not empty when trimmed. + * citation, (2) each entry is either Optional.empty or its content is not empty when trimmed. + * + * As a special case: pageInfosForCitations may be null. In this case + * the result is a list filled with Optional.empty() values. */ - public static List - regularizePageInfosForCitations(List pageInfosForCitations, + public static List> + regularizePageInfosForCitations(List> pageInfosForCitations, int nCitations) { if (pageInfosForCitations == null) { - List res = new ArrayList<>(nCitations); + List> res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { - res.add(null); + res.add(Optional.empty()); } return res; } else { @@ -963,10 +962,10 @@ public static OOFormattedText regularizePageInfo(OOFormattedText p) { throw new RuntimeException("regularizePageInfosForCitations:" + " pageInfosForCitations.size() != nCitations"); } - List res = new ArrayList<>(nCitations); + List> res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { - OOFormattedText p = pageInfosForCitations.get(i); - res.add(regularizePageInfo(p)); + Optional p = pageInfosForCitations.get(i); + res.add(CitationSort.regularizeOptionalPageInfo(p)); } return res; } diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 06ed61c8f9f..9ef2756706f 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -14,6 +14,7 @@ import org.jabref.model.entry.field.OrFields; import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.CitationMarkerEntry; +import org.jabref.model.oostyle.CitationSort; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.strings.StringUtil; @@ -367,11 +368,11 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, CitationMarkerEntry * @return The formatted citation. * */ - private static OOFormattedText getAuthorYearParenthesisMarker(OOBibStyle style, - AuthorYearMarkerPurpose purpose, - List ces, - boolean[] startsNewGroup, - Optional maxAuthorsOverride) { + private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, + AuthorYearMarkerPurpose purpose, + List ces, + boolean[] startsNewGroup, + Optional maxAuthorsOverride) { boolean inParenthesis = (purpose == AuthorYearMarkerPurpose.IN_PARENTHESIS || purpose == AuthorYearMarkerPurpose.NORMALIZED); @@ -465,11 +466,11 @@ private static OOFormattedText getAuthorYearParenthesisMarker(OOBibStyle style, sb.append(uniqueLetter); } - OOFormattedText pageInfo = - OOBibStyle.regularizePageInfo(ce.getPageInfo().orElse(null)); - if (pageInfo != null) { + Optional pageInfo = + CitationSort.regularizeOptionalPageInfo(ce.getPageInfo()); + if (pageInfo.isPresent()) { sb.append(pageInfoSeparator); - sb.append(OOFormattedText.toString(pageInfo)); + sb.append(OOFormattedText.toString(pageInfo.get())); } } @@ -500,7 +501,7 @@ private static String nullToEmptyString(String s) { * @return A normalized citation marker for deciding which * citations need uniqueLetters. * - * For details of what "normalized" means: {@see getAuthorYearParenthesisMarker} + * For details of what "normalized" means: {@see getAuthorYearParenthesisMarker2} * * Note: now includes some markup. */ @@ -508,11 +509,26 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, CitationMarkerEntry ce, Optional maxAuthorsOverride) { boolean[] startsNewGroup = {true}; - return getAuthorYearParenthesisMarker(style, - AuthorYearMarkerPurpose.NORMALIZED, - Collections.singletonList(ce), - startsNewGroup, - maxAuthorsOverride); + return getAuthorYearParenthesisMarker2(style, + AuthorYearMarkerPurpose.NORMALIZED, + Collections.singletonList(ce), + startsNewGroup, + maxAuthorsOverride); + } + + private static List + getNormalizedCitationMarkers(OOBibStyle style, + List citationMarkerEntries, + Optional maxAuthorsOverride) { + + List normalizedMarkers = new ArrayList<>(citationMarkerEntries.size()); + for (CitationMarkerEntry citationMarkerEntry : citationMarkerEntries) { + OOFormattedText nm = getNormalizedCitationMarker(style, + citationMarkerEntry, + maxAuthorsOverride); + normalizedMarkers.add(nm); + } + return normalizedMarkers; } /** @@ -567,23 +583,18 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, // We also assume, that identical entries have the same uniqueLetters. // - List normalizedMarkers = new ArrayList<>(nEntries); - for (CitationMarkerEntry citationMarkerEntry : citationMarkerEntries) { - OOFormattedText nm = getNormalizedCitationMarker(style, - citationMarkerEntry, - Optional.empty()); - normalizedMarkers.add(nm); - } + List normalizedMarkers = getNormalizedCitationMarkers(style, + citationMarkerEntries, + Optional.empty()); // How many authors would be emitted without grouping. - // Later overwritten for group members with value for - // first of the group. int[] nAuthorsToEmit = new int[nEntries]; int[] nAuthorsToEmitRevised = new int[nEntries]; for (int i = 0; i < nEntries; i++) { CitationMarkerEntry ce = citationMarkerEntries.get(i); - nAuthorsToEmit[i] = calculateNAuthorsToEmit(style, ce); - nAuthorsToEmitRevised[i] = calculateNAuthorsToEmit(style, ce); + int n = calculateNAuthorsToEmit(style, ce); + nAuthorsToEmit[i] = n; + nAuthorsToEmitRevised[i] = n; } boolean[] startsNewGroup = new boolean[nEntries]; @@ -597,16 +608,17 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, } for (int i = 1; i < nEntries; i++) { - CitationMarkerEntry ce1 = citationMarkerEntries.get(i - 1); - CitationMarkerEntry ce2 = citationMarkerEntries.get(i); - String nm1 = OOFormattedText.toString(normalizedMarkers.get(i - 1)); - String nm2 = OOFormattedText.toString(normalizedMarkers.get(i)); + final CitationMarkerEntry ce1 = citationMarkerEntries.get(i - 1); + final CitationMarkerEntry ce2 = citationMarkerEntries.get(i); + + final String nm1 = OOFormattedText.toString(normalizedMarkers.get(i - 1)); + final String nm2 = OOFormattedText.toString(normalizedMarkers.get(i)); - boolean isUnresolved1 = ce1.getDatabaseLookupResult().isEmpty(); - boolean isUnresolved2 = ce2.getDatabaseLookupResult().isEmpty(); + final boolean isUnresolved1 = ce1.getDatabaseLookupResult().isEmpty(); + final boolean isUnresolved2 = ce2.getDatabaseLookupResult().isEmpty(); boolean startingNewGroup; - boolean sameAsPrev; + boolean sameAsPrev; /* true indicates ce2 may be omitted from output */ if (isUnresolved2) { startingNewGroup = true; sameAsPrev = false; // keep it visible @@ -616,12 +628,12 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, // between maxAuthors and maxAuthorsFirst may invalidate // our expectation that adding uniqueLetter is valid. - boolean firstAppearanceInhibitsJoin; + boolean nAuthorsShownInhibitsJoin; if (isUnresolved1) { - firstAppearanceInhibitsJoin = true; // no join for unresolved + nAuthorsShownInhibitsJoin = true; // no join for unresolved } else { - boolean isFirst1 = ce1.getIsFirstAppearanceOfSource(); - boolean isFirst2 = ce2.getIsFirstAppearanceOfSource(); + final boolean isFirst1 = ce1.getIsFirstAppearanceOfSource(); + final boolean isFirst2 = ce2.getIsFirstAppearanceOfSource(); // nAuthorsToEmitRevised[i-1] may have been indirectly increased, // we have to check that too. @@ -629,68 +641,62 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, !isFirst2 && (nAuthorsToEmitRevised[i - 1] == nAuthorsToEmit[i - 1])) { // we can rely on normalizedMarkers - firstAppearanceInhibitsJoin = false; + nAuthorsShownInhibitsJoin = false; } else if (style.getMaxAuthors() == style.getMaxAuthorsFirst()) { // we can rely on normalizedMarkers - firstAppearanceInhibitsJoin = false; + nAuthorsShownInhibitsJoin = false; } else { - int prevShown = nAuthorsToEmitRevised[i - 1]; - int need = nAuthorsToEmit[i]; + final int prevShown = nAuthorsToEmitRevised[i - 1]; + final int need = nAuthorsToEmit[i]; if (prevShown < need) { // We do not retrospectively change the number of authors shown // at the previous entry, take that as decided. - firstAppearanceInhibitsJoin = true; + nAuthorsShownInhibitsJoin = true; } else { // prevShown >= need // Check with extended normalizedMarkers. - OOFormattedText fnmx1 = + OOFormattedText nmx1 = getNormalizedCitationMarker(style, ce1, Optional.of(prevShown)); - String nmx1 = OOFormattedText.toString(fnmx1); - OOFormattedText fnmx2 = + OOFormattedText nmx2 = getNormalizedCitationMarker(style, ce2, Optional.of(prevShown)); - String nmx2 = OOFormattedText.toString(fnmx2); - firstAppearanceInhibitsJoin = !nmx2.equals(nmx1); + boolean extendedMarkersDiffer = !nmx2.equals(nmx1); + nAuthorsShownInhibitsJoin = extendedMarkersDiffer; } } } - OOFormattedText fpi2 = OOBibStyle.regularizePageInfo(ce2.getPageInfo().orElse(null)); - OOFormattedText fpi1 = OOBibStyle.regularizePageInfo(ce1.getPageInfo().orElse(null)); - String pi2 = nullToEmptyString(OOFormattedText.toString(fpi2)); - String pi1 = nullToEmptyString(OOFormattedText.toString(fpi1)); + final boolean citationKeysDiffer = !ce2.getCitationKey().equals(ce1.getCitationKey()); + final boolean normalizedMarkersDiffer = !nm2.equals(nm1); - String ul2 = ce2.getUniqueLetter().orElse(null); - String ul1 = ce1.getUniqueLetter().orElse(null); + Optional pageInfo2 = + CitationSort.regularizeOptionalPageInfo(ce2.getPageInfo()); + Optional pageInfo1 = + CitationSort.regularizeOptionalPageInfo(ce1.getPageInfo()); + final boolean bothPageInfosAreEmpty = pageInfo2.isEmpty() && pageInfo1.isEmpty(); + final boolean pageInfosDiffer = !pageInfo2.equals(pageInfo1); - boolean uniqueLetterPresenceChanged = (ul2 == null) != (ul1 == null); + Optional ul2 = ce2.getUniqueLetter(); + Optional ul1 = ce1.getUniqueLetter(); + final boolean uniqueLetterPresenceChanged = (ul2.isPresent() != ul1.isPresent()); + final boolean uniqueLettersDiffer = !ul2.equals(ul1); - String xul2 = nullToEmptyString(ul2); - String xul1 = nullToEmptyString(ul1); - - String k2 = ce2.getCitationKey(); - String k1 = ce1.getCitationKey(); - - boolean uniqueLetterDoesNotMakeUnique = (nm2.equals(nm1) - && xul2.equals(xul1) - && !k2.equals(k1)); + final boolean uniqueLetterDoesNotMakeUnique = (citationKeysDiffer + && !normalizedMarkersDiffer + && !uniqueLettersDiffer); if (uniqueLetterDoesNotMakeUnique && - nonUniqueCitationMarkerHandling == NonUniqueCitationMarker.THROWS) { + nonUniqueCitationMarkerHandling.equals(NonUniqueCitationMarker.THROWS)) { throw new RuntimeException("different citation keys," + " but same normalizedMarker and uniqueLetter"); } - boolean pageInfoInhibitsJoin; - if (pi1.equals("") && pi2.equals("")) { - pageInfoInhibitsJoin = false; - } else { - pageInfoInhibitsJoin = !(k2.equals(k1) && pi2.equals(pi1)); - } + final boolean pageInfoInhibitsJoin = (bothPageInfosAreEmpty + ? false + : (citationKeysDiffer || pageInfosDiffer)); - boolean normalizedMarkerChanged = !nm2.equals(nm1); - startingNewGroup = (normalizedMarkerChanged - || firstAppearanceInhibitsJoin + startingNewGroup = (normalizedMarkersDiffer + || nAuthorsShownInhibitsJoin || pageInfoInhibitsJoin || uniqueLetterPresenceChanged || uniqueLetterDoesNotMakeUnique); @@ -701,9 +707,9 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, } sameAsPrev = (!startingNewGroup - && xul2.equals(xul1) - && k2.equals(k1) - && pi2.equals(pi1)); + && !uniqueLettersDiffer + && !citationKeysDiffer + && !pageInfosDiffer); } if (!sameAsPrev) { @@ -713,8 +719,8 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, } } - return getAuthorYearParenthesisMarker(style, - (inParenthesis + return getAuthorYearParenthesisMarker2(style, + (inParenthesis ? AuthorYearMarkerPurpose.IN_PARENTHESIS : AuthorYearMarkerPurpose.IN_TEXT), filteredCitationMarkerEntries, diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index 635fe62029b..d92e5a112ed 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Optional; import java.util.function.ToIntFunction; import org.jabref.model.oostyle.CitationSort; @@ -16,8 +17,8 @@ class OOBibStyleGetNumCitationMarker { */ private static class NumberWithPageInfo { int num; - OOFormattedText pageInfo; - NumberWithPageInfo(int num, OOFormattedText pageInfo) { + Optional pageInfo; + NumberWithPageInfo(int num, Optional pageInfo) { this.num = num; this.pageInfo = pageInfo; } @@ -49,7 +50,7 @@ private enum CitationMarkerPurpose { public static OOFormattedText getNumCitationMarker(OOBibStyle style, List numbers, int minGroupingCount, - List pageInfosForCitations) { + List> pageInfosForCitations) { return getNumCitationMarkerCommon(style, numbers, minGroupingCount, @@ -101,8 +102,8 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty * - If their pageInfos differ, the number is emitted with each * distinct pageInfo. * - * For pageInfo null and "" (after - * pageInfo.trim()) are considered equal (and missing). + * For pageInfo Optional.empty and "" (after + * pageInfo.get(),trim()) are considered equal (and missing). * * @param minGroupingCount Zero and negative means never group * @@ -113,8 +114,8 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty * and BRACKET_AFTER_IN_LIST over BRACKET_AFTER. * Ignore pageInfosForCitations. * - * @param pageInfosForCitations Null for "none", or a list with a - * pageInfo for each citation. Any or all of these can be null as well. + * @param pageInfosForCitations Null for "none", or a list with an optional + * pageInfo for each citation. Any or all of these can be Optional.empty * * @return The text for the citation. * @@ -124,7 +125,7 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty List numbers, int minGroupingCount, CitationMarkerPurpose purpose, - List pageInfosForCitations) { + List> pageInfosForCitations) { final boolean joinIsDisabled = (minGroupingCount <= 0); final int notFoundInDatabases = 0; @@ -183,7 +184,7 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty * get here, and {@code purpose==BIBLIOGRAPHY}, then we just fill * pageInfos with null values. */ - List pageInfos = + List> pageInfos = OOBibStyle.regularizePageInfosForCitations((purpose == CitationMarkerPurpose.BIBLIOGRAPHY ? null : pageInfosForCitations), @@ -248,9 +249,10 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty ? OOBibStyle.UNDEFINED_CITATION_MARKER : String.valueOf(num)); // Emit pageInfo - OOFormattedText pageInfo = block.get(0).pageInfo; - if (pageInfo != null) { - sb.append(style.getPageInfoSeparator() + OOFormattedText.toString(pageInfo)); + Optional pageInfo = block.get(0).pageInfo; + if (pageInfo.isPresent()) { + sb.append(style.getPageInfoSeparator()); + sb.append(OOFormattedText.toString(pageInfo.get())); } } else { // block has at least 2 elements @@ -262,8 +264,8 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty // None of these elements has a pageInfo, // because if it had, we would not join. for (NumberWithPageInfo x : block) { - if (x.pageInfo != null) { - throw new RuntimeException("impossible: (x.pageInfo != null)"); + if (x.pageInfo.isPresent()) { + throw new RuntimeException("impossible: (x.pageInfo.isPresent())"); } } // None of these elements needs UNDEFINED_CITATION_MARKER, @@ -343,8 +345,8 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty } else if (compareNumberWithPageInfo(current, prev) == 0) { // Same as prev, just forget it. } else if ((current.num == (prev.num + 1)) - && (prev.pageInfo == null) - && (current.pageInfo == null)) { + && (prev.pageInfo.isEmpty()) + && (current.pageInfo.isEmpty())) { // Just two consecutive numbers without pageInfo: join currentBlock.add(current); } else { diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index c5e673fec89..07ada95d249 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -243,7 +243,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getCitationNumbersInLocalOrder(); - List pageInfos = cg.getPageInfosForCitationsInLocalOrder(); + List> pageInfos = cg.getPageInfosForCitationsInLocalOrder(); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, @@ -272,7 +272,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); List numbers = cg.getCitationNumbersInLocalOrder(); - List pageInfos = cg.getPageInfosForCitationsInLocalOrder(); + List> pageInfos = cg.getPageInfosForCitationsInLocalOrder(); citMarkers.put(cgid, style.getNumCitationMarker(numbers, minGroupingCount, @@ -289,8 +289,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, * @param style Bibliography style. */ private static Map - produceCitationMarkersForNormalStyle(CitationGroups cgs, - OOBibStyle style) { + produceCitationMarkersForNormalStyle(CitationGroups cgs, OOBibStyle style) { assert !style.isCitationKeyCiteMarkers(); assert !style.isNumberEntries(); @@ -315,7 +314,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, List cits = cg.getCitationsInLocalOrder(); final int nCitedEntries = cits.size(); - List pageInfosForCitations = cg.getPageInfosForCitationsInLocalOrder(); + List> pageInfosForCitations = cg.getPageInfosForCitationsInLocalOrder(); List citationMarkerEntries = new ArrayList<>(nCitedEntries); @@ -337,7 +336,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, new CitationMarkerEntryImpl(currentKey, cit.db, uniqueLetterForKey, - Optional.ofNullable(pageInfosForCitations.get(j)), + pageInfosForCitations.get(j), isFirst); citationMarkerEntries.add(cm); } diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 5da5e1e277d..bb84b093573 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -171,14 +171,15 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str return cg; } - static Optional normalizePageInfoToOptional(OOFormattedText o) { - String s; - if (o == null || "".equals(OOFormattedText.toString(o))) { - s = null; - } else { - s = OOFormattedText.toString(o); + static Optional normalizePageInfo(Optional o) { + if (o == null || o.isEmpty() || "".equals(OOFormattedText.toString(o.get()))) { + return Optional.empty(); + } + String s = OOFormattedText.toString(o.get()); + if (s.trim().equals("")) { + return Optional.empty(); } - return Optional.ofNullable(OOFormattedText.fromString(s)); + return Optional.of(OOFormattedText.fromString(s)); } /** @@ -195,7 +196,7 @@ static Optional normalizePageInfoToOptional(OOFormattedText o) */ public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, - List pageInfosForCitations, + List> pageInfosForCitations, InTextCitationType citationType, XTextCursor position, boolean insertSpaceAfter) @@ -229,7 +230,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, Citation cit = new Citation(citationKeys.get(i)); citations.add(cit); - Optional pageInfo = normalizePageInfoToOptional(pageInfosForCitations.get(i)); + Optional pageInfo = normalizePageInfo(pageInfosForCitations.get(i)); switch (dataModel) { case JabRef52: if (i == last) { @@ -255,10 +256,9 @@ public CitationGroup createCitationGroup(XTextDocument doc, switch (dataModel) { case JabRef52: - Optional pageInfo = - normalizePageInfoToOptional(pageInfosForCitations.get(last)); + Optional pageInfo = normalizePageInfo(pageInfosForCitations.get(last)); - if (pageInfo.isPresent() && !"".equals(OOFormattedText.toString(pageInfo.get()))) { + if (pageInfo.isPresent()) { String pageInfoString = OOFormattedText.toString(pageInfo.get()); UnoUserDefinedProperty.createStringProperty(doc, refMarkName, pageInfoString); } else { @@ -281,8 +281,9 @@ public CitationGroup createCitationGroup(XTextDocument doc, * TODO: JabRef52 combinePageInfos is not reversible. Should warn * user to check the result. Or ask what to do. */ - public static List combinePageInfosCommon(OOStyleDataModelVersion dataModel, - List joinableGroup) { + public static List> + combinePageInfosCommon(OOStyleDataModelVersion dataModel, + List joinableGroup) { switch (dataModel) { case JabRef52: // collect to cgPageInfos @@ -301,13 +302,15 @@ public static List combinePageInfosCommon(OOStyleDataModelVersi int nCitations = (joinableGroup.stream() .map(cg -> cg.numberOfCitations()) .mapToInt(Integer::intValue).sum()); - + if ("".equals(cgPageInfo)) { + cgPageInfo = null; + } return OOStyleDataModelVersion.fakePageInfosForCitations(cgPageInfo, nCitations); case JabRef53: return (joinableGroup.stream() .flatMap(cg -> (cg.citationsInStorageOrder.stream() - .map(cit -> cit.pageInfo.orElse(null)))) + .map(cit -> cit.pageInfo))) .collect(Collectors.toList())); default: throw new RuntimeException("unhandled dataModel here"); @@ -317,7 +320,7 @@ public static List combinePageInfosCommon(OOStyleDataModelVersi /** * */ - public List combinePageInfos(List joinableGroup) { + public List> combinePageInfos(List joinableGroup) { return combinePageInfosCommon(this.dataModel, joinableGroup); } diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 539c61b6eff..01b855ddc39 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -116,7 +116,7 @@ public static void insertCitationGroup(XTextDocument doc, final int nEntries = entries.size(); // JabRef53 style pageInfo list - List pageInfosForCitations = + List> pageInfosForCitations = OOStyleDataModelVersion.fakePageInfosForCitations(pageInfo, nEntries); List citationMarkerEntries = new ArrayList<>(nEntries); @@ -131,7 +131,7 @@ public static void insertCitationGroup(XTextDocument doc, // Optional.ofNullable(entries.get(i)), // Optional.ofNullable(database), Optional.empty(), // uniqueLetter - Optional.ofNullable(pageInfosForCitations.get(i)), + pageInfosForCitations.get(i), false /* isFirstAppearanceOfSource */); citationMarkerEntries.add(cm); } diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 50c27eb8653..e27d0c2ca87 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.stream.Collectors; import org.jabref.logic.JabRefException; @@ -290,7 +291,7 @@ public static void mergeCitationGroups(XTextDocument doc, // cgPageInfos belong to the CitationGroup (DataModel JabRef52), // but it is not clear how should we handle them here. // We delegate the problem to the backend. - List pageInfosForCitations = + List> pageInfosForCitations = fr.backend.combinePageInfos(joinableGroup); // Remove the old citation groups from the document. diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 0c46198ea74..6b8d0358aad 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; import org.jabref.logic.JabRefException; @@ -70,7 +71,7 @@ public static void separateCitations(XTextDocument doc, XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); // Note: JabRef52 returns cg.pageInfo for the last citation. - List pageInfosForCitations = + List> pageInfosForCitations = cg.getPageInfosForCitationsInStorageOrder(); List cits = cg.citationsInStorageOrder; @@ -91,8 +92,10 @@ public static void separateCitations(XTextDocument doc, for (int i = 0; i < keys.size(); i++) { boolean insertSpaceAfter = (i != last); List citationKeys1 = keys.subList(i, i + 1); - List pageInfos1 = pageInfosForCitations.subList(i, i + 1); - OOFormattedText citationText1 = OOFormattedText.fromString("tmp"); + List> pageInfos1 = pageInfosForCitations.subList(i, i + 1); + // String tmpLabel = "tmp"; + String tmpLabel = keys.get(i); + OOFormattedText citationText1 = OOFormattedText.fromString(tmpLabel); UpdateCitationMarkers.createAndFillCitationGroup(fr, doc, citationKeys1, diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 0ae671efca6..e3c51478cfc 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -255,7 +255,7 @@ public Optional healthReport(XTextDocument doc) */ public CitationGroupID createCitationGroup(XTextDocument doc, List citationKeys, - List pageInfosForCitations, + List> pageInfosForCitations, InTextCitationType citationType, XTextCursor position, boolean insertSpaceAfter) diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index de8d086bdd7..93efc8ae684 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -3,6 +3,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import org.jabref.logic.JabRefException; import org.jabref.logic.oostyle.OOBibStyle; @@ -132,7 +133,7 @@ public static void fillCitationMarkInCursor(XTextDocument doc, public static void createAndFillCitationGroup(OOFrontend fr, XTextDocument doc, List citationKeys, - List pageInfosForCitations, + List> pageInfosForCitations, InTextCitationType citationType, OOFormattedText citationText, XTextCursor position, diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index f3f05f4a82c..b00dc11c213 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -194,22 +194,22 @@ public List getCitationNumbersInLocalOrder() { * The list itself is not null. * */ - public List getPageInfosForCitationsInStorageOrder() { + public List> getPageInfosForCitationsInStorageOrder() { CitationGroup cg = this; // pageInfo values from citations, empty mapped to null. return (cg.citationsInStorageOrder.stream() - .map(cit -> cit.pageInfo.orElse(null)) + .map(cit -> cit.pageInfo) .collect(Collectors.toList())); } /** - * @return List of nullable pageInfo values, one for each citation, in localOrder. + * @return List of optional pageInfo values, one for each citation, in localOrder. */ - public List getPageInfosForCitationsInLocalOrder() { + public List> getPageInfosForCitationsInLocalOrder() { CitationGroup cg = this; - // pageInfo values from citations, empty mapped to null. + // pageInfo values from citations return (cg.getCitationsInLocalOrder().stream() - .map(cit -> cit.pageInfo.orElse(null)) + .map(cit -> cit.pageInfo) .collect(Collectors.toList())); } diff --git a/src/main/java/org/jabref/model/oostyle/CitationSort.java b/src/main/java/org/jabref/model/oostyle/CitationSort.java index abb713a50a2..ae6d9f8b005 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationSort.java +++ b/src/main/java/org/jabref/model/oostyle/CitationSort.java @@ -45,13 +45,16 @@ public int compare(ComparableCitation a, ComparableCitation b) { } // Also consider pageInfo if (res == 0) { - CitationSort.comparePageInfo(a.getPageInfo().orElse(null), - b.getPageInfo().orElse(null)); + CitationSort.comparePageInfo(a.getPageInfo(), + b.getPageInfo()); } return res; } } + /* + * Empty (after trimming) becomes null + */ public static String regularizePageInfoToString(OOFormattedText p) { if (p == null) { return null; @@ -60,24 +63,43 @@ public static String regularizePageInfoToString(OOFormattedText p) { return (pt.equals("") ? null : pt); } + public static OOFormattedText regularizePageInfo(OOFormattedText p) { + String reg = CitationSort.regularizePageInfoToString(p); + if (reg == null) { + return null; + } + return OOFormattedText.fromString(reg); + } + + public static Optional regularizeOptionalPageInfo(Optional p) { + if (p.isEmpty()) { + return Optional.empty(); + } + String reg = CitationSort.regularizePageInfoToString(p.get()); + if (reg == null) { + return Optional.empty(); + } + return Optional.of(OOFormattedText.fromString(reg)); + } + /** * Defines sort order for pageInfo strings. * * null comes before non-null */ - public static int comparePageInfo(OOFormattedText a, OOFormattedText b) { + public static int comparePageInfo(Optional a, Optional b) { - String aa = regularizePageInfoToString(a); - String bb = regularizePageInfoToString(b); - if (aa == null && bb == null) { + Optional aa = regularizeOptionalPageInfo(a); + Optional bb = regularizeOptionalPageInfo(b); + if (aa.isEmpty() && bb.isEmpty()) { return 0; } - if (aa == null) { + if (aa.isEmpty()) { return -1; } - if (bb == null) { + if (bb.isEmpty()) { return +1; } - return aa.compareTo(bb); + return aa.get().asString().compareTo(bb.get().asString()); } } diff --git a/src/main/java/org/jabref/model/oostyle/OOFormattedText.java b/src/main/java/org/jabref/model/oostyle/OOFormattedText.java index b514edc6cce..6b8ea2abbf6 100644 --- a/src/main/java/org/jabref/model/oostyle/OOFormattedText.java +++ b/src/main/java/org/jabref/model/oostyle/OOFormattedText.java @@ -1,10 +1,13 @@ package org.jabref.model.oostyle; +import java.util.Objects; + public class OOFormattedText { private final String data; private OOFormattedText(String data) { + Objects.requireNonNull(data); this.data = data; } @@ -25,4 +28,25 @@ public static String toString(OOFormattedText s) { public String asString() { return data; } + + @Override + public boolean equals(Object o) { + + if (o == this) { + return true; + } + + if (!(o instanceof OOFormattedText)) { + return false; + } + + OOFormattedText c = (OOFormattedText) o; + + return data.equals(c.data); + } + + @Override + public int hashCode() { + return data.hashCode(); + } } diff --git a/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java b/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java index 2f6f35142d3..1ba61a51ce8 100644 --- a/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java +++ b/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; /** What is the data stored? */ public enum OOStyleDataModelVersion { @@ -36,14 +37,14 @@ public enum OOStyleDataModelVersion { * @param pageInfo Nullable. * @return JabRef53 style pageInfo list */ - public static List fakePageInfosForCitations(String pageInfo, - int nCitations) { - List pageInfosForCitations = new ArrayList<>(nCitations); + public static List> fakePageInfosForCitations(String pageInfo, + int nCitations) { + List> pageInfosForCitations = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { - if (i == nCitations - 1) { - pageInfosForCitations.add(OOFormattedText.fromString(pageInfo)); + if (i == (nCitations - 1) && (pageInfo != null)) { + pageInfosForCitations.add(Optional.of(OOFormattedText.fromString(pageInfo))); } else { - pageInfosForCitations.add(null); + pageInfosForCitations.add(Optional.empty()); } } return pageInfosForCitations; diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index c4d1e7fb37a..cae65221312 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -15,6 +15,7 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.jabref.logic.layout.Layout; import org.jabref.logic.layout.LayoutFormatterPreferences; @@ -88,10 +89,11 @@ void testNumerical() throws IOException { assertTrue(style.isSortByPosition()); } - List asOOFormattedText(List s) { - return (s.stream() - .map(OOFormattedText::fromString) - .collect(Collectors.toList())); + List> asPageInfos(String... s) { + return (Stream.of(s) + .map(OOFormattedText::fromString) + .map(Optional::ofNullable) + .collect(Collectors.toList())); } @Test @@ -99,7 +101,7 @@ void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - List empty = null; + List> empty = null; // Unfortunately these two are both "; " in // jabref/src/main/resources/resource/openoffice/default_numerical.jstyle @@ -129,8 +131,8 @@ void testGetNumCitationMarker() throws IOException { assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", style.getNumCitationMarker(Arrays.asList(1,1,2,2,3,3), 1, - asOOFormattedText(Arrays.asList("p1a","p1b","p2","p2", - null, null))).asString()); + asPageInfos("p1a","p1b","p2","p2", + null, null)).asString()); // Consecutive numbers can become a range ... assertEquals("[1-3]", @@ -152,22 +154,22 @@ void testGetNumCitationMarker() throws IOException { // ... a pageInfo needs to be emitted assertEquals("[1; p1; 2-3]", style.getNumCitationMarker(Arrays.asList(1, 2, 3), - 1, /* minGroupingCount */ - asOOFormattedText(Arrays.asList("p1",null,null))) + 1, /* minGroupingCount */ + asPageInfos("p1",null,null)) .asString()); // null and "" pageInfos are taken as equal. // Due to trimming, " " is the same as well. assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - asOOFormattedText(Arrays.asList("",null," "))) + 1, /* minGroupingCount */ + asPageInfos("",null," ")) .asString()); // pageInfos are trimmed assertEquals("[1; p1]", style.getNumCitationMarker(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - asOOFormattedText(Arrays.asList("p1"," p1","p1 "))) + 1, /* minGroupingCount */ + asPageInfos("p1"," p1","p1 ")) .asString()); // The citation numbers come out sorted @@ -181,24 +183,24 @@ void testGetNumCitationMarker() throws IOException { // but not empty-or-null) assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), - 1, - asOOFormattedText(Arrays.asList("px", "p7", "p3", "p4", - "px", "px", "p5"))) + 1, + asPageInfos("px", "p7", "p3", "p4", + "px", "px", "p5")) .asString()); // pageInfo sorting (for the same number) assertEquals("[1; 1; a; 1; b]", style.getNumCitationMarker(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - asOOFormattedText(Arrays.asList("","b","a "))) + 1, /* minGroupingCount */ + asPageInfos("","b","a ")) .asString()); // pageInfo sorting (for the same number) is not numeric. assertEquals("[1; p100; 1; p20; 1; p9]", style.getNumCitationMarker(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - asOOFormattedText(Arrays.asList("p20","p9","p100"))) + 1, /* minGroupingCount */ + asPageInfos("p20","p9","p100")) .asString()); assertEquals("[1-3]", @@ -238,30 +240,30 @@ void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - List empty = null; + List> empty = null; // unresolved citations look like [??] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", style.getNumCitationMarker(Arrays.asList(0), - 1, - empty).asString()); + 1, + empty).asString()); // pageInfo is shown for unresolved citations assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; p1]", style.getNumCitationMarker(Arrays.asList(0), - 1, - asOOFormattedText(Arrays.asList("p1"))).asString()); + 1, + asPageInfos("p1")).asString()); // unresolved citations sorted to the front assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4]", style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), - 1, - empty).asString()); + 1, + empty).asString()); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3]", style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), - 1, - empty).asString()); + 1, + empty).asString()); // multiple unresolved citations are not collapsed assertEquals("[" @@ -269,8 +271,8 @@ void testGetNumCitationMarkerUndefined() throws IOException { + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", style.getNumCitationMarker(Arrays.asList(0, 0, 0), - 1, - empty).asString()); + 1, + empty).asString()); /* * BIBLIOGRAPHY From 89770eead23ea7fdec009b66220b73db64e8bf99 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 19:01:54 +0200 Subject: [PATCH 0755/1068] pageInfo normalization done in a single place --- .../org/jabref/logic/oostyle/OOBibStyle.java | 4 +-- .../oostyle/OOBibStyleGetCitationMarker.java | 10 +++--- .../jabref/logic/openoffice/Backend52.java | 16 ++------- .../org/jabref/model/oostyle/Citation.java | 12 +++++++ .../jabref/model/oostyle/CitationSort.java | 34 ++----------------- 5 files changed, 23 insertions(+), 53 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 88bd3037391..e4cc316afd4 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -30,8 +30,8 @@ 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.oostyle.Citation; import org.jabref.model.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.CitationSort; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; @@ -965,7 +965,7 @@ public OOFormattedText getNumCitationMarkerForBibliography(int number) { List> res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { Optional p = pageInfosForCitations.get(i); - res.add(CitationSort.regularizeOptionalPageInfo(p)); + res.add(Citation.normalizePageInfo(p)); } return res; } diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 9ef2756706f..b9bd096de00 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -12,9 +12,9 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; +import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.CitationSort; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.strings.StringUtil; @@ -467,7 +467,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, } Optional pageInfo = - CitationSort.regularizeOptionalPageInfo(ce.getPageInfo()); + Citation.normalizePageInfo(ce.getPageInfo()); if (pageInfo.isPresent()) { sb.append(pageInfoSeparator); sb.append(OOFormattedText.toString(pageInfo.get())); @@ -669,10 +669,8 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, final boolean citationKeysDiffer = !ce2.getCitationKey().equals(ce1.getCitationKey()); final boolean normalizedMarkersDiffer = !nm2.equals(nm1); - Optional pageInfo2 = - CitationSort.regularizeOptionalPageInfo(ce2.getPageInfo()); - Optional pageInfo1 = - CitationSort.regularizeOptionalPageInfo(ce1.getPageInfo()); + Optional pageInfo2 = Citation.normalizePageInfo(ce2.getPageInfo()); + Optional pageInfo1 = Citation.normalizePageInfo(ce1.getPageInfo()); final boolean bothPageInfosAreEmpty = pageInfo2.isEmpty() && pageInfo1.isEmpty(); final boolean pageInfosDiffer = !pageInfo2.equals(pageInfo1); diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index bb84b093573..1e067495132 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -171,17 +171,6 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str return cg; } - static Optional normalizePageInfo(Optional o) { - if (o == null || o.isEmpty() || "".equals(OOFormattedText.toString(o.get()))) { - return Optional.empty(); - } - String s = OOFormattedText.toString(o.get()); - if (s.trim().equals("")) { - return Optional.empty(); - } - return Optional.of(OOFormattedText.fromString(s)); - } - /** * Create a reference mark with the given name, at the * end of position. @@ -230,7 +219,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, Citation cit = new Citation(citationKeys.get(i)); citations.add(cit); - Optional pageInfo = normalizePageInfo(pageInfosForCitations.get(i)); + Optional pageInfo = Citation.normalizePageInfo(pageInfosForCitations.get(i)); switch (dataModel) { case JabRef52: if (i == last) { @@ -256,7 +245,8 @@ public CitationGroup createCitationGroup(XTextDocument doc, switch (dataModel) { case JabRef52: - Optional pageInfo = normalizePageInfo(pageInfosForCitations.get(last)); + Optional pageInfo = + Citation.normalizePageInfo(pageInfosForCitations.get(last)); if (pageInfo.isPresent()) { String pageInfoString = OOFormattedText.toString(pageInfo.get()); diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 498c430a948..08b9d8d07a6 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -69,4 +69,16 @@ public static void setUniqueLetter(Pair> x) { Citation cit = x.a; cit.uniqueLetter = x.b; } + + + public static Optional normalizePageInfo(Optional o) { + if (o == null || o.isEmpty() || "".equals(OOFormattedText.toString(o.get()))) { + return Optional.empty(); + } + String s = OOFormattedText.toString(o.get()); + if (s.trim().equals("")) { + return Optional.empty(); + } + return Optional.of(OOFormattedText.fromString(s)); + } } diff --git a/src/main/java/org/jabref/model/oostyle/CitationSort.java b/src/main/java/org/jabref/model/oostyle/CitationSort.java index ae6d9f8b005..e6ea5116778 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationSort.java +++ b/src/main/java/org/jabref/model/oostyle/CitationSort.java @@ -52,36 +52,6 @@ public int compare(ComparableCitation a, ComparableCitation b) { } } - /* - * Empty (after trimming) becomes null - */ - public static String regularizePageInfoToString(OOFormattedText p) { - if (p == null) { - return null; - } - String pt = OOFormattedText.toString(p).trim(); - return (pt.equals("") ? null : pt); - } - - public static OOFormattedText regularizePageInfo(OOFormattedText p) { - String reg = CitationSort.regularizePageInfoToString(p); - if (reg == null) { - return null; - } - return OOFormattedText.fromString(reg); - } - - public static Optional regularizeOptionalPageInfo(Optional p) { - if (p.isEmpty()) { - return Optional.empty(); - } - String reg = CitationSort.regularizePageInfoToString(p.get()); - if (reg == null) { - return Optional.empty(); - } - return Optional.of(OOFormattedText.fromString(reg)); - } - /** * Defines sort order for pageInfo strings. * @@ -89,8 +59,8 @@ public static Optional regularizeOptionalPageInfo(Optional a, Optional b) { - Optional aa = regularizeOptionalPageInfo(a); - Optional bb = regularizeOptionalPageInfo(b); + Optional aa = Citation.normalizePageInfo(a); + Optional bb = Citation.normalizePageInfo(b); if (aa.isEmpty() && bb.isEmpty()) { return 0; } From 01e5b90dcdd25137876217b11692a6fd6b8bef45 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 19:06:24 +0200 Subject: [PATCH 0756/1068] Citation.db is private --- src/main/java/org/jabref/logic/oostyle/OOProcess.java | 4 ++-- src/main/java/org/jabref/model/oostyle/Citation.java | 8 +++++--- src/main/java/org/jabref/model/oostyle/CitedKey.java | 4 ++-- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 07ada95d249..9117dadfa61 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -328,13 +328,13 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, seenBefore.add(currentKey); } Optional uniqueLetterForKey = cit.uniqueLetter; - if (cit.db.isEmpty()) { + if (cit.getDatabaseLookupResult().isEmpty()) { hasUnresolved = true; } CitationMarkerEntry cm = new CitationMarkerEntryImpl(currentKey, - cit.db, + cit.getDatabaseLookupResult(), uniqueLetterForKey, pageInfosForCitations.get(j), isFirst); diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 08b9d8d07a6..b1ce38b9bc1 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -8,11 +8,14 @@ public class Citation implements CitationSort.ComparableCitation { /** key in database */ - public String citationKey; + public final String citationKey; + /** Result from database lookup. Optional.empty() if not found. */ - public Optional db; + private Optional db; + /** The number used for numbered citation styles . */ public Optional number; + /** Letter that makes the in-text citation unique. */ public Optional uniqueLetter; @@ -70,7 +73,6 @@ public static void setUniqueLetter(Pair> x) { cit.uniqueLetter = x.b; } - public static Optional normalizePageInfo(Optional o) { if (o == null || o.isEmpty() || "".equals(OOFormattedText.toString(o.get()))) { return Optional.empty(); diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index c7a72fe7d2d..68c6ba3b6ab 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -19,7 +19,7 @@ public class CitedKey implements CitationSort.ComparableCitation { this.citationKey = citationKey; this.where = new LinkedHashSet<>(); // remember order this.where.add(p); - this.db = cit.db; + this.db = cit.getDatabaseLookupResult(); this.number = cit.number; this.uniqueLetter = cit.uniqueLetter; this.normCitMarker = Optional.empty(); @@ -52,7 +52,7 @@ public Optional getPageInfo() { */ void addPath(CitationPath p, Citation cit) { this.where.add(p); - if (cit.db != this.db) { + if (cit.getDatabaseLookupResult() != this.db) { throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); } if (cit.number != this.number) { From 3ee8e243046e42e473b6cae0034eec33c64a3c86 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 19:12:06 +0200 Subject: [PATCH 0757/1068] Citation.number is private --- src/main/java/org/jabref/model/oostyle/Citation.java | 12 +++++++++++- .../java/org/jabref/model/oostyle/CitationGroup.java | 2 +- src/main/java/org/jabref/model/oostyle/CitedKey.java | 4 ++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index b1ce38b9bc1..1657988bb89 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -14,7 +14,7 @@ public class Citation implements CitationSort.ComparableCitation { private Optional db; /** The number used for numbered citation styles . */ - public Optional number; + private Optional number; /** Letter that makes the in-text citation unique. */ public Optional uniqueLetter; @@ -58,6 +58,13 @@ public Optional getDatabaseLookupResult() { return db; } + public Optional getNumber() { + return number; + } + + /* + * Setters for CitationGroups.distribute() + */ public static void setDatabaseLookupResult(Pair> x) { Citation cit = x.a; cit.db = x.b; @@ -73,6 +80,9 @@ public static void setUniqueLetter(Pair> x) { cit.uniqueLetter = x.b; } + /* + * pageInfo normalization + */ public static Optional normalizePageInfo(Optional o) { if (o == null || o.isEmpty() || "".equals(OOFormattedText.toString(o.get()))) { return Optional.empty(); diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index b00dc11c213..a817836398b 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -182,7 +182,7 @@ public List getCitationsInLocalOrder() { public List getCitationNumbersInLocalOrder() { List cits = getCitationsInLocalOrder(); return (cits.stream() - .map(cit -> cit.number.orElseThrow(RuntimeException::new)) + .map(cit -> cit.getNumber().orElseThrow(RuntimeException::new)) .collect(Collectors.toList())); } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index 68c6ba3b6ab..f977292d3eb 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -20,7 +20,7 @@ public class CitedKey implements CitationSort.ComparableCitation { this.where = new LinkedHashSet<>(); // remember order this.where.add(p); this.db = cit.getDatabaseLookupResult(); - this.number = cit.number; + this.number = cit.getNumber(); this.uniqueLetter = cit.uniqueLetter; this.normCitMarker = Optional.empty(); } @@ -55,7 +55,7 @@ void addPath(CitationPath p, Citation cit) { if (cit.getDatabaseLookupResult() != this.db) { throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); } - if (cit.number != this.number) { + if (cit.getNumber() != this.number) { throw new RuntimeException("CitedKey.addPath: mismatch on cit.number"); } if (cit.uniqueLetter != this.uniqueLetter) { From 605cc03ebdca61f9f2007294b367a6e71efc14f9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 19:35:45 +0200 Subject: [PATCH 0758/1068] Citation.normalizePageInfo trims --- src/main/java/org/jabref/model/oostyle/Citation.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 1657988bb89..d725d0374e3 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -91,6 +91,6 @@ public static Optional normalizePageInfo(Optional Date: Mon, 17 May 2021 19:42:59 +0200 Subject: [PATCH 0759/1068] Citation.uniqueLetter and pageInfo are private --- .../org/jabref/logic/oostyle/OOProcess.java | 2 +- .../org/jabref/logic/openoffice/Backend52.java | 14 ++++++++------ .../org/jabref/model/oostyle/Citation.java | 18 +++++++++++++++--- .../jabref/model/oostyle/CitationGroup.java | 12 ++++++------ .../org/jabref/model/oostyle/CitedKey.java | 4 ++-- 5 files changed, 32 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 9117dadfa61..a69f9ea80b1 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -327,7 +327,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, isFirst = true; seenBefore.add(currentKey); } - Optional uniqueLetterForKey = cit.uniqueLetter; + Optional uniqueLetterForKey = cit.getUniqueLetter(); if (cit.getDatabaseLookupResult().isEmpty()) { hasUnresolved = true; } diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 1e067495132..89d8d1f54bd 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -107,7 +107,7 @@ private static void setPageInfoInDataInitial(List citations, Optional pageInfo) { // attribute to last citation (initially localOrder == storageOrder) if (citations.size() > 0) { - citations.get(citations.size() - 1).pageInfo = pageInfo; + citations.get(citations.size() - 1).setPageInfo(pageInfo); } } @@ -115,14 +115,14 @@ private static void setPageInfoInData(CitationGroup cg, Optional pageInfo) { List citations = cg.getCitationsInLocalOrder(); if (citations.size() > 0) { - citations.get(citations.size() - 1).pageInfo = pageInfo; + citations.get(citations.size() - 1).setPageInfo(pageInfo); } } private static Optional getPageInfoFromData(CitationGroup cg) { List citations = cg.getCitationsInLocalOrder(); if (citations.size() > 0) { - return citations.get(citations.size() - 1).pageInfo; + return citations.get(citations.size() - 1).getPageInfo(); } else { return Optional.empty(); } @@ -223,15 +223,17 @@ public CitationGroup createCitationGroup(XTextDocument doc, switch (dataModel) { case JabRef52: if (i == last) { - cit.pageInfo = pageInfo; + cit.setPageInfo(pageInfo); } else { if (pageInfo.isPresent()) { LOGGER.warn("dataModel JabRef52" + " only supports pageInfo for the last citation of a group"); } } + break; case JabRef53: - cit.pageInfo = pageInfo; + cit.setPageInfo(pageInfo); + break; } } @@ -300,7 +302,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, case JabRef53: return (joinableGroup.stream() .flatMap(cg -> (cg.citationsInStorageOrder.stream() - .map(cit -> cit.pageInfo))) + .map(cit -> cit.getPageInfo()))) .collect(Collectors.toList())); default: throw new RuntimeException("unhandled dataModel here"); diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index d725d0374e3..0f5a8e70508 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -17,10 +17,10 @@ public class Citation implements CitationSort.ComparableCitation { private Optional number; /** Letter that makes the in-text citation unique. */ - public Optional uniqueLetter; + private Optional uniqueLetter; - /** pageInfo: For Compat.DataModel.JabRef53 */ - public Optional pageInfo; + /** pageInfo */ + private Optional pageInfo; /* missing: something that differentiates this from other * citations of the same citationKey. In particular, a @@ -62,6 +62,18 @@ public Optional getNumber() { return number; } + public Optional getUniqueLetter() { + return uniqueLetter; + } + + public void setPageInfo(Optional v) { + Optional vv = normalizePageInfo(v); + if (!vv.equals(v)) { + throw new RuntimeException("setPageInfo argument is not normalied"); + } + this.pageInfo = vv; + } + /* * Setters for CitationGroups.distribute() */ diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index a817836398b..c2b11546f37 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -116,7 +116,7 @@ public Optional getBibEntry() { @Override public Optional getPageInfo() { - return c.pageInfo; + return c.getPageInfo(); } } @@ -134,8 +134,8 @@ void imposeLocalOrderByComparator(Comparator entryComparator) { final int last = nCitations - 1; Optional lastPageInfo = Optional.empty(); if (dataModel == OOStyleDataModelVersion.JabRef52) { - lastPageInfo = getCitationsInLocalOrder().get(last).pageInfo; - getCitationsInLocalOrder().get(last).pageInfo = Optional.empty(); + lastPageInfo = getCitationsInLocalOrder().get(last).getPageInfo(); + getCitationsInLocalOrder().get(last).setPageInfo(Optional.empty()); } List cis = new ArrayList<>(nCitations); @@ -155,7 +155,7 @@ void imposeLocalOrderByComparator(Comparator entryComparator) { this.localOrder = ordered; if (dataModel == OOStyleDataModelVersion.JabRef52) { - getCitationsInLocalOrder().get(last).pageInfo = lastPageInfo; + getCitationsInLocalOrder().get(last).setPageInfo(lastPageInfo); } } @@ -198,7 +198,7 @@ public List> getPageInfosForCitationsInStorageOrder() CitationGroup cg = this; // pageInfo values from citations, empty mapped to null. return (cg.citationsInStorageOrder.stream() - .map(cit -> cit.pageInfo) + .map(cit -> cit.getPageInfo()) .collect(Collectors.toList())); } @@ -209,7 +209,7 @@ public List> getPageInfosForCitationsInLocalOrder() { CitationGroup cg = this; // pageInfo values from citations return (cg.getCitationsInLocalOrder().stream() - .map(cit -> cit.pageInfo) + .map(cit -> cit.getPageInfo()) .collect(Collectors.toList())); } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index f977292d3eb..65e1607fb7a 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -21,7 +21,7 @@ public class CitedKey implements CitationSort.ComparableCitation { this.where.add(p); this.db = cit.getDatabaseLookupResult(); this.number = cit.getNumber(); - this.uniqueLetter = cit.uniqueLetter; + this.uniqueLetter = cit.getUniqueLetter(); this.normCitMarker = Optional.empty(); } @@ -58,7 +58,7 @@ void addPath(CitationPath p, Citation cit) { if (cit.getNumber() != this.number) { throw new RuntimeException("CitedKey.addPath: mismatch on cit.number"); } - if (cit.uniqueLetter != this.uniqueLetter) { + if (cit.getUniqueLetter() != this.uniqueLetter) { throw new RuntimeException("CitedKey.addPath: mismatch on cit.uniqueLetter"); } } From 7889d006e262d87d45e6b6137912e675513bd478 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 19:46:46 +0200 Subject: [PATCH 0760/1068] drop comment --- src/main/java/org/jabref/model/oostyle/Citation.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 0f5a8e70508..3f8c5e4e557 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -22,13 +22,9 @@ public class Citation implements CitationSort.ComparableCitation { /** pageInfo */ private Optional pageInfo; - /* missing: something that differentiates this from other - * citations of the same citationKey. In particular, a - * CitationGroup may contain multiple citations of the same - * source. We use CitationPath.storageIndexInGroup to refer to - * citations. + /** + * */ - public Citation(String citationKey) { this.citationKey = citationKey; this.db = Optional.empty(); From b7993fd830a7bf4b906b5b7f6021acded1cfc8a0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 19:55:22 +0200 Subject: [PATCH 0761/1068] format --- .../java/org/jabref/model/oostyle/CitationDatabaseLookup.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java b/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java index 8e490b7ed2a..2cb2ba3e062 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java @@ -1,7 +1,5 @@ package org.jabref.model.oostyle; -// import org.jabref.model.oostyle.CitationDatabaseLookup; - import java.util.List; import java.util.Objects; import java.util.Optional; @@ -12,8 +10,10 @@ public class CitationDatabaseLookup { public static class Result { + public final BibEntry entry; public final BibDatabase database; + public Result(BibEntry entry, BibDatabase database) { Objects.requireNonNull(entry); Objects.requireNonNull(database); From dfd5ec73ac75d9cff54498f31ddf2267698d2222 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 21:17:49 +0200 Subject: [PATCH 0762/1068] separateCitations simplified. Now imposes localOrder --- .../org/jabref/logic/oostyle/OOProcess.java | 2 +- .../jabref/logic/openoffice/Backend52.java | 6 +- .../jabref/logic/openoffice/EditSeparate.java | 72 ++++++++----------- .../jabref/model/oostyle/CitationGroup.java | 4 ++ 4 files changed, 38 insertions(+), 46 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index a69f9ea80b1..5bf7227517a 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -72,7 +72,7 @@ private static Comparator makeYearAuthorTitleComparator() { * * Yes, they are always sorted one way or another. */ - private static Comparator comparatorForMulticite(OOBibStyle style) { + public static Comparator comparatorForMulticite(OOBibStyle style) { if (style.getMultiCiteChronological()) { return OOProcess.YEAR_AUTHOR_TITLE_COMPARATOR; } else { diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 89d8d1f54bd..edc3ef584dd 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -151,6 +151,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str Optional pageInfo = (UnoUserDefinedProperty.getStringValue(doc, refMarkName) .map(OOFormattedText::fromString)); + pageInfo = Citation.normalizePageInfo(pageInfo); setPageInfoInDataInitial(citations, pageInfo); @@ -427,10 +428,11 @@ public void applyCitationEntries(XTextDocument doc, List citation switch (dataModel) { case JabRef52: for (CitationEntry entry : citationEntries) { - Optional pageInfo = entry.getPageInfo(); + Optional pageInfo = entry.getPageInfo().map(OOFormattedText::fromString); + pageInfo = Citation.normalizePageInfo(pageInfo); if (pageInfo.isPresent()) { String name = entry.getRefMarkName(); - UnoUserDefinedProperty.createStringProperty(doc, name, pageInfo.get()); + UnoUserDefinedProperty.createStringProperty(doc, name, pageInfo.get().asString()); } } break; diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 6b8d0358aad..f1dc76ad9d3 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -2,11 +2,10 @@ import java.util.ArrayList; import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; import org.jabref.logic.JabRefException; import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.oostyle.OOProcess; import org.jabref.model.database.BibDatabase; import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; @@ -50,71 +49,58 @@ public static void separateCitations(XTextDocument doc, boolean madeModifications = false; - // {@code names} does not need to be sorted. - List names = - new ArrayList<>(fr.citationGroups.getCitationGroupIDsUnordered()); + // To reduce surprises in JabRef52 mode, impose localOrder to + // decide the visually last Citation i the group. Unless the + // style changed since refresh this is the last on the screen + // as well. + fr.citationGroups.lookupEntriesInDatabases(databases); + fr.citationGroups.imposeLocalOrderByComparator(OOProcess.comparatorForMulticite(style)); + + List names = new ArrayList<>(fr.citationGroups.getCitationGroupIDsUnordered()); - final boolean useLockControllers = true; try { - if (useLockControllers) { - UnoScreenRefresh.lockControllers(doc); - } + UnoScreenRefresh.lockControllers(doc); - int pivot = 0; + for (CitationGroupID cgid : names) { - while (pivot < (names.size())) { - CitationGroupID cgid = names.get(pivot); CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); XTextRange range1 = (fr .getMarkRange(doc, cgid) .orElseThrow(RuntimeException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); - // Note: JabRef52 returns cg.pageInfo for the last citation. - List> pageInfosForCitations = - cg.getPageInfosForCitationsInStorageOrder(); - - List cits = cg.citationsInStorageOrder; + List cits = cg.getCitationsInStorageOrder(); if (cits.size() <= 1) { - pivot++; continue; } - List keys = - cits.stream().map(cit -> cit.citationKey).collect(Collectors.toList()); - fr.removeCitationGroup(cg, doc); - // Now we own the content of cits - // Insert mark for each key - final int last = keys.size() - 1; - for (int i = 0; i < keys.size(); i++) { + // Create a citation group for each citation. + final int last = cits.size() - 1; + for (int i = 0; i < cits.size(); i++) { boolean insertSpaceAfter = (i != last); - List citationKeys1 = keys.subList(i, i + 1); - List> pageInfos1 = pageInfosForCitations.subList(i, i + 1); - // String tmpLabel = "tmp"; - String tmpLabel = keys.get(i); - OOFormattedText citationText1 = OOFormattedText.fromString(tmpLabel); - UpdateCitationMarkers.createAndFillCitationGroup(fr, - doc, - citationKeys1, - pageInfos1, - cg.citationType, - citationText1, - textCursor, - style, - insertSpaceAfter); + Citation cit = cits.get(i); + + UpdateCitationMarkers.createAndFillCitationGroup( + fr, + doc, + List.of(cit.citationKey), + List.of(cit.getPageInfo()), + cg.citationType, + OOFormattedText.fromString(cit.citationKey), + textCursor, + style, + insertSpaceAfter); + textCursor.collapseToEnd(); } madeModifications = true; - pivot++; } } finally { - if (useLockControllers) { - UnoScreenRefresh.unlockControllers(doc); - } + UnoScreenRefresh.unlockControllers(doc); } if (madeModifications) { diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index c2b11546f37..33fbc9a8fa2 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -167,6 +167,10 @@ public List getLocalOrder() { * citations */ + public List getCitationsInStorageOrder() { + return new ArrayList<>(citationsInStorageOrder); + } + public List getCitationsInLocalOrder() { List res = new ArrayList<>(citationsInStorageOrder.size()); for (int i : localOrder) { From c3df0e420d619309d21f489a8ffda4a824c82f0c Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 17 May 2021 21:33:24 +0200 Subject: [PATCH 0763/1068] drop getCitationsInStorageOrder --- src/main/java/org/jabref/logic/openoffice/EditSeparate.java | 2 +- src/main/java/org/jabref/model/oostyle/CitationGroup.java | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index f1dc76ad9d3..37bf5757648 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -69,7 +69,7 @@ public static void separateCitations(XTextDocument doc, .orElseThrow(RuntimeException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); - List cits = cg.getCitationsInStorageOrder(); + List cits = cg.citationsInStorageOrder; if (cits.size() <= 1) { continue; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index 33fbc9a8fa2..c2b11546f37 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -167,10 +167,6 @@ public List getLocalOrder() { * citations */ - public List getCitationsInStorageOrder() { - return new ArrayList<>(citationsInStorageOrder); - } - public List getCitationsInLocalOrder() { List res = new ArrayList<>(citationsInStorageOrder.size()); for (int i : localOrder) { From 01e5d0a28f9c2d19fb1d96ecf1d35572f0f18f40 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 18 May 2021 00:20:19 +0200 Subject: [PATCH 0764/1068] broke body of mergeCitationGroups to smaller functions --- .../jabref/logic/openoffice/EditMerge.java | 514 ++++++++++-------- 1 file changed, 278 insertions(+), 236 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index e27d0c2ca87..49d607ca2b2 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -35,6 +35,266 @@ public class EditMerge { private static final Logger LOGGER = LoggerFactory.getLogger(EditMerge.class); + private static class JoinableGroupData { + /* + * A list of consecutive citation groups only separated by spaces. + */ + List group; + /* + * A cursor covering the XTextRange of each entry in group + * (and the spaces between them) + */ + XTextCursor groupCursor; + + JoinableGroupData(List group, XTextCursor groupCursor) { + this.group = group; + this.groupCursor = groupCursor; + } + } + + private static class ScanState { + + // Citation groups in the current group + List currentGroup; + + // A cursor that covers the Citation groups in currentGroup, + // including the space between them. + // Null if currentGroup.isEmpty() + XTextCursor currentGroupCursor; + + // A cursor starting at the end of the last CitationGroup in + // currentGroup. Null if currentGroup.isEmpty() + XTextCursor cursorBetween; + + // The last element of currentGroup. + // Null if currentGroup.isEmpty() + CitationGroup prev; + + // The XTextRange for prev. + // Null if currentGroup.isEmpty() + XTextRange prevRange; + + ScanState() { + reset(); + } + + void reset() { + currentGroup = new ArrayList<>(); + currentGroupCursor = null; + cursorBetween = null; + prev = null; + prevRange = null; + } + } + + /** + * Decide if cg could be added to state.currentGroup + * + * @param cg The CitationGroup to test + * @param currentRange The XTextRange corresponding to cg. + * + * @return false if cannot add, true if can. If returned true, + * then state.cursorBetween and state.currentGroupCursor are + * expanded to end at the start of currentRange. + */ + private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextRange currentRange) { + + if (state.currentGroup.isEmpty()) { + return false; + } + + Objects.requireNonNull(state.currentGroupCursor); + Objects.requireNonNull(state.cursorBetween); + Objects.requireNonNull(state.prev); + Objects.requireNonNull(state.prevRange); + + // Only combine (Author 2000) type citations + if (cg.citationType != InTextCitationType.AUTHORYEAR_PAR) { + return false; + } + + if (state.prev != null) { + + // Even if we combine AUTHORYEAR_INTEXT citations, we + // would not mix them with AUTHORYEAR_PAR + if (cg.citationType != state.prev.citationType) { + return false; + } + + if (!UnoTextRange.comparables(state.prevRange, currentRange)) { + return false; + } + + // Sanity check: the current range should start later than + // the previous. + int textOrder = UnoTextRange.compareStarts(state.prevRange, currentRange); + if (textOrder != (-1)) { + String msg = + String.format("MergeCitationGroups:" + + " \"%s\" supposed to be followed by \"%s\"," + + " but %s", + state.prevRange.getString(), + currentRange.getString(), + ((textOrder == 0) + ? "they start at the same position" + : ("the start of the latter precedes" + + " the start of the first"))); + LOGGER.warn(msg); + return false; + } + } + + if (state.cursorBetween == null) { + return false; + } + + Objects.requireNonNull(state.cursorBetween); + Objects.requireNonNull(state.currentGroupCursor); + + // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() + if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { + String msg = ("MergeCitationGroups:" + + " cursorBetween.end != currentGroupCursor.end"); + throw new RuntimeException(msg); + } + + /* + * Try to expand state.currentGroupCursor and state.cursorBetween by going right + * to reach rangeStart. + */ + XTextRange rangeStart = currentRange.getStart(); + boolean couldExpand = true; + XTextCursor thisCharCursor = + (currentRange.getText().createTextCursorByRange(state.cursorBetween.getEnd())); + + while (couldExpand && (UnoTextRange.compareEnds(state.cursorBetween, rangeStart) < 0)) { + couldExpand = state.cursorBetween.goRight((short) 1, true); + state.currentGroupCursor.goRight((short) 1, true); + // + // Check that we only walk through inline whitespace. + // + thisCharCursor.goRight((short) 1, true); + String thisChar = thisCharCursor.getString(); + thisCharCursor.collapseToEnd(); + if (thisChar.isEmpty() || thisChar.equals("\n") || !thisChar.trim().isEmpty()) { + couldExpand = false; + } + + // These two should move in sync: + if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { + String msg = ("MergeCitationGroups:" + + " cursorBetween.end != currentGroupCursor.end" + + " (during expand)"); + throw new RuntimeException(msg); + } + } // while + + if (!couldExpand) { + return false; + } + + return true; + } + + /** + * Add cg to state.currentGroup + * Set state.cursorBetween to start at currentRange.getEnd() + * Expand state.currentGroupCursor to also cover currentRange + * Set state.prev to cg, state.prevRange to currentRange + */ + private static void addToCurrentGroup(ScanState state, CitationGroup cg, XTextRange currentRange) { + final boolean isNewGroup = state.currentGroup.isEmpty(); + if (!isNewGroup) { + Objects.requireNonNull(state.currentGroupCursor); + Objects.requireNonNull(state.cursorBetween); + Objects.requireNonNull(state.prev); + Objects.requireNonNull(state.prevRange); + } + + // Add the current entry to a group. + state.currentGroup.add(cg); + + // Set up cursorBetween to start at currentRange.getEnd() + XTextRange rangeEnd = currentRange.getEnd(); + state.cursorBetween = currentRange.getText().createTextCursorByRange(rangeEnd); + + // If new group, create currentGroupCursor + if (isNewGroup) { + state.currentGroupCursor = (currentRange.getText() + .createTextCursorByRange(currentRange.getStart())); + } + + // include currentRange in currentGroupCursor + state.currentGroupCursor.goRight((short) (currentRange.getString().length()), true); + + if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { + String msg = ("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end"); + throw new RuntimeException(msg); + } + + /* Store data about last entry in currentGroup */ + state.prev = cg; + state.prevRange = currentRange; + } + + /** + * Scan the document for joinable groups. Return those found. + */ + private static List scan(XTextDocument doc, OOFrontend fr) + throws + NoDocumentException, + WrappedTargetException { + List result = new ArrayList<>(); + + List cgids = + fr.getCitationGroupIDsSortedWithinPartitions(doc, + false /* mapFootnotesToFootnoteMarks */); + if (cgids.isEmpty()) { + return result; + } + + ScanState state = new ScanState(); + + for (CitationGroupID cgid : cgids) { + CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); + + XTextRange currentRange = (fr.getMarkRange(doc, cgid) + .orElseThrow(RuntimeException::new)); + + /* + * Decide if we add cg to the group. False when the group is empty. + */ + boolean addToGroup = checkAddToGroup(state, cg, currentRange); + + /* + * Even if we do not add it to an existing group, + * we might use it to start a new group. + * + * Can it start a new group? + */ + boolean canStartGroup = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); + + if (!addToGroup) { + // close currentGroup + if (state.currentGroup.size() > 1) { + result.add(new JoinableGroupData(state.currentGroup, state.currentGroupCursor)); + } + // Start a new, empty group + state.reset(); + } + + if (addToGroup || canStartGroup) { + addToCurrentGroup(state, cg, currentRange); + } + } // for cgid + + // close currentGroup + if (state.currentGroup.size() > 1) { + result.add(new JoinableGroupData(state.currentGroup, state.currentGroupCursor)); + } + return result; + } + public static void mergeCitationGroups(XTextDocument doc, OOFrontend fr, List databases, @@ -54,252 +314,38 @@ public static void mergeCitationGroups(XTextDocument doc, UnknownPropertyException, WrappedTargetException { - final boolean useLockControllers = true; boolean madeModifications = false; - List referenceMarkNames = - fr.getCitationGroupIDsSortedWithinPartitions(doc, - false /* mapFootnotesToFootnoteMarks */); - - final int nRefMarks = referenceMarkNames.size(); - try { + UnoScreenRefresh.lockControllers(doc); - if (useLockControllers) { - UnoScreenRefresh.lockControllers(doc); - } - - /* - * joinableGroups collects lists of CitationGroup values - * that we think are joinable. - * - * joinableGroupsCursors provides the range for each group - */ - List> joinableGroups = new ArrayList<>(); - List joinableGroupsCursors = new ArrayList<>(); - - // Since we only join groups with identical citationTypes, we - // can get citationType from the first element of each - // joinableGroup. - - if (referenceMarkNames.size() > 0) { - // current group of CitationGroup values - List currentGroup = new ArrayList<>(); - XTextCursor currentGroupCursor = null; - XTextCursor cursorBetween = null; - CitationGroup prev = null; - XTextRange prevRange = null; - - for (CitationGroupID cgid : referenceMarkNames) { - CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); - - XTextRange currentRange = (fr - .getMarkRange(doc, cgid) - .orElseThrow(RuntimeException::new)); - - boolean addToGroup = true; - /* - * Decide if we add cg to the group - */ - - // Only combine (Author 2000) type citations - if (cg.citationType != InTextCitationType.AUTHORYEAR_PAR) { - addToGroup = false; - } - - // Even if we combine AUTHORYEAR_INTEXT citations, we - // would not mix them with AUTHORYEAR_PAR - if (addToGroup && (prev != null)) { - if (cg.citationType != prev.citationType) { - addToGroup = false; - } - } - - if (addToGroup && prev != null) { - Objects.requireNonNull(prevRange); - Objects.requireNonNull(currentRange); - if (!UnoTextRange.comparables(prevRange, currentRange)) { - addToGroup = false; - } else { - int textOrder = UnoTextRange.compareStarts(prevRange, currentRange); - if (textOrder != (-1)) { - String msg = - String.format("MergeCitationGroups:" - + " \"%s\" supposed to be followed by \"%s\"," - + " but %s", - prevRange.getString(), - currentRange.getString(), - ((textOrder == 0) - ? "they start at the same position" - : ("the start of the latter precedes" - + " the start of the first"))); - LOGGER.warn(msg); - addToGroup = false; - } - } - } - - if (addToGroup && (cursorBetween != null)) { - Objects.requireNonNull(currentGroupCursor); - // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() - if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { - String msg = ("MergeCitationGroups:" - + " cursorBetween.end != currentGroupCursor.end"); - throw new RuntimeException(msg); - } - - XTextRange rangeStart = currentRange.getStart(); - - boolean couldExpand = true; - - XTextCursor thisCharCursor = - (currentRange.getText() - .createTextCursorByRange(cursorBetween.getEnd())); - - while (couldExpand && - (UnoTextRange.compareEnds(cursorBetween, rangeStart) < 0)) { - couldExpand = cursorBetween.goRight((short) 1, true); - currentGroupCursor.goRight((short) 1, true); - // - thisCharCursor.goRight((short) 1, true); - String thisChar = thisCharCursor.getString(); - thisCharCursor.collapseToEnd(); - if (thisChar.isEmpty() - || thisChar.equals("\n") - || !thisChar.trim().isEmpty()) { - couldExpand = false; - } - if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { - String msg = ("MergeCitationGroups:" - + " cursorBetween.end != currentGroupCursor.end" - + " (during expand)"); - throw new RuntimeException(msg); - } - } // while - - if (!couldExpand) { - addToGroup = false; - } - } - - /* - * Even if we do not add it to an existing group, - * we might use it to start a new group. - * - * Can it start a new group? - */ - boolean canStartGroup = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); - - if (!addToGroup) { - // close currentGroup - if (currentGroup.size() > 1) { - joinableGroups.add(currentGroup); - joinableGroupsCursors.add(currentGroupCursor); - } - // Start a new, empty group - currentGroup = new ArrayList<>(); - currentGroupCursor = null; - cursorBetween = null; - prev = null; - prevRange = null; - } - - if (addToGroup || canStartGroup) { - // Add the current entry to a group. - currentGroup.add(cg); - // ... and start new cursorBetween - // Set up cursorBetween - // - XTextRange rangeEnd = currentRange.getEnd(); - cursorBetween = - currentRange.getText().createTextCursorByRange(rangeEnd); - // If new group, create currentGroupCursor - if (currentGroupCursor == null) { - currentGroupCursor = (currentRange.getText() - .createTextCursorByRange(currentRange.getStart())); - } - // include self in currentGroupCursor - currentGroupCursor.goRight((short) (currentRange.getString().length()), true); - - if (UnoTextRange.compareEnds(cursorBetween, currentGroupCursor) != 0) { - /* - * A problem discovered using this check: - * when viewing the document in - * two-pages-side-by-side mode, our visual - * firstAppearanceOrder follows the visual - * ordering on the screen. The problem - * this caused: it sees a citation on the - * 2nd line of the 1st page as appearing - * after one at the 1st line of 2nd - * page. Since we create cursorBetween at - * the end of range1Full (on 1st page), it - * is now BEFORE currentGroupCursor (on - * 2nd page). - */ - String msg = - "MergeCitationGroups: " - + "cursorBetween.end != currentGroupCursor.end" - + String.format(" (after %s)", - addToGroup ? "addToGroup" : "startGroup") - + (addToGroup - ? String.format(" comparisonResult: %d\n" - + "cursorBetween: '%s'\n" - + "currentRange: '%s'\n" - + "currentGroupCursor: '%s'\n", - UnoTextRange.compareEnds(cursorBetween, - currentGroupCursor), - cursorBetween.getString(), - currentRange.getString(), - currentGroupCursor.getString()) - : ""); - throw new RuntimeException(msg); - } - prev = cg; - prevRange = currentRange; - } - } // for cgid - - // close currentGroup - if (currentGroup.size() > 1) { - joinableGroups.add(currentGroup); - joinableGroupsCursors.add(currentGroupCursor); - } - } // if (referenceMarkNames.size() > 0) - - /* - * Now we can process the joinable groups - */ - for (int gi = 0; gi < joinableGroups.size(); gi++) { + List joinableGroups = EditMerge.scan(doc, fr); - List joinableGroup = joinableGroups.get(gi); - /* - * Join those in joinableGroups.get(gi) - */ + for (JoinableGroupData joinableGroupData : joinableGroups) { - // - // Note: we are taking ownership of the citations (by - // adding to newGroupCitations, then removing - // the original CitationGroup values) + List cgs = joinableGroupData.group; List newGroupCitations = new ArrayList<>(); - for (CitationGroup rk : joinableGroup) { - newGroupCitations.addAll(rk.citationsInStorageOrder); + for (CitationGroup cg : cgs) { + newGroupCitations.addAll(cg.citationsInStorageOrder); } - InTextCitationType citationType = joinableGroup.get(0).citationType; + // Since we only join groups with identical citationTypes, we + // can get citationType from the first element of each + // joinable group. + InTextCitationType citationType = cgs.get(0).citationType; // cgPageInfos belong to the CitationGroup (DataModel JabRef52), // but it is not clear how should we handle them here. // We delegate the problem to the backend. List> pageInfosForCitations = - fr.backend.combinePageInfos(joinableGroup); + fr.backend.combinePageInfos(cgs); // Remove the old citation groups from the document. - for (int gj = 0; gj < joinableGroup.size(); gj++) { - fr.removeCitationGroups(joinableGroup, doc); - } + fr.removeCitationGroups(cgs, doc); + + XTextCursor textCursor = joinableGroupData.groupCursor; - XTextCursor textCursor = joinableGroupsCursors.get(gi); // Also remove the spaces between. textCursor.setString(""); @@ -309,9 +355,7 @@ public static void mergeCitationGroups(XTextDocument doc, // Insert reference mark: - /* insertSpaceAfter: no, it is already there (or could - * be) - */ + /* insertSpaceAfter: no, it is already there (or could be) */ boolean insertSpaceAfter = false; UpdateCitationMarkers.createAndFillCitationGroup(fr, doc, @@ -322,14 +366,12 @@ public static void mergeCitationGroups(XTextDocument doc, textCursor, style, insertSpaceAfter); - } // for gi + } - madeModifications = (joinableGroups.size() > 0); + madeModifications = !joinableGroups.isEmpty(); } finally { - if (useLockControllers) { - UnoScreenRefresh.unlockControllers(doc); - } + UnoScreenRefresh.unlockControllers(doc); } if (madeModifications) { From 8dab7f69cfa3f194239e26fda80b40c23b9987d0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 19:51:47 +0200 Subject: [PATCH 0765/1068] lowercase OK() and Error() --- .../org/jabref/gui/openoffice/OOBibBase.java | 36 +++++++++---------- .../gui/openoffice/OOBibBaseConnect.java | 4 +-- .../openoffice/FunctionalTextViewCursor.java | 12 ++++--- .../jabref/logic/openoffice/OOFrontend.java | 4 +-- .../org/jabref/model/openoffice/Result.java | 16 ++++----- .../jabref/model/openoffice/VoidResult.java | 8 ++--- 6 files changed, 41 insertions(+), 39 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 6649360ca15..4b6c2e057b3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -165,9 +165,9 @@ VoidResult collectResults(String title, List> resul .map(e -> e.getError().getLocalizedMessage()) .collect(Collectors.joining("\n\n"))); if (msg.isEmpty()) { - return VoidResult.OK(); + return VoidResult.ok(); } else { - return VoidResult.Error(new OOError(title, msg)); + return VoidResult.error(new OOError(title, msg)); } } @@ -200,7 +200,7 @@ Result getUserCursorForTextInsertion(XTextDocument doc, St try { cursor = UnoCursor.getViewCursor(doc).orElse(null); } catch (RuntimeException ex) { - return Result.Error(new OOError(title, + return Result.error(new OOError(title, Localization.lang("Could not get the cursor."), ex)); } @@ -215,9 +215,9 @@ Result getUserCursorForTextInsertion(XTextDocument doc, St + " to the location for the new citation.") + "\n" + Localization.lang("I cannot insert to the cursors current location."); - return Result.Error(new OOError(title, msg, ex)); + return Result.error(new OOError(title, msg, ex)); } - return Result.OK(cursor); + return Result.ok(cursor); } /** @@ -264,39 +264,39 @@ private static VoidResult checkIfOpenOfficeIsRecordingChanges(XTextDocu msg += "\n"; msg += Localization.lang("Use [Edit]/[Track Changes]/[Manage] to resolve them first."); } - return VoidResult.Error(new OOError(title, msg)); + return VoidResult.error(new OOError(title, msg)); } } catch (UnknownPropertyException | WrappedTargetException ex) { String msg = Localization.lang("Error while checking if Writer" + " is recording changes or has recorded changes."); - return VoidResult.Error(new OOError(title, msg, ex)); + return VoidResult.error(new OOError(title, msg, ex)); } - return VoidResult.OK(); + return VoidResult.ok(); } VoidResult styleIsRequired(OOBibStyle style) { if (style == null) { - return VoidResult.Error(OOError.noValidStyleSelected()); + return VoidResult.error(OOError.noValidStyleSelected()); } else { - return VoidResult.OK(); + return VoidResult.ok(); } } VoidResult databaseIsRequired(List databases, Supplier fun) { if (databases == null || databases.isEmpty()) { - return VoidResult.Error(fun.get()); + return VoidResult.error(fun.get()); } else { - return VoidResult.OK(); + return VoidResult.ok(); } } VoidResult selectedBibEntryIsRequired(List entries, Supplier fun) { if (entries == null || entries.isEmpty()) { - return VoidResult.Error(fun.get()); + return VoidResult.error(fun.get()); } else { - return VoidResult.OK(); + return VoidResult.ok(); } } @@ -334,7 +334,7 @@ private VoidResult checkStyleExistsInTheDocument(String familyName, + Localization.lang("Please create it in the document or change in the file:") + "\n" + pathToStyleFile; - return VoidResult.Error(new OOError("StyleIsNotKnown", msg)); + return VoidResult.error(new OOError("StyleIsNotKnown", msg)); } if (!internalName.get().equals(styleName)) { @@ -360,9 +360,9 @@ private VoidResult checkStyleExistsInTheDocument(String familyName, + " to avoid localization problems.") + "\n" + pathToStyleFile; - return VoidResult.Error(new OOError("StyleNameIsNotInternal", msg)); + return VoidResult.error(new OOError("StyleNameIsNotInternal", msg)); } - return VoidResult.OK(); + return VoidResult.ok(); } public VoidResult checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) { @@ -390,7 +390,7 @@ public VoidResult checkStylesExistInTheDocument(OOBibStyle style, XText } } catch (NoSuchElementException | WrappedTargetException ex) { - results.add(VoidResult.Error(new OOError("Other error in checkStyleExistsInTheDocument", + results.add(VoidResult.error(new OOError("Other error in checkStyleExistsInTheDocument", ex.getMessage(), ex))); } diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 77b52311d3c..7bf7dd23008 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -241,9 +241,9 @@ public XTextDocument getXTextDocumentOrThrow() public Result getXTextDocument() { if (isDocumentConnectionMissing()) { - return Result.Error(OOError.from(new NoDocumentException())); + return Result.error(OOError.from(new NoDocumentException())); } - return Result.OK(this.xTextDocument); + return Result.ok(this.xTextDocument); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java index f262bbab10c..94ac818178f 100644 --- a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java @@ -82,7 +82,9 @@ public static Result get(XTextDocumen try { initialPosition = UnoCursor.createTextCursorByRange(viewCursor); viewCursor.getStart(); - return Result.OK(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); + return Result.ok(new FunctionalTextViewCursor(initialPosition, + initialSelection, + viewCursor)); } catch (com.sun.star.uno.RuntimeException ex) { // bad cursor viewCursor = null; @@ -93,7 +95,7 @@ public static Result get(XTextDocumen if (initialSelection == null) { String errorMessage = ("Selection is not available:" + " cannot provide a functional view cursor"); - return Result.Error(new JabRefException(errorMessage, messageOnFailure)); + return Result.error(new JabRefException(errorMessage, messageOnFailure)); } else if (!Arrays.stream(initialSelection.getSupportedServiceNames()) .anyMatch("com.sun.star.text.TextRanges"::equals)) { // initialSelection does not support TextRanges. @@ -106,7 +108,7 @@ public static Result get(XTextDocumen if (viewCursor == null) { restore(doc, initialPosition, initialSelection); String errorMessage = "Could not get the view cursor"; - return Result.Error(new JabRefException(errorMessage, messageOnFailure)); + return Result.error(new JabRefException(errorMessage, messageOnFailure)); } try { @@ -114,10 +116,10 @@ public static Result get(XTextDocumen } catch (com.sun.star.uno.RuntimeException ex) { restore(doc, initialPosition, initialSelection); String errorMessage = "The view cursor failed the functionality test"; - return Result.Error(new JabRefException(errorMessage, messageOnFailure)); + return Result.error(new JabRefException(errorMessage, messageOnFailure)); } - return Result.OK(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); + return Result.ok(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); } public XTextViewCursor getViewCursor() { diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index e3c51478cfc..dc963c7d880 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -467,10 +467,10 @@ public VoidResult checkRangeOverlaps(XTextDocument doc, msg.append(listOfRanges); msg.append("\n"); } - return VoidResult.Error(new JabRefException("Found overlapping or touching ranges", + return VoidResult.error(new JabRefException("Found overlapping or touching ranges", msg.toString())); } else { - return VoidResult.OK(); + return VoidResult.ok(); } } diff --git a/src/main/java/org/jabref/model/openoffice/Result.java b/src/main/java/org/jabref/model/openoffice/Result.java index e55c39fd1f6..600df3a15ad 100644 --- a/src/main/java/org/jabref/model/openoffice/Result.java +++ b/src/main/java/org/jabref/model/openoffice/Result.java @@ -30,14 +30,14 @@ private Result(Optional result, Optional error) { /** * @param result Null is not allowed. */ - public static Result OK(R result) { + public static Result ok(R result) { return new Result(Optional.of(result), Optional.empty()); } /** * @param error Null is not allowed. */ - public static Result Error(E error) { + public static Result error(E error) { return new Result(Optional.empty(), Optional.of(error)); } @@ -96,17 +96,17 @@ public Result ifError(Consumer fun) { public Result map(Function fun) { if (isError()) { - return Error(getError()); + return error(getError()); } else { - return OK(fun.apply(get())); + return ok(fun.apply(get())); } } public Result mapError(Function fun) { if (isError()) { - return Error(fun.apply(getError())); + return error(fun.apply(getError())); } else { - return OK(get()); + return ok(get()); } } @@ -118,9 +118,9 @@ public Optional getOptional() { /** Throw away the result part. */ public VoidResult asVoidResult() { if (isError()) { - return VoidResult.Error(getError()); + return VoidResult.error(getError()); } else { - return VoidResult.OK(); + return VoidResult.ok(); } } diff --git a/src/main/java/org/jabref/model/openoffice/VoidResult.java b/src/main/java/org/jabref/model/openoffice/VoidResult.java index b7add91332e..f1eff235f60 100644 --- a/src/main/java/org/jabref/model/openoffice/VoidResult.java +++ b/src/main/java/org/jabref/model/openoffice/VoidResult.java @@ -14,11 +14,11 @@ private VoidResult(Optional error) { this.error = error; } - public static VoidResult OK() { + public static VoidResult ok() { return new VoidResult(Optional.empty()); } - public static VoidResult Error(E error) { + public static VoidResult error(E error) { return new VoidResult(Optional.of(error)); } @@ -43,9 +43,9 @@ public VoidResult ifError(Consumer fun) { public VoidResult mapError(Function fun) { if (isError()) { - return Error(fun.apply(getError())); + return error(fun.apply(getError())); } else { - return OK(); + return ok(); } } } From a1175d65d40a41f4c0cfe4f1a09e90dd0d016907 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 20:34:43 +0200 Subject: [PATCH 0766/1068] FunctionalTextViewCursor doc --- .../openoffice/FunctionalTextViewCursor.java | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java index 94ac818178f..a93bcc5617d 100644 --- a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java @@ -12,24 +12,35 @@ import com.sun.star.text.XTextViewCursor; /* - * A problem with XTextViewCursor: if it is not in text, - * then we get a crippled version that does not support - * viewCursor.getStart() or viewCursor.gotoRange(range,false), - * and will throw an exception instead. + * A problem with XTextViewCursor: if it is not in text, then we get a + * crippled version that does not support viewCursor.getStart() or + * viewCursor.gotoRange(range,false), and will throw an exception + * instead. * - * Here we manipulate the cursor via getSelection and - * select (of XSelectionSupplier) to move it to the text. + * Here we manipulate the cursor via XSelectionSupplier.getSelection and + * XSelectionSupplierselect to move it to the text. * * Seems to work when the user selected a frame or image. * In these cases restoring the selection works, too. * - * When the cursor is in a comment - * (referred to as "annotation" in OO API) then - * initialSelection is null, and select() - * does not help to get a function viewCursor. + * When the cursor is in a comment (referred to as "annotation" in OO + * API) then initialSelection is null, and select() does not help to + * get a functional viewCursor. + * + * If get() reports error, we have to ask the user to move the cursor + * into the document text. + * + * Usage: + * + * Result fcursor = FunctionalTextViewCursor.get(doc, msg); + * if (fcursor.isError()) { + * ... + * } else { + * XTextViewCursor viewCursor = fcursor.get().getViewCursor(); + * ... + * fc.restore(); + * } * - * If get reports error, we have to ask the user - * to move the cursor into the document text. */ public class FunctionalTextViewCursor { From 2d240b67fd3e2bc15258ef4805092796f0181b63 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 20:35:01 +0200 Subject: [PATCH 0767/1068] shorten imposeLocalOrderByComparator by using stream() --- .../jabref/model/oostyle/CitationGroup.java | 32 +++++++------------ 1 file changed, 11 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index c2b11546f37..e2d3cf58d77 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -125,34 +125,24 @@ public Optional getPageInfo() { */ void imposeLocalOrderByComparator(Comparator entryComparator) { - // Pair citations with their storage index in citations final int nCitations = citationsInStorageOrder.size(); - // For JabRef52 the single pageInfo is always in the - // last-in-localorder citation. - // We adjust here accordingly. + // For JabRef52 the single pageInfo is always in the last-in-localorder citation. + // We adjust here accordingly by taking it out and adding it back after sorting. final int last = nCitations - 1; Optional lastPageInfo = Optional.empty(); if (dataModel == OOStyleDataModelVersion.JabRef52) { - lastPageInfo = getCitationsInLocalOrder().get(last).getPageInfo(); - getCitationsInLocalOrder().get(last).setPageInfo(Optional.empty()); + Citation lastCitation = getCitationsInLocalOrder().get(last); + lastPageInfo = lastCitation.getPageInfo(); + lastCitation.setPageInfo(Optional.empty()); } - List cis = new ArrayList<>(nCitations); - for (int i = 0; i < nCitations; i++) { - Citation c = citationsInStorageOrder.get(i); - cis.add(new CitationAndIndex(c, i)); - } - - // Sort the list - cis.sort(new CitationSort.CitationComparator(entryComparator, true)); - - // Copy ordered storage indices to localOrder - List ordered = new ArrayList<>(nCitations); - for (CitationAndIndex ci : cis) { - ordered.add(ci.i); - } - this.localOrder = ordered; + this.localOrder = (makeIndices(nCitations) + .stream() + .map(i -> new CitationAndIndex(citationsInStorageOrder.get(i), i)) + .sorted(new CitationSort.CitationComparator(entryComparator, true)) + .map(ci -> ci.i) + .collect(Collectors.toList())); if (dataModel == OOStyleDataModelVersion.JabRef52) { getCitationsInLocalOrder().get(last).setPageInfo(lastPageInfo); From 7cbada5ab2d47934a76c144f6601fa2efa23d9c4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 21:44:30 +0200 Subject: [PATCH 0768/1068] add ListUtil, use ListUtil.order in imposeLocalOrderByComparator --- .../jabref/model/oostyle/CitationGroup.java | 25 ++++---------- .../org/jabref/model/oostyle/ListUtil.java | 33 +++++++++++++++++++ 2 files changed, 39 insertions(+), 19 deletions(-) create mode 100644 src/main/java/org/jabref/model/oostyle/ListUtil.java diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index e2d3cf58d77..b572fd579e7 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -1,12 +1,10 @@ package org.jabref.model.oostyle; -import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; -import java.util.stream.Stream; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.StorageBase; @@ -73,7 +71,7 @@ public CitationGroup(OOStyleDataModelVersion dataModel, this.cgRangeStorage = cgRangeStorage; this.citationType = citationType; this.citationsInStorageOrder = Collections.unmodifiableList(citationsInStorageOrder); - this.localOrder = makeIndices(citationsInStorageOrder.size()); + this.localOrder = ListUtil.makeIndices(citationsInStorageOrder.size()); this.referenceMarkNameForLinking = referenceMarkNameForLinking; this.indexInGlobalOrder = Optional.empty(); } @@ -86,11 +84,6 @@ public int numberOfCitations() { * localOrder */ - /** Integers 0..(n-1) */ - static List makeIndices(int n) { - return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); - } - /* * Helper class for imposeLocalOrderByComparator: a citation * paired with its storage index. @@ -137,12 +130,8 @@ void imposeLocalOrderByComparator(Comparator entryComparator) { lastCitation.setPageInfo(Optional.empty()); } - this.localOrder = (makeIndices(nCitations) - .stream() - .map(i -> new CitationAndIndex(citationsInStorageOrder.get(i), i)) - .sorted(new CitationSort.CitationComparator(entryComparator, true)) - .map(ci -> ci.i) - .collect(Collectors.toList())); + this.localOrder = ListUtil.order(citationsInStorageOrder, + new CitationSort.CitationComparator(entryComparator, true)); if (dataModel == OOStyleDataModelVersion.JabRef52) { getCitationsInLocalOrder().get(last).setPageInfo(lastPageInfo); @@ -158,11 +147,9 @@ public List getLocalOrder() { */ public List getCitationsInLocalOrder() { - List res = new ArrayList<>(citationsInStorageOrder.size()); - for (int i : localOrder) { - res.add(citationsInStorageOrder.get(i)); - } - return res; + return (localOrder.stream() + .map(i -> citationsInStorageOrder.get(i)) + .collect(Collectors.toList())); } /* diff --git a/src/main/java/org/jabref/model/oostyle/ListUtil.java b/src/main/java/org/jabref/model/oostyle/ListUtil.java new file mode 100644 index 00000000000..68fd4a1dfc9 --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/ListUtil.java @@ -0,0 +1,33 @@ +package org.jabref.model.oostyle; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +class ListUtil { + public static List map(List list, Function fun) { + return list.stream().map(e -> fun.apply(e)).collect(Collectors.toList()); + } + + /** Integers 0..(n-1) */ + public static List makeIndices(int n) { + return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); + } + + /** Return indices so that list.get(indices.get(i)) is sorted. + * + * Precondition: T must be castable to U. + */ + public static List order(List list, Comparator comparator) { + List ii = makeIndices(list.size()); + Collections.sort(ii, new Comparator() { + @Override public int compare(final Integer o1, final Integer o2) { + return comparator.compare((U) list.get(o1), (U) list.get(o2)); + } + }); + return ii; + } +} From 92a341e7adb87dc89fc585c5dfc705c0461ed915 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 21:46:01 +0200 Subject: [PATCH 0769/1068] drop CitationAndIndex (became unused) --- .../jabref/model/oostyle/CitationGroup.java | 29 ------------------- 1 file changed, 29 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index b572fd579e7..33d839e8fe4 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -84,35 +84,6 @@ public int numberOfCitations() { * localOrder */ - /* - * Helper class for imposeLocalOrderByComparator: a citation - * paired with its storage index. - */ - private class CitationAndIndex implements CitationSort.ComparableCitation { - Citation c; - int i; - - CitationAndIndex(Citation c, int i) { - this.c = c; - this.i = i; - } - - @Override - public String getCitationKey() { - return c.getCitationKey(); - } - - @Override - public Optional getBibEntry() { - return c.getBibEntry(); - } - - @Override - public Optional getPageInfo() { - return c.getPageInfo(); - } - } - /** * Sort citations for presentation within a CitationGroup. */ From e2e473c5cecde5ae8228ad1afa2914dff87f727a Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 22:06:34 +0200 Subject: [PATCH 0770/1068] use ListUtil.map in CitationGroup.java --- .../jabref/model/oostyle/CitationGroup.java | 32 +++++-------------- 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index 33d839e8fe4..4d894c179b4 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -4,7 +4,6 @@ import java.util.Comparator; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.StorageBase; @@ -118,9 +117,7 @@ public List getLocalOrder() { */ public List getCitationsInLocalOrder() { - return (localOrder.stream() - .map(i -> citationsInStorageOrder.get(i)) - .collect(Collectors.toList())); + return ListUtil.map(localOrder, i -> citationsInStorageOrder.get(i)); } /* @@ -128,37 +125,24 @@ public List getCitationsInLocalOrder() { * localOrder. */ public List getCitationNumbersInLocalOrder() { - List cits = getCitationsInLocalOrder(); - return (cits.stream() - .map(cit -> cit.getNumber().orElseThrow(RuntimeException::new)) - .collect(Collectors.toList())); + return ListUtil.map(localOrder, i -> (citationsInStorageOrder.get(i) + .getNumber() + .orElseThrow(RuntimeException::new))); } /** - * @return List of nullable pageInfo values, one for each citation, - * instrage order. - * - * Result contains null for missing pageInfo values. - * The list itself is not null. - * + * @return List of pageInfo values, one for each citation, in + * storage order. */ public List> getPageInfosForCitationsInStorageOrder() { - CitationGroup cg = this; - // pageInfo values from citations, empty mapped to null. - return (cg.citationsInStorageOrder.stream() - .map(cit -> cit.getPageInfo()) - .collect(Collectors.toList())); + return ListUtil.map(citationsInStorageOrder, Citation::getPageInfo); } /** * @return List of optional pageInfo values, one for each citation, in localOrder. */ public List> getPageInfosForCitationsInLocalOrder() { - CitationGroup cg = this; - // pageInfo values from citations - return (cg.getCitationsInLocalOrder().stream() - .map(cit -> cit.getPageInfo()) - .collect(Collectors.toList())); + return ListUtil.map(getCitationsInLocalOrder(), Citation::getPageInfo); } /* From eb34365c77ff50f37d10a24bfb79fc1a9d46b162 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 22:07:03 +0200 Subject: [PATCH 0771/1068] format --- src/main/java/org/jabref/model/oostyle/CitationGroups.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 783959897c7..4fc35237a9e 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -167,8 +167,7 @@ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { throw new RuntimeException("getSortedCitedKeys: no globalOrder"); } for (CitationGroupID cgid : globalOrder.get()) { - CitationGroup cg = getCitationGroup(cgid) - .orElseThrow(RuntimeException::new); + CitationGroup cg = getCitationGroup(cgid).orElseThrow(RuntimeException::new); for (int i : cg.getLocalOrder()) { Citation cit = cg.citationsInStorageOrder.get(i); String citationKey = cit.citationKey; From aa4ee0eb664cb534ce1da5151065ce666525aa08 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 22:37:10 +0200 Subject: [PATCH 0772/1068] ListUtil is public --- src/main/java/org/jabref/model/oostyle/ListUtil.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/oostyle/ListUtil.java b/src/main/java/org/jabref/model/oostyle/ListUtil.java index 68fd4a1dfc9..249c3e6437d 100644 --- a/src/main/java/org/jabref/model/oostyle/ListUtil.java +++ b/src/main/java/org/jabref/model/oostyle/ListUtil.java @@ -7,7 +7,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -class ListUtil { +public class ListUtil { + public static List map(List list, Function fun) { return list.stream().map(e -> fun.apply(e)).collect(Collectors.toList()); } From 6a088b6327268d276515d6fe764b350d1651dd68 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 22:37:40 +0200 Subject: [PATCH 0773/1068] correction: globalOrder needs a .get() --- .../java/org/jabref/model/oostyle/CitationGroups.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 4fc35237a9e..86f836e7e9e 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -108,6 +108,16 @@ public List getSortedCitationGroupIDs() { return globalOrder.get(); } + /** + * Citation groups in {@code globalOrder} + */ + public List getSortedCitationGroups() { + if (globalOrder.isEmpty()) { + throw new RuntimeException("getSortedCitationGroups: not ordered yet"); + } + return ListUtil.map(globalOrder.get(), cgid -> citationGroupsUnordered.get(cgid)); + } + public void setGlobalOrder(List globalOrder) { Objects.requireNonNull(globalOrder); if (globalOrder.size() != citationGroupsUnordered.size()) { From 0f33184605656878586c0937cb8c548d1e8819f4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 22:38:03 +0200 Subject: [PATCH 0774/1068] produceCitationMarkersForIsCitationKeyCiteMarkers uses cgs.getSortedCitationGroups --- .../java/org/jabref/logic/oostyle/OOProcess.java | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 5bf7227517a..cb7a626e127 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -8,7 +8,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; import org.jabref.logic.bibtex.comparator.FieldComparator; import org.jabref.logic.bibtex.comparator.FieldComparatorStack; @@ -24,6 +23,7 @@ import org.jabref.model.oostyle.CitedKey; import org.jabref.model.oostyle.CitedKeys; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.ListUtil; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; @@ -193,8 +193,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, * markers are the citation keys themselves, separated by commas. */ private static Map - produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroups cgs, - OOBibStyle style) { + produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroups cgs, OOBibStyle style) { assert style.isCitationKeyCiteMarkers(); @@ -202,15 +201,12 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, Map citMarkers = new HashMap<>(); - for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - List cits = cgs.getCitationsInLocalOrder(cgid); + for (CitationGroup cg : cgs.getSortedCitationGroups()) { String citMarker = style.getCitationGroupMarkupBefore() - + (cits.stream() - .map(cit -> cit.citationKey) - .collect(Collectors.joining(","))) + + String.join(",", ListUtil.map(cg.getCitationsInLocalOrder(), Citation::getCitationKey)) + style.getCitationGroupMarkupAfter(); - citMarkers.put(cgid, OOFormattedText.fromString(citMarker)); + citMarkers.put(cg.cgid, OOFormattedText.fromString(citMarker)); } return citMarkers; } From f47d0d9baecfc039aa78e12a38fe2140a4684b18 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 22:46:43 +0200 Subject: [PATCH 0775/1068] prefer cgs.getSortedCitationGroups() --- .../org/jabref/logic/oostyle/OOProcess.java | 57 ++++++++----------- .../org/jabref/model/oostyle/Citation.java | 8 +++ 2 files changed, 33 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index cb7a626e127..60dfb5c163f 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -224,8 +224,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, * */ private static Map - produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, - OOBibStyle style) { + produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, OOBibStyle style) { assert style.isNumberEntries(); assert style.isSortByPosition(); @@ -236,14 +235,12 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, Map citMarkers = new HashMap<>(); - for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - List numbers = cg.getCitationNumbersInLocalOrder(); - List> pageInfos = cg.getPageInfosForCitationsInLocalOrder(); - citMarkers.put(cgid, - style.getNumCitationMarker(numbers, + for (CitationGroup cg : cgs.getSortedCitationGroups()) { + List cits = cg.getCitationsInLocalOrder(); + citMarkers.put(cg.cgid, + style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), minGroupingCount, - pageInfos)); + ListUtil.map(cits, Citation::getPageInfo))); } return citMarkers; @@ -254,8 +251,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, * when the bibliography is not sorted by position. */ private static Map - produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, - OOBibStyle style) { + produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, OOBibStyle style) { assert style.isNumberEntries(); assert !style.isSortByPosition(); @@ -265,15 +261,14 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, Map citMarkers = new HashMap<>(); - for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - List numbers = cg.getCitationNumbersInLocalOrder(); - List> pageInfos = cg.getPageInfosForCitationsInLocalOrder(); - citMarkers.put(cgid, - style.getNumCitationMarker(numbers, + for (CitationGroup cg : cgs.getSortedCitationGroups()) { + List cits = cg.getCitationsInLocalOrder(); + citMarkers.put(cg.cgid, + style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), minGroupingCount, - pageInfos)); + ListUtil.map(cits, Citation::getPageInfo))); } + return citMarkers; } @@ -305,34 +300,32 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, Map citMarkers = new HashMap<>(); - for (CitationGroupID cgid : cgs.getSortedCitationGroupIDs()) { - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - + for (CitationGroup cg : cgs.getSortedCitationGroups()) { List cits = cg.getCitationsInLocalOrder(); final int nCitedEntries = cits.size(); - List> pageInfosForCitations = cg.getPageInfosForCitationsInLocalOrder(); - - List citationMarkerEntries = new ArrayList<>(nCitedEntries); + // Check unresolved entries + // Convert each Citation to CitationMarkerEntry + // Mark first appearance of each citationKey boolean hasUnresolved = false; - for (int j = 0; j < nCitedEntries; j++) { - Citation cit = cits.get(j); + List citationMarkerEntries = new ArrayList<>(nCitedEntries); + for (Citation cit : cits) { String currentKey = cit.citationKey; boolean isFirst = false; if (!seenBefore.contains(currentKey)) { isFirst = true; seenBefore.add(currentKey); } - Optional uniqueLetterForKey = cit.getUniqueLetter(); - if (cit.getDatabaseLookupResult().isEmpty()) { + + if (cit.isUnresolved()) { hasUnresolved = true; } CitationMarkerEntry cm = new CitationMarkerEntryImpl(currentKey, cit.getDatabaseLookupResult(), - uniqueLetterForKey, - pageInfosForCitations.get(j), + cit.getUniqueLetter(), + cit.getPageInfo(), isFirst); citationMarkerEntries.add(cm); } @@ -361,7 +354,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, s = s + String.format("(Unresolved(%s))", cm.getCitationKey()); } } - citMarkers.put(cgid, OOFormattedText.fromString(s)); + citMarkers.put(cg.cgid, OOFormattedText.fromString(s)); } else { /* * All entries are resolved. @@ -369,7 +362,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, OOFormattedText citMarker = style.getCitationMarker(citationMarkerEntries, inParenthesis, strictlyUnique); - citMarkers.put(cgid, citMarker); + citMarkers.put(cg.cgid, citMarker); } } diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 3f8c5e4e557..3cc0675206c 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -54,10 +54,18 @@ public Optional getDatabaseLookupResult() { return db; } + public boolean isUnresolved() { + return db.isEmpty(); + } + public Optional getNumber() { return number; } + public int getNumberOrThrow() { + return number.get(); + } + public Optional getUniqueLetter() { return uniqueLetter; } From 94752a8bfad06e7778bf0a0b9ccb4c3a3fd04a4b Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 23:13:05 +0200 Subject: [PATCH 0776/1068] drop getSortedCitationGroupIDs (unused) --- .../java/org/jabref/model/oostyle/CitationGroups.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 86f836e7e9e..25eea53e75c 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -98,16 +98,6 @@ public Set getCitationGroupIDsUnordered() { return citationGroupsUnordered.keySet(); } - /** - * Citation group IDs in {@code globalOrder} - */ - public List getSortedCitationGroupIDs() { - if (globalOrder.isEmpty()) { - throw new RuntimeException("getSortedCitationGroupIDs: not ordered yet"); - } - return globalOrder.get(); - } - /** * Citation groups in {@code globalOrder} */ From 5dbfffb984d6736eec58e7fb2531608d0a274795 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 23:25:49 +0200 Subject: [PATCH 0777/1068] prefer getCitationGroupsUnordered --- .../java/org/jabref/logic/openoffice/OOFrontend.java | 9 +++------ .../java/org/jabref/model/oostyle/CitationGroups.java | 5 +++++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index dc963c7d880..987fccf2344 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -366,14 +366,11 @@ private List> citationRanges(XTextDocument List> result = new ArrayList<>(citationGroups.numberOfCitationGroups()); - List cgids = new ArrayList<>(citationGroups.getCitationGroupIDsUnordered()); - - for (CitationGroupID cgid : cgids) { - XTextRange range = this.getMarkRange(doc, cgid).orElseThrow(RuntimeException::new); - CitationGroup cg = citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { + XTextRange range = this.getMarkRange(doc, cg.cgid).orElseThrow(RuntimeException::new); String name = cg.cgRangeStorage.getName(); result.add(new RangeForOverlapCheck(range, - cgid, + cg.cgid, RangeForOverlapCheck.REFERENCE_MARK_KIND, name)); } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 25eea53e75c..8d4214404f3 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -1,5 +1,6 @@ package org.jabref.model.oostyle; +import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; @@ -98,6 +99,10 @@ public Set getCitationGroupIDsUnordered() { return citationGroupsUnordered.keySet(); } + public List getCitationGroupsUnordered() { + return new ArrayList<>(citationGroupsUnordered.values()); + } + /** * Citation groups in {@code globalOrder} */ From 75d546962ae7aacba1062acd0239ea100d8d8ccd Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 23:29:54 +0200 Subject: [PATCH 0778/1068] prefer getCitationGroupsUnordered in EditSeparate --- .../java/org/jabref/logic/openoffice/EditSeparate.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 37bf5757648..47966a2fae2 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -1,6 +1,5 @@ package org.jabref.logic.openoffice; -import java.util.ArrayList; import java.util.List; import org.jabref.logic.JabRefException; @@ -9,7 +8,6 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -56,16 +54,15 @@ public static void separateCitations(XTextDocument doc, fr.citationGroups.lookupEntriesInDatabases(databases); fr.citationGroups.imposeLocalOrderByComparator(OOProcess.comparatorForMulticite(style)); - List names = new ArrayList<>(fr.citationGroups.getCitationGroupIDsUnordered()); + List cgs = fr.citationGroups.getCitationGroupsUnordered(); try { UnoScreenRefresh.lockControllers(doc); - for (CitationGroupID cgid : names) { + for (CitationGroup cg : cgs) { - CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); XTextRange range1 = (fr - .getMarkRange(doc, cgid) + .getMarkRange(doc, cg.cgid) .orElseThrow(RuntimeException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); From 76b6f85018f44f33fbde9182eac5790b7ee2cbf0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 23:32:14 +0200 Subject: [PATCH 0779/1068] prefer getCitationGroupsUnordered in Backend52 --- src/main/java/org/jabref/logic/openoffice/Backend52.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index edc3ef584dd..92ce3d6fe2f 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -388,9 +388,8 @@ public List getCitationEntries(XTextDocument doc, CitationGroups // For DataModel.JabRef53 (Backend53) we need one context per Citation int n = cgs.numberOfCitationGroups(); List citations = new ArrayList<>(n); - for (CitationGroupID cgid : cgs.getCitationGroupIDsUnordered()) { - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - String name = cgid.asString(); + for (CitationGroup cg : cgs.getCitationGroupsUnordered()) { + String name = cg.cgid.asString(); XTextCursor cursor = (this .getRawCursorForCitationGroup(cg, doc) .orElseThrow(RuntimeException::new)); From 650129539b76ab3db339401df6080417e0efe2e4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 23:34:57 +0200 Subject: [PATCH 0780/1068] prefer getCitationGroupsUnordered in OOFrontend --- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 987fccf2344..00ae562e0c1 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -117,14 +117,12 @@ public Optional healthReport(XTextDocument doc) NoDocumentException, WrappedTargetException { - List cgids = new ArrayList<>(citationGroups.getCitationGroupIDsUnordered()); - List sortables = new ArrayList<>(); - for (CitationGroupID cgid : cgids) { + for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { XTextRange range = (this - .getMarkRange(doc, cgid) + .getMarkRange(doc, cg.cgid) .orElseThrow(RuntimeException::new)); - sortables.add(new RangeSortEntry(range, 0, cgid)); + sortables.add(new RangeSortEntry(range, 0, cg.cgid)); } /* From 2cd626210def36dedea57dd827593485ec4cf959 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 23:35:59 +0200 Subject: [PATCH 0781/1068] drop getCitationGroupIDsUnordered (unused) --- src/main/java/org/jabref/model/oostyle/CitationGroups.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 8d4214404f3..23fe29622f2 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -95,10 +95,6 @@ public CitedKeys lookupEntriesInDatabases(List databases) { return cks; } - public Set getCitationGroupIDsUnordered() { - return citationGroupsUnordered.keySet(); - } - public List getCitationGroupsUnordered() { return new ArrayList<>(citationGroupsUnordered.values()); } From 4d1dc5d1e8b1d08e858875e37ed1953c67e93276 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 21 May 2021 23:40:39 +0200 Subject: [PATCH 0782/1068] drop some unused methods --- .../jabref/model/oostyle/CitationGroup.java | 29 +------------------ 1 file changed, 1 insertion(+), 28 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index 4d894c179b4..7613630ef11 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -88,11 +88,9 @@ public int numberOfCitations() { */ void imposeLocalOrderByComparator(Comparator entryComparator) { - final int nCitations = citationsInStorageOrder.size(); - // For JabRef52 the single pageInfo is always in the last-in-localorder citation. // We adjust here accordingly by taking it out and adding it back after sorting. - final int last = nCitations - 1; + final int last = this.numberOfCitations() - 1; Optional lastPageInfo = Optional.empty(); if (dataModel == OOStyleDataModelVersion.JabRef52) { Citation lastCitation = getCitationsInLocalOrder().get(last); @@ -120,31 +118,6 @@ public List getCitationsInLocalOrder() { return ListUtil.map(localOrder, i -> citationsInStorageOrder.get(i)); } - /* - * Values of the number fields of the citations according to - * localOrder. - */ - public List getCitationNumbersInLocalOrder() { - return ListUtil.map(localOrder, i -> (citationsInStorageOrder.get(i) - .getNumber() - .orElseThrow(RuntimeException::new))); - } - - /** - * @return List of pageInfo values, one for each citation, in - * storage order. - */ - public List> getPageInfosForCitationsInStorageOrder() { - return ListUtil.map(citationsInStorageOrder, Citation::getPageInfo); - } - - /** - * @return List of optional pageInfo values, one for each citation, in localOrder. - */ - public List> getPageInfosForCitationsInLocalOrder() { - return ListUtil.map(getCitationsInLocalOrder(), Citation::getPageInfo); - } - /* * indexInGlobalOrder */ From 9ec0a9e34994f3b0ed44126fb19187742bf4a8fa Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 00:02:06 +0200 Subject: [PATCH 0783/1068] Citation implements CitationMarkerEntry --- .../java/org/jabref/model/oostyle/Citation.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 3cc0675206c..89f59fad8fe 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -5,7 +5,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.Pair; -public class Citation implements CitationSort.ComparableCitation { +public class Citation implements CitationSort.ComparableCitation, CitationMarkerEntry { /** key in database */ public final String citationKey; @@ -22,6 +22,9 @@ public class Citation implements CitationSort.ComparableCitation { /** pageInfo */ private Optional pageInfo; + /** isFirstAppearanceOfSource */ + private boolean isFirstAppearanceOfSource; + /** * */ @@ -31,6 +34,7 @@ public Citation(String citationKey) { this.number = Optional.empty(); this.uniqueLetter = Optional.empty(); this.pageInfo = Optional.empty(); + this.isFirstAppearanceOfSource = false; } @Override @@ -43,6 +47,11 @@ public Optional getPageInfo() { return pageInfo; } + @Override + public boolean getIsFirstAppearanceOfSource() { + return isFirstAppearanceOfSource; + } + @Override public Optional getBibEntry() { return (db.isPresent() @@ -78,6 +87,10 @@ public void setPageInfo(Optional v) { this.pageInfo = vv; } + public void setIsFirstAppearanceOfSource(boolean value) { + isFirstAppearanceOfSource = value; + } + /* * Setters for CitationGroups.distribute() */ From 118e943f15d66c46513dfc5612804c29a3017ecf Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 00:02:35 +0200 Subject: [PATCH 0784/1068] extract setIsFirstAppearanceOfSourceInCitations --- .../org/jabref/logic/oostyle/OOProcess.java | 45 +++++++++++-------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 60dfb5c163f..3a3f44038b9 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -272,6 +272,26 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, return citMarkers; } + /** + * Set isFirstAppearanceOfSource in each citation. + * + * Preconditions: globalOrder, localOrder + */ + private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) { + Set seenBefore = new HashSet<>(); + for (CitationGroup cg : cgs.getSortedCitationGroups()) { + for (Citation cit : cg.getCitationsInLocalOrder()) { + String currentKey = cit.citationKey; + if (!seenBefore.contains(currentKey)) { + cit.setIsFirstAppearanceOfSource(true); + seenBefore.add(currentKey); + } else { + cit.setIsFirstAppearanceOfSource(false); + } + } + } + } + /** * Produce citMarkers for normal * (!isCitationKeyCiteMarkers && !isNumberEntries) styles. @@ -292,11 +312,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, createUniqueLetters(sortedCitedKeys, cgs); // calls distributeUniqueLetters(cgs) cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); - // Finally, go through all citation markers, and update - // those referring to entries in our current list: - final int maxAuthorsFirst = style.getMaxAuthorsFirst(); - - Set seenBefore = new HashSet<>(); + setIsFirstAppearanceOfSourceInCitations(cgs); Map citMarkers = new HashMap<>(); @@ -307,26 +323,17 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, // Check unresolved entries // Convert each Citation to CitationMarkerEntry // Mark first appearance of each citationKey - boolean hasUnresolved = false; - List citationMarkerEntries = new ArrayList<>(nCitedEntries); - for (Citation cit : cits) { - String currentKey = cit.citationKey; - boolean isFirst = false; - if (!seenBefore.contains(currentKey)) { - isFirst = true; - seenBefore.add(currentKey); - } - if (cit.isUnresolved()) { - hasUnresolved = true; - } + boolean hasUnresolved = cits.stream().anyMatch(cit -> cit.isUnresolved()); + List citationMarkerEntries = new ArrayList<>(nCitedEntries); + for (Citation cit : cits) { CitationMarkerEntry cm = - new CitationMarkerEntryImpl(currentKey, + new CitationMarkerEntryImpl(cit.citationKey, cit.getDatabaseLookupResult(), cit.getUniqueLetter(), cit.getPageInfo(), - isFirst); + cit.getIsFirstAppearanceOfSource()); citationMarkerEntries.add(cm); } From 94743e9c5e94b36fbac31b234a2aace47239de95 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 00:06:39 +0200 Subject: [PATCH 0785/1068] use Citation as CitationMarkerEntry --- .../java/org/jabref/logic/oostyle/OOProcess.java | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 3a3f44038b9..9d73f4dd129 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -312,6 +312,7 @@ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) createUniqueLetters(sortedCitedKeys, cgs); // calls distributeUniqueLetters(cgs) cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); + // Mark first appearance of each citationKey setIsFirstAppearanceOfSourceInCitations(cgs); Map citMarkers = new HashMap<>(); @@ -320,22 +321,9 @@ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) List cits = cg.getCitationsInLocalOrder(); final int nCitedEntries = cits.size(); - // Check unresolved entries - // Convert each Citation to CitationMarkerEntry - // Mark first appearance of each citationKey - boolean hasUnresolved = cits.stream().anyMatch(cit -> cit.isUnresolved()); - List citationMarkerEntries = new ArrayList<>(nCitedEntries); - for (Citation cit : cits) { - CitationMarkerEntry cm = - new CitationMarkerEntryImpl(cit.citationKey, - cit.getDatabaseLookupResult(), - cit.getUniqueLetter(), - cit.getPageInfo(), - cit.getIsFirstAppearanceOfSource()); - citationMarkerEntries.add(cm); - } + List citationMarkerEntries = ListUtil.map(cits, e -> e); // TODO: Now we can pass CitationMarkerEntry values with unresolved // keys to style.getCitationMarker, From 27048cb398bc0e8832748539ff4954b1a7c4d63a Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 00:23:24 +0200 Subject: [PATCH 0786/1068] rename to getCitationMarker2, produceCitationMarkersForNormalStyle leaves unresolved to getCitationMarker2 --- .../org/jabref/logic/oostyle/OOBibStyle.java | 10 +- .../oostyle/OOBibStyleGetCitationMarker.java | 8 +- .../org/jabref/logic/oostyle/OOProcess.java | 45 +----- .../jabref/logic/openoffice/EditInsert.java | 6 +- .../jabref/logic/oostyle/OOBibStyleTest.java | 144 +++++++++--------- 5 files changed, 91 insertions(+), 122 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index e4cc316afd4..24377ae4960 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -1006,13 +1006,13 @@ public OOFormattedText getNormalizedCitationMarker(CitationMarkerEntry ce) { * OOFormat.setLocaleNone() and OOFormat.setCharStyle(). * These are added by decorateCitationMarker() */ - public OOFormattedText getCitationMarker(List citationMarkerEntries, + public OOFormattedText getCitationMarker2(List citationMarkerEntries, boolean inParenthesis, NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { - return OOBibStyleGetCitationMarker.getCitationMarker(this, - citationMarkerEntries, - inParenthesis, - nonUniqueCitationMarkerHandling); + return OOBibStyleGetCitationMarker.getCitationMarker2(this, + citationMarkerEntries, + inParenthesis, + nonUniqueCitationMarkerHandling); } /** diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index b9bd096de00..2db0b26d846 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -561,10 +561,10 @@ public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, * */ public static OOFormattedText - getCitationMarker(OOBibStyle style, - List citationMarkerEntries, - boolean inParenthesis, - NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { + getCitationMarker2(OOBibStyle style, + List citationMarkerEntries, + boolean inParenthesis, + NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { final int nEntries = citationMarkerEntries.size(); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 9d73f4dd129..aa81aaf2df6 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -318,47 +318,16 @@ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) Map citMarkers = new HashMap<>(); for (CitationGroup cg : cgs.getSortedCitationGroups()) { - List cits = cg.getCitationsInLocalOrder(); - final int nCitedEntries = cits.size(); - - boolean hasUnresolved = cits.stream().anyMatch(cit -> cit.isUnresolved()); - - List citationMarkerEntries = ListUtil.map(cits, e -> e); - - // TODO: Now we can pass CitationMarkerEntry values with unresolved - // keys to style.getCitationMarker, - // maybe the fall back to ungrouped citations here is - // not needed anymore. final boolean inParenthesis = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); final NonUniqueCitationMarker strictlyUnique = NonUniqueCitationMarker.THROWS; - if (hasUnresolved) { - /* - * Some entries are unresolved. - */ - String s = ""; - for (int j = 0; j < nCitedEntries; j++) { - - CitationMarkerEntry cm = citationMarkerEntries.get(j); - if (cm.getDatabaseLookupResult().isPresent()) { - s = (s - + style.getCitationMarker(citationMarkerEntries.subList(j, j + 1), - inParenthesis, - strictlyUnique)); - } else { - s = s + String.format("(Unresolved(%s))", cm.getCitationKey()); - } - } - citMarkers.put(cg.cgid, OOFormattedText.fromString(s)); - } else { - /* - * All entries are resolved. - */ - OOFormattedText citMarker = style.getCitationMarker(citationMarkerEntries, - inParenthesis, - strictlyUnique); - citMarkers.put(cg.cgid, citMarker); - } + + List cits = cg.getCitationsInLocalOrder(); + List citationMarkerEntries = ListUtil.map(cits, e -> e); + OOFormattedText citMarker = style.getCitationMarker2(citationMarkerEntries, + inParenthesis, + strictlyUnique); + citMarkers.put(cg.cgid, citMarker); } return citMarkers; diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 01b855ddc39..4ac334aca8d 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -140,9 +140,9 @@ public static void insertCitationGroup(XTextDocument doc, OOFormattedText citeText = (style.isNumberEntries() ? OOFormattedText.fromString("[-]") // A dash only. Only refresh later. - : style.getCitationMarker(citationMarkerEntries, - citationType.inParenthesis(), - NonUniqueCitationMarker.FORGIVEN)); + : style.getCitationMarker2(citationMarkerEntries, + citationType.inParenthesis(), + NonUniqueCitationMarker.FORGIVEN)); if ("".equals(OOFormattedText.toString(citeText))) { citeText = OOFormattedText.fromString("[?]"); diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index cae65221312..40221063de4 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -338,14 +338,14 @@ void testGetCitationMarker() throws IOException { * author's name before "et al." */ assertEquals("[Boström et al., 2006]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Boström et al. [2006]", - style.getCitationMarker(citationMarkerEntries, - false, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + false, + NonUniqueCitationMarker.THROWS).asString()); /* * Currently there is no way override for getMaxAuthors(), except @@ -356,9 +356,9 @@ void testGetCitationMarker() throws IOException { citationMarkerEntries.add(cm); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -433,15 +433,15 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" +"; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Boström, Wäyrynen, Bodén, Beznosov & Kruchten [2006a,b]" + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten [2006c]", - style.getCitationMarker(citationMarkerEntries, - false, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + false, + NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the first is isFirstAppearanceOfSource. @@ -461,9 +461,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" +"; Boström et al., 2006c]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the second is isFirstAppearanceOfSource. @@ -485,9 +485,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a" + "; Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006b" + "; Boström et al., 2006c]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the neither is isFirstAppearanceOfSource. @@ -507,9 +507,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a,b,c]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: different entries with identical non-null pageInfo: not joined. @@ -529,9 +529,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a; p1" + "; Boström et al., 2006b; p1" + "; Boström et al., 2006c; p1]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: same entries with identical non-null pageInfo: collapsed. @@ -550,9 +550,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a; p1]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: same entries with different pageInfo: kept separate. // Empty ("") and null pageInfos considered equal her, collapsed. @@ -574,9 +574,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a; p1" + "; Boström et al., 2006a; p2" + "; Boström et al., 2006a]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } } @@ -664,9 +664,9 @@ void testInstitutionAuthorMarker() throws IOException { makeCitationMarkerEntry("JabRef2016", entry, database, null, null, false); citationMarkerEntries.add(cm); assertEquals("[JabRef Development Team, 2016]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -689,9 +689,9 @@ void testVonAuthorMarker() throws IOException { citationMarkerEntries.add(cm); assertEquals("[von Beta, 2016]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -712,9 +712,9 @@ void testNullAuthorMarker() throws IOException { citationMarkerEntries.add(cm); assertEquals("[, 2016]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -735,9 +735,9 @@ void testNullYearMarker() throws IOException { citationMarkerEntries.add(cm); assertEquals("[von Beta, ]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -756,9 +756,9 @@ void testEmptyEntryMarker() throws IOException { makeCitationMarkerEntry("Empty", entry, database, null, null, false); citationMarkerEntries.add(cm); - assertEquals("[, ]", style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS) + assertEquals("[, ]", style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS) .asString()); } @@ -811,9 +811,9 @@ void testGetCitationMarkerUniquefiers() throws IOException { // can throw a RuntimeException. boolean doesItThrow = false; try { - style.getCitationMarker(citationMarkerEntriesA, - false, - NonUniqueCitationMarker.THROWS); + style.getCitationMarker2(citationMarkerEntriesA, + false, + NonUniqueCitationMarker.THROWS); } catch (RuntimeException ex) { doesItThrow = true; } @@ -821,14 +821,14 @@ void testGetCitationMarkerUniquefiers() throws IOException { // Or can just emit a presentation with repeated marks. assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", - style.getCitationMarker(citationMarkerEntriesA, - true, - NonUniqueCitationMarker.FORGIVEN).asString()); + style.getCitationMarker2(citationMarkerEntriesA, + true, + NonUniqueCitationMarker.FORGIVEN).asString()); assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", - style.getCitationMarker(citationMarkerEntriesA, - false, - NonUniqueCitationMarker.FORGIVEN).asString()); + style.getCitationMarker2(citationMarkerEntriesA, + false, + NonUniqueCitationMarker.FORGIVEN).asString()); // With uniquefiers @@ -843,14 +843,14 @@ void testGetCitationMarkerUniquefiers() throws IOException { citationMarkerEntriesB.add(cm2); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", - style.getCitationMarker(citationMarkerEntriesB, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntriesB, + true, + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Beta [2000a,b]; Epsilon [2001]", - style.getCitationMarker(citationMarkerEntriesB, - false, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntriesB, + false, + NonUniqueCitationMarker.THROWS).asString()); } @@ -892,14 +892,14 @@ void testGetCitationMarkerUniquefiersThreeSameAuthor() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Beta, 2000a,b,c]", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Beta [2000a,b,c]", - style.getCitationMarker(citationMarkerEntries, - false, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + false, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -960,9 +960,9 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { makeCitationMarkerEntry("Beta2016", entry, database, null, null, false)); assertEquals("von Beta, Epsilon, & Tau, 2016", - style.getCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.getCitationMarker2(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test From da9316ebbbbe3de0cf8429de7b7f5a6b32f74ec7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 00:46:37 +0200 Subject: [PATCH 0787/1068] show pageInfo for Unresolved --- .../oostyle/OOBibStyleGetCitationMarker.java | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 2db0b26d846..cf9f235deaf 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -404,8 +404,9 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, StringBuilder sb = new StringBuilder(); sb.append(style.getCitationGroupMarkupBefore()); + if (inParenthesis) { - sb.append(startBrace); + sb.append(startBrace); // shared parenthesis } for (int j = 0; j < ces.size(); j++) { @@ -432,11 +433,25 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, sb.append(citationSeparator); } - if (ce.getDatabaseLookupResult().isEmpty()) { + StringBuilder pageInfoPart = new StringBuilder(""); + if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { + Optional pageInfo = + Citation.normalizePageInfo(ce.getPageInfo()); + if (pageInfo.isPresent()) { + pageInfoPart.append(pageInfoSeparator); + pageInfoPart.append(OOFormattedText.toString(pageInfo.get())); + } + } + + final boolean isUnresolved = ce.getDatabaseLookupResult().isEmpty(); + if (isUnresolved) { sb.append(String.format("Unresolved(%s)", ce.getCitationKey())); + if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { + sb.append(pageInfoPart); + } } else { - final CitationDatabaseLookup.Result db = ce.getDatabaseLookupResult().get(); + CitationDatabaseLookup.Result db = ce.getDatabaseLookupResult().get(); int maxAuthors = (purpose == AuthorYearMarkerPurpose.NORMALIZED ? style.getMaxAuthors() @@ -452,7 +467,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, sb.append(yearSep); if (!inParenthesis) { - sb.append(startBrace); + sb.append(startBrace); // parenthesis before year } String year = getCitationMarkerField(style, db, yearFieldNames); @@ -465,23 +480,20 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, if (uniqueLetter != null) { sb.append(uniqueLetter); } + } - Optional pageInfo = - Citation.normalizePageInfo(ce.getPageInfo()); - if (pageInfo.isPresent()) { - sb.append(pageInfoSeparator); - sb.append(OOFormattedText.toString(pageInfo.get())); - } + if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { + sb.append(pageInfoPart); } if (!inParenthesis && endingAGroup) { - sb.append(endBrace); + sb.append(endBrace); // parenthesis after year } } } // for j if (inParenthesis) { - sb.append(endBrace); + sb.append(endBrace); // shared parenthesis } sb.append(style.getCitationGroupMarkupAfter()); return OOFormattedText.fromString(sb.toString()); From 7f24bc25b712798bc2b8b283205dffae307f12e2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 09:58:06 +0200 Subject: [PATCH 0788/1068] EditInsert use ListUtil.map --- src/main/java/org/jabref/logic/openoffice/EditInsert.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 4ac334aca8d..9e35042dc28 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -13,6 +13,7 @@ import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerEntryImpl; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.ListUtil; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.oostyle.OOStyleDataModelVersion; @@ -109,10 +110,7 @@ public static void insertCitationGroup(XTextDocument doc, IllegalTypeException, JabRefException { - List citationKeys = - entries.stream() - .map(EditInsert::insertEntryGetCitationKey) - .collect(Collectors.toList()); + List citationKeys = ListUtil.map(entries, EditInsert::insertEntryGetCitationKey); final int nEntries = entries.size(); // JabRef53 style pageInfo list @@ -128,8 +126,6 @@ public static void insertCitationGroup(XTextDocument doc, CitationMarkerEntry cm = new CitationMarkerEntryImpl(citationKeys.get(i), db, - // Optional.ofNullable(entries.get(i)), - // Optional.ofNullable(database), Optional.empty(), // uniqueLetter pageInfosForCitations.get(i), false /* isFirstAppearanceOfSource */); From b1e7efbcdf08a38163fb4fb55a3215c74eaf01f0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 13:16:44 +0200 Subject: [PATCH 0789/1068] add CitationMarkerNormEntry, drop CitationMarkerEntryImpl --- .../org/jabref/logic/oostyle/OOBibStyle.java | 3 +- .../oostyle/OOBibStyleGetCitationMarker.java | 47 ++++++++++-- .../org/jabref/logic/oostyle/OOProcess.java | 19 +---- .../jabref/logic/openoffice/EditInsert.java | 25 +++---- .../org/jabref/model/oostyle/Citation.java | 16 +++- .../model/oostyle/CitationMarkerEntry.java | 15 +--- .../oostyle/CitationMarkerEntryImpl.java | 74 ------------------- .../oostyle/CitationMarkerNormEntry.java | 23 ++++++ .../org/jabref/model/oostyle/CitedKey.java | 16 +++- .../jabref/logic/oostyle/OOBibStyleTest.java | 18 ++--- 10 files changed, 114 insertions(+), 142 deletions(-) delete mode 100644 src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java create mode 100644 src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 24377ae4960..9869eaac910 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -32,6 +32,7 @@ import org.jabref.model.entry.types.EntryTypeFactory; import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationMarkerEntry; +import org.jabref.model.oostyle.CitationMarkerNormEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; @@ -971,7 +972,7 @@ public OOFormattedText getNumCitationMarkerForBibliography(int number) { } } - public OOFormattedText getNormalizedCitationMarker(CitationMarkerEntry ce) { + public OOFormattedText getNormalizedCitationMarker(CitationMarkerNormEntry ce) { return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, ce, Optional.empty()); } diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index cf9f235deaf..abb7fec7179 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -15,6 +15,7 @@ import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.CitationMarkerEntry; +import org.jabref.model.oostyle.CitationMarkerNormEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.jabref.model.strings.StringUtil; @@ -339,8 +340,7 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, CitationMarkerEntry * * NORMALIZED omits uniqueLetter and pageInfo, * ignores isFirstAppearanceOfSource (always - * style.getMaxAuthors, not getMaxAuthorsFirst) and - * probably assumes a single CitationMarkerEntry. + * style.getMaxAuthors, not getMaxAuthorsFirst) * * @param ces The list of CitationMarkerEntry values to process. * @@ -507,8 +507,42 @@ private static String nullToEmptyString(String s) { return s; } + private static class CitationMarkerNormEntryWrap implements CitationMarkerEntry { + + CitationMarkerNormEntry inner; + + CitationMarkerNormEntryWrap(CitationMarkerNormEntry inner) { + this.inner = inner; + } + + @Override + public String getCitationKey() { + return inner.getCitationKey(); + } + + @Override + public Optional getDatabaseLookupResult() { + return inner.getDatabaseLookupResult(); + } + + @Override + public Optional getUniqueLetter() { + return Optional.empty(); + } + + @Override + public Optional getPageInfo() { + return Optional.empty(); + } + + @Override + public boolean getIsFirstAppearanceOfSource() { + return false; + } + } + /** - * @param ce A citation to process. + * @param cne A citation to process. * * @return A normalized citation marker for deciding which * citations need uniqueLetters. @@ -517,10 +551,11 @@ private static String nullToEmptyString(String s) { * * Note: now includes some markup. */ - public static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, - CitationMarkerEntry ce, - Optional maxAuthorsOverride) { + static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, + CitationMarkerNormEntry cne, + Optional maxAuthorsOverride) { boolean[] startsNewGroup = {true}; + CitationMarkerEntry ce = new CitationMarkerNormEntryWrap(cne); return getAuthorYearParenthesisMarker2(style, AuthorYearMarkerPurpose.NORMALIZED, Collections.singletonList(ce), diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index aa81aaf2df6..bf619dab1fd 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -19,7 +19,6 @@ import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.CitationMarkerEntryImpl; import org.jabref.model.oostyle.CitedKey; import org.jabref.model.oostyle.CitedKeys; import org.jabref.model.oostyle.InTextCitationType; @@ -86,22 +85,6 @@ public static Comparator comparatorForMulticite(OOBibStyle style) { * * **************************************/ - private static OOFormattedText normalizedCitationMarkerForNormalStyle(CitedKey ck, - OOBibStyle style) { - if (ck.db.isEmpty()) { - return OOFormattedText.fromString(String.format("(Unresolved(%s))", ck.citationKey)); - } - // We need "normalized" (in parenthesis) markers - // for uniqueness checking purposes: - // createNormalizedCitationMarker - CitationMarkerEntry ce = new CitationMarkerEntryImpl(ck.citationKey, - ck.db, - Optional.empty(), // uniqueLetter - Optional.empty(), // pageInfo - false /* isFirstAppearanceOfSource */); - return style.getNormalizedCitationMarker(ce); - } - /** * Fills {@code sortedCitedKeys//normCitMarker} */ @@ -109,7 +92,7 @@ private static void createNormalizedCitationMarkersForNormalStyle(CitedKeys sort OOBibStyle style) { for (CitedKey ck : sortedCitedKeys.data.values()) { - ck.normCitMarker = Optional.of(normalizedCitationMarkerForNormalStyle(ck, style)); + ck.normCitMarker = Optional.of(style.getNormalizedCitationMarker(ck)); } } diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 9e35042dc28..397190f3246 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -1,17 +1,16 @@ package org.jabref.logic.openoffice; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import org.jabref.logic.JabRefException; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.CitationDatabaseLookup; +import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.CitationMarkerEntryImpl; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.ListUtil; import org.jabref.model.oostyle.NonUniqueCitationMarker; @@ -113,30 +112,24 @@ public static void insertCitationGroup(XTextDocument doc, List citationKeys = ListUtil.map(entries, EditInsert::insertEntryGetCitationKey); final int nEntries = entries.size(); + // JabRef53 style pageInfo list List> pageInfosForCitations = OOStyleDataModelVersion.fakePageInfosForCitations(pageInfo, nEntries); - List citationMarkerEntries = new ArrayList<>(nEntries); + List citations = new ArrayList<>(nEntries); for (int i = 0; i < nEntries; i++) { - // Using the same database for each entry. - // Probably the GUI limits selection to a single database. - Optional db = - Optional.of(new CitationDatabaseLookup.Result(entries.get(i), database)); - CitationMarkerEntry cm = - new CitationMarkerEntryImpl(citationKeys.get(i), - db, - Optional.empty(), // uniqueLetter - pageInfosForCitations.get(i), - false /* isFirstAppearanceOfSource */); - citationMarkerEntries.add(cm); + Citation cit = new Citation(citationKeys.get(i)); + cit.lookup(Collections.singletonList(database)); + cit.setPageInfo(pageInfosForCitations.get(i)); + citations.add(cit); } // The text we insert OOFormattedText citeText = (style.isNumberEntries() ? OOFormattedText.fromString("[-]") // A dash only. Only refresh later. - : style.getCitationMarker2(citationMarkerEntries, + : style.getCitationMarker2(citations, citationType.inParenthesis(), NonUniqueCitationMarker.FORGIVEN)); diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 89f59fad8fe..7c8e0a1b5a3 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -1,7 +1,9 @@ package org.jabref.model.oostyle; +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.Pair; @@ -59,10 +61,18 @@ public Optional getBibEntry() { : Optional.empty()); } + public void lookup(List databases) { + db = CitationDatabaseLookup.lookup(databases, citationKey); + } + public Optional getDatabaseLookupResult() { return db; } + public void setDatabaseLookupResult(Optional db) { + this.db = db; + } + public boolean isUnresolved() { return db.isEmpty(); } @@ -79,10 +89,14 @@ public Optional getUniqueLetter() { return uniqueLetter; } + public void setUniqueLetter(Optional uniqueLetter) { + this.uniqueLetter = uniqueLetter; + } + public void setPageInfo(Optional v) { Optional vv = normalizePageInfo(v); if (!vv.equals(v)) { - throw new RuntimeException("setPageInfo argument is not normalied"); + throw new RuntimeException("setPageInfo argument is not normalized"); } this.pageInfo = vv; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java index 79313e42a2a..4ba53c1c92f 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java @@ -14,20 +14,7 @@ * not need pageInfo, uniqueLetter and isFirstAppearanceOfSource. * */ -public interface CitationMarkerEntry { - - /** Citation key. This is what we usually get from the document. - * - * Used if getBibEntry() and/or getDatabase() returns - * empty, which indicates failure to lookup in the databases. - * The marker created is "Unresolved({citationKey})". - * - */ - String getCitationKey(); - - /** Result of looking up citation key in databases. - */ - Optional getDatabaseLookupResult(); +public interface CitationMarkerEntry extends CitationMarkerNormEntry { /** * uniqueLetter or Optional.empty() if not needed. diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java deleted file mode 100644 index 5d13148d5f2..00000000000 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntryImpl.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.jabref.model.oostyle; - -import java.util.Objects; -import java.util.Optional; - -/** - * Implement CitationMarkerEntry by containing the data needed. - * - * {@see CitationMarkerEntry} for description. - * - */ -public class CitationMarkerEntryImpl implements CitationMarkerEntry { - final String citationKey; - final Optional db; - final Optional uniqueLetter; - final Optional pageInfo; - final boolean isFirstAppearanceOfSource; - - public CitationMarkerEntryImpl(String citationKey, - Optional databaseLookupResult, - Optional uniqueLetter, - Optional pageInfo, - boolean isFirstAppearanceOfSource) { - Objects.requireNonNull(citationKey); - this.citationKey = citationKey; - this.db = databaseLookupResult; - this.uniqueLetter = uniqueLetter; - this.pageInfo = pageInfo; - this.isFirstAppearanceOfSource = isFirstAppearanceOfSource; - } - -// public CitationMarkerEntryImpl(String citationKey, -// BibEntry entry, -// BibDatabase database, -// String uniqueLetterQ, -// String pageInfoQ, -// boolean isFirstAppearanceOfSource) { -// Optional uniqueLetter = Optional.ofNullable(uniqueLetterQ); -// Optional pageInfo = -// Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); -// -// Objects.requireNonNull(citationKey); -// this.citationKey = citationKey; -// this.db = new CitationDatabaseLookup.Result(entry, database); -// this.uniqueLetter = uniqueLetter; -// this.pageInfo = pageInfo; -// this.isFirstAppearanceOfSource = isFirstAppearanceOfSource; -// } - - @Override - public String getCitationKey() { - return citationKey; - } - - @Override - public Optional getDatabaseLookupResult() { - return db; - } - - @Override - public Optional getUniqueLetter() { - return uniqueLetter; - } - - @Override - public Optional getPageInfo() { - return pageInfo; - } - - @Override - public boolean getIsFirstAppearanceOfSource() { - return isFirstAppearanceOfSource; - } -} diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java new file mode 100644 index 00000000000..34d227cef91 --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java @@ -0,0 +1,23 @@ +package org.jabref.model.oostyle; + +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. + * + * Used if getBibEntry() and/or getDatabase() returns + * empty, which indicates failure to lookup in the databases. + * The marker created is "Unresolved({citationKey})". + * + */ + String getCitationKey(); + + /** Result of looking up citation key in databases. + */ + Optional getDatabaseLookupResult(); +} diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index 65e1607fb7a..f4605dd8d96 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -7,7 +7,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -public class CitedKey implements CitationSort.ComparableCitation { +public class CitedKey implements CitationSort.ComparableCitation, CitationMarkerNormEntry { public String citationKey; public LinkedHashSet where; public Optional db; @@ -38,15 +38,25 @@ public Optional getBibEntry() { } /** No pageInfo is needed for sorting the bibliography, - * getPageInfo always returns Optional.empty. Only exists to implement ComparableCitation. + * getPageInfo always returns Optional.empty. * - * @return null + * Only exists to implement CitationSort.ComparableCitation. + * + * @return Optional.empty() */ @Override public Optional getPageInfo() { return Optional.empty(); } + /* + * Implement CitationMarkerNormEntry + */ + @Override + public Optional getDatabaseLookupResult() { + return db; + } + /** * Appends to end of {@code where} */ diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 40221063de4..373a98c7020 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -17,6 +17,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; + import org.jabref.logic.layout.Layout; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.model.database.BibDatabase; @@ -24,9 +25,9 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; +import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationDatabaseLookup; import org.jabref.model.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.CitationMarkerEntryImpl; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; @@ -301,15 +302,14 @@ private static CitationMarkerEntry makeCitationMarkerEntry(String citationKey, String uniqueLetterQ, String pageInfoQ, boolean isFirstAppearanceOfSource) { - Optional uniqueLetter = Optional.ofNullable(uniqueLetterQ); - Optional pageInfo = - Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); Objects.requireNonNull(citationKey); - return new CitationMarkerEntryImpl(citationKey, - Optional.of(new CitationDatabaseLookup.Result(entry, database)), - uniqueLetter, - pageInfo, - isFirstAppearanceOfSource); + Citation result = new Citation(citationKey); + result.setDatabaseLookupResult(Optional.of(new CitationDatabaseLookup.Result(entry, database))); + result.setUniqueLetter(Optional.ofNullable(uniqueLetterQ)); + Optional pageInfo = Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); + result.setPageInfo(Citation.normalizePageInfo(pageInfo)); + result.setIsFirstAppearanceOfSource(isFirstAppearanceOfSource); + return result; } @Test From 4f295a110df313c97400ed9ec48ba73b55c394ce Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 13:28:42 +0200 Subject: [PATCH 0790/1068] CitationGroups.distributeToCitations, used by CitedKey --- .../jabref/model/oostyle/CitationGroups.java | 21 ++++--------------- .../org/jabref/model/oostyle/CitedKey.java | 6 +++--- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 23fe29622f2..28c3a1c91aa 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -66,14 +66,14 @@ public int numberOfCitationGroups() { * For each citation in {@code where} * call {@code fun.accept(new Pair(citation, value));} */ - public void distribute(Set where, - Consumer> fun, - T value) { + public void distributeToCitations(Set where, + Consumer> fun, + T value) { for (CitationPath p : where) { CitationGroup cg = this.citationGroupsUnordered.get(p.group); if (cg == null) { - LOGGER.warn("CitationGroups.distribute: group missing"); + LOGGER.warn("CitationGroups.distributeToCitations: group missing"); continue; } Citation cit = cg.citationsInStorageOrder.get(p.storageIndexInGroup); @@ -81,11 +81,6 @@ public void distribute(Set where, } } - public void setDatabaseLookupResults(Set where, - Optional db) { - distribute(where, Citation::setDatabaseLookupResult, db); - } - public CitedKeys lookupEntriesInDatabases(List databases) { CitationGroups cgs = this; CitedKeys cks = cgs.getCitedKeysUnordered(); @@ -123,14 +118,6 @@ public void setGlobalOrder(List globalOrder) { } } - public void setNumbers(Set where, Optional number) { - distribute(where, Citation::setNumber, number); - } - - public void setUniqueLetters(Set where, Optional uniqueLetter) { - distribute(where, Citation::setUniqueLetter, uniqueLetter); - } - public void imposeLocalOrderByComparator(Comparator entryComparator) { for (CitationGroup cg : citationGroupsUnordered.values()) { cg.imposeLocalOrderByComparator(entryComparator); diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index f4605dd8d96..347ad5626f3 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -78,14 +78,14 @@ void lookupInDatabases(List databases) { } void distributeDatabaseLookupResult(CitationGroups cgs) { - cgs.setDatabaseLookupResults(where, db); + cgs.distributeToCitations(where, Citation::setDatabaseLookupResult, db); } void distributeNumber(CitationGroups cgs) { - cgs.setNumbers(where, number); + cgs.distributeToCitations(where, Citation::setNumber, number); } void distributeUniqueLetter(CitationGroups cgs) { - cgs.setUniqueLetters(where, uniqueLetter); + cgs.distributeToCitations(where, Citation::setUniqueLetter, uniqueLetter); } } // class CitedKey From 1dcd8650783ad27d5f5a39d87b2141a756a047ad Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 13:32:49 +0200 Subject: [PATCH 0791/1068] use numberOfCitationGroups --- src/main/java/org/jabref/model/oostyle/CitationGroups.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 28c3a1c91aa..a076d824ea3 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -106,9 +106,9 @@ public List getSortedCitationGroups() { public void setGlobalOrder(List globalOrder) { Objects.requireNonNull(globalOrder); - if (globalOrder.size() != citationGroupsUnordered.size()) { + if (globalOrder.size() != numberOfCitationGroups()) { throw new RuntimeException("setGlobalOrder:" - + " globalOrder.size() != citationGroups.size()"); + + " globalOrder.size() != numberOfCitationGroups()"); } this.globalOrder = Optional.of(globalOrder); int i = 0; From 67047453c56b4080ed1758ec8520c7240efa80aa Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 13:53:03 +0200 Subject: [PATCH 0792/1068] rename getSortedCitationGroups to getCitationGroupsInGlobalOrder --- src/main/java/org/jabref/logic/oostyle/OOProcess.java | 10 +++++----- .../java/org/jabref/model/oostyle/CitationGroups.java | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index bf619dab1fd..5923a95de0e 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -184,7 +184,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, Map citMarkers = new HashMap<>(); - for (CitationGroup cg : cgs.getSortedCitationGroups()) { + for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { String citMarker = style.getCitationGroupMarkupBefore() + String.join(",", ListUtil.map(cg.getCitationsInLocalOrder(), Citation::getCitationKey)) @@ -218,7 +218,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, Map citMarkers = new HashMap<>(); - for (CitationGroup cg : cgs.getSortedCitationGroups()) { + for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { List cits = cg.getCitationsInLocalOrder(); citMarkers.put(cg.cgid, style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), @@ -244,7 +244,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, Map citMarkers = new HashMap<>(); - for (CitationGroup cg : cgs.getSortedCitationGroups()) { + for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { List cits = cg.getCitationsInLocalOrder(); citMarkers.put(cg.cgid, style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), @@ -262,7 +262,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, */ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) { Set seenBefore = new HashSet<>(); - for (CitationGroup cg : cgs.getSortedCitationGroups()) { + for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { for (Citation cit : cg.getCitationsInLocalOrder()) { String currentKey = cit.citationKey; if (!seenBefore.contains(currentKey)) { @@ -300,7 +300,7 @@ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) Map citMarkers = new HashMap<>(); - for (CitationGroup cg : cgs.getSortedCitationGroups()) { + for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { final boolean inParenthesis = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); final NonUniqueCitationMarker strictlyUnique = NonUniqueCitationMarker.THROWS; diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index a076d824ea3..f47f67e3c38 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -97,9 +97,9 @@ public List getCitationGroupsUnordered() { /** * Citation groups in {@code globalOrder} */ - public List getSortedCitationGroups() { + public List getCitationGroupsInGlobalOrder() { if (globalOrder.isEmpty()) { - throw new RuntimeException("getSortedCitationGroups: not ordered yet"); + throw new RuntimeException("getCitationGroupsInGlobalOrder: not ordered yet"); } return ListUtil.map(globalOrder.get(), cgid -> citationGroupsUnordered.get(cgid)); } From 22dd424b88430e9fe27ca7df8bada911403ca2bb Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 14:39:07 +0200 Subject: [PATCH 0793/1068] split CitationSort --- .../OOBibStyleGetNumCitationMarker.java | 4 +- .../org/jabref/logic/oostyle/OOProcess.java | 2 +- .../org/jabref/model/oostyle/Citation.java | 2 +- .../jabref/model/oostyle/CitationGroup.java | 2 +- .../jabref/model/oostyle/CitationSort.java | 75 ------------------- .../org/jabref/model/oostyle/CitedKey.java | 17 +---- .../model/oostyle/CitedKeyComparator.java | 41 ++++++++++ .../org/jabref/model/oostyle/CitedKeys.java | 2 +- .../model/oostyle/ComparableCitation.java | 11 +++ .../model/oostyle/ComparableCitedKey.java | 16 ++++ .../jabref/model/oostyle/CompareCitation.java | 52 +++++++++++++ 11 files changed, 130 insertions(+), 94 deletions(-) delete mode 100644 src/main/java/org/jabref/model/oostyle/CitationSort.java create mode 100644 src/main/java/org/jabref/model/oostyle/CitedKeyComparator.java create mode 100644 src/main/java/org/jabref/model/oostyle/ComparableCitation.java create mode 100644 src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java create mode 100644 src/main/java/org/jabref/model/oostyle/CompareCitation.java diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index d92e5a112ed..81604783b4f 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -6,7 +6,7 @@ import java.util.Optional; import java.util.function.ToIntFunction; -import org.jabref.model.oostyle.CitationSort; +import org.jabref.model.oostyle.CompareCitation; import org.jabref.model.oostyle.OOFormattedText; class OOBibStyleGetNumCitationMarker { @@ -32,7 +32,7 @@ private static class NumberWithPageInfo { private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPageInfo b) { int res = Integer.compare(a.num, b.num); if (res == 0) { - res = CitationSort.comparePageInfo(a.pageInfo, b.pageInfo); + res = CompareCitation.comparePageInfo(a.pageInfo, b.pageInfo); } return res; } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 5923a95de0e..3cf0e9efee0 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -292,7 +292,7 @@ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); createNormalizedCitationMarkersForNormalStyle(sortedCitedKeys, style); - createUniqueLetters(sortedCitedKeys, cgs); // calls distributeUniqueLetters(cgs) + createUniqueLetters(sortedCitedKeys, cgs); cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); // Mark first appearance of each citationKey diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 7c8e0a1b5a3..e603a5c7147 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -7,7 +7,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.Pair; -public class Citation implements CitationSort.ComparableCitation, CitationMarkerEntry { +public class Citation implements ComparableCitation, CitationMarkerEntry { /** key in database */ public final String citationKey; diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index 7613630ef11..7d0446b989b 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -99,7 +99,7 @@ void imposeLocalOrderByComparator(Comparator entryComparator) { } this.localOrder = ListUtil.order(citationsInStorageOrder, - new CitationSort.CitationComparator(entryComparator, true)); + new CompareCitation(entryComparator, true)); if (dataModel == OOStyleDataModelVersion.JabRef52) { getCitationsInLocalOrder().get(last).setPageInfo(lastPageInfo); diff --git a/src/main/java/org/jabref/model/oostyle/CitationSort.java b/src/main/java/org/jabref/model/oostyle/CitationSort.java deleted file mode 100644 index e6ea5116778..00000000000 --- a/src/main/java/org/jabref/model/oostyle/CitationSort.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.jabref.model.oostyle; - -import java.util.Comparator; -import java.util.Optional; - -import org.jabref.model.entry.BibEntry; - -public class CitationSort { - - public interface ComparableCitation { - - public String getCitationKey(); - - public Optional getBibEntry(); - - public Optional getPageInfo(); - } - - public static class CitationComparator implements Comparator { - - Comparator entryComparator; - boolean unresolvedComesFirst; - - CitationComparator(Comparator entryComparator, boolean unresolvedComesFirst) { - this.entryComparator = entryComparator; - this.unresolvedComesFirst = unresolvedComesFirst; - } - - public int compare(ComparableCitation a, ComparableCitation b) { - Optional aBibEntry = a.getBibEntry(); - Optional bBibEntry = b.getBibEntry(); - final int mul = unresolvedComesFirst ? (+1) : (-1); - - int res = 0; - if (aBibEntry.isEmpty() && bBibEntry.isEmpty()) { - // Both are unresolved: compare them by citation key. - res = a.getCitationKey().compareTo(b.getCitationKey()); - } else if (aBibEntry.isEmpty()) { - return -mul; - } else if (bBibEntry.isEmpty()) { - return mul; - } else { - // Proper comparison of entries - res = entryComparator.compare(aBibEntry.get(), bBibEntry.get()); - } - // Also consider pageInfo - if (res == 0) { - CitationSort.comparePageInfo(a.getPageInfo(), - b.getPageInfo()); - } - return res; - } - } - - /** - * Defines sort order for pageInfo strings. - * - * null comes before non-null - */ - public static int comparePageInfo(Optional a, Optional b) { - - Optional aa = Citation.normalizePageInfo(a); - Optional bb = Citation.normalizePageInfo(b); - if (aa.isEmpty() && bb.isEmpty()) { - return 0; - } - if (aa.isEmpty()) { - return -1; - } - if (bb.isEmpty()) { - return +1; - } - return aa.get().asString().compareTo(bb.get().asString()); - } -} diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index 347ad5626f3..8431643a6b6 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -7,7 +7,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -public class CitedKey implements CitationSort.ComparableCitation, CitationMarkerNormEntry { +public class CitedKey implements ComparableCitedKey, CitationMarkerNormEntry { public String citationKey; public LinkedHashSet where; public Optional db; @@ -25,6 +25,9 @@ public class CitedKey implements CitationSort.ComparableCitation, CitationMarker this.normCitMarker = Optional.empty(); } + /* + * Implement ComparableCitedKey + */ @Override public String getCitationKey() { return citationKey; @@ -37,18 +40,6 @@ public Optional getBibEntry() { : Optional.empty()); } - /** No pageInfo is needed for sorting the bibliography, - * getPageInfo always returns Optional.empty. - * - * Only exists to implement CitationSort.ComparableCitation. - * - * @return Optional.empty() - */ - @Override - public Optional getPageInfo() { - return Optional.empty(); - } - /* * Implement CitationMarkerNormEntry */ diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeyComparator.java b/src/main/java/org/jabref/model/oostyle/CitedKeyComparator.java new file mode 100644 index 00000000000..fce4a0413f5 --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/CitedKeyComparator.java @@ -0,0 +1,41 @@ +package org.jabref.model.oostyle; + +import java.util.Comparator; +import java.util.Optional; + +import org.jabref.model.entry.BibEntry; + +/* + * Given a Comparator provide a Comparator + * that also handles unresolved citation keys. + */ +public class CitedKeyComparator implements Comparator { + + Comparator entryComparator; + boolean unresolvedComesFirst; + + CitedKeyComparator(Comparator entryComparator, boolean unresolvedComesFirst) { + this.entryComparator = entryComparator; + this.unresolvedComesFirst = unresolvedComesFirst; + } + + public int compare(ComparableCitedKey a, ComparableCitedKey b) { + Optional aBibEntry = a.getBibEntry(); + Optional bBibEntry = b.getBibEntry(); + final int mul = unresolvedComesFirst ? (+1) : (-1); + + int res = 0; + if (aBibEntry.isEmpty() && bBibEntry.isEmpty()) { + // Both are unresolved: compare them by citation key. + res = a.getCitationKey().compareTo(b.getCitationKey()); + } else if (aBibEntry.isEmpty()) { + return -mul; + } else if (bBibEntry.isEmpty()) { + return mul; + } else { + // Proper comparison of entries + res = entryComparator.compare(aBibEntry.get(), bBibEntry.get()); + } + return res; + } +} diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeys.java b/src/main/java/org/jabref/model/oostyle/CitedKeys.java index 7e6199e6fcd..bd0055d39f2 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKeys.java @@ -32,7 +32,7 @@ public List values() { */ void sortByComparator(Comparator entryComparator) { List cks = new ArrayList<>(data.values()); - cks.sort(new CitationSort.CitationComparator(entryComparator, true)); + cks.sort(new CitedKeyComparator(entryComparator, true)); LinkedHashMap newData = new LinkedHashMap<>(); for (CitedKey ck : cks) { newData.put(ck.citationKey, ck); diff --git a/src/main/java/org/jabref/model/oostyle/ComparableCitation.java b/src/main/java/org/jabref/model/oostyle/ComparableCitation.java new file mode 100644 index 00000000000..e1b00c020f1 --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/ComparableCitation.java @@ -0,0 +1,11 @@ +package org.jabref.model.oostyle; + +import java.util.Optional; + +/* + * When sorting citations (in a group), we also consider pageInfo. + * Otherwise we sort citations as cited keys. + */ +public interface ComparableCitation extends ComparableCitedKey { + public Optional getPageInfo(); +} diff --git a/src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java b/src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java new file mode 100644 index 00000000000..17f2e8c1e8a --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java @@ -0,0 +1,16 @@ +package org.jabref.model.oostyle; + +import java.util.Optional; + +import org.jabref.model.entry.BibEntry; + +/* + * This is what we need to sort bibliography entries. + */ +public interface ComparableCitedKey { + + public String getCitationKey(); + + public Optional getBibEntry(); +} + diff --git a/src/main/java/org/jabref/model/oostyle/CompareCitation.java b/src/main/java/org/jabref/model/oostyle/CompareCitation.java new file mode 100644 index 00000000000..4cec3d66aa9 --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/CompareCitation.java @@ -0,0 +1,52 @@ +package org.jabref.model.oostyle; + +import java.util.Comparator; +import java.util.Optional; + +import org.jabref.model.entry.BibEntry; + +/* + * Given a Comparator provide a Comparator + * that can handle unresolved citation keys and take pageInfo into account. + */ +public class CompareCitation implements Comparator { + + CitedKeyComparator citedKeyComparator; + + CompareCitation(Comparator entryComparator, boolean unresolvedComesFirst) { + this.citedKeyComparator = new CitedKeyComparator(entryComparator, unresolvedComesFirst); + } + + public int compare(ComparableCitation a, ComparableCitation b) { + int res = citedKeyComparator.compare(a, b); + + // Also consider pageInfo + if (res == 0) { + res = CompareCitation.comparePageInfo(a.getPageInfo(), b.getPageInfo()); + } + return res; + } + + /** + * Defines sort order for pageInfo strings. + * + * Optional.empty comes before non-empty. + */ + public static int comparePageInfo(Optional a, Optional b) { + + Optional aa = Citation.normalizePageInfo(a); + Optional bb = Citation.normalizePageInfo(b); + if (aa.isEmpty() && bb.isEmpty()) { + return 0; + } + if (aa.isEmpty()) { + return -1; + } + if (bb.isEmpty()) { + return +1; + } + return aa.get().asString().compareTo(bb.get().asString()); + } +} + + From 3a87236806f314090a1407462d1200d4c6dfce12 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 14:48:16 +0200 Subject: [PATCH 0794/1068] rename OOStyleDataModelVersion to OODataModel --- .../org/jabref/logic/openoffice/Backend52.java | 15 +++++++-------- .../org/jabref/logic/openoffice/EditInsert.java | 4 ++-- .../org/jabref/logic/openoffice/OOFrontend.java | 4 ++-- .../org/jabref/model/oostyle/CitationGroup.java | 8 ++++---- ...tyleDataModelVersion.java => OODataModel.java} | 2 +- 5 files changed, 16 insertions(+), 17 deletions(-) rename src/main/java/org/jabref/model/oostyle/{OOStyleDataModelVersion.java => OODataModel.java} (97%) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 92ce3d6fe2f..004fdcad63e 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -13,8 +13,8 @@ import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OODataModel; import org.jabref.model.oostyle.OOFormattedText; -import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -35,12 +35,12 @@ public class Backend52 { private static final Logger LOGGER = LoggerFactory.getLogger(Backend52.class); - public final OOStyleDataModelVersion dataModel; + public final OODataModel dataModel; public final StorageBase.NamedRangeManager citationStorageManager; // uses: Codec52 public Backend52() { - this.dataModel = OOStyleDataModelVersion.JabRef52; + this.dataModel = OODataModel.JabRef52; this.citationStorageManager = new StorageBaseRefMark.Manager(); } @@ -163,7 +163,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str + " referenceMarkName is not in the document"); } - CitationGroup cg = new CitationGroup(OOStyleDataModelVersion.JabRef52, + CitationGroup cg = new CitationGroup(OODataModel.JabRef52, id, storedRange.get(), ov.citationType, @@ -258,7 +258,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, // do not inherit from trash UnoUserDefinedProperty.removeIfExists(doc, refMarkName); } - CitationGroup cg = new CitationGroup(OOStyleDataModelVersion.JabRef52, + CitationGroup cg = new CitationGroup(OODataModel.JabRef52, cgid, storedRange, citationType, citations, Optional.of(refMarkName)); return cg; @@ -275,8 +275,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, * user to check the result. Or ask what to do. */ public static List> - combinePageInfosCommon(OOStyleDataModelVersion dataModel, - List joinableGroup) { + combinePageInfosCommon(OODataModel dataModel, List joinableGroup) { switch (dataModel) { case JabRef52: // collect to cgPageInfos @@ -298,7 +297,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, if ("".equals(cgPageInfo)) { cgPageInfo = null; } - return OOStyleDataModelVersion.fakePageInfosForCitations(cgPageInfo, nCitations); + return OODataModel.fakePageInfosForCitations(cgPageInfo, nCitations); case JabRef53: return (joinableGroup.stream() diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 397190f3246..ad69ea356a6 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -14,8 +14,8 @@ import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.ListUtil; import org.jabref.model.oostyle.NonUniqueCitationMarker; +import org.jabref.model.oostyle.OODataModel; import org.jabref.model.oostyle.OOFormattedText; -import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -115,7 +115,7 @@ public static void insertCitationGroup(XTextDocument doc, // JabRef53 style pageInfo list List> pageInfosForCitations = - OOStyleDataModelVersion.fakePageInfosForCitations(pageInfo, nEntries); + OODataModel.fakePageInfosForCitations(pageInfo, nEntries); List citations = new ArrayList<>(nEntries); for (int i = 0; i < nEntries; i++) { diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 00ae562e0c1..ba32aaa5856 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -15,8 +15,8 @@ import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.OODataModel; import org.jabref.model.oostyle.OOFormattedText; -import org.jabref.model.oostyle.OOStyleDataModelVersion; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -64,7 +64,7 @@ public OOFrontend(XTextDocument doc) this.citationGroups = new CitationGroups(citationGroups); } - public OOStyleDataModelVersion getDataModel() { + public OODataModel getDataModel() { return backend.dataModel; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index 7d0446b989b..702041055d4 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -13,7 +13,7 @@ */ public class CitationGroup { - public final OOStyleDataModelVersion dataModel; + public final OODataModel dataModel; /* * Identifies this citation group. @@ -59,7 +59,7 @@ public class CitationGroup { */ private Optional indexInGlobalOrder; - public CitationGroup(OOStyleDataModelVersion dataModel, + public CitationGroup(OODataModel dataModel, CitationGroupID cgid, StorageBase.NamedRange cgRangeStorage, InTextCitationType citationType, @@ -92,7 +92,7 @@ void imposeLocalOrderByComparator(Comparator entryComparator) { // We adjust here accordingly by taking it out and adding it back after sorting. final int last = this.numberOfCitations() - 1; Optional lastPageInfo = Optional.empty(); - if (dataModel == OOStyleDataModelVersion.JabRef52) { + if (dataModel == OODataModel.JabRef52) { Citation lastCitation = getCitationsInLocalOrder().get(last); lastPageInfo = lastCitation.getPageInfo(); lastCitation.setPageInfo(Optional.empty()); @@ -101,7 +101,7 @@ void imposeLocalOrderByComparator(Comparator entryComparator) { this.localOrder = ListUtil.order(citationsInStorageOrder, new CompareCitation(entryComparator, true)); - if (dataModel == OOStyleDataModelVersion.JabRef52) { + if (dataModel == OODataModel.JabRef52) { getCitationsInLocalOrder().get(last).setPageInfo(lastPageInfo); } } diff --git a/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java b/src/main/java/org/jabref/model/oostyle/OODataModel.java similarity index 97% rename from src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java rename to src/main/java/org/jabref/model/oostyle/OODataModel.java index 1ba61a51ce8..b1e9bac1522 100644 --- a/src/main/java/org/jabref/model/oostyle/OOStyleDataModelVersion.java +++ b/src/main/java/org/jabref/model/oostyle/OODataModel.java @@ -5,7 +5,7 @@ import java.util.Optional; /** What is the data stored? */ -public enum OOStyleDataModelVersion { +public enum OODataModel { /** * JabRef52: * pageInfo belongs to CitationGroup, not Citation. From 0afb68a128e033d3e7775924153ff45e7f07769b Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 15:01:51 +0200 Subject: [PATCH 0795/1068] CitedKeys.data is private, createUniqueLetters uses longer names inside --- .../org/jabref/logic/oostyle/OOProcess.java | 53 +++++++++---------- .../org/jabref/model/oostyle/CitedKeys.java | 8 ++- 2 files changed, 31 insertions(+), 30 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 3cf0e9efee0..a7ef67e2294 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -91,7 +91,7 @@ public static Comparator comparatorForMulticite(OOBibStyle style) { private static void createNormalizedCitationMarkersForNormalStyle(CitedKeys sortedCitedKeys, OOBibStyle style) { - for (CitedKey ck : sortedCitedKeys.data.values()) { + for (CitedKey ck : sortedCitedKeys.values()) { ck.normCitMarker = Optional.of(style.getNormalizedCitationMarker(ck)); } } @@ -111,53 +111,50 @@ private static void createNormalizedCitationMarkersForNormalStyle(CitedKeys sort * * Depends on: style, citations and their order. */ - private static void createUniqueLetters(CitedKeys sortedCitedKeys, - CitationGroups cgs) { + private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroups cgs) { - // ncm2clks: ncm (normCitMarker) to clks (clashing keys : list of citation keys fighting for it). - // - // The entries in the clks lists preserve firstAppearance order - // from sortedCitedKeys.data.values(). + // The entries in the clashingKeys lists preserve + // firstAppearance order from sortedCitedKeys.values(). // - // The index of the citationKey in this order will decide which - // unique letter it receives. + // The index of the citationKey in this order will decide + // which unique letter it receives. // - Map> ncm2clks = new HashMap<>(); - for (CitedKey ck : sortedCitedKeys.values()) { - String ncm = OOFormattedText.toString(ck.normCitMarker.get()); - String citationKey = ck.citationKey; + Map> normCitMarkerToClachingKeys = new HashMap<>(); + for (CitedKey citedKey : sortedCitedKeys.values()) { + String normCitMarker = OOFormattedText.toString(citedKey.normCitMarker.get()); + String citationKey = citedKey.citationKey; - if (!ncm2clks.containsKey(ncm)) { + if (!normCitMarkerToClachingKeys.containsKey(normCitMarker)) { // Found new normCitMarker - List clks = new ArrayList<>(1); - ncm2clks.put(ncm, clks); - clks.add(citationKey); + List clashingKeys = new ArrayList<>(1); + normCitMarkerToClachingKeys.put(normCitMarker, clashingKeys); + clashingKeys.add(citationKey); } else { - List clks = ncm2clks.get(ncm); - if (!clks.contains(citationKey)) { + List clashingKeys = normCitMarkerToClachingKeys.get(normCitMarker); + if (!clashingKeys.contains(citationKey)) { // First appearance of citationKey, add to list. - clks.add(citationKey); + clashingKeys.add(citationKey); } } } // Clear old uniqueLetter values. - for (CitedKey ck : sortedCitedKeys.data.values()) { - ck.uniqueLetter = Optional.empty(); + for (CitedKey citedKey : sortedCitedKeys.values()) { + citedKey.uniqueLetter = Optional.empty(); } // For sets of citation keys figthing for a normCitMarker // add unique letters to the year. - for (List clks : ncm2clks.values()) { - if (clks.size() <= 1) { + for (List clashingKeys : normCitMarkerToClachingKeys.values()) { + if (clashingKeys.size() <= 1) { continue; // No fight, no letters. } - // Multiple citation keys: they get their letters according to their order in clks. + // Multiple citation keys: they get their letters + // according to their order in clashingKeys. int nextUniqueLetter = 'a'; - for (String citationKey : clks) { - // uniqueLetters.put(citationKey, String.valueOf((char) nextUniqueLetter)); + for (String citationKey : clashingKeys) { String ul = String.valueOf((char) nextUniqueLetter); - sortedCitedKeys.data.get(citationKey).uniqueLetter = Optional.of(ul); + sortedCitedKeys.get(citationKey).uniqueLetter = Optional.of(ul); nextUniqueLetter++; } } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeys.java b/src/main/java/org/jabref/model/oostyle/CitedKeys.java index bd0055d39f2..c5fcabf6b32 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKeys.java @@ -14,19 +14,23 @@ public class CitedKeys { /** * Order-preserving map from citation keys to associated data. */ - public LinkedHashMap data; + private LinkedHashMap data; CitedKeys(LinkedHashMap data) { this.data = data; } /** - * The cited keys in sorted order. + * The cited keys in their current order. */ public List values() { return new ArrayList<>(data.values()); } + public CitedKey get(String citationKey) { + return data.get(citationKey); + } + /** * Sort entries for the bibliography. */ From ebfc20d9c037d3f73e861e460adcb9b79bb5a30d Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 15:25:22 +0200 Subject: [PATCH 0796/1068] split OOProcessCitationKeyMarkers --- .../org/jabref/logic/oostyle/OOProcess.java | 37 +++---------------- .../oostyle/OOProcessCitationKeyMarkers.java | 36 ++++++++++++++++++ .../jabref/model/oostyle/CitationGroups.java | 8 ++-- .../org/jabref/model/oostyle/CitedKeys.java | 2 +- 4 files changed, 47 insertions(+), 36 deletions(-) create mode 100644 src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index a7ef67e2294..034dc5c0c73 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -31,10 +31,8 @@ public class OOProcess { - private static final Comparator AUTHOR_YEAR_TITLE_COMPARATOR = - makeAuthorYearTitleComparator(); - private static final Comparator YEAR_AUTHOR_TITLE_COMPARATOR = - makeYearAuthorTitleComparator(); + static final Comparator AUTHOR_YEAR_TITLE_COMPARATOR = makeAuthorYearTitleComparator(); + static final Comparator YEAR_AUTHOR_TITLE_COMPARATOR = makeYearAuthorTitleComparator(); private static final Logger LOGGER = LoggerFactory.getLogger(OOProcess.class); @@ -168,29 +166,6 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup * * **************************************/ - /** - * Produce citation markers for the case when the citation - * markers are the citation keys themselves, separated by commas. - */ - private static Map - produceCitationMarkersForIsCitationKeyCiteMarkers(CitationGroups cgs, OOBibStyle style) { - - assert style.isCitationKeyCiteMarkers(); - - cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); - - Map citMarkers = new HashMap<>(); - - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { - String citMarker = - style.getCitationGroupMarkupBefore() - + String.join(",", ListUtil.map(cg.getCitationsInLocalOrder(), Citation::getCitationKey)) - + style.getCitationGroupMarkupAfter(); - citMarkers.put(cg.cgid, OOFormattedText.fromString(citMarker)); - } - return citMarkers; - } - /** * Produce citation markers for the case of numbered citations * with bibliography sorted by first appearance in the text. @@ -286,10 +261,10 @@ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) assert !style.isNumberEntries(); // Citations in (Au1, Au2 2000) form - CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); + CitedKeys citedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); - createNormalizedCitationMarkersForNormalStyle(sortedCitedKeys, style); - createUniqueLetters(sortedCitedKeys, cgs); + createNormalizedCitationMarkersForNormalStyle(citedKeys, style); + createUniqueLetters(citedKeys, cgs); cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); // Mark first appearance of each citationKey @@ -372,7 +347,7 @@ public static ProduceCitationMarkersResult produceCitationMarkers(CitationGroups Map uniqueLetters = new HashMap<>(); if (style.isCitationKeyCiteMarkers()) { - citMarkers = produceCitationMarkersForIsCitationKeyCiteMarkers(cgs, style); + citMarkers = OOProcessCitationKeyMarkers.produceCitationMarkers(cgs, style); } else if (style.isNumberEntries()) { if (style.isSortByPosition()) { citMarkers = produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java new file mode 100644 index 00000000000..2f22d63e9e8 --- /dev/null +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java @@ -0,0 +1,36 @@ +package org.jabref.logic.oostyle; + +import java.util.HashMap; +import java.util.Map; + +import org.jabref.model.oostyle.Citation; +import org.jabref.model.oostyle.CitationGroup; +import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroups; +import org.jabref.model.oostyle.ListUtil; +import org.jabref.model.oostyle.OOFormattedText; + +class OOProcessCitationKeyMarkers { + /** + * Produce citation markers for the case when the citation + * markers are the citation keys themselves, separated by commas. + */ + static Map + produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { + + assert style.isCitationKeyCiteMarkers(); + + cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); + + Map citMarkers = new HashMap<>(); + + for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { + String citMarker = + style.getCitationGroupMarkupBefore() + + String.join(",", ListUtil.map(cg.getCitationsInLocalOrder(), Citation::getCitationKey)) + + style.getCitationGroupMarkupAfter(); + citMarkers.put(cg.cgid, OOFormattedText.fromString(citMarker)); + } + return citMarkers; + } +} diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index f47f67e3c38..da0cf4e18fd 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -180,10 +180,10 @@ public void createNumberedBibliographySortedInOrderOfAppearance() { throw new RuntimeException("createNumberedBibliographySortedInOrderOfAppearance:" + " already have a bibliography"); } - CitedKeys sortedCitedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); - sortedCitedKeys.numberCitedKeysInCurrentOrder(); - sortedCitedKeys.distributeNumbers(cgs); - cgs.bibliography = Optional.of(sortedCitedKeys); + CitedKeys citedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); + citedKeys.numberCitedKeysInCurrentOrder(); + citedKeys.distributeNumbers(cgs); + cgs.bibliography = Optional.of(citedKeys); } /** diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeys.java b/src/main/java/org/jabref/model/oostyle/CitedKeys.java index c5fcabf6b32..38ec3c4baa1 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKeys.java @@ -47,7 +47,7 @@ void sortByComparator(Comparator entryComparator) { void numberCitedKeysInCurrentOrder() { int i = 1; for (CitedKey ck : data.values()) { - ck.number = Optional.of(i); // was: -1 for unresolved + ck.number = Optional.of(i); i++; } } From 65043cce58d9bc7636395ee6f9fe6750e3288da2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 15:34:59 +0200 Subject: [PATCH 0797/1068] split OOProcessNumericMarkers --- .../org/jabref/logic/oostyle/OOProcess.java | 67 +-------------- .../oostyle/OOProcessNumericMarkers.java | 85 +++++++++++++++++++ 2 files changed, 86 insertions(+), 66 deletions(-) create mode 100644 src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 034dc5c0c73..1789d425acb 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -166,67 +166,6 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup * * **************************************/ - /** - * Produce citation markers for the case of numbered citations - * with bibliography sorted by first appearance in the text. - * - * @param cgs - * @param style - * - * @return Numbered citation markers for each CitationGroupID. - * Numbering is according to first appearance. - * Assumes global order and local order ae already applied. - * - */ - private static Map - produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, OOBibStyle style) { - - assert style.isNumberEntries(); - assert style.isSortByPosition(); - - cgs.createNumberedBibliographySortedInOrderOfAppearance(); - - final int minGroupingCount = style.getMinimumGroupingCount(); - - Map citMarkers = new HashMap<>(); - - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { - List cits = cg.getCitationsInLocalOrder(); - citMarkers.put(cg.cgid, - style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), - minGroupingCount, - ListUtil.map(cits, Citation::getPageInfo))); - } - - return citMarkers; - } - - /** - * Produce citation markers for the case of numbered citations - * when the bibliography is not sorted by position. - */ - private static Map - produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, OOBibStyle style) { - assert style.isNumberEntries(); - assert !style.isSortByPosition(); - - cgs.createNumberedBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); - - final int minGroupingCount = style.getMinimumGroupingCount(); - - Map citMarkers = new HashMap<>(); - - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { - List cits = cg.getCitationsInLocalOrder(); - citMarkers.put(cg.cgid, - style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), - minGroupingCount, - ListUtil.map(cits, Citation::getPageInfo))); - } - - return citMarkers; - } - /** * Set isFirstAppearanceOfSource in each citation. * @@ -349,11 +288,7 @@ public static ProduceCitationMarkersResult produceCitationMarkers(CitationGroups if (style.isCitationKeyCiteMarkers()) { citMarkers = OOProcessCitationKeyMarkers.produceCitationMarkers(cgs, style); } else if (style.isNumberEntries()) { - if (style.isSortByPosition()) { - citMarkers = produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); - } else { - citMarkers = produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); - } + citMarkers = OOProcessNumericMarkers.produceCitationMarkers(cgs, style); } else { /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ citMarkers = produceCitationMarkersForNormalStyle(cgs, style); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java new file mode 100644 index 00000000000..f9f02592826 --- /dev/null +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java @@ -0,0 +1,85 @@ +package org.jabref.logic.oostyle; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jabref.model.oostyle.Citation; +import org.jabref.model.oostyle.CitationGroup; +import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroups; +import org.jabref.model.oostyle.ListUtil; +import org.jabref.model.oostyle.OOFormattedText; + +class OOProcessNumericMarkers { + + /** + * Produce citation markers for the case of numbered citations + * with bibliography sorted by first appearance in the text. + * + * @param cgs + * @param style + * + * @return Numbered citation markers for each CitationGroupID. + * Numbering is according to first appearance. + * Assumes global order and local order ae already applied. + * + */ + static Map + produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, OOBibStyle style) { + + assert style.isNumberEntries(); + assert style.isSortByPosition(); + + cgs.createNumberedBibliographySortedInOrderOfAppearance(); + + final int minGroupingCount = style.getMinimumGroupingCount(); + + Map citMarkers = new HashMap<>(); + + for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { + List cits = cg.getCitationsInLocalOrder(); + citMarkers.put(cg.cgid, + style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), + minGroupingCount, + ListUtil.map(cits, Citation::getPageInfo))); + } + + return citMarkers; + } + + /** + * Produce citation markers for the case of numbered citations + * when the bibliography is not sorted by position. + */ + static Map + produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, OOBibStyle style) { + assert style.isNumberEntries(); + assert !style.isSortByPosition(); + + cgs.createNumberedBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); + + final int minGroupingCount = style.getMinimumGroupingCount(); + + Map citMarkers = new HashMap<>(); + + for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { + List cits = cg.getCitationsInLocalOrder(); + citMarkers.put(cg.cgid, + style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), + minGroupingCount, + ListUtil.map(cits, Citation::getPageInfo))); + } + + return citMarkers; + } + + static Map + produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { + if (style.isSortByPosition()) { + return produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); + } else { + return produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); + } + } +} From bf18a342fe08743ce7d0440d953984784e35448c Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 15:42:15 +0200 Subject: [PATCH 0798/1068] simplify OOProcessNumericMarkers --- .../oostyle/OOProcessNumericMarkers.java | 41 +++---------------- 1 file changed, 5 insertions(+), 36 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java index f9f02592826..e8b6e303413 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java @@ -26,39 +26,16 @@ class OOProcessNumericMarkers { * */ static Map - produceCitationMarkersForIsNumberEntriesIsSortByPosition(CitationGroups cgs, OOBibStyle style) { + produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { assert style.isNumberEntries(); - assert style.isSortByPosition(); - - cgs.createNumberedBibliographySortedInOrderOfAppearance(); - - final int minGroupingCount = style.getMinimumGroupingCount(); - Map citMarkers = new HashMap<>(); - - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { - List cits = cg.getCitationsInLocalOrder(); - citMarkers.put(cg.cgid, - style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), - minGroupingCount, - ListUtil.map(cits, Citation::getPageInfo))); + if (style.isSortByPosition()) { + cgs.createNumberedBibliographySortedInOrderOfAppearance(); + } else { + cgs.createNumberedBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); } - return citMarkers; - } - - /** - * Produce citation markers for the case of numbered citations - * when the bibliography is not sorted by position. - */ - static Map - produceCitationMarkersForIsNumberEntriesNotSortByPosition(CitationGroups cgs, OOBibStyle style) { - assert style.isNumberEntries(); - assert !style.isSortByPosition(); - - cgs.createNumberedBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); - final int minGroupingCount = style.getMinimumGroupingCount(); Map citMarkers = new HashMap<>(); @@ -74,12 +51,4 @@ class OOProcessNumericMarkers { return citMarkers; } - static Map - produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { - if (style.isSortByPosition()) { - return produceCitationMarkersForIsNumberEntriesIsSortByPosition(cgs, style); - } else { - return produceCitationMarkersForIsNumberEntriesNotSortByPosition(cgs, style); - } - } } From cec59a164396ba5fb36255f13a7715ffe798d29c Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 15:52:28 +0200 Subject: [PATCH 0799/1068] split OOProcessAuthorYearMarkers --- .../org/jabref/logic/oostyle/OOProcess.java | 161 +---------------- .../oostyle/OOProcessAuthorYearMarkers.java | 169 ++++++++++++++++++ 2 files changed, 170 insertions(+), 160 deletions(-) create mode 100644 src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 1789d425acb..1d3901a881e 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -3,27 +3,18 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Optional; -import java.util.Set; import org.jabref.logic.bibtex.comparator.FieldComparator; import org.jabref.logic.bibtex.comparator.FieldComparatorStack; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; -import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitedKey; import org.jabref.model.oostyle.CitedKeys; -import org.jabref.model.oostyle.InTextCitationType; -import org.jabref.model.oostyle.ListUtil; -import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; import org.slf4j.Logger; @@ -77,156 +68,6 @@ public static Comparator comparatorForMulticite(OOBibStyle style) { } } - /* *************************************** - * - * Make them unique: uniqueLetters or numbers - * - * **************************************/ - - /** - * Fills {@code sortedCitedKeys//normCitMarker} - */ - private static void createNormalizedCitationMarkersForNormalStyle(CitedKeys sortedCitedKeys, - OOBibStyle style) { - - for (CitedKey ck : sortedCitedKeys.values()) { - ck.normCitMarker = Optional.of(style.getNormalizedCitationMarker(ck)); - } - } - - /** - * For each cited source make the citation keys unique by setting - * the uniqueLetter fields to letters ("a", "b") or Optional.empty() - * - * precondition: sortedCitedKeys already has normalized citation markers. - * precondition: sortedCitedKeys is sorted (according to the order we want the letters to be assigned) - * - * Expects to see data for all cited sources here. - * Clears uniqueLetters before filling. - * - * On return: Each citedKey in sortedCitedKeys has uniqueLetter set as needed. - * The same values are copied to the corresponding citations in cgs. - * - * Depends on: style, citations and their order. - */ - private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroups cgs) { - - // The entries in the clashingKeys lists preserve - // firstAppearance order from sortedCitedKeys.values(). - // - // The index of the citationKey in this order will decide - // which unique letter it receives. - // - Map> normCitMarkerToClachingKeys = new HashMap<>(); - for (CitedKey citedKey : sortedCitedKeys.values()) { - String normCitMarker = OOFormattedText.toString(citedKey.normCitMarker.get()); - String citationKey = citedKey.citationKey; - - if (!normCitMarkerToClachingKeys.containsKey(normCitMarker)) { - // Found new normCitMarker - List clashingKeys = new ArrayList<>(1); - normCitMarkerToClachingKeys.put(normCitMarker, clashingKeys); - clashingKeys.add(citationKey); - } else { - List clashingKeys = normCitMarkerToClachingKeys.get(normCitMarker); - if (!clashingKeys.contains(citationKey)) { - // First appearance of citationKey, add to list. - clashingKeys.add(citationKey); - } - } - } - - // Clear old uniqueLetter values. - for (CitedKey citedKey : sortedCitedKeys.values()) { - citedKey.uniqueLetter = Optional.empty(); - } - - // For sets of citation keys figthing for a normCitMarker - // add unique letters to the year. - for (List clashingKeys : normCitMarkerToClachingKeys.values()) { - if (clashingKeys.size() <= 1) { - continue; // No fight, no letters. - } - // Multiple citation keys: they get their letters - // according to their order in clashingKeys. - int nextUniqueLetter = 'a'; - for (String citationKey : clashingKeys) { - String ul = String.valueOf((char) nextUniqueLetter); - sortedCitedKeys.get(citationKey).uniqueLetter = Optional.of(ul); - nextUniqueLetter++; - } - } - sortedCitedKeys.distributeUniqueLetters(cgs); - } - - /* *************************************** - * - * Calculate presentation of citation groups - * (create citMarkers) - * - * **************************************/ - - /** - * Set isFirstAppearanceOfSource in each citation. - * - * Preconditions: globalOrder, localOrder - */ - private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) { - Set seenBefore = new HashSet<>(); - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { - for (Citation cit : cg.getCitationsInLocalOrder()) { - String currentKey = cit.citationKey; - if (!seenBefore.contains(currentKey)) { - cit.setIsFirstAppearanceOfSource(true); - seenBefore.add(currentKey); - } else { - cit.setIsFirstAppearanceOfSource(false); - } - } - } - } - - /** - * Produce citMarkers for normal - * (!isCitationKeyCiteMarkers && !isNumberEntries) styles. - * - * @param cgs - * @param style Bibliography style. - */ - private static Map - produceCitationMarkersForNormalStyle(CitationGroups cgs, OOBibStyle style) { - - assert !style.isCitationKeyCiteMarkers(); - assert !style.isNumberEntries(); - // Citations in (Au1, Au2 2000) form - - CitedKeys citedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); - - createNormalizedCitationMarkersForNormalStyle(citedKeys, style); - createUniqueLetters(citedKeys, cgs); - cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); - - // Mark first appearance of each citationKey - setIsFirstAppearanceOfSourceInCitations(cgs); - - Map citMarkers = new HashMap<>(); - - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { - - final boolean inParenthesis = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); - final NonUniqueCitationMarker strictlyUnique = NonUniqueCitationMarker.THROWS; - - List cits = cg.getCitationsInLocalOrder(); - List citationMarkerEntries = ListUtil.map(cits, e -> e); - OOFormattedText citMarker = style.getCitationMarker2(citationMarkerEntries, - inParenthesis, - strictlyUnique); - citMarkers.put(cg.cgid, citMarker); - } - - return citMarkers; - } - /** * The main field is citMarkers, the rest is for reuse in caller. */ @@ -291,7 +132,7 @@ public static ProduceCitationMarkersResult produceCitationMarkers(CitationGroups citMarkers = OOProcessNumericMarkers.produceCitationMarkers(cgs, style); } else { /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ - citMarkers = produceCitationMarkersForNormalStyle(cgs, style); + citMarkers = OOProcessAuthorYearMarkers.produceCitationMarkers(cgs, style); } return new ProduceCitationMarkersResult(cgs, /* has bibliography as a side effect */ diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java new file mode 100644 index 00000000000..3bdaaaf723a --- /dev/null +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java @@ -0,0 +1,169 @@ +package org.jabref.logic.oostyle; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import org.jabref.model.oostyle.Citation; +import org.jabref.model.oostyle.CitationGroup; +import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroups; +import org.jabref.model.oostyle.CitationMarkerEntry; +import org.jabref.model.oostyle.CitedKey; +import org.jabref.model.oostyle.CitedKeys; +import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.ListUtil; +import org.jabref.model.oostyle.NonUniqueCitationMarker; +import org.jabref.model.oostyle.OOFormattedText; + +class OOProcessAuthorYearMarkers { + + /** + * Fills {@code sortedCitedKeys//normCitMarker} + */ + private static void createNormalizedCitationMarkersForNormalStyle(CitedKeys sortedCitedKeys, + OOBibStyle style) { + + for (CitedKey ck : sortedCitedKeys.values()) { + ck.normCitMarker = Optional.of(style.getNormalizedCitationMarker(ck)); + } + } + + /** + * For each cited source make the citation keys unique by setting + * the uniqueLetter fields to letters ("a", "b") or Optional.empty() + * + * precondition: sortedCitedKeys already has normalized citation markers. + * precondition: sortedCitedKeys is sorted (according to the order we want the letters to be assigned) + * + * Expects to see data for all cited sources here. + * Clears uniqueLetters before filling. + * + * On return: Each citedKey in sortedCitedKeys has uniqueLetter set as needed. + * The same values are copied to the corresponding citations in cgs. + * + * Depends on: style, citations and their order. + */ + private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroups cgs) { + + // The entries in the clashingKeys lists preserve + // firstAppearance order from sortedCitedKeys.values(). + // + // The index of the citationKey in this order will decide + // which unique letter it receives. + // + Map> normCitMarkerToClachingKeys = new HashMap<>(); + for (CitedKey citedKey : sortedCitedKeys.values()) { + String normCitMarker = OOFormattedText.toString(citedKey.normCitMarker.get()); + String citationKey = citedKey.citationKey; + + if (!normCitMarkerToClachingKeys.containsKey(normCitMarker)) { + // Found new normCitMarker + List clashingKeys = new ArrayList<>(1); + normCitMarkerToClachingKeys.put(normCitMarker, clashingKeys); + clashingKeys.add(citationKey); + } else { + List clashingKeys = normCitMarkerToClachingKeys.get(normCitMarker); + if (!clashingKeys.contains(citationKey)) { + // First appearance of citationKey, add to list. + clashingKeys.add(citationKey); + } + } + } + + // Clear old uniqueLetter values. + for (CitedKey citedKey : sortedCitedKeys.values()) { + citedKey.uniqueLetter = Optional.empty(); + } + + // For sets of citation keys figthing for a normCitMarker + // add unique letters to the year. + for (List clashingKeys : normCitMarkerToClachingKeys.values()) { + if (clashingKeys.size() <= 1) { + continue; // No fight, no letters. + } + // Multiple citation keys: they get their letters + // according to their order in clashingKeys. + int nextUniqueLetter = 'a'; + for (String citationKey : clashingKeys) { + String ul = String.valueOf((char) nextUniqueLetter); + sortedCitedKeys.get(citationKey).uniqueLetter = Optional.of(ul); + nextUniqueLetter++; + } + } + sortedCitedKeys.distributeUniqueLetters(cgs); + } + + /* *************************************** + * + * Calculate presentation of citation groups + * (create citMarkers) + * + * **************************************/ + + /** + * Set isFirstAppearanceOfSource in each citation. + * + * Preconditions: globalOrder, localOrder + */ + private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) { + Set seenBefore = new HashSet<>(); + for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { + for (Citation cit : cg.getCitationsInLocalOrder()) { + String currentKey = cit.citationKey; + if (!seenBefore.contains(currentKey)) { + cit.setIsFirstAppearanceOfSource(true); + seenBefore.add(currentKey); + } else { + cit.setIsFirstAppearanceOfSource(false); + } + } + } + } + + /** + * Produce citMarkers for normal + * (!isCitationKeyCiteMarkers && !isNumberEntries) styles. + * + * @param cgs + * @param style Bibliography style. + */ + static Map + produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { + + assert !style.isCitationKeyCiteMarkers(); + assert !style.isNumberEntries(); + // Citations in (Au1, Au2 2000) form + + CitedKeys citedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); + + createNormalizedCitationMarkersForNormalStyle(citedKeys, style); + createUniqueLetters(citedKeys, cgs); + cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); + + // Mark first appearance of each citationKey + setIsFirstAppearanceOfSourceInCitations(cgs); + + Map citMarkers = new HashMap<>(); + + for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { + + final boolean inParenthesis = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); + final NonUniqueCitationMarker strictlyUnique = NonUniqueCitationMarker.THROWS; + + List cits = cg.getCitationsInLocalOrder(); + List citationMarkerEntries = ListUtil.map(cits, e -> e); + OOFormattedText citMarker = style.getCitationMarker2(citationMarkerEntries, + inParenthesis, + strictlyUnique); + citMarkers.put(cg.cgid, citMarker); + } + + return citMarkers; + } + +} From 258d319318c5e12a8c7400eefa3f305f7ff80372 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 18:31:35 +0200 Subject: [PATCH 0800/1068] produce citation makrers into CitationGroup.citationMarker --- .../org/jabref/logic/oostyle/OOProcess.java | 70 +++---------------- .../oostyle/OOProcessAuthorYearMarkers.java | 10 +-- .../oostyle/OOProcessCitationKeyMarkers.java | 12 +--- .../oostyle/OOProcessNumericMarkers.java | 28 +++----- .../org/jabref/logic/openoffice/Update.java | 9 ++- .../openoffice/UpdateCitationMarkers.java | 40 +++++------ .../jabref/model/oostyle/CitationGroup.java | 15 ++++ .../jabref/model/oostyle/CitationGroups.java | 15 ++++ 8 files changed, 78 insertions(+), 121 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 1d3901a881e..dfbc011ddda 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -2,20 +2,14 @@ import java.util.ArrayList; import java.util.Comparator; -import java.util.HashMap; import java.util.List; -import java.util.Map; import org.jabref.logic.bibtex.comparator.FieldComparator; import org.jabref.logic.bibtex.comparator.FieldComparatorStack; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; -import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.CitedKey; -import org.jabref.model.oostyle.CitedKeys; -import org.jabref.model.oostyle.OOFormattedText; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -69,74 +63,28 @@ public static Comparator comparatorForMulticite(OOBibStyle style) { } /** - * The main field is citMarkers, the rest is for reuse in caller. + * Fill cgs.bibliography and cgs.citationGroupsUnordered//CitationMarker + * according to style. */ - public static class ProduceCitationMarkersResult { - - public CitationGroups cgs; - - /** citation markers */ - public Map citMarkers; - - ProduceCitationMarkersResult(CitationGroups cgs, - Map citMarkers) { - this.cgs = cgs; - this.citMarkers = citMarkers; - if (cgs.getBibliography().isEmpty()) { - throw new RuntimeException("ProduceCitationMarkersResult.constructor:" - + " cgs does not have a bibliography"); - } - } - - public CitedKeys getBibliography() { - if (cgs.getBibliography().isEmpty()) { - throw new RuntimeException("ProduceCitationMarkersResult.getBibliography:" - + " cgs does not have a bibliography"); - } - return cgs.getBibliography().get(); - } - - public List getUnresolvedKeys() { - CitedKeys bib = getBibliography(); - List unresolvedKeys = new ArrayList<>(); - for (CitedKey ck : bib.values()) { - if (ck.db.isEmpty()) { - unresolvedKeys.add(ck.citationKey); - } - } - return unresolvedKeys; - } - } - - public static ProduceCitationMarkersResult produceCitationMarkers(CitationGroups cgs, - List databases, - OOBibStyle style) { + public static void produceCitationMarkers(CitationGroups cgs, + List databases, + OOBibStyle style) { if (!cgs.hasGlobalOrder()) { throw new RuntimeException("produceCitationMarkers: globalOrder is misssing in cgs"); } cgs.lookupEntriesInDatabases(databases); - - // requires cgs.lookupEntryInDatabases: needs BibEntry data cgs.imposeLocalOrderByComparator(comparatorForMulticite(style)); - Map citMarkers; - - // fill citMarkers - Map uniqueLetters = new HashMap<>(); - + // fill CitationGroup.citationMarker if (style.isCitationKeyCiteMarkers()) { - citMarkers = OOProcessCitationKeyMarkers.produceCitationMarkers(cgs, style); + OOProcessCitationKeyMarkers.produceCitationMarkers(cgs, style); } else if (style.isNumberEntries()) { - citMarkers = OOProcessNumericMarkers.produceCitationMarkers(cgs, style); + OOProcessNumericMarkers.produceCitationMarkers(cgs, style); } else { - /* Normal case, (!isCitationKeyCiteMarkers && !isNumberEntries) */ - citMarkers = OOProcessAuthorYearMarkers.produceCitationMarkers(cgs, style); + OOProcessAuthorYearMarkers.produceCitationMarkers(cgs, style); } - - return new ProduceCitationMarkersResult(cgs, /* has bibliography as a side effect */ - citMarkers); } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java index 3bdaaaf723a..9c94b907fa7 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java @@ -10,7 +10,6 @@ import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitedKey; @@ -132,8 +131,7 @@ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) * @param cgs * @param style Bibliography style. */ - static Map - produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { + static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { assert !style.isCitationKeyCiteMarkers(); assert !style.isNumberEntries(); @@ -148,8 +146,6 @@ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) // Mark first appearance of each citationKey setIsFirstAppearanceOfSourceInCitations(cgs); - Map citMarkers = new HashMap<>(); - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { final boolean inParenthesis = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); @@ -160,10 +156,8 @@ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) OOFormattedText citMarker = style.getCitationMarker2(citationMarkerEntries, inParenthesis, strictlyUnique); - citMarkers.put(cg.cgid, citMarker); + cg.setCitationMarker(Optional.of(citMarker)); } - - return citMarkers; } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java index 2f22d63e9e8..4c644638ba1 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java @@ -1,11 +1,9 @@ package org.jabref.logic.oostyle; -import java.util.HashMap; -import java.util.Map; +import java.util.Optional; import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.ListUtil; import org.jabref.model.oostyle.OOFormattedText; @@ -15,22 +13,18 @@ class OOProcessCitationKeyMarkers { * Produce citation markers for the case when the citation * markers are the citation keys themselves, separated by commas. */ - static Map - produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { + static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { assert style.isCitationKeyCiteMarkers(); cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); - Map citMarkers = new HashMap<>(); - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { String citMarker = style.getCitationGroupMarkupBefore() + String.join(",", ListUtil.map(cg.getCitationsInLocalOrder(), Citation::getCitationKey)) + style.getCitationGroupMarkupAfter(); - citMarkers.put(cg.cgid, OOFormattedText.fromString(citMarker)); + cg.setCitationMarker(Optional.of(OOFormattedText.fromString(citMarker))); } - return citMarkers; } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java index e8b6e303413..10724a8325f 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java @@ -1,12 +1,10 @@ package org.jabref.logic.oostyle; -import java.util.HashMap; import java.util.List; -import java.util.Map; +import java.util.Optional; import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.ListUtil; import org.jabref.model.oostyle.OOFormattedText; @@ -17,16 +15,15 @@ class OOProcessNumericMarkers { * Produce citation markers for the case of numbered citations * with bibliography sorted by first appearance in the text. * + * Numbered citation markers for each CitationGroup. + * Numbering is according to first appearance. + * Assumes global order and local order are already applied. + * * @param cgs * @param style * - * @return Numbered citation markers for each CitationGroupID. - * Numbering is according to first appearance. - * Assumes global order and local order ae already applied. - * */ - static Map - produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { + static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { assert style.isNumberEntries(); @@ -38,17 +35,14 @@ class OOProcessNumericMarkers { final int minGroupingCount = style.getMinimumGroupingCount(); - Map citMarkers = new HashMap<>(); - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { List cits = cg.getCitationsInLocalOrder(); - citMarkers.put(cg.cgid, - style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), - minGroupingCount, - ListUtil.map(cits, Citation::getPageInfo))); + OOFormattedText citMarker = + style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), + minGroupingCount, + ListUtil.map(cits, Citation::getPageInfo)); + cg.setCitationMarker(Optional.of(citMarker)); } - - return citMarkers; } } diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index cd51124b2ea..f89b873165f 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -43,24 +43,23 @@ public static List updateDocument(XTextDocument doc, final boolean useLockControllers = true; fr.imposeGlobalOrder(doc, fcursor); - OOProcess.ProduceCitationMarkersResult x = - OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); + OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); try { if (useLockControllers) { UnoScreenRefresh.lockControllers(doc); } - UpdateCitationMarkers.applyNewCitationMarkers(doc, fr, x.citMarkers, style); + UpdateCitationMarkers.applyNewCitationMarkers(doc, fr, style); if (doUpdateBibliography) { UpdateBibliography.rebuildBibTextSection(doc, fr, - x.getBibliography(), + fr.citationGroups.getBibliography().get(), style, alwaysAddCitedOnPages); } - return x.getUnresolvedKeys(); + return fr.citationGroups.getUnresolvedKeys(); } finally { if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { UnoScreenRefresh.unlockControllers(doc); diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 93efc8ae684..94cd9646efa 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -1,7 +1,6 @@ package org.jabref.logic.openoffice; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -24,11 +23,16 @@ import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /* * Update document: citation marks and bibliography */ public class UpdateCitationMarkers { + + private static final Logger LOGGER = LoggerFactory.getLogger(UpdateCitationMarkers.class); + /** * Visit each reference mark in referenceMarkNames, overwrite its * text content. @@ -38,15 +42,11 @@ public class UpdateCitationMarkers { * * @param fr * - * @param citMarkers Corresponding text for each reference mark, - * that replaces the old text. - * * @param style Bibliography style to use. * */ static void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, - Map citMarkers, OOBibStyle style) throws NoDocumentException, @@ -57,29 +57,27 @@ static void applyNewCitationMarkers(XTextDocument doc, NoSuchElementException, JabRefException { - // checkStylesExistInTheDocument(style, doc); - - CitationGroups cgs = fr.citationGroups; - - for (Map.Entry kv : citMarkers.entrySet()) { + CitationGroups citationGroups = fr.citationGroups; - CitationGroupID cgid = kv.getKey(); - Objects.requireNonNull(cgid); - - OOFormattedText citationText = kv.getValue(); - Objects.requireNonNull(citationText); - - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); + for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { boolean withText = (cg.citationType != InTextCitationType.INVISIBLE_CIT); + Optional marker = cg.getCitationMarker(); + + if (!marker.isPresent()) { + String msg = String.format("applyNewCitationMarkers: no marker for %s", + cg.cgid.asString()); + LOGGER.warn(msg); + continue; + } - if (withText) { + if (withText && marker.isPresent()) { - XTextCursor cursor = fr.getFillCursorForCitationGroup(doc, cgid); + XTextCursor cursor = fr.getFillCursorForCitationGroup(doc, cg.cgid); - fillCitationMarkInCursor(doc, cursor, citationText, withText, style); + fillCitationMarkInCursor(doc, cursor, marker.get(), withText, style); - fr.cleanFillCursorForCitationGroup(doc, cgid); + fr.cleanFillCursorForCitationGroup(doc, cg.cgid); } } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index 702041055d4..86b65bf158f 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -59,6 +59,11 @@ public class CitationGroup { */ private Optional indexInGlobalOrder; + /* + * Citation marker. + */ + private Optional citationMarker; + public CitationGroup(OODataModel dataModel, CitationGroupID cgid, StorageBase.NamedRange cgRangeStorage, @@ -73,6 +78,7 @@ public CitationGroup(OODataModel dataModel, this.localOrder = ListUtil.makeIndices(citationsInStorageOrder.size()); this.referenceMarkNameForLinking = referenceMarkNameForLinking; this.indexInGlobalOrder = Optional.empty(); + this.citationMarker = Optional.empty(); } public int numberOfCitations() { @@ -141,4 +147,13 @@ public Optional getReferenceMarkNameForLinking() { public void setReferenceMarkNameForLinking(Optional referenceMarkNameForLinking) { this.referenceMarkNameForLinking = referenceMarkNameForLinking; } + + public void setCitationMarker(Optional citationMarker) { + this.citationMarker = citationMarker; + } + + public Optional getCitationMarker() { + return this.citationMarker; + } + } // class CitationGroup diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index da0cf4e18fd..035fa735dcd 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -174,6 +174,21 @@ public Optional getBibliography() { return bibliography; } + public List getUnresolvedKeys() { + Optional bib = getBibliography(); + if (bib.isEmpty()) { + throw new RuntimeException("getUnresolvedKeys:" + + " CitationGroups does not have a bibliography"); + } + List unresolvedKeys = new ArrayList<>(); + for (CitedKey ck : bib.get().values()) { + if (ck.db.isEmpty()) { + unresolvedKeys.add(ck.citationKey); + } + } + return unresolvedKeys; + } + public void createNumberedBibliographySortedInOrderOfAppearance() { CitationGroups cgs = this; if (!cgs.bibliography.isEmpty()) { From 35561f39dd721e8e8a68afddde8f6ca284009b74 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 19:13:25 +0200 Subject: [PATCH 0801/1068] Update.sync --- .../org/jabref/gui/openoffice/OOBibBase.java | 16 +++--- .../gui/openoffice/OpenOfficePanel.java | 6 +- .../jabref/logic/openoffice/EditInsert.java | 57 +------------------ .../org/jabref/logic/openoffice/Update.java | 49 ++++++++++++++++ 4 files changed, 61 insertions(+), 67 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 4b6c2e057b3..98d4aaa288e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -551,7 +551,7 @@ public void guiActionInsertEntry(List entries, OOBibStyle style, InTextCitationType citationType, String pageInfo, - Optional syncOptions) { + Optional syncOptions) { final String title = "Could not insert citation"; @@ -576,14 +576,12 @@ public void guiActionInsertEntry(List entries, /* * For sync we need a FunctionalTextViewCursor. */ - Optional fcursorOpt = Optional.empty(); - + Result fcursor = null; if (syncOptions.isPresent()) { - Result fcursor = getFunctionalTextViewCursor(doc, title); + fcursor = getFunctionalTextViewCursor(doc, title); if (testDialog(title, fcursor.asVoidResult())) { return; } - fcursorOpt = fcursor.getOptional(); } syncOptions @@ -609,9 +607,11 @@ public void guiActionInsertEntry(List entries, database, style, citationType, - pageInfo, - syncOptions, - fcursorOpt); + pageInfo); + + if (syncOptions.isPresent()) { + Update.sync(doc, style, fcursor.get(), syncOptions.get()); + } } catch (NoDocumentException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 331263cb6bf..e3ea20f2a03 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -45,9 +45,9 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.StyleLoader; -import org.jabref.logic.openoffice.EditInsert; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; +import org.jabref.logic.openoffice.Update; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; @@ -494,9 +494,9 @@ private void pushEntries(InTextCitationType citationType, boolean addPageInfo) { return; } - Optional syncOptions = + Optional syncOptions = (ooPrefs.getSyncWhenCiting() - ? Optional.of(new EditInsert.SyncOptions(getBaseList())) + ? Optional.of(new Update.SyncOptions(getBaseList())) : Optional.empty()); ooBase.guiActionInsertEntry(entries, diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index ad69ea356a6..e73d82306ba 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -28,7 +28,6 @@ import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; -import com.sun.star.text.XTextRange; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,29 +53,6 @@ private static String insertEntryGetCitationKey(BibEntry entry) { return key.get(); } - public static class SyncOptions { - - public final List databases; - boolean updateBibliography; - boolean alwaysAddCitedOnPages; - - public SyncOptions(List databases) { - this.databases = databases; - this.updateBibliography = false; - this.alwaysAddCitedOnPages = false; - } - - public SyncOptions setUpdateBibliography(boolean value) { - this.updateBibliography = value; - return this; - } - - public SyncOptions setAlwaysAddCitedOnPages(boolean value) { - this.alwaysAddCitedOnPages = value; - return this; - } - } - /* * @param cursor Where to insert. * @@ -94,9 +70,7 @@ public static void insertCitationGroup(XTextDocument doc, BibDatabase database, OOBibStyle style, InTextCitationType citationType, - String pageInfo, - Optional sync, - Optional fcursor) + String pageInfo) throws UnknownPropertyException, NoDocumentException, @@ -147,34 +121,5 @@ public static void insertCitationGroup(XTextDocument doc, style, true /* insertSpaceAfter */); - if (sync.isPresent()) { - // Remember this position: we will come back here in the - // end. - XTextRange position = cursor.getEnd(); - - // To account for numbering and for uniqueLetters, we - // must refresh the cite markers: - OOFrontend fr2 = new OOFrontend(doc); - - Update.updateDocument(doc, - fr2, - sync.get().databases, - style, - fcursor.get(), - sync.get().updateBibliography, - sync.get().alwaysAddCitedOnPages); - - /* - * Problem: insertEntry in bibliography - * Reference is destroyed when we want to get there. - */ - // Go back to the relevant position: - try { - cursor.gotoRange(position, false); - } catch (com.sun.star.uno.RuntimeException ex) { - LOGGER.warn("insertCitationGroup:" - + " Could not go back to end of in-text citation", ex); - } - } } } diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index f89b873165f..ed1a7414627 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -66,4 +66,53 @@ public static List updateDocument(XTextDocument doc, } } } + + public static class SyncOptions { + + public final List databases; + boolean updateBibliography; + boolean alwaysAddCitedOnPages; + + public SyncOptions(List databases) { + this.databases = databases; + this.updateBibliography = false; + this.alwaysAddCitedOnPages = false; + } + + public SyncOptions setUpdateBibliography(boolean value) { + this.updateBibliography = value; + return this; + } + + public SyncOptions setAlwaysAddCitedOnPages(boolean value) { + this.alwaysAddCitedOnPages = value; + return this; + } + } + + public static void sync(XTextDocument doc, + OOBibStyle style, + FunctionalTextViewCursor fcursor, + SyncOptions syncOptions) + throws + CreationException, + JabRefException, + NoDocumentException, + NoSuchElementException, + PropertyVetoException, + UnknownPropertyException, + WrappedTargetException, + com.sun.star.lang.IllegalArgumentException { + + OOFrontend fr = new OOFrontend(doc); + + Update.updateDocument(doc, + fr, + syncOptions.databases, + style, + fcursor, + syncOptions.updateBibliography, + syncOptions.alwaysAddCitedOnPages); + } + } From df735c0db6bca67b1d16ce95bcb61c90a844ff00 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 19:46:15 +0200 Subject: [PATCH 0802/1068] call Update.sync Update.resync from OOBibBase --- .../org/jabref/gui/openoffice/OOBibBase.java | 42 ++++++++------ .../jabref/logic/openoffice/EditMerge.java | 24 +++----- .../jabref/logic/openoffice/EditSeparate.java | 22 ++----- .../org/jabref/logic/openoffice/Update.java | 57 +++++++++++++------ 4 files changed, 77 insertions(+), 68 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 98d4aaa288e..bac09a83d11 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -21,6 +21,7 @@ import org.jabref.logic.openoffice.ManageCitations; import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.OOFrontend; +import org.jabref.logic.openoffice.UnoCrossRef; import org.jabref.logic.openoffice.UnoCursor; import org.jabref.logic.openoffice.UnoRedlines; import org.jabref.logic.openoffice.UnoStyle; @@ -610,7 +611,7 @@ public void guiActionInsertEntry(List entries, pageInfo); if (syncOptions.isPresent()) { - Update.sync(doc, style, fcursor.get(), syncOptions.get()); + Update.resync(doc, style, fcursor.get(), syncOptions.get()); } } catch (NoDocumentException ex) { @@ -669,11 +670,12 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle UnoUndo.enterUndoContext(doc, "Merge citations"); OOFrontend fr = new OOFrontend(doc); - EditMerge.mergeCitationGroups(doc, - fr, - databases, - style, - fcursor.get()); + boolean madeModifications = EditMerge.mergeCitationGroups(doc, fr, style); + if (madeModifications) { + UnoCrossRef.refresh(doc); + Update.SyncOptions syncOptions = new Update.SyncOptions(databases); + Update.resync(doc, style, fcursor.get(), syncOptions); + } } catch (NoDocumentException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); @@ -695,6 +697,7 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } finally { UnoUndo.leaveUndoContext(doc); + fcursor.get().restore(doc); } } // MergeCitationGroups @@ -730,7 +733,12 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s UnoUndo.enterUndoContext(doc, "Separate citations"); OOFrontend fr = new OOFrontend(doc); - EditSeparate.separateCitations(doc, fr, databases, style, fcursor.get()); + boolean madeModifications = EditSeparate.separateCitations(doc, fr, databases, style); + if (madeModifications) { + UnoCrossRef.refresh(doc); + Update.SyncOptions syncOptions = new Update.SyncOptions(databases); + Update.resync(doc, style, fcursor.get(), syncOptions); + } } catch (NoDocumentException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); @@ -752,6 +760,7 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); } finally { UnoUndo.leaveUndoContext(doc); + fcursor.get().restore(doc); } } @@ -875,17 +884,18 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl List unresolvedKeys; try { - UnoUndo.enterUndoContext(doc, "Refresh bibliography"); - boolean doUpdateBibliography = true; - unresolvedKeys = Update.updateDocument(doc, - fr, - databases, - style, - fcursor.get(), - doUpdateBibliography, - this.alwaysAddCitedOnPages); + UnoUndo.enterUndoContext(doc, "Refresh bibliography"); + + Update.SyncOptions syncOptions = new Update.SyncOptions(databases); + syncOptions + .setUpdateBibliography(true) + .setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages); + + unresolvedKeys = Update.sync(doc, fr, style, fcursor.get(), syncOptions); + } finally { UnoUndo.leaveUndoContext(doc); + fcursor.get().restore(doc); } if (!unresolvedKeys.isEmpty()) { diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 49d607ca2b2..2cc93ac6250 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -8,7 +8,6 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.model.database.BibDatabase; import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; @@ -295,11 +294,12 @@ private static List scan(XTextDocument doc, OOFrontend fr) return result; } - public static void mergeCitationGroups(XTextDocument doc, - OOFrontend fr, - List databases, - OOBibStyle style, - FunctionalTextViewCursor fcursor) + /* + * @return true if modified document + */ + public static boolean mergeCitationGroups(XTextDocument doc, + OOFrontend fr, + OOBibStyle style) throws CreationException, IllegalArgumentException, @@ -374,16 +374,6 @@ public static void mergeCitationGroups(XTextDocument doc, UnoScreenRefresh.unlockControllers(doc); } - if (madeModifications) { - UnoCrossRef.refresh(doc); - OOFrontend fr2 = new OOFrontend(doc); - Update.updateDocument(doc, - fr2, - databases, - style, - fcursor, - false, /* doUpdateBibliography */ - false /* alwaysAddCitedOnPages */); - } + return madeModifications; } } diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 47966a2fae2..8c9db2f72d8 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -26,11 +26,10 @@ public class EditSeparate { - public static void separateCitations(XTextDocument doc, - OOFrontend fr, - List databases, - OOBibStyle style, - FunctionalTextViewCursor fcursor) + public static boolean separateCitations(XTextDocument doc, + OOFrontend fr, + List databases, + OOBibStyle style) throws CreationException, IllegalTypeException, @@ -99,17 +98,6 @@ public static void separateCitations(XTextDocument doc, } finally { UnoScreenRefresh.unlockControllers(doc); } - - if (madeModifications) { - UnoCrossRef.refresh(doc); - OOFrontend fr2 = new OOFrontend(doc); - Update.updateDocument(doc, - fr2, - databases, - style, - fcursor, - false, /* doUpdateBibliography */ - false /* alwaysAddCitedOnPages */); - } + return madeModifications; } } diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index ed1a7414627..29eb5ce4638 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -23,13 +23,13 @@ public class Update { /* * @return unresolvedKeys */ - public static List updateDocument(XTextDocument doc, - OOFrontend fr, - List databases, - OOBibStyle style, - FunctionalTextViewCursor fcursor, - boolean doUpdateBibliography, - boolean alwaysAddCitedOnPages) + private static List updateDocument(XTextDocument doc, + OOFrontend fr, + List databases, + OOBibStyle style, + FunctionalTextViewCursor fcursor, + boolean doUpdateBibliography, + boolean alwaysAddCitedOnPages) throws CreationException, JabRefException, @@ -90,10 +90,37 @@ public SyncOptions setAlwaysAddCitedOnPages(boolean value) { } } - public static void sync(XTextDocument doc, - OOBibStyle style, - FunctionalTextViewCursor fcursor, - SyncOptions syncOptions) + public static List sync(XTextDocument doc, + OOFrontend fr, + OOBibStyle style, + FunctionalTextViewCursor fcursor, + SyncOptions syncOptions) + throws + CreationException, + JabRefException, + NoDocumentException, + NoSuchElementException, + PropertyVetoException, + UnknownPropertyException, + WrappedTargetException, + com.sun.star.lang.IllegalArgumentException { + + return Update.updateDocument(doc, + fr, + syncOptions.databases, + style, + fcursor, + syncOptions.updateBibliography, + syncOptions.alwaysAddCitedOnPages); + } + + /* + * Reread document before sync + */ + public static List resync(XTextDocument doc, + OOBibStyle style, + FunctionalTextViewCursor fcursor, + SyncOptions syncOptions) throws CreationException, JabRefException, @@ -106,13 +133,7 @@ public static void sync(XTextDocument doc, OOFrontend fr = new OOFrontend(doc); - Update.updateDocument(doc, - fr, - syncOptions.databases, - style, - fcursor, - syncOptions.updateBibliography, - syncOptions.alwaysAddCitedOnPages); + return Update.sync(doc, fr, style, fcursor, syncOptions); } } From 1970e8f2f07d6310c4d05c8711cac980d4cd22b5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 20:09:02 +0200 Subject: [PATCH 0803/1068] CitationDatabaseLookupResult.java --- .../oostyle/OOBibStyleGetCitationMarker.java | 10 +++--- .../jabref/logic/openoffice/EditInsert.java | 2 +- .../org/jabref/model/oostyle/Citation.java | 22 ++++++++---- .../model/oostyle/CitationDatabaseLookup.java | 35 ------------------- .../oostyle/CitationDatabaseLookupResult.java | 19 ++++++++++ .../oostyle/CitationMarkerNormEntry.java | 2 +- .../org/jabref/model/oostyle/CitedKey.java | 6 ++-- .../jabref/logic/oostyle/OOBibStyleTest.java | 2 +- 8 files changed, 46 insertions(+), 52 deletions(-) delete mode 100644 src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java create mode 100644 src/main/java/org/jabref/model/oostyle/CitationDatabaseLookupResult.java diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index abb7fec7179..bca0491014e 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -13,7 +13,7 @@ import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationDatabaseLookup; +import org.jabref.model.oostyle.CitationDatabaseLookupResult; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerNormEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; @@ -263,7 +263,7 @@ private static Optional getRawCitationMarkerField(BibEntry entr * */ private static String getCitationMarkerField(OOBibStyle style, - CitationDatabaseLookup.Result db, + CitationDatabaseLookupResult db, OrFields fields) { Objects.requireNonNull(db); @@ -289,7 +289,7 @@ private static String getCitationMarkerField(OOBibStyle style, return result; } - private static AuthorList getAuthorList(OOBibStyle style, CitationDatabaseLookup.Result db) { + private static AuthorList getAuthorList(OOBibStyle style, CitationDatabaseLookupResult db) { // The bibtex fields providing author names, e.g. "author" or // "editor". @@ -451,7 +451,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, } } else { - CitationDatabaseLookup.Result db = ce.getDatabaseLookupResult().get(); + CitationDatabaseLookupResult db = ce.getDatabaseLookupResult().get(); int maxAuthors = (purpose == AuthorYearMarkerPurpose.NORMALIZED ? style.getMaxAuthors() @@ -521,7 +521,7 @@ public String getCitationKey() { } @Override - public Optional getDatabaseLookupResult() { + public Optional getDatabaseLookupResult() { return inner.getDatabaseLookupResult(); } diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index e73d82306ba..98dbac82956 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -94,7 +94,7 @@ public static void insertCitationGroup(XTextDocument doc, List citations = new ArrayList<>(nEntries); for (int i = 0; i < nEntries; i++) { Citation cit = new Citation(citationKeys.get(i)); - cit.lookup(Collections.singletonList(database)); + cit.lookupInDatabases(Collections.singletonList(database)); cit.setPageInfo(pageInfosForCitations.get(i)); citations.add(cit); } diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index e603a5c7147..406a555d798 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -13,7 +13,7 @@ public class Citation implements ComparableCitation, CitationMarkerEntry { public final String citationKey; /** Result from database lookup. Optional.empty() if not found. */ - private Optional db; + private Optional db; /** The number used for numbered citation styles . */ private Optional number; @@ -61,15 +61,25 @@ public Optional getBibEntry() { : Optional.empty()); } - public void lookup(List databases) { - db = CitationDatabaseLookup.lookup(databases, citationKey); + public static Optional lookup(List databases, String key) { + for (BibDatabase database : databases) { + Optional entry = database.getEntryByCitationKey(key); + if (entry.isPresent()) { + return Optional.of(new CitationDatabaseLookupResult(entry.get(), database)); + } + } + return Optional.empty(); + } + + public void lookupInDatabases(List databases) { + db = Citation.lookup(databases, citationKey); } - public Optional getDatabaseLookupResult() { + public Optional getDatabaseLookupResult() { return db; } - public void setDatabaseLookupResult(Optional db) { + public void setDatabaseLookupResult(Optional db) { this.db = db; } @@ -108,7 +118,7 @@ public void setIsFirstAppearanceOfSource(boolean value) { /* * Setters for CitationGroups.distribute() */ - public static void setDatabaseLookupResult(Pair> x) { + public static void setDatabaseLookupResult(Pair> x) { Citation cit = x.a; cit.db = x.b; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java b/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java deleted file mode 100644 index 2cb2ba3e062..00000000000 --- a/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookup.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.jabref.model.oostyle; - -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; - -public class CitationDatabaseLookup { - - public static class Result { - - public final BibEntry entry; - public final BibDatabase database; - - public Result(BibEntry entry, BibDatabase database) { - Objects.requireNonNull(entry); - Objects.requireNonNull(database); - this.entry = entry; - this.database = database; - } - } - - public static Optional lookup(List databases, String key) { - for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(key); - if (entry.isPresent()) { - return Optional.of(new Result(entry.get(), database)); - } - } - return Optional.empty(); - } - -} diff --git a/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookupResult.java b/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookupResult.java new file mode 100644 index 00000000000..5c4a22b1a89 --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookupResult.java @@ -0,0 +1,19 @@ +package org.jabref.model.oostyle; + +import java.util.Objects; + +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; + +public class CitationDatabaseLookupResult { + + public final BibEntry entry; + public final BibDatabase database; + + public CitationDatabaseLookupResult(BibEntry entry, BibDatabase database) { + Objects.requireNonNull(entry); + Objects.requireNonNull(database); + this.entry = entry; + this.database = database; + } +} diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java index 34d227cef91..19d548f543d 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java @@ -19,5 +19,5 @@ public interface CitationMarkerNormEntry { /** Result of looking up citation key in databases. */ - Optional getDatabaseLookupResult(); + Optional getDatabaseLookupResult(); } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index 8431643a6b6..680807c60eb 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -10,7 +10,7 @@ public class CitedKey implements ComparableCitedKey, CitationMarkerNormEntry { public String citationKey; public LinkedHashSet where; - public Optional db; + public Optional db; public Optional number; // For Numbered citation styles. public Optional uniqueLetter; // For AuthorYear citation styles. public Optional normCitMarker; // For AuthorYear citation styles. @@ -44,7 +44,7 @@ public Optional getBibEntry() { * Implement CitationMarkerNormEntry */ @Override - public Optional getDatabaseLookupResult() { + public Optional getDatabaseLookupResult() { return db; } @@ -65,7 +65,7 @@ void addPath(CitationPath p, Citation cit) { } void lookupInDatabases(List databases) { - this.db = CitationDatabaseLookup.lookup(databases, this.citationKey); + this.db = Citation.lookup(databases, this.citationKey); } void distributeDatabaseLookupResult(CitationGroups cgs) { diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 373a98c7020..b5fdc959b2c 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -304,7 +304,7 @@ private static CitationMarkerEntry makeCitationMarkerEntry(String citationKey, boolean isFirstAppearanceOfSource) { Objects.requireNonNull(citationKey); Citation result = new Citation(citationKey); - result.setDatabaseLookupResult(Optional.of(new CitationDatabaseLookup.Result(entry, database))); + result.setDatabaseLookupResult(Optional.of(new CitationDatabaseLookupResult(entry, database))); result.setUniqueLetter(Optional.ofNullable(uniqueLetterQ)); Optional pageInfo = Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); result.setPageInfo(Citation.normalizePageInfo(pageInfo)); From 8145543953fb738fe7b26abe161a0ef4b83b2fb1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 20:14:16 +0200 Subject: [PATCH 0804/1068] CitationLookupResult --- .../logic/oostyle/OOBibStyleGetCitationMarker.java | 10 +++++----- src/main/java/org/jabref/model/oostyle/Citation.java | 12 ++++++------ ...seLookupResult.java => CitationLookupResult.java} | 4 ++-- .../model/oostyle/CitationMarkerNormEntry.java | 2 +- src/main/java/org/jabref/model/oostyle/CitedKey.java | 4 ++-- .../org/jabref/logic/oostyle/OOBibStyleTest.java | 4 ++-- 6 files changed, 18 insertions(+), 18 deletions(-) rename src/main/java/org/jabref/model/oostyle/{CitationDatabaseLookupResult.java => CitationLookupResult.java} (75%) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index bca0491014e..f77dcaa487b 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -13,7 +13,7 @@ import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationDatabaseLookupResult; +import org.jabref.model.oostyle.CitationLookupResult; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerNormEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; @@ -263,7 +263,7 @@ private static Optional getRawCitationMarkerField(BibEntry entr * */ private static String getCitationMarkerField(OOBibStyle style, - CitationDatabaseLookupResult db, + CitationLookupResult db, OrFields fields) { Objects.requireNonNull(db); @@ -289,7 +289,7 @@ private static String getCitationMarkerField(OOBibStyle style, return result; } - private static AuthorList getAuthorList(OOBibStyle style, CitationDatabaseLookupResult db) { + private static AuthorList getAuthorList(OOBibStyle style, CitationLookupResult db) { // The bibtex fields providing author names, e.g. "author" or // "editor". @@ -451,7 +451,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, } } else { - CitationDatabaseLookupResult db = ce.getDatabaseLookupResult().get(); + CitationLookupResult db = ce.getDatabaseLookupResult().get(); int maxAuthors = (purpose == AuthorYearMarkerPurpose.NORMALIZED ? style.getMaxAuthors() @@ -521,7 +521,7 @@ public String getCitationKey() { } @Override - public Optional getDatabaseLookupResult() { + public Optional getDatabaseLookupResult() { return inner.getDatabaseLookupResult(); } diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 406a555d798..227ad4c1de0 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -13,7 +13,7 @@ public class Citation implements ComparableCitation, CitationMarkerEntry { public final String citationKey; /** Result from database lookup. Optional.empty() if not found. */ - private Optional db; + private Optional db; /** The number used for numbered citation styles . */ private Optional number; @@ -61,11 +61,11 @@ public Optional getBibEntry() { : Optional.empty()); } - public static Optional lookup(List databases, String key) { + public static Optional lookup(List databases, String key) { for (BibDatabase database : databases) { Optional entry = database.getEntryByCitationKey(key); if (entry.isPresent()) { - return Optional.of(new CitationDatabaseLookupResult(entry.get(), database)); + return Optional.of(new CitationLookupResult(entry.get(), database)); } } return Optional.empty(); @@ -75,11 +75,11 @@ public void lookupInDatabases(List databases) { db = Citation.lookup(databases, citationKey); } - public Optional getDatabaseLookupResult() { + public Optional getDatabaseLookupResult() { return db; } - public void setDatabaseLookupResult(Optional db) { + public void setDatabaseLookupResult(Optional db) { this.db = db; } @@ -118,7 +118,7 @@ public void setIsFirstAppearanceOfSource(boolean value) { /* * Setters for CitationGroups.distribute() */ - public static void setDatabaseLookupResult(Pair> x) { + public static void setDatabaseLookupResult(Pair> x) { Citation cit = x.a; cit.db = x.b; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookupResult.java b/src/main/java/org/jabref/model/oostyle/CitationLookupResult.java similarity index 75% rename from src/main/java/org/jabref/model/oostyle/CitationDatabaseLookupResult.java rename to src/main/java/org/jabref/model/oostyle/CitationLookupResult.java index 5c4a22b1a89..f234a4cc848 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationDatabaseLookupResult.java +++ b/src/main/java/org/jabref/model/oostyle/CitationLookupResult.java @@ -5,12 +5,12 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -public class CitationDatabaseLookupResult { +public class CitationLookupResult { public final BibEntry entry; public final BibDatabase database; - public CitationDatabaseLookupResult(BibEntry entry, BibDatabase database) { + public CitationLookupResult(BibEntry entry, BibDatabase database) { Objects.requireNonNull(entry); Objects.requireNonNull(database); this.entry = entry; diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java index 19d548f543d..c0ca88d4524 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java @@ -19,5 +19,5 @@ public interface CitationMarkerNormEntry { /** Result of looking up citation key in databases. */ - Optional getDatabaseLookupResult(); + Optional getDatabaseLookupResult(); } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index 680807c60eb..bbe01020b44 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -10,7 +10,7 @@ public class CitedKey implements ComparableCitedKey, CitationMarkerNormEntry { public String citationKey; public LinkedHashSet where; - public Optional db; + public Optional db; public Optional number; // For Numbered citation styles. public Optional uniqueLetter; // For AuthorYear citation styles. public Optional normCitMarker; // For AuthorYear citation styles. @@ -44,7 +44,7 @@ public Optional getBibEntry() { * Implement CitationMarkerNormEntry */ @Override - public Optional getDatabaseLookupResult() { + public Optional getDatabaseLookupResult() { return db; } diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index b5fdc959b2c..a76e3919ea3 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -26,7 +26,7 @@ import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationDatabaseLookup; +import org.jabref.model.oostyle.CitationLookupResult; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOFormattedText; @@ -304,7 +304,7 @@ private static CitationMarkerEntry makeCitationMarkerEntry(String citationKey, boolean isFirstAppearanceOfSource) { Objects.requireNonNull(citationKey); Citation result = new Citation(citationKey); - result.setDatabaseLookupResult(Optional.of(new CitationDatabaseLookupResult(entry, database))); + result.setDatabaseLookupResult(Optional.of(new CitationLookupResult(entry, database))); result.setUniqueLetter(Optional.ofNullable(uniqueLetterQ)); Optional pageInfo = Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); result.setPageInfo(Citation.normalizePageInfo(pageInfo)); From 095207fcb963097d79294def518052fe92364cec Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 20:21:59 +0200 Subject: [PATCH 0805/1068] renames --- src/main/java/org/jabref/logic/oostyle/OOProcess.java | 4 ++-- .../java/org/jabref/logic/openoffice/EditSeparate.java | 4 ++-- src/main/java/org/jabref/model/oostyle/Citation.java | 4 ++-- src/main/java/org/jabref/model/oostyle/CitationGroup.java | 2 +- .../java/org/jabref/model/oostyle/CitationGroups.java | 8 ++++---- src/main/java/org/jabref/model/oostyle/CitedKey.java | 4 ++-- src/main/java/org/jabref/model/oostyle/CitedKeys.java | 4 ++-- .../java/org/jabref/logic/oostyle/OOBibStyleTest.java | 2 +- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index dfbc011ddda..9899d306fb6 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -74,8 +74,8 @@ public static void produceCitationMarkers(CitationGroups cgs, throw new RuntimeException("produceCitationMarkers: globalOrder is misssing in cgs"); } - cgs.lookupEntriesInDatabases(databases); - cgs.imposeLocalOrderByComparator(comparatorForMulticite(style)); + cgs.lookupCitations(databases); + cgs.imposeLocalOrder(comparatorForMulticite(style)); // fill CitationGroup.citationMarker if (style.isCitationKeyCiteMarkers()) { diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 8c9db2f72d8..d3dca25131c 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -50,8 +50,8 @@ public static boolean separateCitations(XTextDocument doc, // decide the visually last Citation i the group. Unless the // style changed since refresh this is the last on the screen // as well. - fr.citationGroups.lookupEntriesInDatabases(databases); - fr.citationGroups.imposeLocalOrderByComparator(OOProcess.comparatorForMulticite(style)); + fr.citationGroups.lookupCitations(databases); + fr.citationGroups.imposeLocalOrder(OOProcess.comparatorForMulticite(style)); List cgs = fr.citationGroups.getCitationGroupsUnordered(); diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 227ad4c1de0..55ab6be20db 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -79,7 +79,7 @@ public Optional getDatabaseLookupResult() { return db; } - public void setDatabaseLookupResult(Optional db) { + public void setLookupResult(Optional db) { this.db = db; } @@ -118,7 +118,7 @@ public void setIsFirstAppearanceOfSource(boolean value) { /* * Setters for CitationGroups.distribute() */ - public static void setDatabaseLookupResult(Pair> x) { + public static void setLookupResult(Pair> x) { Citation cit = x.a; cit.db = x.b; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index 86b65bf158f..bacf77c1524 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -92,7 +92,7 @@ public int numberOfCitations() { /** * Sort citations for presentation within a CitationGroup. */ - void imposeLocalOrderByComparator(Comparator entryComparator) { + void imposeLocalOrder(Comparator entryComparator) { // For JabRef52 the single pageInfo is always in the last-in-localorder citation. // We adjust here accordingly by taking it out and adding it back after sorting. diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 035fa735dcd..e54c8bbeb75 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -81,12 +81,12 @@ public void distributeToCitations(Set where, } } - public CitedKeys lookupEntriesInDatabases(List databases) { + public CitedKeys lookupCitations(List databases) { CitationGroups cgs = this; CitedKeys cks = cgs.getCitedKeysUnordered(); cks.lookupInDatabases(databases); - cks.distributeDatabaseLookupResults(cgs); + cks.distributeLookupResults(cgs); return cks; } @@ -118,9 +118,9 @@ public void setGlobalOrder(List globalOrder) { } } - public void imposeLocalOrderByComparator(Comparator entryComparator) { + public void imposeLocalOrder(Comparator entryComparator) { for (CitationGroup cg : citationGroupsUnordered.values()) { - cg.imposeLocalOrderByComparator(entryComparator); + cg.imposeLocalOrder(entryComparator); } } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index bbe01020b44..22b7e85648f 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -68,8 +68,8 @@ void lookupInDatabases(List databases) { this.db = Citation.lookup(databases, this.citationKey); } - void distributeDatabaseLookupResult(CitationGroups cgs) { - cgs.distributeToCitations(where, Citation::setDatabaseLookupResult, db); + void distributeLookupResult(CitationGroups cgs) { + cgs.distributeToCitations(where, Citation::setLookupResult, db); } void distributeNumber(CitationGroups cgs) { diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeys.java b/src/main/java/org/jabref/model/oostyle/CitedKeys.java index 38ec3c4baa1..937506b5bd7 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKeys.java @@ -58,9 +58,9 @@ public void lookupInDatabases(List databases) { } } - void distributeDatabaseLookupResults(CitationGroups cgs) { + void distributeLookupResults(CitationGroups cgs) { for (CitedKey ck : this.data.values()) { - ck.distributeDatabaseLookupResult(cgs); + ck.distributeLookupResult(cgs); } } diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index a76e3919ea3..acf10778ad9 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -304,7 +304,7 @@ private static CitationMarkerEntry makeCitationMarkerEntry(String citationKey, boolean isFirstAppearanceOfSource) { Objects.requireNonNull(citationKey); Citation result = new Citation(citationKey); - result.setDatabaseLookupResult(Optional.of(new CitationLookupResult(entry, database))); + result.setLookupResult(Optional.of(new CitationLookupResult(entry, database))); result.setUniqueLetter(Optional.ofNullable(uniqueLetterQ)); Optional pageInfo = Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); result.setPageInfo(Citation.normalizePageInfo(pageInfo)); From e2d27916d50ec172a18695920d85471b0cabf58b Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 20:31:07 +0200 Subject: [PATCH 0806/1068] getLookupResult --- .../oostyle/OOBibStyleGetCitationMarker.java | 16 ++++++++-------- .../java/org/jabref/model/oostyle/Citation.java | 2 +- .../model/oostyle/CitationMarkerNormEntry.java | 2 +- .../java/org/jabref/model/oostyle/CitedKey.java | 6 +++--- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index f77dcaa487b..d07986d9219 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -317,12 +317,12 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, CitationMarkerEntry ? style.getMaxAuthorsFirst() : style.getMaxAuthors()); - if (ce.getDatabaseLookupResult().isEmpty()) { + if (ce.getLookupResult().isEmpty()) { // unresolved return 0; } - AuthorList authorList = getAuthorList(style, ce.getDatabaseLookupResult().get()); + AuthorList authorList = getAuthorList(style, ce.getLookupResult().get()); int nAuthors = authorList.getNumberOfAuthors(); if (maxAuthors == -1) { @@ -443,7 +443,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, } } - final boolean isUnresolved = ce.getDatabaseLookupResult().isEmpty(); + final boolean isUnresolved = ce.getLookupResult().isEmpty(); if (isUnresolved) { sb.append(String.format("Unresolved(%s)", ce.getCitationKey())); if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { @@ -451,7 +451,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, } } else { - CitationLookupResult db = ce.getDatabaseLookupResult().get(); + CitationLookupResult db = ce.getLookupResult().get(); int maxAuthors = (purpose == AuthorYearMarkerPurpose.NORMALIZED ? style.getMaxAuthors() @@ -521,8 +521,8 @@ public String getCitationKey() { } @Override - public Optional getDatabaseLookupResult() { - return inner.getDatabaseLookupResult(); + public Optional getLookupResult() { + return inner.getLookupResult(); } @Override @@ -661,8 +661,8 @@ static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, final String nm1 = OOFormattedText.toString(normalizedMarkers.get(i - 1)); final String nm2 = OOFormattedText.toString(normalizedMarkers.get(i)); - final boolean isUnresolved1 = ce1.getDatabaseLookupResult().isEmpty(); - final boolean isUnresolved2 = ce2.getDatabaseLookupResult().isEmpty(); + final boolean isUnresolved1 = ce1.getLookupResult().isEmpty(); + final boolean isUnresolved2 = ce2.getLookupResult().isEmpty(); boolean startingNewGroup; boolean sameAsPrev; /* true indicates ce2 may be omitted from output */ diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 55ab6be20db..b1cdd6f3770 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -75,7 +75,7 @@ public void lookupInDatabases(List databases) { db = Citation.lookup(databases, citationKey); } - public Optional getDatabaseLookupResult() { + public Optional getLookupResult() { return db; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java index c0ca88d4524..91f7fc55b75 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java @@ -19,5 +19,5 @@ public interface CitationMarkerNormEntry { /** Result of looking up citation key in databases. */ - Optional getDatabaseLookupResult(); + Optional getLookupResult(); } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index 22b7e85648f..ae501af6a5b 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -19,7 +19,7 @@ public class CitedKey implements ComparableCitedKey, CitationMarkerNormEntry { this.citationKey = citationKey; this.where = new LinkedHashSet<>(); // remember order this.where.add(p); - this.db = cit.getDatabaseLookupResult(); + this.db = cit.getLookupResult(); this.number = cit.getNumber(); this.uniqueLetter = cit.getUniqueLetter(); this.normCitMarker = Optional.empty(); @@ -44,7 +44,7 @@ public Optional getBibEntry() { * Implement CitationMarkerNormEntry */ @Override - public Optional getDatabaseLookupResult() { + public Optional getLookupResult() { return db; } @@ -53,7 +53,7 @@ public Optional getDatabaseLookupResult() { */ void addPath(CitationPath p, Citation cit) { this.where.add(p); - if (cit.getDatabaseLookupResult() != this.db) { + if (cit.getLookupResult() != this.db) { throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); } if (cit.getNumber() != this.number) { From 063babf4d45cf77cded801e9319822b0515dd6ab Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 20:55:32 +0200 Subject: [PATCH 0807/1068] rename OOFormattedText to OOText --- .../org/jabref/logic/oostyle/OOBibStyle.java | 34 ++++----- .../oostyle/OOBibStyleGetCitationMarker.java | 48 ++++++------ .../OOBibStyleGetNumCitationMarker.java | 26 +++---- .../org/jabref/logic/oostyle/OOFormat.java | 24 +++--- .../logic/oostyle/OOFormatBibliography.java | 76 +++++++++---------- .../oostyle/OOProcessAuthorYearMarkers.java | 10 +-- .../oostyle/OOProcessCitationKeyMarkers.java | 4 +- .../oostyle/OOProcessNumericMarkers.java | 4 +- .../jabref/logic/openoffice/Backend52.java | 32 ++++---- .../jabref/logic/openoffice/EditInsert.java | 12 +-- .../jabref/logic/openoffice/EditMerge.java | 6 +- .../jabref/logic/openoffice/EditSeparate.java | 4 +- .../jabref/logic/openoffice/OOFrontend.java | 4 +- ...attedTextIntoOO.java => OOTextIntoOO.java} | 18 ++--- .../logic/openoffice/UpdateBibliography.java | 14 ++-- .../openoffice/UpdateCitationMarkers.java | 16 ++-- .../org/jabref/model/oostyle/Citation.java | 16 ++-- .../jabref/model/oostyle/CitationGroup.java | 8 +- .../model/oostyle/CitationMarkerEntry.java | 2 +- .../org/jabref/model/oostyle/CitedKey.java | 2 +- .../model/oostyle/ComparableCitation.java | 2 +- .../jabref/model/oostyle/CompareCitation.java | 6 +- .../org/jabref/model/oostyle/OODataModel.java | 6 +- .../{OOFormattedText.java => OOText.java} | 14 ++-- .../jabref/logic/oostyle/OOBibStyleTest.java | 12 +-- 25 files changed, 200 insertions(+), 200 deletions(-) rename src/main/java/org/jabref/logic/openoffice/{OOFormattedTextIntoOO.java => OOTextIntoOO.java} (98%) rename src/main/java/org/jabref/model/oostyle/{OOFormattedText.java => OOText.java} (67%) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 9869eaac910..66927057929 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -34,7 +34,7 @@ import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerNormEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -443,9 +443,9 @@ public Layout getReferenceFormat(EntryType type) { * @param number The citation numbers. * @return The text for the citation. */ - public OOFormattedText getNumCitationMarker(List number, + public OOText getNumCitationMarker(List number, int minGroupingCount, - List> pageInfosForCitations) { + List> pageInfosForCitations) { return OOBibStyleGetNumCitationMarker.getNumCitationMarker(this, number, minGroupingCount, @@ -866,8 +866,8 @@ protected String getOxfordComma() { /** * Title for the bibliography. */ - public OOFormattedText getReferenceHeaderText() { - return OOFormattedText.fromString(getStringProperty(OOBibStyle.TITLE)); + public OOText getReferenceHeaderText() { + return OOText.fromString(getStringProperty(OOBibStyle.TITLE)); } /** @@ -937,7 +937,7 @@ protected void setDefaultBibLayout(Layout l) { /** * Format a number-based bibliography label for the given number. */ - public OOFormattedText getNumCitationMarkerForBibliography(int number) { + public OOText getNumCitationMarkerForBibliography(int number) { return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, number); } @@ -949,11 +949,11 @@ public OOFormattedText getNumCitationMarkerForBibliography(int number) { * As a special case: pageInfosForCitations may be null. In this case * the result is a list filled with Optional.empty() values. */ - public static List> - regularizePageInfosForCitations(List> pageInfosForCitations, + public static List> + regularizePageInfosForCitations(List> pageInfosForCitations, int nCitations) { if (pageInfosForCitations == null) { - List> res = new ArrayList<>(nCitations); + List> res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { res.add(Optional.empty()); } @@ -963,16 +963,16 @@ public OOFormattedText getNumCitationMarkerForBibliography(int number) { throw new RuntimeException("regularizePageInfosForCitations:" + " pageInfosForCitations.size() != nCitations"); } - List> res = new ArrayList<>(nCitations); + List> res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { - Optional p = pageInfosForCitations.get(i); + Optional p = pageInfosForCitations.get(i); res.add(Citation.normalizePageInfo(p)); } return res; } } - public OOFormattedText getNormalizedCitationMarker(CitationMarkerNormEntry ce) { + public OOText getNormalizedCitationMarker(CitationMarkerNormEntry ce) { return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, ce, Optional.empty()); } @@ -1007,7 +1007,7 @@ public OOFormattedText getNormalizedCitationMarker(CitationMarkerNormEntry ce) { * OOFormat.setLocaleNone() and OOFormat.setCharStyle(). * These are added by decorateCitationMarker() */ - public OOFormattedText getCitationMarker2(List citationMarkerEntries, + public OOText getCitationMarker2(List citationMarkerEntries, boolean inParenthesis, NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { return OOBibStyleGetCitationMarker.getCitationMarker2(this, @@ -1021,9 +1021,9 @@ public OOFormattedText getCitationMarker2(List citationMark * citationText. Called in fillCitationMarkInCursor, so these are * also applied to "Unresolved()" entries and numeric styles. */ - public OOFormattedText decorateCitationMarker(OOFormattedText citationText) { + public OOText decorateCitationMarker(OOText citationText) { OOBibStyle style = this; - OOFormattedText citationText2 = OOFormat.setLocaleNone(citationText); + OOText citationText2 = OOFormat.setLocaleNone(citationText); if (style.isFormatCitations()) { String charStyle = style.getCitationCharacterFormat(); citationText2 = OOFormat.setCharStyle(citationText2, charStyle); @@ -1210,9 +1210,9 @@ private String nullToEmpty(String s) { return (s == null ? "" : s); } - public OOFormattedText getFormattedBibliographyTitle() { + public OOText getFormattedBibliographyTitle() { OOBibStyle style = this; - OOFormattedText title = style.getReferenceHeaderText(); + OOText title = style.getReferenceHeaderText(); String parStyle = style.getReferenceHeaderParagraphFormat(); if (parStyle != null) { title = OOFormat.paragraph(title, parStyle); diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index d07986d9219..292de0f6e37 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -17,7 +17,7 @@ import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerNormEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.jabref.model.strings.StringUtil; class OOBibStyleGetCitationMarker { @@ -368,11 +368,11 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, CitationMarkerEntry * @return The formatted citation. * */ - private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, - AuthorYearMarkerPurpose purpose, - List ces, - boolean[] startsNewGroup, - Optional maxAuthorsOverride) { + private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, + AuthorYearMarkerPurpose purpose, + List ces, + boolean[] startsNewGroup, + Optional maxAuthorsOverride) { boolean inParenthesis = (purpose == AuthorYearMarkerPurpose.IN_PARENTHESIS || purpose == AuthorYearMarkerPurpose.NORMALIZED); @@ -435,11 +435,11 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, StringBuilder pageInfoPart = new StringBuilder(""); if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { - Optional pageInfo = + Optional pageInfo = Citation.normalizePageInfo(ce.getPageInfo()); if (pageInfo.isPresent()) { pageInfoPart.append(pageInfoSeparator); - pageInfoPart.append(OOFormattedText.toString(pageInfo.get())); + pageInfoPart.append(OOText.toString(pageInfo.get())); } } @@ -496,7 +496,7 @@ private static OOFormattedText getAuthorYearParenthesisMarker2(OOBibStyle style, sb.append(endBrace); // shared parenthesis } sb.append(style.getCitationGroupMarkupAfter()); - return OOFormattedText.fromString(sb.toString()); + return OOText.fromString(sb.toString()); } // "" is more convenient to compare for equality than null-or-String @@ -531,7 +531,7 @@ public Optional getUniqueLetter() { } @Override - public Optional getPageInfo() { + public Optional getPageInfo() { return Optional.empty(); } @@ -551,9 +551,9 @@ public boolean getIsFirstAppearanceOfSource() { * * Note: now includes some markup. */ - static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, - CitationMarkerNormEntry cne, - Optional maxAuthorsOverride) { + static OOText getNormalizedCitationMarker(OOBibStyle style, + CitationMarkerNormEntry cne, + Optional maxAuthorsOverride) { boolean[] startsNewGroup = {true}; CitationMarkerEntry ce = new CitationMarkerNormEntryWrap(cne); return getAuthorYearParenthesisMarker2(style, @@ -563,14 +563,14 @@ static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, maxAuthorsOverride); } - private static List + private static List getNormalizedCitationMarkers(OOBibStyle style, List citationMarkerEntries, Optional maxAuthorsOverride) { - List normalizedMarkers = new ArrayList<>(citationMarkerEntries.size()); + List normalizedMarkers = new ArrayList<>(citationMarkerEntries.size()); for (CitationMarkerEntry citationMarkerEntry : citationMarkerEntries) { - OOFormattedText nm = getNormalizedCitationMarker(style, + OOText nm = getNormalizedCitationMarker(style, citationMarkerEntry, maxAuthorsOverride); normalizedMarkers.add(nm); @@ -607,7 +607,7 @@ static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, * Note: only consecutive citations are checked. * */ - public static OOFormattedText + public static OOText getCitationMarker2(OOBibStyle style, List citationMarkerEntries, boolean inParenthesis, @@ -630,7 +630,7 @@ static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, // We also assume, that identical entries have the same uniqueLetters. // - List normalizedMarkers = getNormalizedCitationMarkers(style, + List normalizedMarkers = getNormalizedCitationMarkers(style, citationMarkerEntries, Optional.empty()); @@ -658,8 +658,8 @@ static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, final CitationMarkerEntry ce1 = citationMarkerEntries.get(i - 1); final CitationMarkerEntry ce2 = citationMarkerEntries.get(i); - final String nm1 = OOFormattedText.toString(normalizedMarkers.get(i - 1)); - final String nm2 = OOFormattedText.toString(normalizedMarkers.get(i)); + final String nm1 = OOText.toString(normalizedMarkers.get(i - 1)); + final String nm2 = OOText.toString(normalizedMarkers.get(i)); final boolean isUnresolved1 = ce1.getLookupResult().isEmpty(); final boolean isUnresolved2 = ce2.getLookupResult().isEmpty(); @@ -703,9 +703,9 @@ static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, } else { // prevShown >= need // Check with extended normalizedMarkers. - OOFormattedText nmx1 = + OOText nmx1 = getNormalizedCitationMarker(style, ce1, Optional.of(prevShown)); - OOFormattedText nmx2 = + OOText nmx2 = getNormalizedCitationMarker(style, ce2, Optional.of(prevShown)); boolean extendedMarkersDiffer = !nmx2.equals(nmx1); nAuthorsShownInhibitsJoin = extendedMarkersDiffer; @@ -716,8 +716,8 @@ static OOFormattedText getNormalizedCitationMarker(OOBibStyle style, final boolean citationKeysDiffer = !ce2.getCitationKey().equals(ce1.getCitationKey()); final boolean normalizedMarkersDiffer = !nm2.equals(nm1); - Optional pageInfo2 = Citation.normalizePageInfo(ce2.getPageInfo()); - Optional pageInfo1 = Citation.normalizePageInfo(ce1.getPageInfo()); + Optional pageInfo2 = Citation.normalizePageInfo(ce2.getPageInfo()); + Optional pageInfo1 = Citation.normalizePageInfo(ce1.getPageInfo()); final boolean bothPageInfosAreEmpty = pageInfo2.isEmpty() && pageInfo1.isEmpty(); final boolean pageInfosDiffer = !pageInfo2.equals(pageInfo1); diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index 81604783b4f..476d0316df9 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -7,7 +7,7 @@ import java.util.function.ToIntFunction; import org.jabref.model.oostyle.CompareCitation; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; class OOBibStyleGetNumCitationMarker { @@ -17,8 +17,8 @@ class OOBibStyleGetNumCitationMarker { */ private static class NumberWithPageInfo { int num; - Optional pageInfo; - NumberWithPageInfo(int num, Optional pageInfo) { + Optional pageInfo; + NumberWithPageInfo(int num, Optional pageInfo) { this.num = num; this.pageInfo = pageInfo; } @@ -47,10 +47,10 @@ private enum CitationMarkerPurpose { /** * See {@see getNumCitationMarkerCommon} for details. */ - public static OOFormattedText getNumCitationMarker(OOBibStyle style, + public static OOText getNumCitationMarker(OOBibStyle style, List numbers, int minGroupingCount, - List> pageInfosForCitations) { + List> pageInfosForCitations) { return getNumCitationMarkerCommon(style, numbers, minGroupingCount, @@ -71,7 +71,7 @@ public static OOFormattedText getNumCitationMarker(OOBibStyle style, * "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER) * "${number}" stands for the formatted number. */ - public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle style, + public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, int number) { return getNumCitationMarkerCommon(style, Collections.singletonList(number), @@ -120,12 +120,12 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty * @return The text for the citation. * */ - private static OOFormattedText + private static OOText getNumCitationMarkerCommon(OOBibStyle style, List numbers, int minGroupingCount, CitationMarkerPurpose purpose, - List> pageInfosForCitations) { + List> pageInfosForCitations) { final boolean joinIsDisabled = (minGroupingCount <= 0); final int notFoundInDatabases = 0; @@ -171,7 +171,7 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty : OOBibStyle.UNDEFINED_CITATION_MARKER); sb.append(bracketAfter); sb.append(style.getCitationGroupMarkupAfter()); - return OOFormattedText.fromString(sb.toString()); + return OOText.fromString(sb.toString()); } } @@ -184,7 +184,7 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty * get here, and {@code purpose==BIBLIOGRAPHY}, then we just fill * pageInfos with null values. */ - List> pageInfos = + List> pageInfos = OOBibStyle.regularizePageInfosForCitations((purpose == CitationMarkerPurpose.BIBLIOGRAPHY ? null : pageInfosForCitations), @@ -249,10 +249,10 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty ? OOBibStyle.UNDEFINED_CITATION_MARKER : String.valueOf(num)); // Emit pageInfo - Optional pageInfo = block.get(0).pageInfo; + Optional pageInfo = block.get(0).pageInfo; if (pageInfo.isPresent()) { sb.append(style.getPageInfoSeparator()); - sb.append(OOFormattedText.toString(pageInfo.get())); + sb.append(OOText.toString(pageInfo.get())); } } else { // block has at least 2 elements @@ -385,7 +385,7 @@ public static OOFormattedText getNumCitationMarkerForBibliography(OOBibStyle sty // Emit: "]" sb.append(bracketAfter); - return OOFormattedText.fromString(sb.toString()); + return OOText.fromString(sb.toString()); } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index fb77c13d4ae..d45be75b20f 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -1,6 +1,6 @@ package org.jabref.logic.oostyle; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; public class OOFormat { @@ -17,8 +17,8 @@ public class OOFormat { * vendor and browser-specific", so probably best to avoid them if possible. * */ - public static OOFormattedText setLocale(OOFormattedText s, String locale) { - return OOFormattedText.fromString(String.format("", locale) + public static OOText setLocale(OOText s, String locale) { + return OOText.fromString(String.format("", locale) + s.asString() + ""); } @@ -30,7 +30,7 @@ public static OOFormattedText setLocale(OOFormattedText s, String locale) { * Used around citation marks, probably to turn off spellchecking. * */ - public static OOFormattedText setLocaleNone(OOFormattedText s) { + public static OOText setLocaleNone(OOText s) { return OOFormat.setLocale(s, "zxx"); } @@ -41,8 +41,8 @@ public static OOFormattedText setLocaleNone(OOFormattedText s) { * empty for "Standard", which in turn means do not override any properties. * */ - public static OOFormattedText setCharStyle(OOFormattedText s, String charStyle) { - return OOFormattedText.fromString(String.format("", charStyle) + public static OOText setCharStyle(OOText s, String charStyle) { + return OOText.fromString(String.format("", charStyle) + s.asString() + ""); } @@ -50,11 +50,11 @@ public static OOFormattedText setCharStyle(OOFormattedText s, String charStyle) /** * Mark {@code s} as part of a paragraph with style {@code paraStyle} */ - public static OOFormattedText paragraph(OOFormattedText s, String paraStyle) { + public static OOText paragraph(OOText s, String paraStyle) { if (paraStyle == null || "".equals(paraStyle)) { return paragraph(s); } - return OOFormattedText.fromString(String.format("

", paraStyle) + return OOText.fromString(String.format("

", paraStyle) + s.asString() + "

"); } @@ -62,15 +62,15 @@ public static OOFormattedText paragraph(OOFormattedText s, String paraStyle) { /** * Mark {@code s} as part of a paragraph. */ - public static OOFormattedText paragraph(OOFormattedText s) { - return OOFormattedText.fromString("

" + public static OOText paragraph(OOText s) { + return OOText.fromString("

" + s.asString() + "

"); } - public static OOFormattedText formatReferenceToPageNumberOfReferenceMark(String referencMarkName) { + public static OOText formatReferenceToPageNumberOfReferenceMark(String referencMarkName) { String s = String.format("", referencMarkName); - return OOFormattedText.fromString(s); + return OOText.fromString(s); } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index 7147c2945ff..6b0cddab0a4 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -16,7 +16,7 @@ import org.jabref.model.oostyle.CitationPath; import org.jabref.model.oostyle.CitedKey; import org.jabref.model.oostyle.CitedKeys; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; public class OOFormatBibliography { private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); @@ -28,11 +28,11 @@ private OOFormatBibliography() { /* * @return just the body. No label, "Cited on pages" or paragraph. */ - public static OOFormattedText formatBibliographyEntryBody(CitedKey ck, - OOBibStyle style) { + public static OOText formatBibliographyEntryBody(CitedKey ck, + OOBibStyle style) { if (ck.db.isEmpty()) { // Unresolved entry - return OOFormattedText.fromString(String.format("Unresolved(%s)", ck.citationKey)); + return OOText.fromString(String.format("Unresolved(%s)", ck.citationKey)); } else { // Resolved entry, use the layout engine BibEntry bibentry = ck.db.get().entry; @@ -49,10 +49,10 @@ public static OOFormattedText formatBibliographyEntryBody(CitedKey ck, /* * @return a paragraph. Includes label and "Cited on pages". */ - public static OOFormattedText formatBibliographyEntry(CitationGroups cgs, - CitedKey ck, - OOBibStyle style, - boolean alwaysAddCitedOnPages) { + public static OOText formatBibliographyEntry(CitationGroups cgs, + CitedKey ck, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { StringBuilder sb = new StringBuilder(); // insert marker "[1]" @@ -64,7 +64,7 @@ public static OOFormattedText formatBibliographyEntry(CitationGroups cgs, } int number = ck.number.get(); - OOFormattedText marker = style.getNumCitationMarkerForBibliography(number); + OOText marker = style.getNumCitationMarkerForBibliography(number); sb.append(marker.asString()); } else { // !style.isNumberEntries() : emit no prefix @@ -72,7 +72,7 @@ public static OOFormattedText formatBibliographyEntry(CitationGroups cgs, } // Add entry body - OOFormattedText formattedText = formatBibliographyEntryBody(ck, style); + OOText formattedText = formatBibliographyEntryBody(ck, style); sb.append(formattedText.asString()); // Add "Cited on pages" @@ -87,7 +87,7 @@ public static OOFormattedText formatBibliographyEntry(CitationGroups cgs, } // Add paragraph - OOFormattedText entryText = OOFormattedText.fromString(sb.toString()); + OOText entryText = OOText.fromString(sb.toString()); String parStyle = style.getReferenceParagraphFormat(); return OOFormat.paragraph(entryText, parStyle); } @@ -95,10 +95,10 @@ public static OOFormattedText formatBibliographyEntry(CitationGroups cgs, /** * Format body of bibliography. */ - public static OOFormattedText formatBibliographyBody(CitationGroups cgs, - CitedKeys bibliography, - OOBibStyle style, - boolean alwaysAddCitedOnPages) { + public static OOText formatBibliographyBody(CitationGroups cgs, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { final boolean debugThisFun = false; @@ -120,27 +120,27 @@ public static OOFormattedText formatBibliographyBody(CitationGroups cgs, : String.format("%02d", ck.number.get()))); } - OOFormattedText entryText = formatBibliographyEntry(cgs, ck, style, alwaysAddCitedOnPages); + OOText entryText = formatBibliographyEntry(cgs, ck, style, alwaysAddCitedOnPages); // Add full entry to bibliography. stringBuilder.append(entryText.asString()); } // for CitedKey - OOFormattedText full = OOFormattedText.fromString(stringBuilder.toString()); + OOText full = OOText.fromString(stringBuilder.toString()); return full; } - public static OOFormattedText formatBibliography(CitationGroups cgs, - CitedKeys bibliography, - OOBibStyle style, - boolean alwaysAddCitedOnPages) { - - OOFormattedText title = style.getFormattedBibliographyTitle(); - OOFormattedText body = OOFormatBibliography.formatBibliographyBody(cgs, - bibliography, - style, - alwaysAddCitedOnPages); - return OOFormattedText.fromString(title.asString() + body.asString()); + public static OOText formatBibliography(CitationGroups cgs, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { + + OOText title = style.getFormattedBibliographyTitle(); + OOText body = OOFormatBibliography.formatBibliographyBody(cgs, + bibliography, + style, + alwaysAddCitedOnPages); + return OOText.fromString(title.asString() + body.asString()); } /** @@ -151,12 +151,12 @@ public static OOFormattedText formatBibliography(CitationGroups cgs, * @param database The database the entry belongs to. * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. * - * @return OOFormattedText suitable for insertOOFormattedTextAtCurrentLocation2() + * @return OOText suitable for OOTextIntoOO.write() */ - private static OOFormattedText formatFullReferenceOfBibEbtry(Layout layout, - BibEntry entry, - BibDatabase database, - String uniquefier) { + private static OOText formatFullReferenceOfBibEbtry(Layout layout, + BibEntry entry, + BibDatabase database, + String uniquefier) { // Backup the value of the uniq field, just in case the entry already has it: Optional oldUniqVal = entry.getField(UNIQUEFIER_FIELD); @@ -169,7 +169,7 @@ private static OOFormattedText formatFullReferenceOfBibEbtry(Layout layout, } // Do the layout for this entry: - OOFormattedText formattedText = OOFormattedText.fromString(layout.doLayout(entry, database)); + OOText formattedText = OOText.fromString(layout.doLayout(entry, database)); // Afterwards, reset the old value: if (oldUniqVal.isPresent()) { @@ -181,9 +181,9 @@ private static OOFormattedText formatFullReferenceOfBibEbtry(Layout layout, return formattedText; } - private static OOFormattedText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { + private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { if (!cgs.citationGroupsProvideReferenceMarkNameForLinking()) { - return OOFormattedText.fromString(""); + return OOText.fromString(""); } // Format links to citations. @@ -223,13 +223,13 @@ private static OOFormattedText formatCitedOnPages(CitationGroups cgs, CitedKey c } String referenceMarkName = (cg.getReferenceMarkNameForLinking() .orElseThrow(RuntimeException::new)); - OOFormattedText xref = + OOText xref = OOFormat.formatReferenceToPageNumberOfReferenceMark(referenceMarkName); sb.append(xref.asString()); i++; } sb.append(suffix); - return OOFormattedText.fromString(sb.toString()); + return OOText.fromString(sb.toString()); } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java index 9c94b907fa7..9811822d679 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java @@ -17,7 +17,7 @@ import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.ListUtil; import org.jabref.model.oostyle.NonUniqueCitationMarker; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; class OOProcessAuthorYearMarkers { @@ -57,7 +57,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup // Map> normCitMarkerToClachingKeys = new HashMap<>(); for (CitedKey citedKey : sortedCitedKeys.values()) { - String normCitMarker = OOFormattedText.toString(citedKey.normCitMarker.get()); + String normCitMarker = OOText.toString(citedKey.normCitMarker.get()); String citationKey = citedKey.citationKey; if (!normCitMarkerToClachingKeys.containsKey(normCitMarker)) { @@ -153,9 +153,9 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { List cits = cg.getCitationsInLocalOrder(); List citationMarkerEntries = ListUtil.map(cits, e -> e); - OOFormattedText citMarker = style.getCitationMarker2(citationMarkerEntries, - inParenthesis, - strictlyUnique); + OOText citMarker = style.getCitationMarker2(citationMarkerEntries, + inParenthesis, + strictlyUnique); cg.setCitationMarker(Optional.of(citMarker)); } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java index 4c644638ba1..f3dcd48551f 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java @@ -6,7 +6,7 @@ import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.ListUtil; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; class OOProcessCitationKeyMarkers { /** @@ -24,7 +24,7 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { style.getCitationGroupMarkupBefore() + String.join(",", ListUtil.map(cg.getCitationsInLocalOrder(), Citation::getCitationKey)) + style.getCitationGroupMarkupAfter(); - cg.setCitationMarker(Optional.of(OOFormattedText.fromString(citMarker))); + cg.setCitationMarker(Optional.of(OOText.fromString(citMarker))); } } } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java index 10724a8325f..a88c68de1d1 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java @@ -7,7 +7,7 @@ import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.ListUtil; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; class OOProcessNumericMarkers { @@ -37,7 +37,7 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { List cits = cg.getCitationsInLocalOrder(); - OOFormattedText citMarker = + OOText citMarker = style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), minGroupingCount, ListUtil.map(cits, Citation::getPageInfo)); diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 004fdcad63e..32bdc8605d1 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -14,7 +14,7 @@ import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OODataModel; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -104,7 +104,7 @@ public Optional healthReport(XTextDocument doc) } private static void setPageInfoInDataInitial(List citations, - Optional pageInfo) { + Optional pageInfo) { // attribute to last citation (initially localOrder == storageOrder) if (citations.size() > 0) { citations.get(citations.size() - 1).setPageInfo(pageInfo); @@ -112,14 +112,14 @@ private static void setPageInfoInDataInitial(List citations, } private static void setPageInfoInData(CitationGroup cg, - Optional pageInfo) { + Optional pageInfo) { List citations = cg.getCitationsInLocalOrder(); if (citations.size() > 0) { citations.get(citations.size() - 1).setPageInfo(pageInfo); } } - private static Optional getPageInfoFromData(CitationGroup cg) { + private static Optional getPageInfoFromData(CitationGroup cg) { List citations = cg.getCitationsInLocalOrder(); if (citations.size() > 0) { return citations.get(citations.size() - 1).getPageInfo(); @@ -148,9 +148,9 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str .map(Citation::new) .collect(Collectors.toList())); - Optional pageInfo = + Optional pageInfo = (UnoUserDefinedProperty.getStringValue(doc, refMarkName) - .map(OOFormattedText::fromString)); + .map(OOText::fromString)); pageInfo = Citation.normalizePageInfo(pageInfo); setPageInfoInDataInitial(citations, pageInfo); @@ -186,7 +186,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str */ public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, - List> pageInfosForCitations, + List> pageInfosForCitations, InTextCitationType citationType, XTextCursor position, boolean insertSpaceAfter) @@ -220,7 +220,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, Citation cit = new Citation(citationKeys.get(i)); citations.add(cit); - Optional pageInfo = Citation.normalizePageInfo(pageInfosForCitations.get(i)); + Optional pageInfo = Citation.normalizePageInfo(pageInfosForCitations.get(i)); switch (dataModel) { case JabRef52: if (i == last) { @@ -248,11 +248,11 @@ public CitationGroup createCitationGroup(XTextDocument doc, switch (dataModel) { case JabRef52: - Optional pageInfo = + Optional pageInfo = Citation.normalizePageInfo(pageInfosForCitations.get(last)); if (pageInfo.isPresent()) { - String pageInfoString = OOFormattedText.toString(pageInfo.get()); + String pageInfoString = OOText.toString(pageInfo.get()); UnoUserDefinedProperty.createStringProperty(doc, refMarkName, pageInfoString); } else { // do not inherit from trash @@ -274,12 +274,12 @@ public CitationGroup createCitationGroup(XTextDocument doc, * TODO: JabRef52 combinePageInfos is not reversible. Should warn * user to check the result. Or ask what to do. */ - public static List> + public static List> combinePageInfosCommon(OODataModel dataModel, List joinableGroup) { switch (dataModel) { case JabRef52: // collect to cgPageInfos - List> cgPageInfos = + List> cgPageInfos = (joinableGroup.stream() .map(cg -> getPageInfoFromData(cg)) .collect(Collectors.toList())); @@ -287,7 +287,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, // Try to do something of the cgPageInfos. String cgPageInfo = (cgPageInfos.stream() .filter(pi -> pi.isPresent()) - .map(pi -> OOFormattedText.toString(pi.get())) + .map(pi -> OOText.toString(pi.get())) .distinct() .collect(Collectors.joining("; "))); @@ -312,7 +312,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, /** * */ - public List> combinePageInfos(List joinableGroup) { + public List> combinePageInfos(List joinableGroup) { return combinePageInfosCommon(this.dataModel, joinableGroup); } @@ -395,7 +395,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups String context = OOUtil.getCursorStringWithContext(cursor, 30, 30, true); Optional pageInfo = (cg.numberOfCitations() > 0 ? (getPageInfoFromData(cg) - .map(e -> OOFormattedText.toString(e))) + .map(e -> OOText.toString(e))) : Optional.empty()); CitationEntry entry = new CitationEntry(name, context, pageInfo); citations.add(entry); @@ -426,7 +426,7 @@ public void applyCitationEntries(XTextDocument doc, List citation switch (dataModel) { case JabRef52: for (CitationEntry entry : citationEntries) { - Optional pageInfo = entry.getPageInfo().map(OOFormattedText::fromString); + Optional pageInfo = entry.getPageInfo().map(OOText::fromString); pageInfo = Citation.normalizePageInfo(pageInfo); if (pageInfo.isPresent()) { String name = entry.getRefMarkName(); diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 98dbac82956..4d730ce601e 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -15,7 +15,7 @@ import org.jabref.model.oostyle.ListUtil; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OODataModel; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -88,7 +88,7 @@ public static void insertCitationGroup(XTextDocument doc, final int nEntries = entries.size(); // JabRef53 style pageInfo list - List> pageInfosForCitations = + List> pageInfosForCitations = OODataModel.fakePageInfosForCitations(pageInfo, nEntries); List citations = new ArrayList<>(nEntries); @@ -100,15 +100,15 @@ public static void insertCitationGroup(XTextDocument doc, } // The text we insert - OOFormattedText citeText = + OOText citeText = (style.isNumberEntries() - ? OOFormattedText.fromString("[-]") // A dash only. Only refresh later. + ? OOText.fromString("[-]") // A dash only. Only refresh later. : style.getCitationMarker2(citations, citationType.inParenthesis(), NonUniqueCitationMarker.FORGIVEN)); - if ("".equals(OOFormattedText.toString(citeText))) { - citeText = OOFormattedText.fromString("[?]"); + if ("".equals(OOText.toString(citeText))) { + citeText = OOText.fromString("[?]"); } UpdateCitationMarkers.createAndFillCitationGroup(fr, diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 2cc93ac6250..c0113c5a53c 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -12,7 +12,7 @@ import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -338,7 +338,7 @@ public static boolean mergeCitationGroups(XTextDocument doc, // cgPageInfos belong to the CitationGroup (DataModel JabRef52), // but it is not clear how should we handle them here. // We delegate the problem to the backend. - List> pageInfosForCitations = + List> pageInfosForCitations = fr.backend.combinePageInfos(cgs); // Remove the old citation groups from the document. @@ -362,7 +362,7 @@ public static boolean mergeCitationGroups(XTextDocument doc, citationKeys, pageInfosForCitations, citationType, - OOFormattedText.fromString("tmp"), + OOText.fromString("tmp"), textCursor, style, insertSpaceAfter); diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index d3dca25131c..173961c0d9d 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -8,7 +8,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -85,7 +85,7 @@ public static boolean separateCitations(XTextDocument doc, List.of(cit.citationKey), List.of(cit.getPageInfo()), cg.citationType, - OOFormattedText.fromString(cit.citationKey), + OOText.fromString(cit.citationKey), textCursor, style, insertSpaceAfter); diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index ba32aaa5856..e765f119c0f 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -16,7 +16,7 @@ import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OODataModel; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -253,7 +253,7 @@ public Optional healthReport(XTextDocument doc) */ public CitationGroupID createCitationGroup(XTextDocument doc, List citationKeys, - List> pageInfosForCitations, + List> pageInfosForCitations, InTextCitationType citationType, XTextCursor position, boolean insertSpaceAfter) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java rename to src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 8160fb463e6..7a348ac7613 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFormattedTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -13,7 +13,7 @@ import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.Pair; @@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory; /** - * Interpret OOFormattedText into an OpenOffice or LibreOffice writer + * Interpret OOText into an OpenOffice or LibreOffice writer * document. * * On the question of what should it understand: apart from what @@ -61,9 +61,9 @@ * */ @AllowedToUseAwt("Requires AWT for changing document properties") -public class OOFormattedTextIntoOO { +public class OOTextIntoOO { - private static final Logger LOGGER = LoggerFactory.getLogger(OOFormattedTextIntoOO.class); + private static final Logger LOGGER = LoggerFactory.getLogger(OOTextIntoOO.class); /** * "ParaStyleName" is an OpenOffice Property name. @@ -103,7 +103,7 @@ public class OOFormattedTextIntoOO { private static final Pattern ATTRIBUTE_PATTERN = Pattern.compile("\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP); - private OOFormattedTextIntoOO() { + private OOTextIntoOO() { // Just to hide the public constructor } @@ -509,7 +509,7 @@ Optional getPropertyValue(String name) { */ public static void write(XTextDocument doc, XTextCursor position, - OOFormattedText ootext) + OOText ootext) throws UnknownPropertyException, PropertyVetoException, @@ -520,7 +520,7 @@ public static void write(XTextDocument doc, final boolean debugThisFun = false; - String lText = OOFormattedText.toString(ootext); + String lText = OOText.toString(ootext); if (debugThisFun) { System.out.println(lText); @@ -704,7 +704,7 @@ public static void write(XTextDocument doc, for (String s : expectEnd) { rest = String.format("<%s>", s) + rest; } - LOGGER.warn(String.format("insertOOFormattedTextAtCurrentLocation2:" + LOGGER.warn(String.format("OOTextIntoOO.write:" + " expectEnd stack is not empty at the end: %s%n", rest)); } @@ -774,7 +774,7 @@ public static void removeDirectFormatting(XTextCursor cursor) { if (knownToFail.contains(p.Name)) { continue; } - LOGGER.warn(String.format("OOFormattedTextIntoOO.removeDirectFormatting failed on '%s'", + LOGGER.warn(String.format("OOTextIntoOO.removeDirectFormatting failed on '%s'", p.Name)); } } diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java index 0f71793f098..10799c83e37 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -5,7 +5,7 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOFormatBibliography; import org.jabref.model.oostyle.CitedKeys; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -119,12 +119,12 @@ private static void populateBibTextSection(XTextDocument doc, XTextCursor cursor = doc.getText().createTextCursorByRange(section.getAnchor()); // emit the title of the bibliography - OOFormattedTextIntoOO.removeDirectFormatting(cursor); - OOFormattedText bibliographyText = OOFormatBibliography.formatBibliography(fr.citationGroups, - bibliography, - style, - alwaysAddCitedOnPages); - OOFormattedTextIntoOO.write(doc, cursor, bibliographyText); + OOTextIntoOO.removeDirectFormatting(cursor); + OOText bibliographyText = OOFormatBibliography.formatBibliography(fr.citationGroups, + bibliography, + style, + alwaysAddCitedOnPages); + OOTextIntoOO.write(doc, cursor, bibliographyText); cursor.collapseToEnd(); // remove the inital empty paragraph from the section. diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 94cd9646efa..179caba51d6 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -10,7 +10,7 @@ import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -62,7 +62,7 @@ static void applyNewCitationMarkers(XTextDocument doc, for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { boolean withText = (cg.citationType != InTextCitationType.INVISIBLE_CIT); - Optional marker = cg.getCitationMarker(); + Optional marker = cg.getCitationMarker(); if (!marker.isPresent()) { String msg = String.format("applyNewCitationMarkers: no marker for %s", @@ -85,7 +85,7 @@ static void applyNewCitationMarkers(XTextDocument doc, public static void fillCitationMarkInCursor(XTextDocument doc, XTextCursor cursor, - OOFormattedText citationText, + OOText citationText, boolean withText, OOBibStyle style) throws @@ -101,11 +101,11 @@ public static void fillCitationMarkInCursor(XTextDocument doc, Objects.requireNonNull(style); if (withText) { - OOFormattedText citationText2 = style.decorateCitationMarker(citationText); + OOText citationText2 = style.decorateCitationMarker(citationText); // inject a ZERO_WIDTH_SPACE to hold the initial character format final String ZERO_WIDTH_SPACE = "\u200b"; - citationText2 = OOFormattedText.fromString(ZERO_WIDTH_SPACE + citationText2.asString()); - OOFormattedTextIntoOO.write(doc, cursor, citationText2); + citationText2 = OOText.fromString(ZERO_WIDTH_SPACE + citationText2.asString()); + OOTextIntoOO.write(doc, cursor, citationText2); } else { cursor.setString(""); } @@ -131,9 +131,9 @@ public static void fillCitationMarkInCursor(XTextDocument doc, public static void createAndFillCitationGroup(OOFrontend fr, XTextDocument doc, List citationKeys, - List> pageInfosForCitations, + List> pageInfosForCitations, InTextCitationType citationType, - OOFormattedText citationText, + OOText citationText, XTextCursor position, OOBibStyle style, boolean insertSpaceAfter) diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index b1cdd6f3770..f7fd3f75048 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -22,7 +22,7 @@ public class Citation implements ComparableCitation, CitationMarkerEntry { private Optional uniqueLetter; /** pageInfo */ - private Optional pageInfo; + private Optional pageInfo; /** isFirstAppearanceOfSource */ private boolean isFirstAppearanceOfSource; @@ -45,7 +45,7 @@ public String getCitationKey() { } @Override - public Optional getPageInfo() { + public Optional getPageInfo() { return pageInfo; } @@ -103,8 +103,8 @@ public void setUniqueLetter(Optional uniqueLetter) { this.uniqueLetter = uniqueLetter; } - public void setPageInfo(Optional v) { - Optional vv = normalizePageInfo(v); + public void setPageInfo(Optional v) { + Optional vv = normalizePageInfo(v); if (!vv.equals(v)) { throw new RuntimeException("setPageInfo argument is not normalized"); } @@ -136,14 +136,14 @@ public static void setUniqueLetter(Pair> x) { /* * pageInfo normalization */ - public static Optional normalizePageInfo(Optional o) { - if (o == null || o.isEmpty() || "".equals(OOFormattedText.toString(o.get()))) { + public static Optional normalizePageInfo(Optional o) { + if (o == null || o.isEmpty() || "".equals(OOText.toString(o.get()))) { return Optional.empty(); } - String s = OOFormattedText.toString(o.get()); + String s = OOText.toString(o.get()); if (s.trim().equals("")) { return Optional.empty(); } - return Optional.of(OOFormattedText.fromString(s.trim())); + return Optional.of(OOText.fromString(s.trim())); } } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index bacf77c1524..f85719acef7 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -62,7 +62,7 @@ public class CitationGroup { /* * Citation marker. */ - private Optional citationMarker; + private Optional citationMarker; public CitationGroup(OODataModel dataModel, CitationGroupID cgid, @@ -97,7 +97,7 @@ void imposeLocalOrder(Comparator entryComparator) { // For JabRef52 the single pageInfo is always in the last-in-localorder citation. // We adjust here accordingly by taking it out and adding it back after sorting. final int last = this.numberOfCitations() - 1; - Optional lastPageInfo = Optional.empty(); + Optional lastPageInfo = Optional.empty(); if (dataModel == OODataModel.JabRef52) { Citation lastCitation = getCitationsInLocalOrder().get(last); lastPageInfo = lastCitation.getPageInfo(); @@ -148,11 +148,11 @@ public void setReferenceMarkNameForLinking(Optional referenceMarkNameFor this.referenceMarkNameForLinking = referenceMarkNameForLinking; } - public void setCitationMarker(Optional citationMarker) { + public void setCitationMarker(Optional citationMarker) { this.citationMarker = citationMarker; } - public Optional getCitationMarker() { + public Optional getCitationMarker() { return this.citationMarker; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java index 4ba53c1c92f..2243480d1d5 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java @@ -25,7 +25,7 @@ public interface CitationMarkerEntry extends CitationMarkerNormEntry { * pageInfo for this citation, provided by the user. * May be empty, for none. */ - Optional getPageInfo(); + Optional getPageInfo(); /** * @return true if this citation is the first appearance of the diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index ae501af6a5b..73079c4ce7b 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -13,7 +13,7 @@ public class CitedKey implements ComparableCitedKey, CitationMarkerNormEntry { public Optional db; public Optional number; // For Numbered citation styles. public Optional uniqueLetter; // For AuthorYear citation styles. - public Optional normCitMarker; // For AuthorYear citation styles. + public Optional normCitMarker; // For AuthorYear citation styles. CitedKey(String citationKey, CitationPath p, Citation cit) { this.citationKey = citationKey; diff --git a/src/main/java/org/jabref/model/oostyle/ComparableCitation.java b/src/main/java/org/jabref/model/oostyle/ComparableCitation.java index e1b00c020f1..06250c2e7b0 100644 --- a/src/main/java/org/jabref/model/oostyle/ComparableCitation.java +++ b/src/main/java/org/jabref/model/oostyle/ComparableCitation.java @@ -7,5 +7,5 @@ * Otherwise we sort citations as cited keys. */ public interface ComparableCitation extends ComparableCitedKey { - public Optional getPageInfo(); + public Optional getPageInfo(); } diff --git a/src/main/java/org/jabref/model/oostyle/CompareCitation.java b/src/main/java/org/jabref/model/oostyle/CompareCitation.java index 4cec3d66aa9..442fcc667d8 100644 --- a/src/main/java/org/jabref/model/oostyle/CompareCitation.java +++ b/src/main/java/org/jabref/model/oostyle/CompareCitation.java @@ -32,10 +32,10 @@ public int compare(ComparableCitation a, ComparableCitation b) { * * Optional.empty comes before non-empty. */ - public static int comparePageInfo(Optional a, Optional b) { + public static int comparePageInfo(Optional a, Optional b) { - Optional aa = Citation.normalizePageInfo(a); - Optional bb = Citation.normalizePageInfo(b); + Optional aa = Citation.normalizePageInfo(a); + Optional bb = Citation.normalizePageInfo(b); if (aa.isEmpty() && bb.isEmpty()) { return 0; } diff --git a/src/main/java/org/jabref/model/oostyle/OODataModel.java b/src/main/java/org/jabref/model/oostyle/OODataModel.java index b1e9bac1522..b4fe0229988 100644 --- a/src/main/java/org/jabref/model/oostyle/OODataModel.java +++ b/src/main/java/org/jabref/model/oostyle/OODataModel.java @@ -37,12 +37,12 @@ public enum OODataModel { * @param pageInfo Nullable. * @return JabRef53 style pageInfo list */ - public static List> fakePageInfosForCitations(String pageInfo, + public static List> fakePageInfosForCitations(String pageInfo, int nCitations) { - List> pageInfosForCitations = new ArrayList<>(nCitations); + List> pageInfosForCitations = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { if (i == (nCitations - 1) && (pageInfo != null)) { - pageInfosForCitations.add(Optional.of(OOFormattedText.fromString(pageInfo))); + pageInfosForCitations.add(Optional.of(OOText.fromString(pageInfo))); } else { pageInfosForCitations.add(Optional.empty()); } diff --git a/src/main/java/org/jabref/model/oostyle/OOFormattedText.java b/src/main/java/org/jabref/model/oostyle/OOText.java similarity index 67% rename from src/main/java/org/jabref/model/oostyle/OOFormattedText.java rename to src/main/java/org/jabref/model/oostyle/OOText.java index 6b8ea2abbf6..aca69dd9474 100644 --- a/src/main/java/org/jabref/model/oostyle/OOFormattedText.java +++ b/src/main/java/org/jabref/model/oostyle/OOText.java @@ -2,23 +2,23 @@ import java.util.Objects; -public class OOFormattedText { +public class OOText { private final String data; - private OOFormattedText(String data) { + private OOText(String data) { Objects.requireNonNull(data); this.data = data; } - public static OOFormattedText fromString(String s) { + public static OOText fromString(String s) { if (s == null) { return null; } - return new OOFormattedText(s); + return new OOText(s); } - public static String toString(OOFormattedText s) { + public static String toString(OOText s) { if (s == null) { return null; } @@ -36,11 +36,11 @@ public boolean equals(Object o) { return true; } - if (!(o instanceof OOFormattedText)) { + if (!(o instanceof OOText)) { return false; } - OOFormattedText c = (OOFormattedText) o; + OOText c = (OOText) o; return data.equals(c.data); } diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index acf10778ad9..5f1dfff4414 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -29,7 +29,7 @@ import org.jabref.model.oostyle.CitationLookupResult; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; -import org.jabref.model.oostyle.OOFormattedText; +import org.jabref.model.oostyle.OOText; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -90,9 +90,9 @@ void testNumerical() throws IOException { assertTrue(style.isSortByPosition()); } - List> asPageInfos(String... s) { + List> asPageInfos(String... s) { return (Stream.of(s) - .map(OOFormattedText::fromString) + .map(OOText::fromString) .map(Optional::ofNullable) .collect(Collectors.toList())); } @@ -102,7 +102,7 @@ void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - List> empty = null; + List> empty = null; // Unfortunately these two are both "; " in // jabref/src/main/resources/resource/openoffice/default_numerical.jstyle @@ -241,7 +241,7 @@ void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - List> empty = null; + List> empty = null; // unresolved citations look like [??] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", @@ -306,7 +306,7 @@ private static CitationMarkerEntry makeCitationMarkerEntry(String citationKey, Citation result = new Citation(citationKey); result.setLookupResult(Optional.of(new CitationLookupResult(entry, database))); result.setUniqueLetter(Optional.ofNullable(uniqueLetterQ)); - Optional pageInfo = Optional.ofNullable(OOFormattedText.fromString(pageInfoQ)); + Optional pageInfo = Optional.ofNullable(OOText.fromString(pageInfoQ)); result.setPageInfo(Citation.normalizePageInfo(pageInfo)); result.setIsFirstAppearanceOfSource(isFirstAppearanceOfSource); return result; From d3758360baadd4321e5c359885b2056800a5bb90 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 21:10:02 +0200 Subject: [PATCH 0808/1068] getRangeName --- .../java/org/jabref/logic/openoffice/Backend52.java | 2 +- .../java/org/jabref/logic/openoffice/OOFrontend.java | 2 +- .../jabref/logic/openoffice/StorageBaseRefMark.java | 12 ++++++------ .../org/jabref/model/openoffice/StorageBase.java | 10 ++-------- 4 files changed, 10 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 32bdc8605d1..cdf43917224 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -325,7 +325,7 @@ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) IllegalTypeException, PropertyExistException { - String refMarkName = cg.cgRangeStorage.getName(); + String refMarkName = cg.cgRangeStorage.getRangeName(); cg.cgRangeStorage.removeFromDocument(doc); UnoUserDefinedProperty.removeIfExists(doc, refMarkName); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index e765f119c0f..043c0154935 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -366,7 +366,7 @@ private List> citationRanges(XTextDocument for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { XTextRange range = this.getMarkRange(doc, cg.cgid).orElseThrow(RuntimeException::new); - String name = cg.cgRangeStorage.getName(); + String name = cg.cgRangeStorage.getRangeName(); result.add(new RangeForOverlapCheck(range, cg.cgid, RangeForOverlapCheck.REFERENCE_MARK_KIND, diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index 1426273147e..be886a9341b 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -157,11 +157,11 @@ public void removeFromDocument(XTextDocument doc) WrappedTargetException, NoDocumentException, NoSuchElementException { - UnoReferenceMark.remove(doc, this.getName()); + UnoReferenceMark.remove(doc, this.getRangeName()); } @Override - public String getName() { + public String getRangeName() { return id; } @@ -177,7 +177,7 @@ public Optional getMarkRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - String name = this.getName(); + String name = this.getRangeName(); return UnoReferenceMark.getAnchor(doc, name); } @@ -196,7 +196,7 @@ public Optional getRawCursor(XTextDocument doc) NoDocumentException, WrappedTargetException { - String name = this.getName(); + String name = this.getRangeName(); Optional full = Optional.empty(); Optional markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name); @@ -225,7 +225,7 @@ public XTextCursor getFillCursor(XTextDocument doc) WrappedTargetException, CreationException { - String name = this.getName(); + String name = this.getRangeName(); final boolean debugThisFun = false; final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; @@ -434,7 +434,7 @@ public void cleanFillCursor(XTextDocument doc) final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); - String name = this.getName(); + String name = this.getRangeName(); XTextCursor full = this.getRawCursor(doc).orElseThrow(RuntimeException::new); final String fullText = full.getString(); diff --git a/src/main/java/org/jabref/model/openoffice/StorageBase.java b/src/main/java/org/jabref/model/openoffice/StorageBase.java index 988f3a82a1b..445e9a85893 100644 --- a/src/main/java/org/jabref/model/openoffice/StorageBase.java +++ b/src/main/java/org/jabref/model/openoffice/StorageBase.java @@ -11,11 +11,9 @@ public class StorageBase { - public interface HasName { - public String getName(); - } + public interface NamedRange { - public interface HasTextRange { + public String getRangeName(); /** * @return Optional.empty if the mark is missing from the document. @@ -66,10 +64,6 @@ public void removeFromDocument(XTextDocument doc) NoSuchElementException; } - public interface NamedRange extends HasName, HasTextRange { - // nothing new here - } - public interface NamedRangeManager { public NamedRange create(XTextDocument doc, String markName, From 1da590be4d90085c79baa1aa858b09d7737c6d18 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 21:28:38 +0200 Subject: [PATCH 0809/1068] split StorageBase to NamedRange and NamedRangeManager --- .../jabref/logic/openoffice/Backend52.java | 11 +-- .../logic/openoffice/StorageBaseRefMark.java | 21 ++--- .../jabref/model/oostyle/CitationGroup.java | 6 +- .../jabref/model/openoffice/NamedRange.java | 62 ++++++++++++++ .../model/openoffice/NamedRangeManager.java | 28 ++++++ .../jabref/model/openoffice/StorageBase.java | 85 ------------------- 6 files changed, 110 insertions(+), 103 deletions(-) create mode 100644 src/main/java/org/jabref/model/openoffice/NamedRange.java create mode 100644 src/main/java/org/jabref/model/openoffice/NamedRangeManager.java delete mode 100644 src/main/java/org/jabref/model/openoffice/StorageBase.java diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index cdf43917224..0f59d038702 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -17,8 +17,9 @@ import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NamedRange; +import org.jabref.model.openoffice.NamedRangeManager; import org.jabref.model.openoffice.NoDocumentException; -import org.jabref.model.openoffice.StorageBase; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -36,7 +37,7 @@ public class Backend52 { private static final Logger LOGGER = LoggerFactory.getLogger(Backend52.class); public final OODataModel dataModel; - public final StorageBase.NamedRangeManager citationStorageManager; + public final NamedRangeManager citationStorageManager; // uses: Codec52 public Backend52() { @@ -155,8 +156,8 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str setPageInfoInDataInitial(citations, pageInfo); - Optional storedRange = (citationStorageManager - .getFromDocument(doc, refMarkName)); + Optional storedRange = (citationStorageManager + .getFromDocument(doc, refMarkName)); if (storedRange.isEmpty()) { throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" @@ -242,7 +243,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, * Apply to document */ boolean withoutBrackets = (citationType == InTextCitationType.INVISIBLE_CIT); - StorageBase.NamedRange storedRange = + NamedRange storedRange = this.citationStorageManager.create(doc, refMarkName, position, insertSpaceAfter, withoutBrackets); diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java index be886a9341b..5a7b3da35a5 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java @@ -4,8 +4,9 @@ import java.util.Optional; import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NamedRange; +import org.jabref.model.openoffice.NamedRangeManager; import org.jabref.model.openoffice.NoDocumentException; -import org.jabref.model.openoffice.StorageBase; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; @@ -17,7 +18,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -class StorageBaseRefMark implements StorageBase.NamedRange { +class StorageBaseRefMark implements NamedRange { private static final String ZERO_WIDTH_SPACE = "\u200b"; @@ -495,13 +496,13 @@ private static List getUsedNames(XTextDocument doc) return UnoReferenceMark.getListOfNames(doc); } - public static class Manager implements StorageBase.NamedRangeManager { + public static class Manager implements NamedRangeManager { @Override - public StorageBase.NamedRange create(XTextDocument doc, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) + public NamedRange create(XTextDocument doc, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException { return StorageBaseRefMark.create(doc, @@ -519,8 +520,8 @@ public List getUsedNames(XTextDocument doc) } @Override - public Optional getFromDocument(XTextDocument doc, - String refMarkName) + public Optional getFromDocument(XTextDocument doc, + String refMarkName) throws NoDocumentException, WrappedTargetException { diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index f85719acef7..d55ce88d3c9 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -6,7 +6,7 @@ import java.util.Optional; import org.jabref.model.entry.BibEntry; -import org.jabref.model.openoffice.StorageBase; +import org.jabref.model.openoffice.NamedRange; /* * A CitationGroup describes a group of citations. @@ -23,7 +23,7 @@ public class CitationGroup { /* * Identifies location in the document for the backend. */ - public final StorageBase.NamedRange cgRangeStorage; + public final NamedRange cgRangeStorage; /* * The core data, stored in the document: @@ -66,7 +66,7 @@ public class CitationGroup { public CitationGroup(OODataModel dataModel, CitationGroupID cgid, - StorageBase.NamedRange cgRangeStorage, + NamedRange cgRangeStorage, InTextCitationType citationType, List citationsInStorageOrder, Optional referenceMarkNameForLinking) { diff --git a/src/main/java/org/jabref/model/openoffice/NamedRange.java b/src/main/java/org/jabref/model/openoffice/NamedRange.java new file mode 100644 index 00000000000..ac056ea888b --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/NamedRange.java @@ -0,0 +1,62 @@ +package org.jabref.model.openoffice; + +import java.util.Optional; + +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; + +public interface NamedRange { + + public String getRangeName(); + + /** + * @return Optional.empty if the mark is missing from the document. + */ + public Optional getMarkRange(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException; + + /** + * Cursor for the reference marks as is, not prepared for filling, + * but does not need cleanFillCursorForCitationGroup either. + */ + public Optional getRawCursor(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException; + + /** + * Get a cursor for filling in text. + * + * Must be followed by cleanFillCursor() + */ + public XTextCursor getFillCursor(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException, + CreationException; + + /** + * Remove brackets, but if the result would become empty, leave + * them; if the result would be a single characer, leave the left bracket. + * + */ + public void cleanFillCursor(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException, + CreationException; + + /** + * Note: create is in NamedRangeManager + */ + public void removeFromDocument(XTextDocument doc) + throws + WrappedTargetException, + NoDocumentException, + NoSuchElementException; +} diff --git a/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java b/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java new file mode 100644 index 00000000000..fb5e5b3cbb5 --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java @@ -0,0 +1,28 @@ +package org.jabref.model.openoffice; + +import java.util.List; +import java.util.Optional; + +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; + +public interface NamedRangeManager { + + public NamedRange create(XTextDocument doc, + String markName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) + throws + CreationException; + + public List getUsedNames(XTextDocument doc) + throws + NoDocumentException; + + public Optional getFromDocument(XTextDocument doc, String markName) + throws + NoDocumentException, + WrappedTargetException; +} diff --git a/src/main/java/org/jabref/model/openoffice/StorageBase.java b/src/main/java/org/jabref/model/openoffice/StorageBase.java deleted file mode 100644 index 445e9a85893..00000000000 --- a/src/main/java/org/jabref/model/openoffice/StorageBase.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.jabref.model.openoffice; - -import java.util.List; -import java.util.Optional; - -import com.sun.star.container.NoSuchElementException; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XTextCursor; -import com.sun.star.text.XTextDocument; -import com.sun.star.text.XTextRange; - -public class StorageBase { - - public interface NamedRange { - - public String getRangeName(); - - /** - * @return Optional.empty if the mark is missing from the document. - */ - public Optional getMarkRange(XTextDocument doc) - throws - NoDocumentException, - WrappedTargetException; - - /** - * Cursor for the reference marks as is, not prepared for filling, - * but does not need cleanFillCursorForCitationGroup either. - */ - public Optional getRawCursor(XTextDocument doc) - throws - NoDocumentException, - WrappedTargetException; - - /** - * Get a cursor for filling in text. - * - * Must be followed by cleanFillCursor() - */ - public XTextCursor getFillCursor(XTextDocument doc) - throws - NoDocumentException, - WrappedTargetException, - CreationException; - - /** - * Remove brackets, but if the result would become empty, leave - * them; if the result would be a single characer, leave the left bracket. - * - */ - public void cleanFillCursor(XTextDocument doc) - throws - NoDocumentException, - WrappedTargetException, - CreationException; - - /** - * Note: create is in NamedRangeManager - */ - public void removeFromDocument(XTextDocument doc) - throws - WrappedTargetException, - NoDocumentException, - NoSuchElementException; - } - - public interface NamedRangeManager { - public NamedRange create(XTextDocument doc, - String markName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) - throws - CreationException; - - public List getUsedNames(XTextDocument doc) - throws - NoDocumentException; - - public Optional getFromDocument(XTextDocument doc, String markName) - throws - NoDocumentException, - WrappedTargetException; - } -} From 2b14e2149bce37e7b016471a75de4413259f35b9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 21:48:27 +0200 Subject: [PATCH 0810/1068] split StorageBaseRefMark to NamedRangeManagerReferenceMark NamedRangeReferenceMark --- .../jabref/logic/openoffice/Backend52.java | 2 +- .../NamedRangeManagerReferenceMark.java | 50 ++++++++++++ ...Mark.java => NamedRangeReferenceMark.java} | 79 +++++-------------- 3 files changed, 70 insertions(+), 61 deletions(-) create mode 100644 src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java rename src/main/java/org/jabref/logic/openoffice/{StorageBaseRefMark.java => NamedRangeReferenceMark.java} (86%) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 0f59d038702..033e1f55c4c 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -42,7 +42,7 @@ public class Backend52 { // uses: Codec52 public Backend52() { this.dataModel = OODataModel.JabRef52; - this.citationStorageManager = new StorageBaseRefMark.Manager(); + this.citationStorageManager = new NamedRangeManagerReferenceMark(); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java new file mode 100644 index 00000000000..9e7a0f7659b --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java @@ -0,0 +1,50 @@ +package org.jabref.logic.openoffice; + +import java.util.List; +import java.util.Optional; + +import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.NamedRange; +import org.jabref.model.openoffice.NamedRangeManager; +import org.jabref.model.openoffice.NoDocumentException; + +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; + +public class NamedRangeManagerReferenceMark implements NamedRangeManager { + + @Override + public NamedRange create(XTextDocument doc, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) + throws + CreationException { + return NamedRangeReferenceMark.create(doc, + refMarkName, + position, + insertSpaceAfter, + withoutBrackets); + } + + @Override + public List getUsedNames(XTextDocument doc) + throws + NoDocumentException { + return UnoReferenceMark.getListOfNames(doc); + } + + @Override + public Optional getFromDocument(XTextDocument doc, + String refMarkName) + throws + NoDocumentException, + WrappedTargetException { + return (NamedRangeReferenceMark + .getFromDocument(doc, refMarkName) + .map(x -> x)); + } +} + diff --git a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java similarity index 86% rename from src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java rename to src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java index 5a7b3da35a5..d636b45f18f 100644 --- a/src/main/java/org/jabref/logic/openoffice/StorageBaseRefMark.java +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java @@ -1,11 +1,9 @@ package org.jabref.logic.openoffice; -import java.util.List; import java.util.Optional; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NamedRange; -import org.jabref.model.openoffice.NamedRangeManager; import org.jabref.model.openoffice.NoDocumentException; import com.sun.star.container.NoSuchElementException; @@ -18,7 +16,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -class StorageBaseRefMark implements NamedRange { +// was StorageBaseRefMark + +class NamedRangeReferenceMark implements NamedRange { private static final String ZERO_WIDTH_SPACE = "\u200b"; @@ -32,11 +32,11 @@ class StorageBaseRefMark implements NamedRange { public static final String REFERENCE_MARK_RIGHT_BRACKET = REFERENCE_MARK_USE_INVISIBLE_BRACKETS ? ZERO_WIDTH_SPACE : ">"; - private static final Logger LOGGER = LoggerFactory.getLogger(StorageBaseRefMark.class); + private static final Logger LOGGER = LoggerFactory.getLogger(NamedRangeReferenceMark.class); private String id; /* reference mark name */ - private StorageBaseRefMark(String id) { + private NamedRangeReferenceMark(String id) { this.id = id; } @@ -99,8 +99,8 @@ private static void createReprInDocument(XTextDocument doc, cursor.goRight((short) 1, false); // now we are between two spaces - final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; - final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; + final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; + final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); String bracketedContent = (withoutBrackets @@ -119,11 +119,11 @@ private static void createReprInDocument(XTextDocument doc, } } - private static StorageBaseRefMark create(XTextDocument doc, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) + static NamedRangeReferenceMark create(XTextDocument doc, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException { @@ -132,19 +132,19 @@ private static StorageBaseRefMark create(XTextDocument doc, position, insertSpaceAfter, withoutBrackets); - return new StorageBaseRefMark(refMarkName); + return new NamedRangeReferenceMark(refMarkName); } /** * @return Optional.empty if there is no corresponding range. */ - private static Optional getFromDocument(XTextDocument doc, - String refMarkName) + static Optional getFromDocument(XTextDocument doc, + String refMarkName) throws NoDocumentException, WrappedTargetException { return (UnoReferenceMark.getAnchor(doc, refMarkName) - .map(e -> new StorageBaseRefMark(refMarkName))); + .map(e -> new NamedRangeReferenceMark(refMarkName))); } /* @@ -229,8 +229,8 @@ public XTextCursor getFillCursor(XTextDocument doc) String name = this.getRangeName(); final boolean debugThisFun = false; - final String left = StorageBaseRefMark.REFERENCE_MARK_LEFT_BRACKET; - final String right = StorageBaseRefMark.REFERENCE_MARK_RIGHT_BRACKET; + final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; + final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); @@ -367,7 +367,7 @@ public XTextCursor getFillCursor(XTextDocument doc) omega.getString(), right); } - StorageBaseRefMark.checkFillCursor(beta); + NamedRangeReferenceMark.checkFillCursor(beta); return beta; } @@ -489,45 +489,4 @@ public void cleanFillCursor(XTextDocument doc) alpha.setString(""); } } - - private static List getUsedNames(XTextDocument doc) - throws - NoDocumentException { - return UnoReferenceMark.getListOfNames(doc); - } - - public static class Manager implements NamedRangeManager { - @Override - public NamedRange create(XTextDocument doc, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) - throws - CreationException { - return StorageBaseRefMark.create(doc, - refMarkName, - position, - insertSpaceAfter, - withoutBrackets); - } - - @Override - public List getUsedNames(XTextDocument doc) - throws - NoDocumentException { - return StorageBaseRefMark.getUsedNames(doc); - } - - @Override - public Optional getFromDocument(XTextDocument doc, - String refMarkName) - throws - NoDocumentException, - WrappedTargetException { - return (StorageBaseRefMark - .getFromDocument(doc, refMarkName) - .map(x -> x)); - } - } } From c04a9bcf30995b70edad951b942126b13e398053 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 22:14:04 +0200 Subject: [PATCH 0811/1068] prefix NamedRange methods with nr --- .../jabref/logic/openoffice/Backend52.java | 12 +-- .../openoffice/NamedRangeReferenceMark.java | 76 +++++++++---------- .../jabref/logic/openoffice/OOFrontend.java | 2 +- .../jabref/model/openoffice/NamedRange.java | 16 ++-- 4 files changed, 53 insertions(+), 53 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 033e1f55c4c..47fa7c5f206 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -326,8 +326,8 @@ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) IllegalTypeException, PropertyExistException { - String refMarkName = cg.cgRangeStorage.getRangeName(); - cg.cgRangeStorage.removeFromDocument(doc); + String refMarkName = cg.cgRangeStorage.nrGetRangeName(); + cg.cgRangeStorage.nrRemoveFromDocument(doc); UnoUserDefinedProperty.removeIfExists(doc, refMarkName); } @@ -341,7 +341,7 @@ public Optional getMarkRange(CitationGroup cg, XTextDocument doc) NoDocumentException, WrappedTargetException { - return cg.cgRangeStorage.getMarkRange(doc); + return cg.cgRangeStorage.nrGetMarkRange(doc); } /** @@ -352,7 +352,7 @@ public Optional getRawCursorForCitationGroup(CitationGroup cg, XTex throws NoDocumentException, WrappedTargetException { - return cg.cgRangeStorage.getRawCursor(doc); + return cg.cgRangeStorage.nrGetRawCursor(doc); } /** @@ -364,7 +364,7 @@ public XTextCursor getFillCursorForCitationGroup(CitationGroup cg, XTextDocument WrappedTargetException, CreationException { - return cg.cgRangeStorage.getFillCursor(doc); + return cg.cgRangeStorage.nrGetFillCursor(doc); } /** To be called after getFillCursorForCitationGroup */ @@ -373,7 +373,7 @@ public void cleanFillCursorForCitationGroup(CitationGroup cg, XTextDocument doc) NoDocumentException, WrappedTargetException, CreationException { - cg.cgRangeStorage.cleanFillCursor(doc); + cg.cgRangeStorage.nrCleanFillCursor(doc); } public List getCitationEntries(XTextDocument doc, CitationGroups cgs) diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java index d636b45f18f..32ff32528d6 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java @@ -153,16 +153,16 @@ static Optional getFromDocument(XTextDocument doc, * See: removeCitationGroups */ @Override - public void removeFromDocument(XTextDocument doc) + public void nrRemoveFromDocument(XTextDocument doc) throws WrappedTargetException, NoDocumentException, NoSuchElementException { - UnoReferenceMark.remove(doc, this.getRangeName()); + UnoReferenceMark.remove(doc, this.nrGetRangeName()); } @Override - public String getRangeName() { + public String nrGetRangeName() { return id; } @@ -174,17 +174,17 @@ public String getRangeName() { * See: UnoReferenceMark.getAnchor */ @Override - public Optional getMarkRange(XTextDocument doc) + public Optional nrGetMarkRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - String name = this.getRangeName(); + String name = this.nrGetRangeName(); return UnoReferenceMark.getAnchor(doc, name); } /** * Cursor for the reference marks as is, not prepared for filling, - * but does not need cleanFillCursorForCitationGroup either. + * but does not need nrCleanFillCursor either. * * @return Optional.empty() if reference mark is missing from the document, * otherwise an XTextCursor for getMarkRange @@ -192,24 +192,24 @@ public Optional getMarkRange(XTextDocument doc) * See: getRawCursorForCitationGroup */ @Override - public Optional getRawCursor(XTextDocument doc) + public Optional nrGetRawCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - String name = this.getRangeName(); + String name = this.nrGetRangeName(); Optional full = Optional.empty(); Optional markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name); if (markAsTextContent.isEmpty()) { - String msg = String.format("getRawCursor: markAsTextContent(%s).isEmpty()", name); + String msg = String.format("nrGetRawCursor: markAsTextContent(%s).isEmpty()", name); LOGGER.warn(msg); } full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()); if (full.isEmpty()) { - String msg = "getRawCursor: full.isEmpty()"; + String msg = "nrGetRawCursor: full.isEmpty()"; LOGGER.warn(msg); return Optional.empty(); } @@ -220,13 +220,13 @@ public Optional getRawCursor(XTextDocument doc) * See: getFillCursorForCitationGroup */ @Override - public XTextCursor getFillCursor(XTextDocument doc) + public XTextCursor nrGetFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, CreationException { - String name = this.getRangeName(); + String name = this.nrGetRangeName(); final boolean debugThisFun = false; final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; @@ -240,7 +240,7 @@ public XTextCursor getFillCursor(XTextDocument doc) Optional markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name); if (markAsTextContent.isEmpty()) { - String msg = String.format("getFillCursor:" + String msg = String.format("nrGetFillCursor:" + " markAsTextContent(%s).isEmpty (attempt %d)", name, i); @@ -249,39 +249,39 @@ public XTextCursor getFillCursor(XTextDocument doc) full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()).orElse(null); if (full == null) { - String msg = String.format("getFillCursor: full == null (attempt %d)", i); + String msg = String.format("nrGetFillCursor: full == null (attempt %d)", i); throw new RuntimeException(msg); } fullText = full.getString(); if (debugThisFun) { - System.out.printf("getFillCursor: fulltext = '%s'%n", fullText); + System.out.printf("nrGetFillCursor: fulltext = '%s'%n", fullText); } if (fullText.length() >= 2) { if (debugThisFun) { - System.out.printf("getFillCursor: (attempt: %d) fulltext.length() >= 2," + System.out.printf("nrGetFillCursor: (attempt: %d) fulltext.length() >= 2," + " break loop%n", i); } break; } else { // (fullText.length() < 2) if (i == 2) { - String msg = String.format("getFillCursor:" + String msg = String.format("nrGetFillCursor:" + " (fullText.length() < 2) (attempt %d)", i); throw new RuntimeException(msg); } // too short, recreate if (debugThisFun) { - System.out.println("getFillCursor: too short, recreate"); + System.out.println("nrGetFillCursor: too short, recreate"); } full.setString(""); try { UnoReferenceMark.remove(doc, name); } catch (NoSuchElementException ex) { - String msg = String.format("getFillCursor got NoSuchElementException" + String msg = String.format("nrGetFillCursor got NoSuchElementException" + " for '%s'", name); LOGGER.warn(msg); @@ -295,15 +295,15 @@ public XTextCursor getFillCursor(XTextDocument doc) } if (full == null) { - throw new RuntimeException("getFillCursorFor: full == null (after loop)"); + throw new RuntimeException("nrGetFillCursorFor: full == null (after loop)"); } if (fullText == null) { - throw new RuntimeException("getFillCursor: fullText == null (after loop)"); + throw new RuntimeException("nrGetFillCursor: fullText == null (after loop)"); } fullText = full.getString(); if (fullText.length() < 2) { - throw new RuntimeException("getFillCursor: fullText.length() < 2 (after loop)'%n"); + throw new RuntimeException("nrGetFillCursor: fullText.length() < 2 (after loop)'%n"); } // we have at least two characters inside XTextCursor alpha = full.getText().createTextCursorByRange(full); @@ -316,7 +316,7 @@ public XTextCursor getFillCursor(XTextDocument doc) beta.goRight((short) 1, false); beta.goRight((short) (fullText.length() - 2), true); if (debugThisFun) { - System.out.printf("getFillCursor: beta(1) covers '%s'%n", beta.getString()); + System.out.printf("nrGetFillCursor: beta(1) covers '%s'%n", beta.getString()); } // beta now covers everything except first and last character // Replace its content with brackets @@ -325,7 +325,7 @@ public XTextCursor getFillCursor(XTextDocument doc) String paddingz = "z"; beta.setString(paddingx + left + paddingy + right + paddingz); if (debugThisFun) { - System.out.printf("getFillCursor: beta(2) covers '%s'%n", beta.getString()); + System.out.printf("nrGetFillCursor: beta(2) covers '%s'%n", beta.getString()); } // move beta to before the right bracket beta.collapseToEnd(); @@ -333,7 +333,7 @@ public XTextCursor getFillCursor(XTextDocument doc) // remove middle padding beta.goLeft((short) 1, true); if (debugThisFun) { - System.out.printf("getFillCursor: beta(3) covers '%s'%n", beta.getString()); + System.out.printf("nrGetFillCursor: beta(3) covers '%s'%n", beta.getString()); } // only drop paddingy later: beta.setString(""); @@ -341,29 +341,29 @@ public XTextCursor getFillCursor(XTextDocument doc) alpha.collapseToStart(); alpha.goRight((short) (1 + 1), true); if (debugThisFun) { - System.out.printf("getFillCursor: alpha(4) covers '%s'%n", alpha.getString()); + System.out.printf("nrGetFillCursor: alpha(4) covers '%s'%n", alpha.getString()); } alpha.setString(""); // drop the last character and paddingz omega.collapseToEnd(); omega.goLeft((short) (1 + 1), true); if (debugThisFun) { - System.out.printf("getFillCursor: omega(5) covers '%s'%n", omega.getString()); + System.out.printf("nrGetFillCursor: omega(5) covers '%s'%n", omega.getString()); } omega.setString(""); // drop paddingy now if (debugThisFun) { - System.out.printf("getFillCursor: beta(6) covers '%s'%n", beta.getString()); + System.out.printf("nrGetFillCursor: beta(6) covers '%s'%n", beta.getString()); } beta.setString(""); // should be OK now. if (debugThisFun) { alpha.goRight(leftLength, true); - System.out.printf("getFillCursor: alpha(7) covers '%s', should be '%s'%n", + System.out.printf("nrGetFillCursor: alpha(7) covers '%s', should be '%s'%n", alpha.getString(), left); omega.goLeft(rightLength, true); - System.out.printf("getFillCursor: omega(8) covers '%s', should be '%s'%n", + System.out.printf("nrGetFillCursor: omega(8) covers '%s', should be '%s'%n", omega.getString(), right); } @@ -416,15 +416,15 @@ public static void checkFillCursor(XTextCursor cursor) { * See: cleanFillCursorForCitationGroup */ @Override - public void cleanFillCursor(XTextDocument doc) + public void nrCleanFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, CreationException { // alwaysRemoveBrackets : full compatibility with JabRef 5.2: - // brackets are temporary, only exist between getFillCursor - // and cleanFillCursor. + // brackets are temporary, only exist between nrGetFillCursor + // and nrCleanFillCursor. final boolean alwaysRemoveBrackets = true; // removeBracketsFromEmpty is intended to force removal if we // are working on an "Empty citation" (INVISIBLE_CIT). @@ -435,9 +435,9 @@ public void cleanFillCursor(XTextDocument doc) final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); - String name = this.getRangeName(); + String name = this.nrGetRangeName(); - XTextCursor full = this.getRawCursor(doc).orElseThrow(RuntimeException::new); + XTextCursor full = this.nrGetRawCursor(doc).orElseThrow(RuntimeException::new); final String fullText = full.getString(); final int fullTextLength = fullText.length(); @@ -452,14 +452,14 @@ public void cleanFillCursor(XTextDocument doc) omega.collapseToEnd(); if (!fullText.startsWith(left)) { - String msg = String.format("cleanFillCursor:" + String msg = String.format("nrCleanFillCursor:" + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", name); throw new RuntimeException(msg); } if (!fullText.endsWith(right)) { - String msg = String.format("cleanFillCursor:" + String msg = String.format("nrCleanFillCursor:" + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", name); throw new RuntimeException(msg); @@ -467,7 +467,7 @@ public void cleanFillCursor(XTextDocument doc) final int contentLength = (fullTextLength - (leftLength + rightLength)); if (contentLength < 0) { - String msg = String.format("cleanFillCursor: length(%s) < 0", name); + String msg = String.format("nrCleanFillCursor: length(%s) < 0", name); throw new RuntimeException(msg); } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 043c0154935..69f87b3939b 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -366,7 +366,7 @@ private List> citationRanges(XTextDocument for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { XTextRange range = this.getMarkRange(doc, cg.cgid).orElseThrow(RuntimeException::new); - String name = cg.cgRangeStorage.getRangeName(); + String name = cg.cgRangeStorage.nrGetRangeName(); result.add(new RangeForOverlapCheck(range, cg.cgid, RangeForOverlapCheck.REFERENCE_MARK_KIND, diff --git a/src/main/java/org/jabref/model/openoffice/NamedRange.java b/src/main/java/org/jabref/model/openoffice/NamedRange.java index ac056ea888b..586a1e78141 100644 --- a/src/main/java/org/jabref/model/openoffice/NamedRange.java +++ b/src/main/java/org/jabref/model/openoffice/NamedRange.java @@ -10,21 +10,21 @@ public interface NamedRange { - public String getRangeName(); + public String nrGetRangeName(); /** * @return Optional.empty if the mark is missing from the document. */ - public Optional getMarkRange(XTextDocument doc) + public Optional nrGetMarkRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException; /** * Cursor for the reference marks as is, not prepared for filling, - * but does not need cleanFillCursorForCitationGroup either. + * but does not need nrCleanFillCursor either. */ - public Optional getRawCursor(XTextDocument doc) + public Optional nrGetRawCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException; @@ -32,9 +32,9 @@ public Optional getRawCursor(XTextDocument doc) /** * Get a cursor for filling in text. * - * Must be followed by cleanFillCursor() + * Must be followed by nrCleanFillCursor() */ - public XTextCursor getFillCursor(XTextDocument doc) + public XTextCursor nrGetFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, @@ -45,7 +45,7 @@ public XTextCursor getFillCursor(XTextDocument doc) * them; if the result would be a single characer, leave the left bracket. * */ - public void cleanFillCursor(XTextDocument doc) + public void nrCleanFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, @@ -54,7 +54,7 @@ public void cleanFillCursor(XTextDocument doc) /** * Note: create is in NamedRangeManager */ - public void removeFromDocument(XTextDocument doc) + public void nrRemoveFromDocument(XTextDocument doc) throws WrappedTargetException, NoDocumentException, From f0a63413f36edbb01240988b2e68b78d34d535a5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 22:27:41 +0200 Subject: [PATCH 0812/1068] prefix NamedRangeManager methods with nrm --- .../org/jabref/logic/openoffice/Backend52.java | 10 +++++----- .../openoffice/NamedRangeManagerReferenceMark.java | 8 ++++---- .../jabref/model/openoffice/NamedRangeManager.java | 14 +++++++------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 47fa7c5f206..1b725ca9411 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -55,7 +55,7 @@ public Backend52() { public List getJabRefReferenceMarkNames(XTextDocument doc) throws NoDocumentException { - List allNames = this.citationStorageManager.getUsedNames(doc); + List allNames = this.citationStorageManager.nrmGetUsedNames(doc); return Codec52.filterIsJabRefReferenceMarkName(allNames); } @@ -157,7 +157,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str setPageInfoInDataInitial(citations, pageInfo); Optional storedRange = (citationStorageManager - .getFromDocument(doc, refMarkName)); + .nrmGetFromDocument(doc, refMarkName)); if (storedRange.isEmpty()) { throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" @@ -206,7 +206,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, } // Get a new refMarkName - Set usedNames = new HashSet<>(this.citationStorageManager.getUsedNames(doc)); + Set usedNames = new HashSet<>(this.citationStorageManager.nrmGetUsedNames(doc)); String xkey = (citationKeys.stream().collect(Collectors.joining(","))); String refMarkName = Codec52.getUniqueMarkName(usedNames, xkey, citationType); @@ -244,8 +244,8 @@ public CitationGroup createCitationGroup(XTextDocument doc, */ boolean withoutBrackets = (citationType == InTextCitationType.INVISIBLE_CIT); NamedRange storedRange = - this.citationStorageManager.create(doc, refMarkName, position, insertSpaceAfter, - withoutBrackets); + this.citationStorageManager.nrmCreate(doc, refMarkName, position, insertSpaceAfter, + withoutBrackets); switch (dataModel) { case JabRef52: diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java index 9e7a0f7659b..a582d663657 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java @@ -15,7 +15,7 @@ public class NamedRangeManagerReferenceMark implements NamedRangeManager { @Override - public NamedRange create(XTextDocument doc, + public NamedRange nrmCreate(XTextDocument doc, String refMarkName, XTextCursor position, boolean insertSpaceAfter, @@ -30,15 +30,15 @@ public NamedRange create(XTextDocument doc, } @Override - public List getUsedNames(XTextDocument doc) + public List nrmGetUsedNames(XTextDocument doc) throws NoDocumentException { return UnoReferenceMark.getListOfNames(doc); } @Override - public Optional getFromDocument(XTextDocument doc, - String refMarkName) + public Optional nrmGetFromDocument(XTextDocument doc, + String refMarkName) throws NoDocumentException, WrappedTargetException { diff --git a/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java b/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java index fb5e5b3cbb5..06f27204475 100644 --- a/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java +++ b/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java @@ -9,19 +9,19 @@ public interface NamedRangeManager { - public NamedRange create(XTextDocument doc, - String markName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) + public NamedRange nrmCreate(XTextDocument doc, + String markName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException; - public List getUsedNames(XTextDocument doc) + public List nrmGetUsedNames(XTextDocument doc) throws NoDocumentException; - public Optional getFromDocument(XTextDocument doc, String markName) + public Optional nrmGetFromDocument(XTextDocument doc, String markName) throws NoDocumentException, WrappedTargetException; From 4d4a6f3691cc65fc06185224a46f5d8dcada1ba5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 23:01:15 +0200 Subject: [PATCH 0813/1068] association of CitationGroup to NamedRange moved to Backend --- .../jabref/logic/openoffice/Backend52.java | 57 ++++++++++++------- .../NamedRangeManagerReferenceMark.java | 11 ++-- .../jabref/logic/openoffice/OOFrontend.java | 4 +- .../jabref/model/oostyle/CitationGroup.java | 7 +-- 4 files changed, 48 insertions(+), 31 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 1b725ca9411..f4113cd0e2d 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -1,8 +1,10 @@ package org.jabref.logic.openoffice; import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -37,12 +39,14 @@ public class Backend52 { private static final Logger LOGGER = LoggerFactory.getLogger(Backend52.class); public final OODataModel dataModel; - public final NamedRangeManager citationStorageManager; + private final NamedRangeManager citationStorageManager; + private final Map cgidToNamedRange; // uses: Codec52 public Backend52() { this.dataModel = OODataModel.JabRef52; this.citationStorageManager = new NamedRangeManagerReferenceMark(); + this.cgidToNamedRange = new HashMap<>(); } /** @@ -104,16 +108,14 @@ public Optional healthReport(XTextDocument doc) return Optional.of(msg); } - private static void setPageInfoInDataInitial(List citations, - Optional pageInfo) { + private static void setPageInfoInDataInitial(List citations, Optional pageInfo) { // attribute to last citation (initially localOrder == storageOrder) if (citations.size() > 0) { citations.get(citations.size() - 1).setPageInfo(pageInfo); } } - private static void setPageInfoInData(CitationGroup cg, - Optional pageInfo) { + private static void setPageInfoInData(CitationGroup cg, Optional pageInfo) { List citations = cg.getCitationsInLocalOrder(); if (citations.size() > 0) { citations.get(citations.size() - 1).setPageInfo(pageInfo); @@ -144,7 +146,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str + " found unparsable referenceMarkName"); } Codec52.ParsedMarkName ov = op.get(); - CitationGroupID id = new CitationGroupID(refMarkName); + CitationGroupID cgid = new CitationGroupID(refMarkName); List citations = (ov.citationKeys.stream() .map(Citation::new) .collect(Collectors.toList())); @@ -156,20 +158,20 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str setPageInfoInDataInitial(citations, pageInfo); - Optional storedRange = (citationStorageManager - .nrmGetFromDocument(doc, refMarkName)); + Optional namedRange = citationStorageManager.nrmGetFromDocument(doc, refMarkName); - if (storedRange.isEmpty()) { + if (namedRange.isEmpty()) { throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" + " referenceMarkName is not in the document"); } CitationGroup cg = new CitationGroup(OODataModel.JabRef52, - id, - storedRange.get(), + cgid, + // namedRange.get(), ov.citationType, citations, Optional.of(refMarkName)); + this.cgidToNamedRange.put(cgid, namedRange.get()); return cg; } @@ -243,7 +245,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, * Apply to document */ boolean withoutBrackets = (citationType == InTextCitationType.INVISIBLE_CIT); - NamedRange storedRange = + NamedRange namedRange = this.citationStorageManager.nrmCreate(doc, refMarkName, position, insertSpaceAfter, withoutBrackets); @@ -260,8 +262,10 @@ public CitationGroup createCitationGroup(XTextDocument doc, UnoUserDefinedProperty.removeIfExists(doc, refMarkName); } CitationGroup cg = new CitationGroup(OODataModel.JabRef52, - cgid, storedRange, citationType, citations, + cgid, + citationType, citations, Optional.of(refMarkName)); + this.cgidToNamedRange.put(cgid, namedRange); return cg; default: throw new RuntimeException("Backend52 requires JabRef52 dataModel"); @@ -317,6 +321,15 @@ public List> combinePageInfos(List joinableGroup return combinePageInfosCommon(this.dataModel, joinableGroup); } + private NamedRange getNamedRangeOrThrow(CitationGroup cg) { + NamedRange namedRange = this.cgidToNamedRange.get(cg.cgid); + if (namedRange == null) { + LOGGER.warn("getNamedRange: could not lookup namedRange"); + throw new RuntimeException("getNamedRange: could not lookup namedRange"); + } + return namedRange; + } + public void removeCitationGroup(CitationGroup cg, XTextDocument doc) throws WrappedTargetException, @@ -326,9 +339,11 @@ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) IllegalTypeException, PropertyExistException { - String refMarkName = cg.cgRangeStorage.nrGetRangeName(); - cg.cgRangeStorage.nrRemoveFromDocument(doc); + NamedRange namedRange = getNamedRangeOrThrow(cg); + String refMarkName = namedRange.nrGetRangeName(); + namedRange.nrRemoveFromDocument(doc); UnoUserDefinedProperty.removeIfExists(doc, refMarkName); + this.cgidToNamedRange.remove(cg.cgid); } /** @@ -341,7 +356,8 @@ public Optional getMarkRange(CitationGroup cg, XTextDocument doc) NoDocumentException, WrappedTargetException { - return cg.cgRangeStorage.nrGetMarkRange(doc); + NamedRange namedRange = getNamedRangeOrThrow(cg); + return namedRange.nrGetMarkRange(doc); } /** @@ -352,7 +368,8 @@ public Optional getRawCursorForCitationGroup(CitationGroup cg, XTex throws NoDocumentException, WrappedTargetException { - return cg.cgRangeStorage.nrGetRawCursor(doc); + NamedRange namedRange = getNamedRangeOrThrow(cg); + return namedRange.nrGetRawCursor(doc); } /** @@ -364,7 +381,8 @@ public XTextCursor getFillCursorForCitationGroup(CitationGroup cg, XTextDocument WrappedTargetException, CreationException { - return cg.cgRangeStorage.nrGetFillCursor(doc); + NamedRange namedRange = getNamedRangeOrThrow(cg); + return namedRange.nrGetFillCursor(doc); } /** To be called after getFillCursorForCitationGroup */ @@ -373,7 +391,8 @@ public void cleanFillCursorForCitationGroup(CitationGroup cg, XTextDocument doc) NoDocumentException, WrappedTargetException, CreationException { - cg.cgRangeStorage.nrCleanFillCursor(doc); + NamedRange namedRange = getNamedRangeOrThrow(cg); + namedRange.nrCleanFillCursor(doc); } public List getCitationEntries(XTextDocument doc, CitationGroups cgs) diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java index a582d663657..64011254e73 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java @@ -16,10 +16,10 @@ public class NamedRangeManagerReferenceMark implements NamedRangeManager { @Override public NamedRange nrmCreate(XTextDocument doc, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException { return NamedRangeReferenceMark.create(doc, @@ -37,8 +37,7 @@ public List nrmGetUsedNames(XTextDocument doc) } @Override - public Optional nrmGetFromDocument(XTextDocument doc, - String refMarkName) + public Optional nrmGetFromDocument(XTextDocument doc, String refMarkName) throws NoDocumentException, WrappedTargetException { diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 69f87b3939b..81b5d87f44e 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -366,11 +366,11 @@ private List> citationRanges(XTextDocument for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { XTextRange range = this.getMarkRange(doc, cg.cgid).orElseThrow(RuntimeException::new); - String name = cg.cgRangeStorage.nrGetRangeName(); + String description = cg.cgid.asString(); // cg.cgRangeStorage.nrGetRangeName(); result.add(new RangeForOverlapCheck(range, cg.cgid, RangeForOverlapCheck.REFERENCE_MARK_KIND, - name)); + description)); } return result; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index d55ce88d3c9..dd17f832ec6 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -6,7 +6,6 @@ import java.util.Optional; import org.jabref.model.entry.BibEntry; -import org.jabref.model.openoffice.NamedRange; /* * A CitationGroup describes a group of citations. @@ -23,7 +22,7 @@ public class CitationGroup { /* * Identifies location in the document for the backend. */ - public final NamedRange cgRangeStorage; + // public final NamedRange cgRangeStorage; /* * The core data, stored in the document: @@ -66,13 +65,13 @@ public class CitationGroup { public CitationGroup(OODataModel dataModel, CitationGroupID cgid, - NamedRange cgRangeStorage, + // NamedRange cgRangeStorage, InTextCitationType citationType, List citationsInStorageOrder, Optional referenceMarkNameForLinking) { this.dataModel = dataModel; this.cgid = cgid; - this.cgRangeStorage = cgRangeStorage; + // this.cgRangeStorage = cgRangeStorage; this.citationType = citationType; this.citationsInStorageOrder = Collections.unmodifiableList(citationsInStorageOrder); this.localOrder = ListUtil.makeIndices(citationsInStorageOrder.size()); From ed4d4bb3831d98d0d604a33698364815c03af4de Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 23:16:05 +0200 Subject: [PATCH 0814/1068] format --- .../logic/oostyle/OOFormatBibliography.java | 10 ++++------ .../org/jabref/model/oostyle/CitationGroup.java | 15 ++++++--------- .../org/jabref/model/oostyle/CitationGroups.java | 2 ++ 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index 6b0cddab0a4..d38f72f94bc 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -209,12 +209,10 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { // sort the citationGroups according to their indexInGlobalOrder citationGroups.sort((a, b) -> { - return (a - .getIndexInGlobalOrder() - .orElseThrow(RuntimeException::new) - .compareTo(b - .getIndexInGlobalOrder() - .orElseThrow(RuntimeException::new))); }); + Integer aa = a.getIndexInGlobalOrder().orElseThrow(RuntimeException::new); + Integer bb = b.getIndexInGlobalOrder().orElseThrow(RuntimeException::new); + return (aa.compareTo(bb)); + }); int i = 0; for (CitationGroup cg : citationGroups) { diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index dd17f832ec6..f929f9a0854 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -19,11 +19,6 @@ public class CitationGroup { */ public final CitationGroupID cgid; - /* - * Identifies location in the document for the backend. - */ - // public final NamedRange cgRangeStorage; - /* * The core data, stored in the document: * The type of citation and citations in storage order. @@ -37,7 +32,7 @@ public class CitationGroup { /* * A name of a reference mark to link to by formatCitedOnPages. - * May be ininitially empty, if backend does not use reference marks. + * May be initially empty, if backend does not use reference marks. * * produceCitationMarkers might want fill it to support * cross-references to citation groups from the bibliography. @@ -65,13 +60,11 @@ public class CitationGroup { public CitationGroup(OODataModel dataModel, CitationGroupID cgid, - // NamedRange cgRangeStorage, InTextCitationType citationType, List citationsInStorageOrder, Optional referenceMarkNameForLinking) { this.dataModel = dataModel; this.cgid = cgid; - // this.cgRangeStorage = cgRangeStorage; this.citationType = citationType; this.citationsInStorageOrder = Collections.unmodifiableList(citationsInStorageOrder); this.localOrder = ListUtil.makeIndices(citationsInStorageOrder.size()); @@ -147,6 +140,10 @@ public void setReferenceMarkNameForLinking(Optional referenceMarkNameFor this.referenceMarkNameForLinking = referenceMarkNameForLinking; } + /* + * citationMarker + */ + public void setCitationMarker(Optional citationMarker) { this.citationMarker = citationMarker; } @@ -155,4 +152,4 @@ public Optional getCitationMarker() { return this.citationMarker; } -} // class CitationGroup +} diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index e54c8bbeb75..195fcef79bb 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -111,6 +111,8 @@ public void setGlobalOrder(List globalOrder) { + " globalOrder.size() != numberOfCitationGroups()"); } this.globalOrder = Optional.of(globalOrder); + + // Propagate to each CitationGroup int i = 0; for (CitationGroupID cgid : globalOrder) { citationGroupsUnordered.get(cgid).setIndexInGlobalOrder(Optional.of(i)); From 6e1a52fae8d562939decf70918bf9fbd7ec11855 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 22 May 2021 23:46:05 +0200 Subject: [PATCH 0815/1068] format and reorder in OOFormatBibliography.java --- .../logic/oostyle/OOFormatBibliography.java | 144 +++++++----------- 1 file changed, 55 insertions(+), 89 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index d38f72f94bc..d6337aea27d 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -25,25 +25,35 @@ public class OOFormatBibliography { private OOFormatBibliography() { } - /* - * @return just the body. No label, "Cited on pages" or paragraph. + /** + * Format the bibliography, including its title. */ - public static OOText formatBibliographyEntryBody(CitedKey ck, - OOBibStyle style) { - if (ck.db.isEmpty()) { - // Unresolved entry - return OOText.fromString(String.format("Unresolved(%s)", ck.citationKey)); - } else { - // Resolved entry, use the layout engine - BibEntry bibentry = ck.db.get().entry; - Layout layout = style.getReferenceFormat(bibentry.getType()); - layout.setPostFormatter(POSTFORMATTER); + public static OOText formatBibliography(CitationGroups cgs, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { - return formatFullReferenceOfBibEbtry(layout, - bibentry, - ck.db.get().database, - ck.uniqueLetter.orElse(null)); + OOText title = style.getFormattedBibliographyTitle(); + OOText body = formatBibliographyBody(cgs, bibliography, style, alwaysAddCitedOnPages); + return OOText.fromString(title.asString() + body.asString()); + } + + /** + * Format the body of bibliography. Excludes the title. + */ + public static OOText formatBibliographyBody(CitationGroups cgs, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) { + + StringBuilder stringBuilder = new StringBuilder(); + + for (CitedKey ck : bibliography.values()) { + OOText entryText = formatBibliographyEntry(cgs, ck, style, alwaysAddCitedOnPages); + stringBuilder.append(entryText.asString()); } + + return OOText.fromString(stringBuilder.toString()); } /* @@ -57,33 +67,22 @@ public static OOText formatBibliographyEntry(CitationGroups cgs, // insert marker "[1]" if (style.isNumberEntries()) { - if (ck.number.isEmpty()) { throw new RuntimeException("formatBibliographyEntry:" + " numbered style, but found unnumbered entry"); } - - int number = ck.number.get(); - OOText marker = style.getNumCitationMarkerForBibliography(number); - sb.append(marker.asString()); + sb.append(style.getNumCitationMarkerForBibliography(ck.number.get()).asString()); } else { // !style.isNumberEntries() : emit no prefix // Note: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); } // Add entry body - OOText formattedText = formatBibliographyEntryBody(ck, style); - sb.append(formattedText.asString()); + sb.append(formatBibliographyEntryBody(ck, style).asString()); // Add "Cited on pages" - if (ck.db.isEmpty()) { - // Unresolved entry: add links to citations + if (ck.db.isEmpty() || alwaysAddCitedOnPages) { sb.append(formatCitedOnPages(cgs, ck).asString()); - } else { - // Resolved entry - if (alwaysAddCitedOnPages) { - sb.append(formatCitedOnPages(cgs, ck).asString()); - } } // Add paragraph @@ -92,55 +91,24 @@ public static OOText formatBibliographyEntry(CitationGroups cgs, return OOFormat.paragraph(entryText, parStyle); } - /** - * Format body of bibliography. + /* + * @return just the body. No label, "Cited on pages" or paragraph. */ - public static OOText formatBibliographyBody(CitationGroups cgs, - CitedKeys bibliography, - OOBibStyle style, - boolean alwaysAddCitedOnPages) { - - final boolean debugThisFun = false; + public static OOText formatBibliographyEntryBody(CitedKey ck, OOBibStyle style) { + if (ck.db.isEmpty()) { + // Unresolved entry + return OOText.fromString(String.format("Unresolved(%s)", ck.citationKey)); + } else { + // Resolved entry, use the layout engine + BibEntry bibentry = ck.db.get().entry; + Layout layout = style.getReferenceFormat(bibentry.getType()); + layout.setPostFormatter(POSTFORMATTER); - if (debugThisFun) { - System.out.printf("Ref IsSortByPosition %s\n", style.isSortByPosition()); - System.out.printf("Ref IsNumberEntries %s\n", style.isNumberEntries()); + return formatFullReferenceOfBibEntry(layout, + bibentry, + ck.db.get().database, + ck.uniqueLetter.orElse(null)); } - - StringBuilder stringBuilder = new StringBuilder(); - - for (CitedKey ck : bibliography.values()) { - StringBuilder sb = new StringBuilder(); - - if (debugThisFun) { - System.out.printf("Ref cit %-20s ck.number %7s%n", - String.format("'%s'", ck.citationKey), - (ck.number.isEmpty() - ? "(empty)" - : String.format("%02d", ck.number.get()))); - } - - OOText entryText = formatBibliographyEntry(cgs, ck, style, alwaysAddCitedOnPages); - - // Add full entry to bibliography. - stringBuilder.append(entryText.asString()); - } // for CitedKey - - OOText full = OOText.fromString(stringBuilder.toString()); - return full; - } - - public static OOText formatBibliography(CitationGroups cgs, - CitedKeys bibliography, - OOBibStyle style, - boolean alwaysAddCitedOnPages) { - - OOText title = style.getFormattedBibliographyTitle(); - OOText body = OOFormatBibliography.formatBibliographyBody(cgs, - bibliography, - style, - alwaysAddCitedOnPages); - return OOText.fromString(title.asString() + body.asString()); } /** @@ -153,7 +121,7 @@ public static OOText formatBibliography(CitationGroups cgs, * * @return OOText suitable for OOTextIntoOO.write() */ - private static OOText formatFullReferenceOfBibEbtry(Layout layout, + private static OOText formatFullReferenceOfBibEntry(Layout layout, BibEntry entry, BibDatabase database, String uniquefier) { @@ -181,19 +149,19 @@ private static OOText formatFullReferenceOfBibEbtry(Layout layout, return formattedText; } + /* + * Format links to citations of the source (ck). + * + * Requires reference marks for citation groups. + * + * - The links are created as references that show page numbers of the reference marks. + * - We do not control the text shown, that is provided by OpenOffice. + */ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { if (!cgs.citationGroupsProvideReferenceMarkNameForLinking()) { return OOText.fromString(""); } - // Format links to citations. - // - // Requires reference marks for citation groups. - // - // - With Reference - // - we do not control the text shown - // - using page numbers: useful in print - // StringBuilder sb = new StringBuilder(); String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); @@ -219,10 +187,8 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { if (i > 0) { sb.append(", "); } - String referenceMarkName = (cg.getReferenceMarkNameForLinking() - .orElseThrow(RuntimeException::new)); - OOText xref = - OOFormat.formatReferenceToPageNumberOfReferenceMark(referenceMarkName); + String markName = cg.getReferenceMarkNameForLinking().orElseThrow(RuntimeException::new); + OOText xref = OOFormat.formatReferenceToPageNumberOfReferenceMark(markName); sb.append(xref.asString()); i++; } From 169ba2ff9ab0dea0f5849cbc77f2233d53794dba Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 09:48:12 +0200 Subject: [PATCH 0816/1068] drop unused nullToEmpty --- src/main/java/org/jabref/logic/oostyle/OOBibStyle.java | 4 ---- .../jabref/logic/oostyle/OOBibStyleGetCitationMarker.java | 8 -------- 2 files changed, 12 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 66927057929..64391d93259 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -1206,10 +1206,6 @@ public String getBracketAfterInListWithFallBack() { getBracketAfter()); } - private String nullToEmpty(String s) { - return (s == null ? "" : s); - } - public OOText getFormattedBibliographyTitle() { OOBibStyle style = this; OOText title = style.getReferenceHeaderText(); diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 292de0f6e37..978219d9a75 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -499,14 +499,6 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, return OOText.fromString(sb.toString()); } - // "" is more convenient to compare for equality than null-or-String - private static String nullToEmptyString(String s) { - if (s == null) { - return ""; - } - return s; - } - private static class CitationMarkerNormEntryWrap implements CitationMarkerEntry { CitationMarkerNormEntry inner; From 5e8c18d3beb7b99d56750f028303995457aae09d Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 10:38:41 +0200 Subject: [PATCH 0817/1068] fakePageInfosForCitations renames fakePageInfos --- .../jabref/logic/openoffice/Backend52.java | 2 +- .../jabref/logic/openoffice/EditInsert.java | 2 +- .../org/jabref/model/oostyle/OODataModel.java | 34 +++++-------------- 3 files changed, 11 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index f4113cd0e2d..8f074fd9371 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -302,7 +302,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, if ("".equals(cgPageInfo)) { cgPageInfo = null; } - return OODataModel.fakePageInfosForCitations(cgPageInfo, nCitations); + return OODataModel.fakePageInfos(cgPageInfo, nCitations); case JabRef53: return (joinableGroup.stream() diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 4d730ce601e..c5044e15d4c 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -89,7 +89,7 @@ public static void insertCitationGroup(XTextDocument doc, // JabRef53 style pageInfo list List> pageInfosForCitations = - OODataModel.fakePageInfosForCitations(pageInfo, nEntries); + OODataModel.fakePageInfos(pageInfo, nEntries); List citations = new ArrayList<>(nEntries); for (int i = 0; i < nEntries; i++) { diff --git a/src/main/java/org/jabref/model/oostyle/OODataModel.java b/src/main/java/org/jabref/model/oostyle/OODataModel.java index b4fe0229988..3804bedf63a 100644 --- a/src/main/java/org/jabref/model/oostyle/OODataModel.java +++ b/src/main/java/org/jabref/model/oostyle/OODataModel.java @@ -6,47 +6,31 @@ /** What is the data stored? */ public enum OODataModel { + /** * JabRef52: * pageInfo belongs to CitationGroup, not Citation. - * - * Note: pageInfo stored in [File]/[Properties]/[Custom Properties] - * - * under the same name as the reference mark for the - * CitationGroup. - * - * JabRef "Merge" leaves pageInfo values of the parts joined - * around. Separate, or a new citation may pick these up. - * - * In-text citep format: "[ ... ; pageInfo]", injected just before the - * closing parenthesis (here "]"), with "; " as a separator. - * - * citet format: the same, (injected to parens around - * year of last citation of the group) */ JabRef52, /** * JabRef53: * pageInfo belongs to Citation. - * Need: formatting citation needs to know about these, inject after each year part */ JabRef53; /** * @param pageInfo Nullable. - * @return JabRef53 style pageInfo list + * @return JabRef53 style pageInfo list with pageInfo in the last slot. */ - public static List> fakePageInfosForCitations(String pageInfo, - int nCitations) { - List> pageInfosForCitations = new ArrayList<>(nCitations); + public static List> fakePageInfos(String pageInfo, int nCitations) { + List> pageInfos = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { - if (i == (nCitations - 1) && (pageInfo != null)) { - pageInfosForCitations.add(Optional.of(OOText.fromString(pageInfo))); - } else { - pageInfosForCitations.add(Optional.empty()); - } + pageInfos.add(Optional.empty()); + } + if (pageInfo != null) { + pageInfos.set(last, Optional.ofNullable(OOText.fromString(pageInfo))); } - return pageInfosForCitations; + return pageInfos; } } From 1fa28c674f2aca3640f5f8faf3efd01c6702ec34 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 11:36:17 +0200 Subject: [PATCH 0818/1068] pageInfosForCitations -> pageInfos, ListUtil -> OOListUtil --- .../org/jabref/logic/oostyle/OOBibStyle.java | 35 +++++++++---------- .../OOBibStyleGetNumCitationMarker.java | 20 +++++------ .../oostyle/OOProcessAuthorYearMarkers.java | 4 +-- .../oostyle/OOProcessCitationKeyMarkers.java | 4 +-- .../oostyle/OOProcessNumericMarkers.java | 6 ++-- .../jabref/logic/openoffice/Backend52.java | 12 +++---- .../jabref/logic/openoffice/EditInsert.java | 13 +++---- .../jabref/logic/openoffice/EditMerge.java | 20 ++--------- .../jabref/logic/openoffice/OOFrontend.java | 12 +++---- .../openoffice/UpdateCitationMarkers.java | 12 +++---- .../jabref/model/oostyle/CitationGroup.java | 8 ++--- .../jabref/model/oostyle/CitationGroups.java | 2 +- .../org/jabref/model/oostyle/OODataModel.java | 4 ++- .../{ListUtil.java => OOListUtil.java} | 9 ++--- 14 files changed, 71 insertions(+), 90 deletions(-) rename src/main/java/org/jabref/model/oostyle/{ListUtil.java => OOListUtil.java} (84%) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 64391d93259..c9c0a379cb6 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -34,6 +34,7 @@ import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerNormEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; +import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; import org.slf4j.Logger; @@ -445,11 +446,11 @@ public Layout getReferenceFormat(EntryType type) { */ public OOText getNumCitationMarker(List number, int minGroupingCount, - List> pageInfosForCitations) { + List> pageInfos) { return OOBibStyleGetNumCitationMarker.getNumCitationMarker(this, number, minGroupingCount, - pageInfosForCitations); + pageInfos); } /* moved to OOBibStyleGetCitationMarker @@ -946,30 +947,28 @@ public OOText getNumCitationMarkerForBibliography(int number) { * Make sure that (1) we have exactly one entry for each * citation, (2) each entry is either Optional.empty or its content is not empty when trimmed. * - * As a special case: pageInfosForCitations may be null. In this case + * As a special case: pageInfos may be null. In this case * the result is a list filled with Optional.empty() values. */ - public static List> - regularizePageInfosForCitations(List> pageInfosForCitations, - int nCitations) { - if (pageInfosForCitations == null) { + static List> + normalizePageInfos(List> pageInfos, int nCitations) { + + // translate null to all-empty + if (pageInfos == null) { List> res = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { res.add(Optional.empty()); } return res; - } else { - if (pageInfosForCitations.size() != nCitations) { - throw new RuntimeException("regularizePageInfosForCitations:" - + " pageInfosForCitations.size() != nCitations"); - } - List> res = new ArrayList<>(nCitations); - for (int i = 0; i < nCitations; i++) { - Optional p = pageInfosForCitations.get(i); - res.add(Citation.normalizePageInfo(p)); - } - return res; } + + // not null, check size + if (pageInfos.size() != nCitations) { + throw new RuntimeException("normalizePageInfos: pageInfos.size() != nCitations"); + } + + // not null, normalize elementwise + return OOListUtil.map(pageInfos, Citation::normalizePageInfo); } public OOText getNormalizedCitationMarker(CitationMarkerNormEntry ce) { diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index 476d0316df9..9adb9673fb9 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -50,12 +50,12 @@ private enum CitationMarkerPurpose { public static OOText getNumCitationMarker(OOBibStyle style, List numbers, int minGroupingCount, - List> pageInfosForCitations) { + List> pageInfos) { return getNumCitationMarkerCommon(style, numbers, minGroupingCount, CitationMarkerPurpose.CITATION, - pageInfosForCitations); + pageInfos); } /** @@ -112,9 +112,9 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, * * If BIBLIOGRAPHY: Prefer BRACKET_BEFORE_IN_LIST over BRACKET_BEFORE, * and BRACKET_AFTER_IN_LIST over BRACKET_AFTER. - * Ignore pageInfosForCitations. + * Ignore pageInfos. * - * @param pageInfosForCitations Null for "none", or a list with an optional + * @param pageInfosIn Null for "none", or a list with an optional * pageInfo for each citation. Any or all of these can be Optional.empty * * @return The text for the citation. @@ -125,7 +125,7 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, List numbers, int minGroupingCount, CitationMarkerPurpose purpose, - List> pageInfosForCitations) { + List> pageInfosIn) { final boolean joinIsDisabled = (minGroupingCount <= 0); final int notFoundInDatabases = 0; @@ -178,17 +178,17 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, /* * From here: * - formatting for in-text (not for bibliography) - * - need to care about pageInfosForCitations + * - need to care about pageInfos * * - In case {@code strictPurpose} above is set to false and allows us to * get here, and {@code purpose==BIBLIOGRAPHY}, then we just fill * pageInfos with null values. */ List> pageInfos = - OOBibStyle.regularizePageInfosForCitations((purpose == CitationMarkerPurpose.BIBLIOGRAPHY - ? null - : pageInfosForCitations), - numbers.size()); + OOBibStyle.normalizePageInfos((purpose == CitationMarkerPurpose.BIBLIOGRAPHY + ? null + : pageInfosIn), + numbers.size()); // Sort the numbers, together with the corresponding pageInfo values List nps = new ArrayList<>(); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java index 9811822d679..2e240647fa2 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java @@ -15,8 +15,8 @@ import org.jabref.model.oostyle.CitedKey; import org.jabref.model.oostyle.CitedKeys; import org.jabref.model.oostyle.InTextCitationType; -import org.jabref.model.oostyle.ListUtil; import org.jabref.model.oostyle.NonUniqueCitationMarker; +import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; class OOProcessAuthorYearMarkers { @@ -152,7 +152,7 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { final NonUniqueCitationMarker strictlyUnique = NonUniqueCitationMarker.THROWS; List cits = cg.getCitationsInLocalOrder(); - List citationMarkerEntries = ListUtil.map(cits, e -> e); + List citationMarkerEntries = OOListUtil.map(cits, e -> e); OOText citMarker = style.getCitationMarker2(citationMarkerEntries, inParenthesis, strictlyUnique); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java index f3dcd48551f..70a7118f43c 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java @@ -5,7 +5,7 @@ import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.ListUtil; +import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; class OOProcessCitationKeyMarkers { @@ -22,7 +22,7 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { String citMarker = style.getCitationGroupMarkupBefore() - + String.join(",", ListUtil.map(cg.getCitationsInLocalOrder(), Citation::getCitationKey)) + + String.join(",", OOListUtil.map(cg.getCitationsInLocalOrder(), Citation::getCitationKey)) + style.getCitationGroupMarkupAfter(); cg.setCitationMarker(Optional.of(OOText.fromString(citMarker))); } diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java index a88c68de1d1..dbd1f248560 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java @@ -6,7 +6,7 @@ import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.ListUtil; +import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; class OOProcessNumericMarkers { @@ -38,9 +38,9 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { List cits = cg.getCitationsInLocalOrder(); OOText citMarker = - style.getNumCitationMarker(ListUtil.map(cits, Citation::getNumberOrThrow), + style.getNumCitationMarker(OOListUtil.map(cits, Citation::getNumberOrThrow), minGroupingCount, - ListUtil.map(cits, Citation::getPageInfo)); + OOListUtil.map(cits, Citation::getPageInfo)); cg.setCitationMarker(Optional.of(citMarker)); } } diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 8f074fd9371..2b75f1471a2 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -189,7 +189,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str */ public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, - List> pageInfosForCitations, + List> pageInfos, InTextCitationType citationType, XTextCursor position, boolean insertSpaceAfter) @@ -202,9 +202,9 @@ public CitationGroup createCitationGroup(XTextDocument doc, PropertyVetoException, IllegalTypeException { - Objects.requireNonNull(pageInfosForCitations); - if (pageInfosForCitations.size() != citationKeys.size()) { - throw new RuntimeException("pageInfosForCitations.size != citationKeys.size"); + Objects.requireNonNull(pageInfos); + if (pageInfos.size() != citationKeys.size()) { + throw new RuntimeException("pageInfos.size != citationKeys.size"); } // Get a new refMarkName @@ -223,7 +223,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, Citation cit = new Citation(citationKeys.get(i)); citations.add(cit); - Optional pageInfo = Citation.normalizePageInfo(pageInfosForCitations.get(i)); + Optional pageInfo = Citation.normalizePageInfo(pageInfos.get(i)); switch (dataModel) { case JabRef52: if (i == last) { @@ -252,7 +252,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, switch (dataModel) { case JabRef52: Optional pageInfo = - Citation.normalizePageInfo(pageInfosForCitations.get(last)); + Citation.normalizePageInfo(pageInfos.get(last)); if (pageInfo.isPresent()) { String pageInfoString = OOText.toString(pageInfo.get()); diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index c5044e15d4c..f3614ecaf9b 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -12,9 +12,9 @@ import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.InTextCitationType; -import org.jabref.model.oostyle.ListUtil; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OODataModel; +import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -83,19 +83,16 @@ public static void insertCitationGroup(XTextDocument doc, IllegalTypeException, JabRefException { - List citationKeys = ListUtil.map(entries, EditInsert::insertEntryGetCitationKey); + List citationKeys = OOListUtil.map(entries, EditInsert::insertEntryGetCitationKey); final int nEntries = entries.size(); - - // JabRef53 style pageInfo list - List> pageInfosForCitations = - OODataModel.fakePageInfos(pageInfo, nEntries); + List> pageInfos = OODataModel.fakePageInfos(pageInfo, nEntries); List citations = new ArrayList<>(nEntries); for (int i = 0; i < nEntries; i++) { Citation cit = new Citation(citationKeys.get(i)); cit.lookupInDatabases(Collections.singletonList(database)); - cit.setPageInfo(pageInfosForCitations.get(i)); + cit.setPageInfo(pageInfos.get(i)); citations.add(cit); } @@ -114,7 +111,7 @@ public static void insertCitationGroup(XTextDocument doc, UpdateCitationMarkers.createAndFillCitationGroup(fr, doc, citationKeys, - pageInfosForCitations, + pageInfos, citationType, citeText, cursor, diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index c0113c5a53c..c954218f612 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -330,37 +330,23 @@ public static boolean mergeCitationGroups(XTextDocument doc, newGroupCitations.addAll(cg.citationsInStorageOrder); } - // Since we only join groups with identical citationTypes, we - // can get citationType from the first element of each - // joinable group. InTextCitationType citationType = cgs.get(0).citationType; + List> pageInfos = fr.backend.combinePageInfos(cgs); - // cgPageInfos belong to the CitationGroup (DataModel JabRef52), - // but it is not clear how should we handle them here. - // We delegate the problem to the backend. - List> pageInfosForCitations = - fr.backend.combinePageInfos(cgs); - - // Remove the old citation groups from the document. fr.removeCitationGroups(cgs, doc); - XTextCursor textCursor = joinableGroupData.groupCursor; - - // Also remove the spaces between. - textCursor.setString(""); + textCursor.setString(""); // Also remove the spaces between. List citationKeys = (newGroupCitations.stream() .map(cit -> cit.citationKey) .collect(Collectors.toList())); - // Insert reference mark: - /* insertSpaceAfter: no, it is already there (or could be) */ boolean insertSpaceAfter = false; UpdateCitationMarkers.createAndFillCitationGroup(fr, doc, citationKeys, - pageInfosForCitations, + pageInfos, citationType, OOText.fromString("tmp"), textCursor, diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 81b5d87f44e..7b328b15548 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -244,7 +244,7 @@ public Optional healthReport(XTextDocument doc) * inserted space, or at the end of the reference mark. * * @param citationKeys In storage order - * @param pageInfosForCitations In storage order + * @param pageInfos In storage order * @param citationType * @param position Collapsed to its end. * @param insertSpaceAfter If true, we insert a space after the mark, that @@ -253,7 +253,7 @@ public Optional healthReport(XTextDocument doc) */ public CitationGroupID createCitationGroup(XTextDocument doc, List citationKeys, - List> pageInfosForCitations, + List> pageInfos, InTextCitationType citationType, XTextCursor position, boolean insertSpaceAfter) @@ -266,13 +266,13 @@ public CitationGroupID createCitationGroup(XTextDocument doc, PropertyVetoException, IllegalTypeException { - Objects.requireNonNull(pageInfosForCitations); - if (pageInfosForCitations.size() != citationKeys.size()) { - throw new RuntimeException("pageInfosForCitations.size != citationKeys.size"); + Objects.requireNonNull(pageInfos); + if (pageInfos.size() != citationKeys.size()) { + throw new RuntimeException("pageInfos.size != citationKeys.size"); } CitationGroup cg = backend.createCitationGroup(doc, citationKeys, - pageInfosForCitations, + pageInfos, citationType, position, insertSpaceAfter); diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 179caba51d6..e9f461c3f5c 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -115,7 +115,7 @@ public static void fillCitationMarkInCursor(XTextDocument doc, * Inserts a citation group in the document: creates and fills it. * * @param citationKeys BibTeX keys of - * @param pageInfosForCitations + * @param pageInfos * @param citationType * * @param citationText Text for the citation. A citation mark or @@ -131,7 +131,7 @@ public static void fillCitationMarkInCursor(XTextDocument doc, public static void createAndFillCitationGroup(OOFrontend fr, XTextDocument doc, List citationKeys, - List> pageInfosForCitations, + List> pageInfos, InTextCitationType citationType, OOText citationText, XTextCursor position, @@ -150,13 +150,13 @@ public static void createAndFillCitationGroup(OOFrontend fr, IllegalTypeException, NoSuchElementException { - Objects.requireNonNull(pageInfosForCitations); - if (pageInfosForCitations.size() != citationKeys.size()) { - throw new RuntimeException("pageInfosForCitations.size != citationKeys.size"); + Objects.requireNonNull(pageInfos); + if (pageInfos.size() != citationKeys.size()) { + throw new RuntimeException("pageInfos.size != citationKeys.size"); } CitationGroupID cgid = fr.createCitationGroup(doc, citationKeys, - pageInfosForCitations, + pageInfos, citationType, position, insertSpaceAfter); diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index f929f9a0854..559514d3921 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -67,7 +67,7 @@ public CitationGroup(OODataModel dataModel, this.cgid = cgid; this.citationType = citationType; this.citationsInStorageOrder = Collections.unmodifiableList(citationsInStorageOrder); - this.localOrder = ListUtil.makeIndices(citationsInStorageOrder.size()); + this.localOrder = OOListUtil.makeIndices(citationsInStorageOrder.size()); this.referenceMarkNameForLinking = referenceMarkNameForLinking; this.indexInGlobalOrder = Optional.empty(); this.citationMarker = Optional.empty(); @@ -96,8 +96,8 @@ void imposeLocalOrder(Comparator entryComparator) { lastCitation.setPageInfo(Optional.empty()); } - this.localOrder = ListUtil.order(citationsInStorageOrder, - new CompareCitation(entryComparator, true)); + this.localOrder = OOListUtil.order(citationsInStorageOrder, + new CompareCitation(entryComparator, true)); if (dataModel == OODataModel.JabRef52) { getCitationsInLocalOrder().get(last).setPageInfo(lastPageInfo); @@ -113,7 +113,7 @@ public List getLocalOrder() { */ public List getCitationsInLocalOrder() { - return ListUtil.map(localOrder, i -> citationsInStorageOrder.get(i)); + return OOListUtil.map(localOrder, i -> citationsInStorageOrder.get(i)); } /* diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 195fcef79bb..f4498611912 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -101,7 +101,7 @@ public List getCitationGroupsInGlobalOrder() { if (globalOrder.isEmpty()) { throw new RuntimeException("getCitationGroupsInGlobalOrder: not ordered yet"); } - return ListUtil.map(globalOrder.get(), cgid -> citationGroupsUnordered.get(cgid)); + return OOListUtil.map(globalOrder.get(), cgid -> citationGroupsUnordered.get(cgid)); } public void setGlobalOrder(List globalOrder) { diff --git a/src/main/java/org/jabref/model/oostyle/OODataModel.java b/src/main/java/org/jabref/model/oostyle/OODataModel.java index 3804bedf63a..ed735db81ee 100644 --- a/src/main/java/org/jabref/model/oostyle/OODataModel.java +++ b/src/main/java/org/jabref/model/oostyle/OODataModel.java @@ -29,7 +29,9 @@ public static List> fakePageInfos(String pageInfo, int nCitatio pageInfos.add(Optional.empty()); } if (pageInfo != null) { - pageInfos.set(last, Optional.ofNullable(OOText.fromString(pageInfo))); + final int last = nCitations - 1; + Optional pi = Optional.ofNullable(OOText.fromString(pageInfo)); + pageInfos.set(last, Citation.normalizePageInfo(pi)); } return pageInfos; } diff --git a/src/main/java/org/jabref/model/oostyle/ListUtil.java b/src/main/java/org/jabref/model/oostyle/OOListUtil.java similarity index 84% rename from src/main/java/org/jabref/model/oostyle/ListUtil.java rename to src/main/java/org/jabref/model/oostyle/OOListUtil.java index 249c3e6437d..b7c11e1269e 100644 --- a/src/main/java/org/jabref/model/oostyle/ListUtil.java +++ b/src/main/java/org/jabref/model/oostyle/OOListUtil.java @@ -7,7 +7,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -public class ListUtil { +public class OOListUtil { public static List map(List list, Function fun) { return list.stream().map(e -> fun.apply(e)).collect(Collectors.toList()); @@ -18,11 +18,8 @@ public static List makeIndices(int n) { return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); } - /** Return indices so that list.get(indices.get(i)) is sorted. - * - * Precondition: T must be castable to U. - */ - public static List order(List list, Comparator comparator) { + /** Return indices so that list.get(indices.get(i)) is sorted. */ + public static List order(List list, Comparator comparator) { List ii = makeIndices(list.size()); Collections.sort(ii, new Comparator() { @Override public int compare(final Integer o1, final Integer o2) { From 3b170171e7a8935ebe69cb89b5167887e5207108 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 13:10:24 +0200 Subject: [PATCH 0819/1068] extract emitBlock --- .../OOBibStyleGetNumCitationMarker.java | 257 +++++++++--------- 1 file changed, 124 insertions(+), 133 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index 9adb9673fb9..db64c649177 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -4,13 +4,17 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.function.ToIntFunction; import org.jabref.model.oostyle.CompareCitation; import org.jabref.model.oostyle.OOText; class OOBibStyleGetNumCitationMarker { + /* + * The number encoding "this entry is unresolved" + */ + public final static int UNRESOLVED_ENTRY_NUMBER = 0; + /* * Helper class for sorting citation numbers while * maintaining their correspondence to pageInfos. @@ -48,9 +52,9 @@ private enum CitationMarkerPurpose { * See {@see getNumCitationMarkerCommon} for details. */ public static OOText getNumCitationMarker(OOBibStyle style, - List numbers, - int minGroupingCount, - List> pageInfos) { + List numbers, + int minGroupingCount, + List> pageInfos) { return getNumCitationMarkerCommon(style, numbers, minGroupingCount, @@ -71,8 +75,7 @@ public static OOText getNumCitationMarker(OOBibStyle style, * "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER) * "${number}" stands for the formatted number. */ - public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, - int number) { + public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, int number) { return getNumCitationMarkerCommon(style, Collections.singletonList(number), 0, @@ -80,6 +83,108 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, null); } + /* + * emitBlock + * + * Given a block containing 1 or (two or more) + * NumberWithPageInfo entries that are either singletons or + * joinable into an "i-j" form, append to {@code sb} the + * formatted text. + * + * Assumes: + * + * - block is not empty + * + * - For a block with a single element the element may have + * pageInfo and its num part may be UNRESOLVED_ENTRY_NUMBER. + * + * - For a block with two or more elements + * + * - The elements do not have pageInfo and their num part is + * not zero. + * + * - The elements num parts are consecutive positive integers, + * without repetition. + * + * Note: this function is long enough to move into a separate method. + * On the other hand, its assumptions strongly tie it to + * the loop below that collects the block. + */ + private static void emitBlock(List block, + OOBibStyle style, + int minGroupingCount, + StringBuilder sb) { + + final int blockSize = block.size(); + if (blockSize == 0) { + throw new RuntimeException("The block is empty"); + } + + if (blockSize == 1) { + // Add single entry: + final int num = block.get(0).num; + sb.append(num == UNRESOLVED_ENTRY_NUMBER + ? OOBibStyle.UNDEFINED_CITATION_MARKER + : String.valueOf(num)); + // Emit pageInfo + Optional pageInfo = block.get(0).pageInfo; + if (pageInfo.isPresent()) { + sb.append(style.getPageInfoSeparator()); + sb.append(OOText.toString(pageInfo.get())); + } + return; + } + + if (blockSize >= 2) { + + /* + * Check assumptions + */ + + if (block.stream().anyMatch(x -> x.pageInfo.isPresent())) { + throw new RuntimeException("Found pageInfo in a block with more than one elements"); + } + + if (block.stream().anyMatch(x -> x.num == UNRESOLVED_ENTRY_NUMBER)) { + throw new RuntimeException("Found UNRESOLVED_ENTRY_NUMBER" + + " in a block with more than one elements"); + } + + for (int j = 1; j < blockSize; j++) { + if ((block.get(j).num - block.get(j - 1).num) != 1) { + throw new RuntimeException("Numbers are not consecutive"); + } + } + + /* + * Do the actual work + */ + + if (blockSize >= minGroupingCount) { + int first = block.get(0).num; + int last = block.get(blockSize - 1).num; + if (last != (first + blockSize - 1)) { + throw new RuntimeException("blockSize and length of num range differ"); + } + + // Emit: "first-last" + sb.append(first); + sb.append(style.getGroupedNumbersSeparator()); + sb.append(last); + } else { + + // Emit: first, first+1,..., last + for (int j = 0; j < blockSize; j++) { + if (j > 0) { + sb.append(style.getCitationSeparator()); + } + sb.append(block.get(j).num); + } + } + return; + } + } + /** * Format a number-based citation marker for the given number or numbers. * @@ -128,7 +233,6 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, List> pageInfosIn) { final boolean joinIsDisabled = (minGroupingCount <= 0); - final int notFoundInDatabases = 0; final int nCitations = numbers.size(); /* @@ -166,7 +270,7 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, if (current < 0) { throw new RuntimeException("getNumCitationMarker: found negative value"); } - sb.append(current != notFoundInDatabases + sb.append(current != UNRESOLVED_ENTRY_NUMBER ? String.valueOf(current) : OOBibStyle.UNDEFINED_CITATION_MARKER); sb.append(bracketAfter); @@ -200,116 +304,6 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, // "[" StringBuilder sb = new StringBuilder(bracketBefore); - /* - * int emitBlock(List block) - * - * Given a block containing 1 or (two or more) - * NumberWithPageInfo entries collected as singletons or - * joinable into an "i-j" form, append to {@code sb} the - * formatted text. - * - * Assumes: - * - * - block is not empty - * - * - For a block with a single element the element may have - * pageInfo and its num part may be zero - * (notFoundInDatabases). - * - * - For a block with two or more elements - * - * - The elements do not have pageInfo and their num part is - * not zero. - * - * - The elements num parts are consecutive positive integers, - * without repetition. - * - * Note: this function is long enough to move into a separate method. - * On the other hand, its assumptions strongly tie it to - * the loop below that collects the block. - * - * @return The number of blocks emitted. Since currently - * throws if the block is empty, the returned value is - * always 1. - * - */ - ToIntFunction> emitBlock = (List block) -> { - // uses: sb, this, - - final int blockSize = block.size(); - if (blockSize == 0) { - throw new RuntimeException("We should not get here"); - // return 0; - } - - if (blockSize == 1) { - // Add single entry: - final int num = block.get(0).num; - sb.append(num == notFoundInDatabases - ? OOBibStyle.UNDEFINED_CITATION_MARKER - : String.valueOf(num)); - // Emit pageInfo - Optional pageInfo = block.get(0).pageInfo; - if (pageInfo.isPresent()) { - sb.append(style.getPageInfoSeparator()); - sb.append(OOText.toString(pageInfo.get())); - } - } else { - // block has at least 2 elements - - /* - * Check assumptions - */ - - // None of these elements has a pageInfo, - // because if it had, we would not join. - for (NumberWithPageInfo x : block) { - if (x.pageInfo.isPresent()) { - throw new RuntimeException("impossible: (x.pageInfo.isPresent())"); - } - } - // None of these elements needs UNDEFINED_CITATION_MARKER, - // because if it did, we would not join. - for (NumberWithPageInfo x : block) { - if (x.num == notFoundInDatabases) { - throw new RuntimeException("impossible: (x.num == notFoundInDatabases)"); - } - } - // consecutive elements have consecutive numbers - for (int j = 1; j < blockSize; j++) { - if (block.get(j).num != (block.get(j - 1).num + 1)) { - throw new RuntimeException("impossible: consecutive elements" - + " without consecutive numbers"); - } - } - - /* - * Do the actual work - */ - if (blockSize >= minGroupingCount) { - int first = block.get(0).num; - int last = block.get(blockSize - 1).num; - if (((last + 1) - first) != blockSize) { - throw new RuntimeException("impossible:" - + " blockSize and length of num range differ"); - } - // Emit: "first-last" - sb.append(first); - sb.append(style.getGroupedNumbersSeparator()); - sb.append(last); - } else { - // Emit: first, first+1,..., last - for (int j = 0; j < blockSize; j++) { - if (j > 0) { - sb.append(style.getCitationSeparator()); - } - sb.append(block.get(j).num); - } - } - } - return 1; - }; - /* * Original: * [2,3,4] -> [2-4] @@ -322,7 +316,7 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, * [1 "pp nn",1 "pp nn"] -> [1 "pp nn"] */ - int blocksEmitted = 0; + boolean blocksEmitted = false; List currentBlock = new ArrayList<>(); List nextBlock = new ArrayList<>(); @@ -337,8 +331,8 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, currentBlock.add(current); } else { NumberWithPageInfo prev = currentBlock.get(currentBlock.size() - 1); - if ((notFoundInDatabases == current.num) - || (notFoundInDatabases == prev.num)) { + if ((UNRESOLVED_ENTRY_NUMBER == current.num) + || (UNRESOLVED_ENTRY_NUMBER == prev.num)) { nextBlock.add(current); // do not join if not found } else if (joinIsDisabled) { nextBlock.add(current); // join disabled @@ -357,19 +351,16 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, if (nextBlock.size() > 0) { // emit current block - // We are emitting a block - if (blocksEmitted > 0) { + if (blocksEmitted) { sb.append(style.getCitationSeparator()); } - int emittedNow = emitBlock.applyAsInt(currentBlock); - if (emittedNow > 0) { - blocksEmitted += emittedNow; - currentBlock = nextBlock; - nextBlock = new ArrayList<>(); - } - } // blockSize != 0 + emitBlock(currentBlock, style, minGroupingCount, sb); + blocksEmitted = true; + currentBlock = nextBlock; + nextBlock = new ArrayList<>(); + } - } // for i + } if (nextBlock.size() != 0) { throw new RuntimeException("impossible: (nextBlock.size() != 0) after loop"); @@ -377,10 +368,10 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, if (currentBlock.size() > 0) { // We are emitting a block - if (blocksEmitted > 0) { + if (blocksEmitted) { sb.append(style.getCitationSeparator()); } - emitBlock.applyAsInt(currentBlock); + emitBlock(currentBlock, style, minGroupingCount, sb); } // Emit: "]" From fb8ff9162307ebaa8b07eb44933da5b125eecf19 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 15:04:02 +0200 Subject: [PATCH 0820/1068] add OOListUtil.zip --- .../java/org/jabref/model/oostyle/OOListUtil.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/main/java/org/jabref/model/oostyle/OOListUtil.java b/src/main/java/org/jabref/model/oostyle/OOListUtil.java index b7c11e1269e..8498e909140 100644 --- a/src/main/java/org/jabref/model/oostyle/OOListUtil.java +++ b/src/main/java/org/jabref/model/oostyle/OOListUtil.java @@ -1,8 +1,10 @@ package org.jabref.model.oostyle; +import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -13,6 +15,19 @@ public static List map(List list, Function fun) { return list.stream().map(e -> fun.apply(e)).collect(Collectors.toList()); } + public static List zip(List a, + List b, + BiFunction fun) { + if (a.size() != b.size()) { + throw new RuntimeException("a.size != b.size"); + } + List result = new ArrayList<>(a.size()); + for (int i = 0; i < a.size(); i++) { + result.add(fun.apply(a.get(i), b.get(i))); + } + return result; + } + /** Integers 0..(n-1) */ public static List makeIndices(int n) { return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); From a04bc607a7e0f89bf67a970730ddf11d76003d33 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 15:05:02 +0200 Subject: [PATCH 0821/1068] rename getNumCitationMarker to getNumCitationMarker2 --- .../org/jabref/logic/oostyle/OOBibStyle.java | 14 +++--- .../OOBibStyleGetNumCitationMarker.java | 20 ++++---- .../oostyle/OOProcessNumericMarkers.java | 6 +-- .../jabref/logic/oostyle/OOBibStyleTest.java | 48 +++++++++---------- 4 files changed, 43 insertions(+), 45 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index c9c0a379cb6..0893b36d0bc 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -444,13 +444,13 @@ public Layout getReferenceFormat(EntryType type) { * @param number The citation numbers. * @return The text for the citation. */ - public OOText getNumCitationMarker(List number, - int minGroupingCount, - List> pageInfos) { - return OOBibStyleGetNumCitationMarker.getNumCitationMarker(this, - number, - minGroupingCount, - pageInfos); + public OOText getNumCitationMarker2(List number, + int minGroupingCount, + List> pageInfos) { + return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, + number, + minGroupingCount, + pageInfos); } /* moved to OOBibStyleGetCitationMarker diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index db64c649177..3d645e69d46 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -6,6 +6,7 @@ import java.util.Optional; import org.jabref.model.oostyle.CompareCitation; +import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; class OOBibStyleGetNumCitationMarker { @@ -51,7 +52,7 @@ private enum CitationMarkerPurpose { /** * See {@see getNumCitationMarkerCommon} for details. */ - public static OOText getNumCitationMarker(OOBibStyle style, + public static OOText getNumCitationMarker2(OOBibStyle style, List numbers, int minGroupingCount, List> pageInfos) { @@ -189,7 +190,7 @@ private static void emitBlock(List block, * Format a number-based citation marker for the given number or numbers. * * This is the common implementation behind - * getNumCitationMarker and + * getNumCitationMarker2 and * getNumCitationMarkerForBibliography. The latter could be easily * separated unless there is (or going to be) a need for handling * multiple numbers or page info by getNumCitationMarkerForBibliography. @@ -258,7 +259,7 @@ private static void emitBlock(List block, // If (purpose==BIBLIOGRAPHY), then // we expect exactly one number here, and can handle quickly if (nCitations != 1) { - throw new RuntimeException("getNumCitationMarker:" + throw new RuntimeException("getNumCitationMarker2:" + "nCitations != 1 for purpose==BIBLIOGRAPHY." + String.format(" nCitations = %d", nCitations)); } @@ -268,7 +269,7 @@ private static void emitBlock(List block, sb.append(bracketBefore); final int current = numbers.get(0); if (current < 0) { - throw new RuntimeException("getNumCitationMarker: found negative value"); + throw new RuntimeException("getNumCitationMarker2: found negative value"); } sb.append(current != UNRESOLVED_ENTRY_NUMBER ? String.valueOf(current) @@ -295,11 +296,8 @@ private static void emitBlock(List block, numbers.size()); // Sort the numbers, together with the corresponding pageInfo values - List nps = new ArrayList<>(); - for (int i = 0; i < nCitations; i++) { - nps.add(new NumberWithPageInfo(numbers.get(i), pageInfos.get(i))); - } - nps.sort(OOBibStyleGetNumCitationMarker::compareNumberWithPageInfo); + List sorted = OOListUtil.zip(numbers, pageInfos, NumberWithPageInfo::new); + sorted.sort(OOBibStyleGetNumCitationMarker::compareNumberWithPageInfo); // "[" StringBuilder sb = new StringBuilder(bracketBefore); @@ -322,9 +320,9 @@ private static void emitBlock(List block, for (int i = 0; i < nCitations; i++) { - final NumberWithPageInfo current = nps.get(i); + final NumberWithPageInfo current = sorted.get(i); if (current.num < 0) { - throw new RuntimeException("getNumCitationMarker: found negative value"); + throw new RuntimeException("getNumCitationMarker2: found negative value"); } if (currentBlock.size() == 0) { diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java index dbd1f248560..e5829646982 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java @@ -38,9 +38,9 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { List cits = cg.getCitationsInLocalOrder(); OOText citMarker = - style.getNumCitationMarker(OOListUtil.map(cits, Citation::getNumberOrThrow), - minGroupingCount, - OOListUtil.map(cits, Citation::getPageInfo)); + style.getNumCitationMarker2(OOListUtil.map(cits, Citation::getNumberOrThrow), + minGroupingCount, + OOListUtil.map(cits, Citation::getPageInfo)); cg.setCitationMarker(Optional.of(citMarker)); } } diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 5f1dfff4414..10c9f69f51e 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -114,47 +114,47 @@ void testGetNumCitationMarker() throws IOException { * but "[1] " with space after "]" for the bibliography. */ assertEquals("[1]", - style.getNumCitationMarker(Arrays.asList(1), + style.getNumCitationMarker2(Arrays.asList(1), -1, empty).asString()); // Identical numeric entries are joined. assertEquals("[1; 2]", - style.getNumCitationMarker(Arrays.asList(1,2,1,2), + style.getNumCitationMarker2(Arrays.asList(1,2,1,2), 3, empty).asString()); // ... unless minGroupingCount <= 0 assertEquals("[1; 1; 2; 2]", - style.getNumCitationMarker(Arrays.asList(1,2,1,2), + style.getNumCitationMarker2(Arrays.asList(1,2,1,2), 0, empty).asString()); // ... or have different pageInfos assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", - style.getNumCitationMarker(Arrays.asList(1,1,2,2,3,3), + style.getNumCitationMarker2(Arrays.asList(1,1,2,2,3,3), 1, asPageInfos("p1a","p1b","p2","p2", null, null)).asString()); // Consecutive numbers can become a range ... assertEquals("[1-3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), + style.getNumCitationMarker2(Arrays.asList(1, 2, 3), 1, /* minGroupingCount */ empty).asString()); // ... unless minGroupingCount is too high assertEquals("[1; 2; 3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), + style.getNumCitationMarker2(Arrays.asList(1, 2, 3), 4, /* minGroupingCount */ empty).asString()); // ... or if minGroupingCount <= 0 assertEquals("[1; 2; 3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), + style.getNumCitationMarker2(Arrays.asList(1, 2, 3), 0, /* minGroupingCount */ empty).asString()); // ... a pageInfo needs to be emitted assertEquals("[1; p1; 2-3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), + style.getNumCitationMarker2(Arrays.asList(1, 2, 3), 1, /* minGroupingCount */ asPageInfos("p1",null,null)) .asString()); @@ -162,20 +162,20 @@ void testGetNumCitationMarker() throws IOException { // null and "" pageInfos are taken as equal. // Due to trimming, " " is the same as well. assertEquals("[1]", - style.getNumCitationMarker(Arrays.asList(1, 1, 1), + style.getNumCitationMarker2(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ asPageInfos("",null," ")) .asString()); // pageInfos are trimmed assertEquals("[1; p1]", - style.getNumCitationMarker(Arrays.asList(1, 1, 1), + style.getNumCitationMarker2(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ asPageInfos("p1"," p1","p1 ")) .asString()); // The citation numbers come out sorted assertEquals("[3-5; 7; 10-12]", - style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, empty).asString()); @@ -183,7 +183,7 @@ void testGetNumCitationMarker() throws IOException { // (but they inhibit ranges where they are, even if they are identical, // but not empty-or-null) assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", - style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, asPageInfos("px", "p7", "p3", "p4", "px", "px", "p5")) @@ -192,36 +192,36 @@ void testGetNumCitationMarker() throws IOException { // pageInfo sorting (for the same number) assertEquals("[1; 1; a; 1; b]", - style.getNumCitationMarker(Arrays.asList(1, 1, 1), + style.getNumCitationMarker2(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ asPageInfos("","b","a ")) .asString()); // pageInfo sorting (for the same number) is not numeric. assertEquals("[1; p100; 1; p20; 1; p9]", - style.getNumCitationMarker(Arrays.asList(1, 1, 1), + style.getNumCitationMarker2(Arrays.asList(1, 1, 1), 1, /* minGroupingCount */ asPageInfos("p20","p9","p100")) .asString()); assertEquals("[1-3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), + style.getNumCitationMarker2(Arrays.asList(1, 2, 3), 1, /* minGroupingCount */ empty).asString()); assertEquals("[1; 2; 3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), + style.getNumCitationMarker2(Arrays.asList(1, 2, 3), 5, empty).asString()); assertEquals("[1; 2; 3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3), + style.getNumCitationMarker2(Arrays.asList(1, 2, 3), -1, empty).asString()); assertEquals("[1; 3; 12]", - style.getNumCitationMarker(Arrays.asList(1, 12, 3), + style.getNumCitationMarker2(Arrays.asList(1, 12, 3), 1, empty).asString()); assertEquals("[3-5; 7; 10-12]", - style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, empty).asString()); /* @@ -245,24 +245,24 @@ void testGetNumCitationMarkerUndefined() throws IOException { // unresolved citations look like [??] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", - style.getNumCitationMarker(Arrays.asList(0), + style.getNumCitationMarker2(Arrays.asList(0), 1, empty).asString()); // pageInfo is shown for unresolved citations assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; p1]", - style.getNumCitationMarker(Arrays.asList(0), + style.getNumCitationMarker2(Arrays.asList(0), 1, asPageInfos("p1")).asString()); // unresolved citations sorted to the front assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4]", - style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), + style.getNumCitationMarker2(Arrays.asList(4, 2, 3, 0), 1, empty).asString()); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3]", - style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), + style.getNumCitationMarker2(Arrays.asList(1, 2, 3, 0), 1, empty).asString()); @@ -271,7 +271,7 @@ void testGetNumCitationMarkerUndefined() throws IOException { + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", - style.getNumCitationMarker(Arrays.asList(0, 0, 0), + style.getNumCitationMarker2(Arrays.asList(0, 0, 0), 1, empty).asString()); From f262e79f32ce1c8ad44b441d103598bf1d6c667a Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 16:32:03 +0200 Subject: [PATCH 0822/1068] CompareCitedKey, CitationMarkerNumericEntry --- .../org/jabref/logic/oostyle/OOBibStyle.java | 4 +- .../OOBibStyleGetNumCitationMarker.java | 232 +++++++----------- .../org/jabref/model/oostyle/Citation.java | 3 +- .../oostyle/CitationMarkerNumericEntry.java | 14 ++ .../org/jabref/model/oostyle/CitedKeys.java | 2 +- .../jabref/model/oostyle/CompareCitation.java | 4 +- ...eyComparator.java => CompareCitedKey.java} | 4 +- 7 files changed, 114 insertions(+), 149 deletions(-) create mode 100644 src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java rename src/main/java/org/jabref/model/oostyle/{CitedKeyComparator.java => CompareCitedKey.java} (87%) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 0893b36d0bc..66de3cd0782 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -1188,8 +1188,6 @@ private String getBracketBeforeInList() { return getStringCitProperty(OOBibStyle.BRACKET_BEFORE_IN_LIST); } - // Should be protected, but that needs getNumCitationMarkerCommon - // to take over handling Unresolved public String getBracketBeforeInListWithFallBack() { return Objects.requireNonNullElse(getBracketBeforeInList(), getBracketBefore()); @@ -1200,7 +1198,7 @@ private String getBracketAfterInList() { return getStringCitProperty(OOBibStyle.BRACKET_AFTER_IN_LIST); } - public String getBracketAfterInListWithFallBack() { + String getBracketAfterInListWithFallBack() { return Objects.requireNonNullElse(getBracketAfterInList(), getBracketAfter()); } diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index 3d645e69d46..17f7baba128 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -1,10 +1,10 @@ package org.jabref.logic.oostyle; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Optional; +import org.jabref.model.oostyle.CitationMarkerNumericEntry; import org.jabref.model.oostyle.CompareCitation; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; @@ -17,50 +17,43 @@ class OOBibStyleGetNumCitationMarker { public final static int UNRESOLVED_ENTRY_NUMBER = 0; /* - * Helper class for sorting citation numbers while - * maintaining their correspondence to pageInfos. + * Minimal implementation for CitationMarkerNumericEntry */ - private static class NumberWithPageInfo { - int num; - Optional pageInfo; + private static class NumberWithPageInfo implements CitationMarkerNumericEntry { + + private Optional num; + private Optional pageInfo; + NumberWithPageInfo(int num, Optional pageInfo) { - this.num = num; + this.num = (num == UNRESOLVED_ENTRY_NUMBER + ? Optional.empty() + : Optional.of(num)); this.pageInfo = pageInfo; } - } - /** - * Defines sort order for NumberWithPageInfo entries. - * - * null comes before non-null - */ - private static int compareNumberWithPageInfo(NumberWithPageInfo a, NumberWithPageInfo b) { - int res = Integer.compare(a.num, b.num); - if (res == 0) { - res = CompareCitation.comparePageInfo(a.pageInfo, b.pageInfo); + @Override + public Optional getNumber() { + return num; } - return res; - } - private enum CitationMarkerPurpose { - /** Creating citation marker for in-text citation. */ - CITATION, - /** Creating citation marker for the bibliography. */ - BIBLIOGRAPHY + @Override + public Optional getPageInfo() { + return pageInfo; + } } /** - * See {@see getNumCitationMarkerCommon} for details. + * Defines sort order for CitationMarkerNumericEntry. */ - public static OOText getNumCitationMarker2(OOBibStyle style, - List numbers, - int minGroupingCount, - List> pageInfos) { - return getNumCitationMarkerCommon(style, - numbers, - minGroupingCount, - CitationMarkerPurpose.CITATION, - pageInfos); + private static int compareCitationMarkerNumericEntry(CitationMarkerNumericEntry a, + CitationMarkerNumericEntry b) { + int na = a.getNumber().orElse(UNRESOLVED_ENTRY_NUMBER); + int nb = b.getNumber().orElse(UNRESOLVED_ENTRY_NUMBER); + int res = Integer.compare(na, nb); + if (res == 0) { + res = CompareCitation.comparePageInfo(a.getPageInfo(), b.getPageInfo()); + } + return res; } /** @@ -77,11 +70,26 @@ public static OOText getNumCitationMarker2(OOBibStyle style, * "${number}" stands for the formatted number. */ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, int number) { - return getNumCitationMarkerCommon(style, - Collections.singletonList(number), - 0, - CitationMarkerPurpose.BIBLIOGRAPHY, - null); + return (getNumCitationMarkerForBibliography( + style, + new NumberWithPageInfo(number, Optional.empty()))); + } + + public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, + CitationMarkerNumericEntry entry) { + // prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST + String bracketBefore = style.getBracketBeforeInListWithFallBack(); + String bracketAfter = style.getBracketAfterInListWithFallBack(); + StringBuilder sb = new StringBuilder(); + sb.append(style.getCitationGroupMarkupBefore()); + sb.append(bracketBefore); + final Optional current = entry.getNumber(); + sb.append(current.isPresent() + ? String.valueOf(current.get()) + : OOBibStyle.UNDEFINED_CITATION_MARKER); + sb.append(bracketAfter); + sb.append(style.getCitationGroupMarkupAfter()); + return OOText.fromString(sb.toString()); } /* @@ -111,7 +119,7 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, int n * On the other hand, its assumptions strongly tie it to * the loop below that collects the block. */ - private static void emitBlock(List block, + private static void emitBlock(List block, OOBibStyle style, int minGroupingCount, StringBuilder sb) { @@ -123,12 +131,12 @@ private static void emitBlock(List block, if (blockSize == 1) { // Add single entry: - final int num = block.get(0).num; - sb.append(num == UNRESOLVED_ENTRY_NUMBER + final Optional num = block.get(0).getNumber(); + sb.append(num.isEmpty() ? OOBibStyle.UNDEFINED_CITATION_MARKER : String.valueOf(num)); // Emit pageInfo - Optional pageInfo = block.get(0).pageInfo; + Optional pageInfo = block.get(0).getPageInfo(); if (pageInfo.isPresent()) { sb.append(style.getPageInfoSeparator()); sb.append(OOText.toString(pageInfo.get())); @@ -142,17 +150,17 @@ private static void emitBlock(List block, * Check assumptions */ - if (block.stream().anyMatch(x -> x.pageInfo.isPresent())) { + if (block.stream().anyMatch(x -> x.getPageInfo().isPresent())) { throw new RuntimeException("Found pageInfo in a block with more than one elements"); } - if (block.stream().anyMatch(x -> x.num == UNRESOLVED_ENTRY_NUMBER)) { + if (block.stream().anyMatch(x -> x.getNumber().isEmpty())) { throw new RuntimeException("Found UNRESOLVED_ENTRY_NUMBER" + " in a block with more than one elements"); } for (int j = 1; j < blockSize; j++) { - if ((block.get(j).num - block.get(j - 1).num) != 1) { + if ((block.get(j).getNumber().get() - block.get(j - 1).getNumber().get()) != 1) { throw new RuntimeException("Numbers are not consecutive"); } } @@ -162,8 +170,8 @@ private static void emitBlock(List block, */ if (blockSize >= minGroupingCount) { - int first = block.get(0).num; - int last = block.get(blockSize - 1).num; + int first = block.get(0).getNumber().get(); + int last = block.get(blockSize - 1).getNumber().get(); if (last != (first + blockSize - 1)) { throw new RuntimeException("blockSize and length of num range differ"); } @@ -179,7 +187,7 @@ private static void emitBlock(List block, if (j > 0) { sb.append(style.getCitationSeparator()); } - sb.append(block.get(j).num); + sb.append(block.get(j).getNumber().get()); } } return; @@ -189,15 +197,9 @@ private static void emitBlock(List block, /** * Format a number-based citation marker for the given number or numbers. * - * This is the common implementation behind - * getNumCitationMarker2 and - * getNumCitationMarkerForBibliography. The latter could be easily - * separated unless there is (or going to be) a need for handling - * multiple numbers or page info by getNumCitationMarkerForBibliography. - * * @param numbers The citation numbers. * - * A zero in the list means: could not look this up + * A zero (UNRESOLVED_ENTRY_NUMBER) in the list means: could not look this up * in the databases. Positive integers are the valid numbers. * * Duplicate citation numbers are allowed: @@ -209,95 +211,46 @@ private static void emitBlock(List block, * distinct pageInfo. * * For pageInfo Optional.empty and "" (after - * pageInfo.get(),trim()) are considered equal (and missing). + * pageInfo.get().trim()) are considered equal (and missing). * * @param minGroupingCount Zero and negative means never group * - * @param purpose BIBLIOGRAPHY (was: inList==True) when creating for a bibliography entry, - * CITATION (was: inList=false) when creating in-text citation. - * - * If BIBLIOGRAPHY: Prefer BRACKET_BEFORE_IN_LIST over BRACKET_BEFORE, - * and BRACKET_AFTER_IN_LIST over BRACKET_AFTER. - * Ignore pageInfos. - * - * @param pageInfosIn Null for "none", or a list with an optional + * @param pageInfos Null for "none", or a list with an optional * pageInfo for each citation. Any or all of these can be Optional.empty * * @return The text for the citation. * */ + public static OOText getNumCitationMarker2(OOBibStyle style, + List numbers, + int minGroupingCount, + List> pageInfos) { + final int nCitations = numbers.size(); + List> pageInfosNormalized = + OOBibStyle.normalizePageInfos(pageInfos, numbers.size()); + + List entries = + OOListUtil.zip(numbers, pageInfosNormalized, NumberWithPageInfo::new); + + return getNumCitationMarkerCommon(style, + entries, + minGroupingCount); + } + private static OOText getNumCitationMarkerCommon(OOBibStyle style, - List numbers, - int minGroupingCount, - CitationMarkerPurpose purpose, - List> pageInfosIn) { + List entries, + int minGroupingCount) { final boolean joinIsDisabled = (minGroupingCount <= 0); - final int nCitations = numbers.size(); - - /* - * strictPurpose: if true, require (nCitations == 1) when (purpose == BIBLIOGRAPHY), - * otherwise allow multiple citation numbers and process the BIBLIOGRAPHY case - * as CITATION with no pageInfo. - */ - final boolean strictPurpose = true; + final int nCitations = entries.size(); String bracketBefore = style.getBracketBefore(); String bracketAfter = style.getBracketAfter(); - /* - * purpose == BIBLIOGRAPHY means: we are formatting for the - * bibliography, (not for in-text citation). - */ - if (purpose == CitationMarkerPurpose.BIBLIOGRAPHY) { - // prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST - bracketBefore = style.getBracketBeforeInListWithFallBack(); - bracketAfter = style.getBracketAfterInListWithFallBack(); - - if (strictPurpose) { - // If (purpose==BIBLIOGRAPHY), then - // we expect exactly one number here, and can handle quickly - if (nCitations != 1) { - throw new RuntimeException("getNumCitationMarker2:" - + "nCitations != 1 for purpose==BIBLIOGRAPHY." - + String.format(" nCitations = %d", nCitations)); - } - // - StringBuilder sb = new StringBuilder(); - sb.append(style.getCitationGroupMarkupBefore()); - sb.append(bracketBefore); - final int current = numbers.get(0); - if (current < 0) { - throw new RuntimeException("getNumCitationMarker2: found negative value"); - } - sb.append(current != UNRESOLVED_ENTRY_NUMBER - ? String.valueOf(current) - : OOBibStyle.UNDEFINED_CITATION_MARKER); - sb.append(bracketAfter); - sb.append(style.getCitationGroupMarkupAfter()); - return OOText.fromString(sb.toString()); - } - } - - /* - * From here: - * - formatting for in-text (not for bibliography) - * - need to care about pageInfos - * - * - In case {@code strictPurpose} above is set to false and allows us to - * get here, and {@code purpose==BIBLIOGRAPHY}, then we just fill - * pageInfos with null values. - */ - List> pageInfos = - OOBibStyle.normalizePageInfos((purpose == CitationMarkerPurpose.BIBLIOGRAPHY - ? null - : pageInfosIn), - numbers.size()); - - // Sort the numbers, together with the corresponding pageInfo values - List sorted = OOListUtil.zip(numbers, pageInfos, NumberWithPageInfo::new); - sorted.sort(OOBibStyleGetNumCitationMarker::compareNumberWithPageInfo); + // Sort a copy of entries + List sorted = OOListUtil.map(entries, e -> e); + sorted.sort(OOBibStyleGetNumCitationMarker::compareCitationMarkerNumericEntry); // "[" StringBuilder sb = new StringBuilder(bracketBefore); @@ -315,30 +268,29 @@ private static void emitBlock(List block, */ boolean blocksEmitted = false; - List currentBlock = new ArrayList<>(); - List nextBlock = new ArrayList<>(); + List currentBlock = new ArrayList<>(); + List nextBlock = new ArrayList<>(); for (int i = 0; i < nCitations; i++) { - final NumberWithPageInfo current = sorted.get(i); - if (current.num < 0) { + final CitationMarkerNumericEntry current = sorted.get(i); + if (current.getNumber().isPresent() && current.getNumber().get() < 0) { throw new RuntimeException("getNumCitationMarker2: found negative value"); } if (currentBlock.size() == 0) { currentBlock.add(current); } else { - NumberWithPageInfo prev = currentBlock.get(currentBlock.size() - 1); - if ((UNRESOLVED_ENTRY_NUMBER == current.num) - || (UNRESOLVED_ENTRY_NUMBER == prev.num)) { + CitationMarkerNumericEntry prev = currentBlock.get(currentBlock.size() - 1); + if (current.getNumber().isEmpty() || prev.getNumber().isEmpty()) { nextBlock.add(current); // do not join if not found } else if (joinIsDisabled) { nextBlock.add(current); // join disabled - } else if (compareNumberWithPageInfo(current, prev) == 0) { + } else if (compareCitationMarkerNumericEntry(current, prev) == 0) { // Same as prev, just forget it. - } else if ((current.num == (prev.num + 1)) - && (prev.pageInfo.isEmpty()) - && (current.pageInfo.isEmpty())) { + } else if ((current.getNumber().get() == (prev.getNumber().get() + 1)) + && (prev.getPageInfo().isEmpty()) + && (current.getPageInfo().isEmpty())) { // Just two consecutive numbers without pageInfo: join currentBlock.add(current); } else { diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index f7fd3f75048..4c8e59b8106 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -7,7 +7,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.Pair; -public class Citation implements ComparableCitation, CitationMarkerEntry { +public class Citation implements ComparableCitation, CitationMarkerEntry, CitationMarkerNumericEntry { /** key in database */ public final String citationKey; @@ -87,6 +87,7 @@ public boolean isUnresolved() { return db.isEmpty(); } + @Override public Optional getNumber() { return number; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java new file mode 100644 index 00000000000..ba944c1702d --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java @@ -0,0 +1,14 @@ +package org.jabref.model.oostyle; + +import java.util.Optional; + +/** + * This is what we need for getCitationMarker to produce numeric + * citation markers. + */ +public interface CitationMarkerNumericEntry { + + Optional getNumber(); + + Optional getPageInfo(); +} diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeys.java b/src/main/java/org/jabref/model/oostyle/CitedKeys.java index 937506b5bd7..cc036f8d0d3 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKeys.java @@ -36,7 +36,7 @@ public CitedKey get(String citationKey) { */ void sortByComparator(Comparator entryComparator) { List cks = new ArrayList<>(data.values()); - cks.sort(new CitedKeyComparator(entryComparator, true)); + cks.sort(new CompareCitedKey(entryComparator, true)); LinkedHashMap newData = new LinkedHashMap<>(); for (CitedKey ck : cks) { newData.put(ck.citationKey, ck); diff --git a/src/main/java/org/jabref/model/oostyle/CompareCitation.java b/src/main/java/org/jabref/model/oostyle/CompareCitation.java index 442fcc667d8..6e922f83d58 100644 --- a/src/main/java/org/jabref/model/oostyle/CompareCitation.java +++ b/src/main/java/org/jabref/model/oostyle/CompareCitation.java @@ -11,10 +11,10 @@ */ public class CompareCitation implements Comparator { - CitedKeyComparator citedKeyComparator; + CompareCitedKey citedKeyComparator; CompareCitation(Comparator entryComparator, boolean unresolvedComesFirst) { - this.citedKeyComparator = new CitedKeyComparator(entryComparator, unresolvedComesFirst); + this.citedKeyComparator = new CompareCitedKey(entryComparator, unresolvedComesFirst); } public int compare(ComparableCitation a, ComparableCitation b) { diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeyComparator.java b/src/main/java/org/jabref/model/oostyle/CompareCitedKey.java similarity index 87% rename from src/main/java/org/jabref/model/oostyle/CitedKeyComparator.java rename to src/main/java/org/jabref/model/oostyle/CompareCitedKey.java index fce4a0413f5..a02341339ac 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKeyComparator.java +++ b/src/main/java/org/jabref/model/oostyle/CompareCitedKey.java @@ -9,12 +9,12 @@ * Given a Comparator provide a Comparator * that also handles unresolved citation keys. */ -public class CitedKeyComparator implements Comparator { +public class CompareCitedKey implements Comparator { Comparator entryComparator; boolean unresolvedComesFirst; - CitedKeyComparator(Comparator entryComparator, boolean unresolvedComesFirst) { + CompareCitedKey(Comparator entryComparator, boolean unresolvedComesFirst) { this.entryComparator = entryComparator; this.unresolvedComesFirst = unresolvedComesFirst; } From 3c779672c4ffca5677bf8560bec9e23b5bacd081 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 16:56:13 +0200 Subject: [PATCH 0823/1068] CitationMarkerNumericEntryImpl.java --- .../org/jabref/logic/oostyle/OOBibStyle.java | 20 +++++++++ .../OOBibStyleGetNumCitationMarker.java | 44 ++++--------------- .../oostyle/OOProcessNumericMarkers.java | 11 ++--- .../CitationMarkerNumericEntryImpl.java | 34 ++++++++++++++ 4 files changed, 65 insertions(+), 44 deletions(-) create mode 100644 src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 66de3cd0782..b2a297f8b75 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -33,6 +33,7 @@ import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerNormEntry; +import org.jabref.model.oostyle.CitationMarkerNumericEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; @@ -438,6 +439,25 @@ public Layout getReferenceFormat(EntryType type) { } } + /** + * Format a number-based citation marker for the given entries. + * + * @return The text for the citation. + */ + public OOText getNumCitationMarker2(List entries) { + final int minGroupingCount = this.getMinimumGroupingCount(); + return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, + entries, + minGroupingCount); + } + + public OOText getNumCitationMarker2(List entries, + int minGroupingCount) { + return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, + entries, + minGroupingCount); + } + /** * Format a number-based citation marker for the given number. * diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index 17f7baba128..c71e18059aa 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -5,6 +5,7 @@ import java.util.Optional; import org.jabref.model.oostyle.CitationMarkerNumericEntry; +import org.jabref.model.oostyle.CitationMarkerNumericEntryImpl; import org.jabref.model.oostyle.CompareCitation; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; @@ -16,32 +17,6 @@ class OOBibStyleGetNumCitationMarker { */ public final static int UNRESOLVED_ENTRY_NUMBER = 0; - /* - * Minimal implementation for CitationMarkerNumericEntry - */ - private static class NumberWithPageInfo implements CitationMarkerNumericEntry { - - private Optional num; - private Optional pageInfo; - - NumberWithPageInfo(int num, Optional pageInfo) { - this.num = (num == UNRESOLVED_ENTRY_NUMBER - ? Optional.empty() - : Optional.of(num)); - this.pageInfo = pageInfo; - } - - @Override - public Optional getNumber() { - return num; - } - - @Override - public Optional getPageInfo() { - return pageInfo; - } - } - /** * Defines sort order for CitationMarkerNumericEntry. */ @@ -72,7 +47,7 @@ private static int compareCitationMarkerNumericEntry(CitationMarkerNumericEntry public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, int number) { return (getNumCitationMarkerForBibliography( style, - new NumberWithPageInfo(number, Optional.empty()))); + new CitationMarkerNumericEntryImpl(number, Optional.empty()))); } public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, @@ -96,7 +71,7 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, * emitBlock * * Given a block containing 1 or (two or more) - * NumberWithPageInfo entries that are either singletons or + * CitationMarkerNumericEntryImpl entries that are either singletons or * joinable into an "i-j" form, append to {@code sb} the * formatted text. * @@ -230,17 +205,14 @@ public static OOText getNumCitationMarker2(OOBibStyle style, OOBibStyle.normalizePageInfos(pageInfos, numbers.size()); List entries = - OOListUtil.zip(numbers, pageInfosNormalized, NumberWithPageInfo::new); + OOListUtil.zip(numbers, pageInfosNormalized, CitationMarkerNumericEntryImpl::new); - return getNumCitationMarkerCommon(style, - entries, - minGroupingCount); + return getNumCitationMarker2(style, entries, minGroupingCount); } - private static OOText - getNumCitationMarkerCommon(OOBibStyle style, - List entries, - int minGroupingCount) { + public static OOText getNumCitationMarker2(OOBibStyle style, + List entries, + int minGroupingCount) { final boolean joinIsDisabled = (minGroupingCount <= 0); final int nCitations = entries.size(); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java index e5829646982..d8f964d6656 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java @@ -3,9 +3,9 @@ import java.util.List; import java.util.Optional; -import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroups; +import org.jabref.model.oostyle.CitationMarkerNumericEntry; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; @@ -33,14 +33,9 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { cgs.createNumberedBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); } - final int minGroupingCount = style.getMinimumGroupingCount(); - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { - List cits = cg.getCitationsInLocalOrder(); - OOText citMarker = - style.getNumCitationMarker2(OOListUtil.map(cits, Citation::getNumberOrThrow), - minGroupingCount, - OOListUtil.map(cits, Citation::getPageInfo)); + List cits = OOListUtil.map(cg.getCitationsInLocalOrder(), e -> e); + OOText citMarker = style.getNumCitationMarker2(cits); cg.setCitationMarker(Optional.of(citMarker)); } } diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java new file mode 100644 index 00000000000..50a50a6f19d --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java @@ -0,0 +1,34 @@ +package org.jabref.model.oostyle; + +import java.util.Optional; + +/* + * Minimal implementation for CitationMarkerNumericEntry + */ +public class CitationMarkerNumericEntryImpl implements CitationMarkerNumericEntry { + + /* + * The number encoding "this entry is unresolved" for the constructor. + */ + public final static int UNRESOLVED_ENTRY_NUMBER = 0; + + private Optional num; + private Optional pageInfo; + + public CitationMarkerNumericEntryImpl(int num, Optional pageInfo) { + this.num = (num == UNRESOLVED_ENTRY_NUMBER + ? Optional.empty() + : Optional.of(num)); + this.pageInfo = pageInfo; + } + + @Override + public Optional getNumber() { + return num; + } + + @Override + public Optional getPageInfo() { + return pageInfo; + } +} From f96a29ac810c38967da360b8b714b0fbecb89937 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 19:20:58 +0200 Subject: [PATCH 0824/1068] ck.db is private --- .../jabref/logic/oostyle/OOFormatBibliography.java | 14 +++++--------- .../org/jabref/logic/openoffice/ExportCited.java | 6 +++--- .../org/jabref/model/oostyle/CitationGroups.java | 2 +- .../java/org/jabref/model/oostyle/CitedKey.java | 6 +++--- .../java/org/jabref/model/oostyle/CitedKeys.java | 11 +++++++++-- 5 files changed, 21 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index d6337aea27d..046d665871e 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -67,11 +67,7 @@ public static OOText formatBibliographyEntry(CitationGroups cgs, // insert marker "[1]" if (style.isNumberEntries()) { - if (ck.number.isEmpty()) { - throw new RuntimeException("formatBibliographyEntry:" - + " numbered style, but found unnumbered entry"); - } - sb.append(style.getNumCitationMarkerForBibliography(ck.number.get()).asString()); + sb.append(style.getNumCitationMarkerForBibliography(ck.number.orElse(0)).asString()); } else { // !style.isNumberEntries() : emit no prefix // Note: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); @@ -81,7 +77,7 @@ public static OOText formatBibliographyEntry(CitationGroups cgs, sb.append(formatBibliographyEntryBody(ck, style).asString()); // Add "Cited on pages" - if (ck.db.isEmpty() || alwaysAddCitedOnPages) { + if (ck.getLookupResult().isEmpty() || alwaysAddCitedOnPages) { sb.append(formatCitedOnPages(cgs, ck).asString()); } @@ -95,18 +91,18 @@ public static OOText formatBibliographyEntry(CitationGroups cgs, * @return just the body. No label, "Cited on pages" or paragraph. */ public static OOText formatBibliographyEntryBody(CitedKey ck, OOBibStyle style) { - if (ck.db.isEmpty()) { + if (ck.getLookupResult().isEmpty()) { // Unresolved entry return OOText.fromString(String.format("Unresolved(%s)", ck.citationKey)); } else { // Resolved entry, use the layout engine - BibEntry bibentry = ck.db.get().entry; + BibEntry bibentry = ck.getLookupResult().get().entry; Layout layout = style.getReferenceFormat(bibentry.getType()); layout.setPostFormatter(POSTFORMATTER); return formatFullReferenceOfBibEntry(layout, bibentry, - ck.db.get().database, + ck.getLookupResult().get().database, ck.uniqueLetter.orElse(null)); } } diff --git a/src/main/java/org/jabref/logic/openoffice/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/ExportCited.java index 78c09cc95df..5b14e78d645 100644 --- a/src/main/java/org/jabref/logic/openoffice/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/ExportCited.java @@ -61,12 +61,12 @@ public static GenerateDatabaseResult generateDatabase(XTextDocument doc, List seen = new HashSet<>(); // Only add crossReference once. for (CitedKey ck : cks.values()) { - if (ck.db.isEmpty()) { + if (ck.getLookupResult().isEmpty()) { unresolvedKeys.add(ck.citationKey); continue; } else { - BibEntry entry = ck.db.get().entry; - BibDatabase loopDatabase = ck.db.get().database; + BibEntry entry = ck.getLookupResult().get().entry; + BibDatabase loopDatabase = ck.getLookupResult().get().database; // If entry found BibEntry clonedEntry = (BibEntry) entry.clone(); diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index f4498611912..d0cda6dd653 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -184,7 +184,7 @@ public List getUnresolvedKeys() { } List unresolvedKeys = new ArrayList<>(); for (CitedKey ck : bib.get().values()) { - if (ck.db.isEmpty()) { + if (ck.getLookupResult().isEmpty()) { unresolvedKeys.add(ck.citationKey); } } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index 73079c4ce7b..7456a65aea6 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -8,9 +8,9 @@ import org.jabref.model.entry.BibEntry; public class CitedKey implements ComparableCitedKey, CitationMarkerNormEntry { - public String citationKey; - public LinkedHashSet where; - public Optional db; + public final String citationKey; + public final LinkedHashSet where; + private Optional db; public Optional number; // For Numbered citation styles. public Optional uniqueLetter; // For AuthorYear citation styles. public Optional normCitMarker; // For AuthorYear citation styles. diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeys.java b/src/main/java/org/jabref/model/oostyle/CitedKeys.java index cc036f8d0d3..48e9df816be 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKeys.java @@ -44,11 +44,18 @@ void sortByComparator(Comparator entryComparator) { data = newData; } + /** + * Unresolved citations do not get a number. + */ void numberCitedKeysInCurrentOrder() { int i = 1; for (CitedKey ck : data.values()) { - ck.number = Optional.of(i); - i++; + if (ck.getLookupResult().isPresent()) { + ck.number = Optional.of(i); + i++; + } else { + ck.number = Optional.empty(); + } } } From 367d331bc4eadb3d7ba0e62c75327836ce55acdb Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 21:21:41 +0200 Subject: [PATCH 0825/1068] CitationMarkerNumericBibEntry --- .../org/jabref/logic/oostyle/OOBibStyle.java | 10 +- .../OOBibStyleGetNumCitationMarker.java | 34 +- .../logic/oostyle/OOFormatBibliography.java | 2 +- .../org/jabref/model/oostyle/Citation.java | 4 + .../CitationMarkerNumericBibEntry.java | 13 + .../oostyle/CitationMarkerNumericEntry.java | 2 + .../CitationMarkerNumericEntryImpl.java | 23 +- .../org/jabref/model/oostyle/CitedKey.java | 15 +- .../org/jabref/model/oostyle/OOListUtil.java | 22 +- .../org/jabref/model/openoffice/Tuple3.java | 13 + .../jabref/logic/oostyle/OOBibStyleTest.java | 340 ++++++++++++------ 11 files changed, 341 insertions(+), 137 deletions(-) create mode 100644 src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java create mode 100644 src/main/java/org/jabref/model/openoffice/Tuple3.java diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index b2a297f8b75..576a432bce2 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -33,6 +33,7 @@ import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerNormEntry; +import org.jabref.model.oostyle.CitationMarkerNumericBibEntry; import org.jabref.model.oostyle.CitationMarkerNumericEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOListUtil; @@ -464,10 +465,12 @@ public OOText getNumCitationMarker2(List entries, * @param number The citation numbers. * @return The text for the citation. */ - public OOText getNumCitationMarker2(List number, + public OOText getNumCitationMarker2(List citationKeys, + List number, int minGroupingCount, List> pageInfos) { return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, + citationKeys, number, minGroupingCount, pageInfos); @@ -958,9 +961,8 @@ protected void setDefaultBibLayout(Layout l) { /** * Format a number-based bibliography label for the given number. */ - public OOText getNumCitationMarkerForBibliography(int number) { - return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, - number); + public OOText getNumCitationMarkerForBibliography(CitationMarkerNumericBibEntry entry) { + return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, entry); } /** diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index c71e18059aa..d8d0c669e4a 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -4,11 +4,13 @@ import java.util.List; import java.util.Optional; +import org.jabref.model.oostyle.CitationMarkerNumericBibEntry; import org.jabref.model.oostyle.CitationMarkerNumericEntry; import org.jabref.model.oostyle.CitationMarkerNumericEntryImpl; import org.jabref.model.oostyle.CompareCitation; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; +import org.jabref.model.openoffice.Tuple3; class OOBibStyleGetNumCitationMarker { @@ -44,14 +46,8 @@ private static int compareCitationMarkerNumericEntry(CitationMarkerNumericEntry * "]" stands for BRACKET_AFTER_IN_LIST (with fallback BRACKET_AFTER) * "${number}" stands for the formatted number. */ - public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, int number) { - return (getNumCitationMarkerForBibliography( - style, - new CitationMarkerNumericEntryImpl(number, Optional.empty()))); - } - public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, - CitationMarkerNumericEntry entry) { + CitationMarkerNumericBibEntry entry) { // prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST String bracketBefore = style.getBracketBeforeInListWithFallBack(); String bracketAfter = style.getBracketAfterInListWithFallBack(); @@ -61,7 +57,7 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, final Optional current = entry.getNumber(); sb.append(current.isPresent() ? String.valueOf(current.get()) - : OOBibStyle.UNDEFINED_CITATION_MARKER); + : (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey())); sb.append(bracketAfter); sb.append(style.getCitationGroupMarkupAfter()); return OOText.fromString(sb.toString()); @@ -106,12 +102,13 @@ private static void emitBlock(List block, if (blockSize == 1) { // Add single entry: - final Optional num = block.get(0).getNumber(); + CitationMarkerNumericEntry entry = block.get(0); + final Optional num = entry.getNumber(); sb.append(num.isEmpty() - ? OOBibStyle.UNDEFINED_CITATION_MARKER + ? (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey()) : String.valueOf(num)); // Emit pageInfo - Optional pageInfo = block.get(0).getPageInfo(); + Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { sb.append(style.getPageInfoSeparator()); sb.append(OOText.toString(pageInfo.get())); @@ -130,7 +127,7 @@ private static void emitBlock(List block, } if (block.stream().anyMatch(x -> x.getNumber().isEmpty())) { - throw new RuntimeException("Found UNRESOLVED_ENTRY_NUMBER" + throw new RuntimeException("Found unresolved entry" + " in a block with more than one elements"); } @@ -197,15 +194,20 @@ private static void emitBlock(List block, * */ public static OOText getNumCitationMarker2(OOBibStyle style, - List numbers, - int minGroupingCount, - List> pageInfos) { + List citationKeys, + List numbers, + int minGroupingCount, + List> pageInfos) { final int nCitations = numbers.size(); + List> pageInfosNormalized = OOBibStyle.normalizePageInfos(pageInfos, numbers.size()); + List>> xs = + OOListUtil.zip3(citationKeys, numbers, pageInfosNormalized); + List entries = - OOListUtil.zip(numbers, pageInfosNormalized, CitationMarkerNumericEntryImpl::new); + OOListUtil.map(xs, CitationMarkerNumericEntryImpl::from); return getNumCitationMarker2(style, entries, minGroupingCount); } diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index 046d665871e..d7ce585782d 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -67,7 +67,7 @@ public static OOText formatBibliographyEntry(CitationGroups cgs, // insert marker "[1]" if (style.isNumberEntries()) { - sb.append(style.getNumCitationMarkerForBibliography(ck.number.orElse(0)).asString()); + sb.append(style.getNumCitationMarkerForBibliography(ck).asString()); } else { // !style.isNumberEntries() : emit no prefix // Note: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index 4c8e59b8106..b58e7ea04cf 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -92,6 +92,10 @@ public Optional getNumber() { return number; } + public void setNumber(Optional n) { + number = n; + } + public int getNumberOrThrow() { return number.get(); } diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java new file mode 100644 index 00000000000..9ddc21457cc --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java @@ -0,0 +1,13 @@ +package org.jabref.model.oostyle; + +import java.util.Optional; + +/** + * This is for the bibliography labels. + */ +public interface CitationMarkerNumericBibEntry { + + String getCitationKey(); + + Optional getNumber(); +} diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java index ba944c1702d..7f83c470b10 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java @@ -8,6 +8,8 @@ */ public interface CitationMarkerNumericEntry { + String getCitationKey(); + Optional getNumber(); Optional getPageInfo(); diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java index 50a50a6f19d..1dc2886ffe5 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java @@ -2,6 +2,8 @@ import java.util.Optional; +import org.jabref.model.openoffice.Tuple3; + /* * Minimal implementation for CitationMarkerNumericEntry */ @@ -12,16 +14,23 @@ public class CitationMarkerNumericEntryImpl implements CitationMarkerNumericEntr */ public final static int UNRESOLVED_ENTRY_NUMBER = 0; + private String citationKey; private Optional num; private Optional pageInfo; - public CitationMarkerNumericEntryImpl(int num, Optional pageInfo) { + public CitationMarkerNumericEntryImpl(String citationKey, int num, Optional pageInfo) { + this.citationKey = citationKey; this.num = (num == UNRESOLVED_ENTRY_NUMBER ? Optional.empty() : Optional.of(num)); this.pageInfo = pageInfo; } + @Override + public String getCitationKey() { + return citationKey; + } + @Override public Optional getNumber() { return num; @@ -31,4 +40,16 @@ public Optional getNumber() { public Optional getPageInfo() { return pageInfo; } + + public static CitationMarkerNumericEntry from(Tuple3> x) { + return new CitationMarkerNumericEntryImpl(x.a, x.b, x.c); + } + + /* + * pageInfo is String and may be null + */ + public static CitationMarkerNumericEntry fromRaw(Tuple3 x) { + Optional pageInfo = Optional.ofNullable(OOText.fromString(x.c)); + return new CitationMarkerNumericEntryImpl(x.a, x.b, pageInfo); + } } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index 7456a65aea6..3d0133508f2 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -7,13 +7,16 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -public class CitedKey implements ComparableCitedKey, CitationMarkerNormEntry { +public class CitedKey implements + ComparableCitedKey, + CitationMarkerNormEntry, + CitationMarkerNumericBibEntry { public final String citationKey; public final LinkedHashSet where; - private Optional db; public Optional number; // For Numbered citation styles. public Optional uniqueLetter; // For AuthorYear citation styles. public Optional normCitMarker; // For AuthorYear citation styles. + private Optional db; CitedKey(String citationKey, CitationPath p, Citation cit) { this.citationKey = citationKey; @@ -48,6 +51,14 @@ public Optional getLookupResult() { return db; } + /* + * Implement CitationMarkerNumericBibEntry + */ + @Override + public Optional getNumber() { + return number; + } + /** * Appends to end of {@code where} */ diff --git a/src/main/java/org/jabref/model/oostyle/OOListUtil.java b/src/main/java/org/jabref/model/oostyle/OOListUtil.java index 8498e909140..a3ebcc626e1 100644 --- a/src/main/java/org/jabref/model/oostyle/OOListUtil.java +++ b/src/main/java/org/jabref/model/oostyle/OOListUtil.java @@ -9,15 +9,17 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import org.jabref.model.openoffice.Tuple3; + public class OOListUtil { public static List map(List list, Function fun) { return list.stream().map(e -> fun.apply(e)).collect(Collectors.toList()); } - public static List zip(List a, - List b, - BiFunction fun) { + public static List zipWith(List a, + List b, + BiFunction fun) { if (a.size() != b.size()) { throw new RuntimeException("a.size != b.size"); } @@ -28,6 +30,20 @@ public static List zip(List a, return result; } + public static List> zip3(List a, List b, List c) { + if (a.size() != b.size()) { + throw new RuntimeException("a.size != b.size"); + } + if (a.size() != c.size()) { + throw new RuntimeException("a.size != c.size"); + } + List> result = new ArrayList<>(a.size()); + for (int i = 0; i < a.size(); i++) { + result.add(new Tuple3(a.get(i), b.get(i), c.get(i))); + } + return result; + } + /** Integers 0..(n-1) */ public static List makeIndices(int n) { return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); diff --git a/src/main/java/org/jabref/model/openoffice/Tuple3.java b/src/main/java/org/jabref/model/openoffice/Tuple3.java new file mode 100644 index 00000000000..d15f0006b49 --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/Tuple3.java @@ -0,0 +1,13 @@ +package org.jabref.model.openoffice; + +public class Tuple3 { + public final A a; + public final B b; + public final C c; + public Tuple3(A a, B b, C c) { + this.a = a; + this.b = b; + this.c = c; + } +} + diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 10c9f69f51e..fdaf802ce26 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -90,20 +90,27 @@ void testNumerical() throws IOException { assertTrue(style.isSortByPosition()); } - List> asPageInfos(String... s) { - return (Stream.of(s) - .map(OOText::fromString) - .map(Optional::ofNullable) - .collect(Collectors.toList())); + List mkNum(OOBibStyle style, + int minGroupingCount, + Tuple3... s) { + List input = (Stream.of(s) + .map(CitationMarkerEntryImpl::fromRaw) + .collect(Collectors.toList())); + return style.getNumCitationMarker2(input, minGroupingCount).asString()); } +// List> asPageInfos(String... s) { +// return (Stream.of(s) +// .map(OOText::fromString) +// .map(Optional::ofNullable) +// .collect(Collectors.toList())); +// } + @Test void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - List> empty = null; - // Unfortunately these two are both "; " in // jabref/src/main/resources/resource/openoffice/default_numerical.jstyle // We might want to change one of them @@ -113,117 +120,202 @@ void testGetNumCitationMarker() throws IOException { /* The default numerical style uses "[1]", no space after "]" for in-text, * but "[1] " with space after "]" for the bibliography. */ - assertEquals("[1]", - style.getNumCitationMarker2(Arrays.asList(1), - -1, - empty).asString()); + assertEquals("[1]", mkNum(style, -1, Tuple3("xx", 1, null)).asString()); + // style.getNumCitationMarker2(Arrays.asList(1), -1, empty).asString()); // Identical numeric entries are joined. - assertEquals("[1; 2]", - style.getNumCitationMarker2(Arrays.asList(1,2,1,2), - 3, - empty).asString()); + assertEquals("[1; 2]", mkNum(style, 3, + Tuple3("x1",1,null), + Tuple3("x2",2,null), + Tuple3("x1",2,null), + Tuple3("x2",1,null))); + // style.getNumCitationMarker2(Arrays.asList(1,2,1,2), 3, empty).asString()); + + // ... unless minGroupingCount <= 0 - assertEquals("[1; 1; 2; 2]", - style.getNumCitationMarker2(Arrays.asList(1,2,1,2), - 0, - empty).asString()); + assertEquals("[1; 1; 2; 2]", mkNum(style, 0, + Tuple3("x1",1,null), + Tuple3("x2",2,null), + Tuple3("x1",2,null), + Tuple3("x2",1,null))); + // style.getNumCitationMarker2(Arrays.asList(1,2,1,2),0,empty).asString()); + // ... or have different pageInfos - assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", - style.getNumCitationMarker2(Arrays.asList(1,1,2,2,3,3), - 1, - asPageInfos("p1a","p1b","p2","p2", - null, null)).asString()); + assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", mkNum(style, 1, + Tuple3("x1", 1, "p1a"), + Tuple3("x1", 1, "p1b"), + Tuple3("x2", 2, "p2"), + Tuple3("x2", 2, "p2"), + Tuple3("x3", 3, null), + Tuple3("x3", 4, null))); + // style.getNumCitationMarker2(Arrays.asList(1,1,2,2,3,3), + // 1, + // asPageInfos("p1a","p1b","p2","p2", + // null, null)).asString()); // Consecutive numbers can become a range ... - assertEquals("[1-3]", - style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - 1, /* minGroupingCount */ - empty).asString()); + assertEquals("[1-3]", mkNum(style, 1 + Tuple3("x1", 1, null), + Tuple3("x2", 2, null), + Tuple3("x3", 3, null))); + // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), + // 1, /* minGroupingCount */ + // empty).asString()); // ... unless minGroupingCount is too high - assertEquals("[1; 2; 3]", - style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - 4, /* minGroupingCount */ - empty).asString()); + assertEquals("[1; 2; 3]", mkNum(style, 4, + Tuple3("x1", 1, null), + Tuple3("x2", 2, null), + Tuple3("x3", 3, null))); + // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), + // 4, /* minGroupingCount */ + // empty).asString()); // ... or if minGroupingCount <= 0 - assertEquals("[1; 2; 3]", - style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - 0, /* minGroupingCount */ - empty).asString()); + assertEquals("[1; 2; 3]", mkNum(style, 0, + Tuple3("x1", 1, null), + Tuple3("x2", 2, null), + Tuple3("x3", 3, null))); + // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), + // 0, /* minGroupingCount */ + // empty).asString()); + // ... a pageInfo needs to be emitted - assertEquals("[1; p1; 2-3]", - style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - 1, /* minGroupingCount */ - asPageInfos("p1",null,null)) - .asString()); + assertEquals("[1; p1; 2-3]", mkNum(style, 1, + Tuple3("x1", 1, "p1"), + Tuple3("x2", 2, null), + Tuple3("x3", 3, null))); + + // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), + // 1, /* minGroupingCount */ + // asPageInfos("p1",null,null)) + // .asString()); // null and "" pageInfos are taken as equal. // Due to trimming, " " is the same as well. - assertEquals("[1]", - style.getNumCitationMarker2(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - asPageInfos("",null," ")) - .asString()); + assertEquals("[1]", mkNum(style, 1, + Tuple3("x1", 1, ""), + Tuple3("x1", 1, null), + Tuple3("x1", 1, " "))); + // style.getNumCitationMarker2(Arrays.asList(1, 1, 1), + // 1, /* minGroupingCount */ + // asPageInfos("",null," ")) + // .asString()); + // pageInfos are trimmed - assertEquals("[1; p1]", - style.getNumCitationMarker2(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - asPageInfos("p1"," p1","p1 ")) - .asString()); + assertEquals("[1; p1]", mkNum(style, 1, + Tuple3("x1", 1, "p1"), + Tuple3("x1", 1, " p1"), + Tuple3("x1", 1, "p1 "))); + // style.getNumCitationMarker2(Arrays.asList(1, 1, 1), + // 1, /* minGroupingCount */ + // asPageInfos("p1"," p1","p1 ")) + // .asString()); // The citation numbers come out sorted - assertEquals("[3-5; 7; 10-12]", - style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), - 1, - empty).asString()); + assertEquals("[3-5; 7; 10-12]", mkNum(style, 1, + Tuple3("x12", 12, null), + Tuple3("x7", 7, null), + Tuple3("x3", 3, null), + Tuple3("x4", 4, null), + Tuple3("x11", 11, null), + Tuple3("x10", 10, null), + Tuple3("x5", 5, null))); + // style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + // 1, + // empty).asString()); // pageInfos are sorted together with the numbers // (but they inhibit ranges where they are, even if they are identical, // but not empty-or-null) assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", - style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), - 1, - asPageInfos("px", "p7", "p3", "p4", - "px", "px", "p5")) - .asString()); + mkNum(style, 1, + Tuple3("x12", 12, "px"), + Tuple3("x7", 7, "p7"), + Tuple3("x3", 3, "p3"), + Tuple3("x4", 4, "p4"), + Tuple3("x11", 11, "px"), + Tuple3("x10", 10, "px"), + Tuple3("x5", 5, "p5"))); + + // style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + // 1, + // asPageInfos("px", "p7", "p3", "p4", + // "px", "px", "p5")) + // .asString()); // pageInfo sorting (for the same number) assertEquals("[1; 1; a; 1; b]", - style.getNumCitationMarker2(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - asPageInfos("","b","a ")) - .asString()); + mkNum(style, 1, + Tuple3("x1", 1, ""), + Tuple3("x1", 1, "b"), + Tuple3("x1", 1, "a"))); + // style.getNumCitationMarker2(Arrays.asList(1, 1, 1), + // 1, /* minGroupingCount */ + // asPageInfos("","b","a ")) + // .asString()); // pageInfo sorting (for the same number) is not numeric. assertEquals("[1; p100; 1; p20; 1; p9]", - style.getNumCitationMarker2(Arrays.asList(1, 1, 1), - 1, /* minGroupingCount */ - asPageInfos("p20","p9","p100")) - .asString()); + mkNum(style, 1, + Tuple3("x1", 1, "p20"), + Tuple3("x1", 1, "p9"), + Tuple3("x1", 1, "p100"))); + // style.getNumCitationMarker2(Arrays.asList(1, 1, 1), + // 1, /* minGroupingCount */ + // asPageInfos("p20","p9","p100")) + // .asString()); assertEquals("[1-3]", - style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - 1, /* minGroupingCount */ - empty).asString()); + mkNum(style, 1, + Tuple3("x1", 1, null), + Tuple3("x2", 2, null), + Tuple3("x3", 3, null))); + // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), + // 1, /* minGroupingCount */ + // empty).asString()); + assertEquals("[1; 2; 3]", - style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - 5, - empty).asString()); + mkNum(style, 5, + Tuple3("x1", 1, null), + Tuple3("x2", 2, null), + Tuple3("x3", 3, null))); + // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), + // 5, + // empty).asString()); + assertEquals("[1; 2; 3]", - style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - -1, - empty).asString()); + mkNum(style, -1, + Tuple3("x1", 1, null), + Tuple3("x2", 2, null), + Tuple3("x3", 3, null))); + // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), + // -1, + // empty).asString()); + assertEquals("[1; 3; 12]", - style.getNumCitationMarker2(Arrays.asList(1, 12, 3), - 1, - empty).asString()); + mkNum(style, 1, + Tuple3("x1", 1, null), + Tuple3("x12", 12, null), + Tuple3("x3", 3, null))); + // style.getNumCitationMarker2(Arrays.asList(1, 12, 3), + // 1, + // empty).asString()); + assertEquals("[3-5; 7; 10-12]", - style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), - 1, - empty).asString()); + mkNum(style, 1, + Tuple3("x12", 12, ""), + Tuple3("x7", 7, ""), + Tuple3("x3", 3, ""), + Tuple3("x4", 4, ""), + Tuple3("x11", 11, ""), + Tuple3("x10", 10, ""), + Tuple3("x5", 5, ""))); + // style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), + // 1, + // empty).asString()); + /* * BIBLIOGRAPHY : I think * style.getNumCitationMarkerForBibliography(int num); @@ -231,8 +323,13 @@ void testGetNumCitationMarker() throws IOException { * Consequently minGroupingCount is not needed. * Nor do we need pageInfo in the bibliography. */ - assertEquals("[1] ", - style.getNumCitationMarkerForBibliography(1).asString()); + { + Citation x = new Citation("key"); + x.setNumber(Optional.of(1)); + // x.setPageInfo(Optional.empty()); + assertEquals("[1] ", + style.getNumCitationMarkerForBibliography(x).asString()); + } } @@ -243,43 +340,66 @@ void testGetNumCitationMarkerUndefined() throws IOException { List> empty = null; - // unresolved citations look like [??] - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", - style.getNumCitationMarker2(Arrays.asList(0), - 1, - empty).asString()); + // unresolved citations look like [??key] + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "]", + mkNum(style, 1, + Tuple3("key",0,null))); + // style.getNumCitationMarker2(Arrays.asList(0), + // 1, + // empty).asString()); // pageInfo is shown for unresolved citations assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; p1]", - style.getNumCitationMarker2(Arrays.asList(0), - 1, - asPageInfos("p1")).asString()); + mkNum(style, 1, + Tuple3("key",0,"p1"))); + // style.getNumCitationMarker2(Arrays.asList(0), + // 1, + // asPageInfos("p1")).asString()); // unresolved citations sorted to the front - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4]", - style.getNumCitationMarker2(Arrays.asList(4, 2, 3, 0), - 1, - empty).asString()); - - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3]", - style.getNumCitationMarker2(Arrays.asList(1, 2, 3, 0), - 1, - empty).asString()); + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 2-4]", + mkNum(style, 1, + Tuple3("x4",4,""), + Tuple3("x2",2,""), + Tuple3("x3",3,""), + Tuple3("key",0,""))); + // style.getNumCitationMarker2(Arrays.asList(4, 2, 3, 0), + // 1, + // empty).asString()); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 1-3]", + mkNum(style, 1, + Tuple3("x1",1,""), + Tuple3("x2",2,""), + Tuple3("y3",3,""), + Tuple3("key",0,""))); + // style.getNumCitationMarker2(Arrays.asList(1, 2, 3, 0), + // 1, + // empty).asString()); // multiple unresolved citations are not collapsed assertEquals("[" - + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " - + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " - + OOBibStyle.UNDEFINED_CITATION_MARKER + "]", - style.getNumCitationMarker2(Arrays.asList(0, 0, 0), - 1, - empty).asString()); + + OOBibStyle.UNDEFINED_CITATION_MARKER + "x1" + "; " + + OOBibStyle.UNDEFINED_CITATION_MARKER + "x1" + "; " + + OOBibStyle.UNDEFINED_CITATION_MARKER + "x3" + "]", + mkNum(style, 1, + Tuple3("x1",0,""), + Tuple3("x2",0,""), + Tuple3("x3",0,""))); + // style.getNumCitationMarker2(Arrays.asList(0, 0, 0), + // 1, + // empty).asString()); /* * BIBLIOGRAPHY */ - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarkerForBibliography(0).asString()); + { + Citation x = new Citation("key"); + // x.setPageInfo(Optional.empty()); + // x.setNumber(Optional.empty()); + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", + style.getNumCitationMarkerForBibliography(x).asString()); + } } From 8c8a6718db47406bab9e624c556b276347be52f0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 22:03:12 +0200 Subject: [PATCH 0826/1068] update OOBibStyleTest, act on errors --- .../OOBibStyleGetNumCitationMarker.java | 2 +- .../CitationMarkerNumericEntryImpl.java | 2 +- .../jabref/logic/oostyle/OOBibStyleTest.java | 309 +++++++----------- 3 files changed, 129 insertions(+), 184 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index d8d0c669e4a..536a659ada8 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -106,7 +106,7 @@ private static void emitBlock(List block, final Optional num = entry.getNumber(); sb.append(num.isEmpty() ? (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey()) - : String.valueOf(num)); + : String.valueOf(num.get())); // Emit pageInfo Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java index 1dc2886ffe5..eeb9b5a780d 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java @@ -23,7 +23,7 @@ public CitationMarkerNumericEntryImpl(String citationKey, int num, Optional mkNum(OOBibStyle style, - int minGroupingCount, - Tuple3... s) { - List input = (Stream.of(s) - .map(CitationMarkerEntryImpl::fromRaw) - .collect(Collectors.toList())); - return style.getNumCitationMarker2(input, minGroupingCount).asString()); + static String mkNum(OOBibStyle style, + int minGroupingCount, + Tuple3... s) { + List input = (Stream.of(s) + .map(CitationMarkerNumericEntryImpl::fromRaw) + .collect(Collectors.toList())); + OOText res = style.getNumCitationMarker2(input, minGroupingCount); + return OOText.toString(res); } -// List> asPageInfos(String... s) { -// return (Stream.of(s) -// .map(OOText::fromString) -// .map(Optional::ofNullable) -// .collect(Collectors.toList())); -// } + static Tuple3 tup3(String a,Integer b, String c) { + return new Tuple3(a,b,c); + } + + static class CitationMarkerNumericBibEntryImpl implements CitationMarkerNumericBibEntry { + String key; + Optional number; + + public CitationMarkerNumericBibEntryImpl(String key, Optional number) { + this.key = key; + this.number = number; + } + + @Override + public String getCitationKey() { + return key; + } + + @Override + public Optional getNumber() { + return number; + } + } @Test void testGetNumCitationMarker() throws IOException { @@ -120,83 +142,61 @@ void testGetNumCitationMarker() throws IOException { /* The default numerical style uses "[1]", no space after "]" for in-text, * but "[1] " with space after "]" for the bibliography. */ - assertEquals("[1]", mkNum(style, -1, Tuple3("xx", 1, null)).asString()); - // style.getNumCitationMarker2(Arrays.asList(1), -1, empty).asString()); + assertEquals("[1]", mkNum(style, -1, tup3("xx", 1, null))); // Identical numeric entries are joined. assertEquals("[1; 2]", mkNum(style, 3, - Tuple3("x1",1,null), - Tuple3("x2",2,null), - Tuple3("x1",2,null), - Tuple3("x2",1,null))); - // style.getNumCitationMarker2(Arrays.asList(1,2,1,2), 3, empty).asString()); - + tup3("x1",1,null), + tup3("x2",2,null), + tup3("x1",2,null), + tup3("x2",1,null))); // ... unless minGroupingCount <= 0 assertEquals("[1; 1; 2; 2]", mkNum(style, 0, - Tuple3("x1",1,null), - Tuple3("x2",2,null), - Tuple3("x1",2,null), - Tuple3("x2",1,null))); - // style.getNumCitationMarker2(Arrays.asList(1,2,1,2),0,empty).asString()); + tup3("x1",1,null), + tup3("x2",2,null), + tup3("x1",2,null), + tup3("x2",1,null))); // ... or have different pageInfos assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", mkNum(style, 1, - Tuple3("x1", 1, "p1a"), - Tuple3("x1", 1, "p1b"), - Tuple3("x2", 2, "p2"), - Tuple3("x2", 2, "p2"), - Tuple3("x3", 3, null), - Tuple3("x3", 4, null))); - // style.getNumCitationMarker2(Arrays.asList(1,1,2,2,3,3), - // 1, - // asPageInfos("p1a","p1b","p2","p2", - // null, null)).asString()); + tup3("x1", 1, "p1a"), + tup3("x1", 1, "p1b"), + tup3("x2", 2, "p2"), + tup3("x2", 2, "p2"), + tup3("x3", 3, null), + tup3("x3", 3, null))); // Consecutive numbers can become a range ... - assertEquals("[1-3]", mkNum(style, 1 - Tuple3("x1", 1, null), - Tuple3("x2", 2, null), - Tuple3("x3", 3, null))); - // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - // 1, /* minGroupingCount */ - // empty).asString()); + assertEquals("[1-3]", mkNum(style, 1, + tup3("x1", 1, null), + tup3("x2", 2, null), + tup3("x3", 3, null))); // ... unless minGroupingCount is too high assertEquals("[1; 2; 3]", mkNum(style, 4, - Tuple3("x1", 1, null), - Tuple3("x2", 2, null), - Tuple3("x3", 3, null))); - // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - // 4, /* minGroupingCount */ - // empty).asString()); + tup3("x1", 1, null), + tup3("x2", 2, null), + tup3("x3", 3, null))); // ... or if minGroupingCount <= 0 assertEquals("[1; 2; 3]", mkNum(style, 0, - Tuple3("x1", 1, null), - Tuple3("x2", 2, null), - Tuple3("x3", 3, null))); - // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - // 0, /* minGroupingCount */ - // empty).asString()); + tup3("x1", 1, null), + tup3("x2", 2, null), + tup3("x3", 3, null))); // ... a pageInfo needs to be emitted assertEquals("[1; p1; 2-3]", mkNum(style, 1, - Tuple3("x1", 1, "p1"), - Tuple3("x2", 2, null), - Tuple3("x3", 3, null))); - - // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - // 1, /* minGroupingCount */ - // asPageInfos("p1",null,null)) - // .asString()); + tup3("x1", 1, "p1"), + tup3("x2", 2, null), + tup3("x3", 3, null))); // null and "" pageInfos are taken as equal. // Due to trimming, " " is the same as well. assertEquals("[1]", mkNum(style, 1, - Tuple3("x1", 1, ""), - Tuple3("x1", 1, null), - Tuple3("x1", 1, " "))); + tup3("x1", 1, ""), + tup3("x1", 1, null), + tup3("x1", 1, " "))); // style.getNumCitationMarker2(Arrays.asList(1, 1, 1), // 1, /* minGroupingCount */ // asPageInfos("",null," ")) @@ -204,117 +204,80 @@ void testGetNumCitationMarker() throws IOException { // pageInfos are trimmed assertEquals("[1; p1]", mkNum(style, 1, - Tuple3("x1", 1, "p1"), - Tuple3("x1", 1, " p1"), - Tuple3("x1", 1, "p1 "))); - // style.getNumCitationMarker2(Arrays.asList(1, 1, 1), - // 1, /* minGroupingCount */ - // asPageInfos("p1"," p1","p1 ")) - // .asString()); + tup3("x1", 1, "p1"), + tup3("x1", 1, " p1"), + tup3("x1", 1, "p1 "))); // The citation numbers come out sorted assertEquals("[3-5; 7; 10-12]", mkNum(style, 1, - Tuple3("x12", 12, null), - Tuple3("x7", 7, null), - Tuple3("x3", 3, null), - Tuple3("x4", 4, null), - Tuple3("x11", 11, null), - Tuple3("x10", 10, null), - Tuple3("x5", 5, null))); - // style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), - // 1, - // empty).asString()); + tup3("x12", 12, null), + tup3("x7", 7, null), + tup3("x3", 3, null), + tup3("x4", 4, null), + tup3("x11", 11, null), + tup3("x10", 10, null), + tup3("x5", 5, null))); // pageInfos are sorted together with the numbers // (but they inhibit ranges where they are, even if they are identical, // but not empty-or-null) assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", mkNum(style, 1, - Tuple3("x12", 12, "px"), - Tuple3("x7", 7, "p7"), - Tuple3("x3", 3, "p3"), - Tuple3("x4", 4, "p4"), - Tuple3("x11", 11, "px"), - Tuple3("x10", 10, "px"), - Tuple3("x5", 5, "p5"))); - - // style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), - // 1, - // asPageInfos("px", "p7", "p3", "p4", - // "px", "px", "p5")) - // .asString()); - + tup3("x12", 12, "px"), + tup3("x7", 7, "p7"), + tup3("x3", 3, "p3"), + tup3("x4", 4, "p4"), + tup3("x11", 11, "px"), + tup3("x10", 10, "px"), + tup3("x5", 5, "p5"))); // pageInfo sorting (for the same number) assertEquals("[1; 1; a; 1; b]", mkNum(style, 1, - Tuple3("x1", 1, ""), - Tuple3("x1", 1, "b"), - Tuple3("x1", 1, "a"))); - // style.getNumCitationMarker2(Arrays.asList(1, 1, 1), - // 1, /* minGroupingCount */ - // asPageInfos("","b","a ")) - // .asString()); + tup3("x1", 1, ""), + tup3("x1", 1, "b"), + tup3("x1", 1, "a"))); // pageInfo sorting (for the same number) is not numeric. assertEquals("[1; p100; 1; p20; 1; p9]", mkNum(style, 1, - Tuple3("x1", 1, "p20"), - Tuple3("x1", 1, "p9"), - Tuple3("x1", 1, "p100"))); - // style.getNumCitationMarker2(Arrays.asList(1, 1, 1), - // 1, /* minGroupingCount */ - // asPageInfos("p20","p9","p100")) - // .asString()); + tup3("x1", 1, "p20"), + tup3("x1", 1, "p9"), + tup3("x1", 1, "p100"))); assertEquals("[1-3]", mkNum(style, 1, - Tuple3("x1", 1, null), - Tuple3("x2", 2, null), - Tuple3("x3", 3, null))); - // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - // 1, /* minGroupingCount */ - // empty).asString()); + tup3("x1", 1, null), + tup3("x2", 2, null), + tup3("x3", 3, null))); assertEquals("[1; 2; 3]", mkNum(style, 5, - Tuple3("x1", 1, null), - Tuple3("x2", 2, null), - Tuple3("x3", 3, null))); - // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - // 5, - // empty).asString()); + tup3("x1", 1, null), + tup3("x2", 2, null), + tup3("x3", 3, null))); assertEquals("[1; 2; 3]", mkNum(style, -1, - Tuple3("x1", 1, null), - Tuple3("x2", 2, null), - Tuple3("x3", 3, null))); - // style.getNumCitationMarker2(Arrays.asList(1, 2, 3), - // -1, - // empty).asString()); + tup3("x1", 1, null), + tup3("x2", 2, null), + tup3("x3", 3, null))); assertEquals("[1; 3; 12]", mkNum(style, 1, - Tuple3("x1", 1, null), - Tuple3("x12", 12, null), - Tuple3("x3", 3, null))); - // style.getNumCitationMarker2(Arrays.asList(1, 12, 3), - // 1, - // empty).asString()); + tup3("x1", 1, null), + tup3("x12", 12, null), + tup3("x3", 3, null))); assertEquals("[3-5; 7; 10-12]", mkNum(style, 1, - Tuple3("x12", 12, ""), - Tuple3("x7", 7, ""), - Tuple3("x3", 3, ""), - Tuple3("x4", 4, ""), - Tuple3("x11", 11, ""), - Tuple3("x10", 10, ""), - Tuple3("x5", 5, ""))); - // style.getNumCitationMarker2(Arrays.asList(12, 7, 3, 4, 11, 10, 5), - // 1, - // empty).asString()); + tup3("x12", 12, ""), + tup3("x7", 7, ""), + tup3("x3", 3, ""), + tup3("x4", 4, ""), + tup3("x11", 11, ""), + tup3("x10", 10, ""), + tup3("x5", 5, ""))); /* * BIBLIOGRAPHY : I think @@ -324,9 +287,7 @@ void testGetNumCitationMarker() throws IOException { * Nor do we need pageInfo in the bibliography. */ { - Citation x = new Citation("key"); - x.setNumber(Optional.of(1)); - // x.setPageInfo(Optional.empty()); + CitationMarkerNumericBibEntry x = new CitationMarkerNumericBibEntryImpl("key", Optional.of(1)); assertEquals("[1] ", style.getNumCitationMarkerForBibliography(x).asString()); } @@ -343,61 +304,45 @@ void testGetNumCitationMarkerUndefined() throws IOException { // unresolved citations look like [??key] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "]", mkNum(style, 1, - Tuple3("key",0,null))); - // style.getNumCitationMarker2(Arrays.asList(0), - // 1, - // empty).asString()); + tup3("key",0,null))); // pageInfo is shown for unresolved citations - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; p1]", + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; p1]", mkNum(style, 1, - Tuple3("key",0,"p1"))); - // style.getNumCitationMarker2(Arrays.asList(0), - // 1, - // asPageInfos("p1")).asString()); + tup3("key",0,"p1"))); // unresolved citations sorted to the front assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 2-4]", mkNum(style, 1, - Tuple3("x4",4,""), - Tuple3("x2",2,""), - Tuple3("x3",3,""), - Tuple3("key",0,""))); - // style.getNumCitationMarker2(Arrays.asList(4, 2, 3, 0), - // 1, - // empty).asString()); + tup3("x4",4,""), + tup3("x2",2,""), + tup3("x3",3,""), + tup3("key",0,""))); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 1-3]", mkNum(style, 1, - Tuple3("x1",1,""), - Tuple3("x2",2,""), - Tuple3("y3",3,""), - Tuple3("key",0,""))); - // style.getNumCitationMarker2(Arrays.asList(1, 2, 3, 0), - // 1, - // empty).asString()); + tup3("x1",1,""), + tup3("x2",2,""), + tup3("y3",3,""), + tup3("key",0,""))); // multiple unresolved citations are not collapsed assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "x1" + "; " - + OOBibStyle.UNDEFINED_CITATION_MARKER + "x1" + "; " + + OOBibStyle.UNDEFINED_CITATION_MARKER + "x2" + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "x3" + "]", mkNum(style, 1, - Tuple3("x1",0,""), - Tuple3("x2",0,""), - Tuple3("x3",0,""))); - // style.getNumCitationMarker2(Arrays.asList(0, 0, 0), - // 1, - // empty).asString()); + tup3("x1",0,""), + tup3("x2",0,""), + tup3("x3",0,""))); /* * BIBLIOGRAPHY */ { - Citation x = new Citation("key"); - // x.setPageInfo(Optional.empty()); - // x.setNumber(Optional.empty()); - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", + CitationMarkerNumericBibEntry x = + new CitationMarkerNumericBibEntryImpl("key", Optional.empty()); + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", style.getNumCitationMarkerForBibliography(x).asString()); } From 06b85c7bc2eb92410d78313722ab8c44adc09408 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 23:22:21 +0200 Subject: [PATCH 0827/1068] CitedKey fields are mostly private --- .../logic/oostyle/OOFormatBibliography.java | 4 +- .../oostyle/OOProcessAuthorYearMarkers.java | 8 ++-- .../CitationMarkerNumericBibEntry.java | 6 ++- .../jabref/model/oostyle/CitationPath.java | 6 ++- .../org/jabref/model/oostyle/CitedKey.java | 48 +++++++++++++++++-- .../org/jabref/model/oostyle/CitedKeys.java | 4 +- 6 files changed, 60 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index d7ce585782d..affd5037f6c 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -103,7 +103,7 @@ public static OOText formatBibliographyEntryBody(CitedKey ck, OOBibStyle style) return formatFullReferenceOfBibEntry(layout, bibentry, ck.getLookupResult().get().database, - ck.uniqueLetter.orElse(null)); + ck.getUniqueLetter().orElse(null)); } } @@ -165,7 +165,7 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { sb.append(prefix); List citationGroups = new ArrayList(); - for (CitationPath p : ck.where) { + for (CitationPath p : ck.getCitationPaths()) { CitationGroupID cgid = p.group; CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); citationGroups.add(cg); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java index 2e240647fa2..13a986134be 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java @@ -28,7 +28,7 @@ private static void createNormalizedCitationMarkersForNormalStyle(CitedKeys sort OOBibStyle style) { for (CitedKey ck : sortedCitedKeys.values()) { - ck.normCitMarker = Optional.of(style.getNormalizedCitationMarker(ck)); + ck.setNormalizedCitationMarker(Optional.of(style.getNormalizedCitationMarker(ck))); } } @@ -57,7 +57,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup // Map> normCitMarkerToClachingKeys = new HashMap<>(); for (CitedKey citedKey : sortedCitedKeys.values()) { - String normCitMarker = OOText.toString(citedKey.normCitMarker.get()); + String normCitMarker = OOText.toString(citedKey.getNormalizedCitationMarker().get()); String citationKey = citedKey.citationKey; if (!normCitMarkerToClachingKeys.containsKey(normCitMarker)) { @@ -76,7 +76,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup // Clear old uniqueLetter values. for (CitedKey citedKey : sortedCitedKeys.values()) { - citedKey.uniqueLetter = Optional.empty(); + citedKey.setUniqueLetter(Optional.empty()); } // For sets of citation keys figthing for a normCitMarker @@ -90,7 +90,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup int nextUniqueLetter = 'a'; for (String citationKey : clashingKeys) { String ul = String.valueOf((char) nextUniqueLetter); - sortedCitedKeys.get(citationKey).uniqueLetter = Optional.of(ul); + sortedCitedKeys.get(citationKey).setUniqueLetter(Optional.of(ul)); nextUniqueLetter++; } } diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java index 9ddc21457cc..d30a2767340 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java @@ -3,7 +3,11 @@ import java.util.Optional; /** - * This is for the bibliography labels. + * This is for the numeric bibliography labels. + * + * getNumber() returning Optional.empty() indicates unresolved + * citation. In this case we also show the citation key to help + * finding the problematic citations. */ public interface CitationMarkerNumericBibEntry { diff --git a/src/main/java/org/jabref/model/oostyle/CitationPath.java b/src/main/java/org/jabref/model/oostyle/CitationPath.java index 9678b30b279..eb295e615c5 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationPath.java +++ b/src/main/java/org/jabref/model/oostyle/CitationPath.java @@ -5,10 +5,12 @@ * its storage index within. */ public class CitationPath { + public final CitationGroupID group; + public final int storageIndexInGroup; - CitationPath(CitationGroupID group, - int storageIndexInGroup) { + + CitationPath(CitationGroupID group, int storageIndexInGroup) { this.group = group; this.storageIndexInGroup = storageIndexInGroup; } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index 3d0133508f2..4bd2507ac2b 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -1,5 +1,6 @@ package org.jabref.model.oostyle; +import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; @@ -7,24 +8,37 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +/** + * Cited keys are collected from the citations in citation groups. + * + * 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; - public final LinkedHashSet where; - public Optional number; // For Numbered citation styles. - public Optional uniqueLetter; // For AuthorYear citation styles. - public Optional normCitMarker; // For AuthorYear citation styles. + private final LinkedHashSet where; + private Optional db; + private Optional number; // For Numbered citation styles. + private Optional uniqueLetter; // For AuthorYear citation styles. + private Optional normCitMarker; // For AuthorYear citation styles. CitedKey(String citationKey, CitationPath p, Citation cit) { + this.citationKey = citationKey; this.where = new LinkedHashSet<>(); // remember order this.where.add(p); + + // sync with citations this.db = cit.getLookupResult(); this.number = cit.getNumber(); this.uniqueLetter = cit.getUniqueLetter(); + this.normCitMarker = Optional.empty(); } @@ -59,6 +73,30 @@ public Optional getNumber() { return number; } + public void setNumber(Optional number) { + this.number = number; + } + + public List getCitationPaths() { + return new ArrayList<>(where); + } + + public Optional getUniqueLetter() { + return uniqueLetter; + } + + public void setUniqueLetter(Optional uniqueLetter) { + this.uniqueLetter = uniqueLetter; + } + + public Optional getNormalizedCitationMarker() { + return normCitMarker; + } + + public void setNormalizedCitationMarker(Optional normCitMarker) { + this.normCitMarker = normCitMarker; + } + /** * Appends to end of {@code where} */ @@ -90,4 +128,4 @@ void distributeNumber(CitationGroups cgs) { void distributeUniqueLetter(CitationGroups cgs) { cgs.distributeToCitations(where, Citation::setUniqueLetter, uniqueLetter); } -} // class CitedKey +} diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeys.java b/src/main/java/org/jabref/model/oostyle/CitedKeys.java index 48e9df816be..ffea786a257 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKeys.java @@ -51,10 +51,10 @@ void numberCitedKeysInCurrentOrder() { int i = 1; for (CitedKey ck : data.values()) { if (ck.getLookupResult().isPresent()) { - ck.number = Optional.of(i); + ck.setNumber(Optional.of(i)); i++; } else { - ck.number = Optional.empty(); + ck.setNumber(Optional.empty()); } } } From 4f358da9b4ea41463dbeea6eac5b4250d32de183 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 23:37:32 +0200 Subject: [PATCH 0828/1068] drop getNumCitationMarker2 from Lists --- .../org/jabref/logic/oostyle/OOBibStyle.java | 20 ++--------- .../OOBibStyleGetNumCitationMarker.java | 34 +++---------------- .../model/oostyle/CitationMarkerEntry.java | 2 +- 3 files changed, 9 insertions(+), 47 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 576a432bce2..f911c32c205 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -452,6 +452,9 @@ public OOText getNumCitationMarker2(List entries) { minGroupingCount); } + /** + * For some tests we need to override minGroupingCount. + */ public OOText getNumCitationMarker2(List entries, int minGroupingCount) { return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, @@ -459,23 +462,6 @@ public OOText getNumCitationMarker2(List entries, minGroupingCount); } - /** - * Format a number-based citation marker for the given number. - * - * @param number The citation numbers. - * @return The text for the citation. - */ - public OOText getNumCitationMarker2(List citationKeys, - List number, - int minGroupingCount, - List> pageInfos) { - return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, - citationKeys, - number, - minGroupingCount, - pageInfos); - } - /* moved to OOBibStyleGetCitationMarker public String getCitationMarker(List entries, Map database, boolean inParenthesis, String[] uniquefiers, int[] unlimAuthors) { diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index 536a659ada8..ec4ce70ee93 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -6,11 +6,9 @@ import org.jabref.model.oostyle.CitationMarkerNumericBibEntry; import org.jabref.model.oostyle.CitationMarkerNumericEntry; -import org.jabref.model.oostyle.CitationMarkerNumericEntryImpl; import org.jabref.model.oostyle.CompareCitation; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; -import org.jabref.model.openoffice.Tuple3; class OOBibStyleGetNumCitationMarker { @@ -169,9 +167,9 @@ private static void emitBlock(List block, /** * Format a number-based citation marker for the given number or numbers. * - * @param numbers The citation numbers. + * @param entries Provide the citation numbers. * - * A zero (UNRESOLVED_ENTRY_NUMBER) in the list means: could not look this up + * An Optional.empty() number means: could not look this up * in the databases. Positive integers are the valid numbers. * * Duplicate citation numbers are allowed: @@ -182,36 +180,14 @@ private static void emitBlock(List block, * - If their pageInfos differ, the number is emitted with each * distinct pageInfo. * - * For pageInfo Optional.empty and "" (after - * pageInfo.get().trim()) are considered equal (and missing). + * pageInfos are expected to be normalized * - * @param minGroupingCount Zero and negative means never group - * - * @param pageInfos Null for "none", or a list with an optional - * pageInfo for each citation. Any or all of these can be Optional.empty + * @param minGroupingCount Zero and negative means never group. + * Only used by tests to override the value in style. * * @return The text for the citation. * */ - public static OOText getNumCitationMarker2(OOBibStyle style, - List citationKeys, - List numbers, - int minGroupingCount, - List> pageInfos) { - final int nCitations = numbers.size(); - - List> pageInfosNormalized = - OOBibStyle.normalizePageInfos(pageInfos, numbers.size()); - - List>> xs = - OOListUtil.zip3(citationKeys, numbers, pageInfosNormalized); - - List entries = - OOListUtil.map(xs, CitationMarkerNumericEntryImpl::from); - - return getNumCitationMarker2(style, entries, minGroupingCount); - } - public static OOText getNumCitationMarker2(OOBibStyle style, List entries, int minGroupingCount) { diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java index 2243480d1d5..b5dc641fcf7 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java @@ -3,7 +3,7 @@ import java.util.Optional; /** - * This is what we need for getCitationMarker to produce author-year + * This is what we need for getCitationMarker2 to produce author-year * citation markers. * * Citation misses two things From aad92dfc2a75e657333b9186578d5830960ac17a Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 23 May 2021 23:54:12 +0200 Subject: [PATCH 0829/1068] format, comments --- .../org/jabref/logic/oostyle/OOBibStyle.java | 10 ++-------- .../OOBibStyleGetNumCitationMarker.java | 18 +++++++----------- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index f911c32c205..bb1717fbe94 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -1067,10 +1067,6 @@ private String getStringProperty(String propName) { return (String) properties.get(propName); } - // private int getIntProperty(String key) { - // return (Integer) properties.get(key); - // } - /** * Should citation markers be italicized? * @@ -1197,8 +1193,7 @@ private String getBracketBeforeInList() { } public String getBracketBeforeInListWithFallBack() { - return Objects.requireNonNullElse(getBracketBeforeInList(), - getBracketBefore()); + return Objects.requireNonNullElse(getBracketBeforeInList(), getBracketBefore()); } /** Closing parenthesis after citation marker in the bibliography */ @@ -1207,8 +1202,7 @@ private String getBracketAfterInList() { } String getBracketAfterInListWithFallBack() { - return Objects.requireNonNullElse(getBracketAfterInList(), - getBracketAfter()); + return Objects.requireNonNullElse(getBracketAfterInList(), getBracketAfter()); } public OOText getFormattedBibliographyTitle() { diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index ec4ce70ee93..8669de8dafb 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -62,11 +62,10 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, } /* - * emitBlock + * emitBlock : a helper for getNumCitationMarker2 * - * Given a block containing 1 or (two or more) - * CitationMarkerNumericEntryImpl entries that are either singletons or - * joinable into an "i-j" form, append to {@code sb} the + * Given a block containing either a single entry or two or more + * entries that are joinable into an "i-j" form, append to {@code sb} the * formatted text. * * Assumes: @@ -74,19 +73,16 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, * - block is not empty * * - For a block with a single element the element may have - * pageInfo and its num part may be UNRESOLVED_ENTRY_NUMBER. + * pageInfo and its num part may be Optional.empty() * * - For a block with two or more elements * - * - The elements do not have pageInfo and their num part is - * not zero. + * - The elements do not have pageInfo and their number part is + * not empty. * - * - The elements num parts are consecutive positive integers, + * - The elements number parts are consecutive positive integers, * without repetition. * - * Note: this function is long enough to move into a separate method. - * On the other hand, its assumptions strongly tie it to - * the loop below that collects the block. */ private static void emitBlock(List block, OOBibStyle style, From cce3f3c24a7224b154865ea5f803fcd93e5441b7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 00:06:09 +0200 Subject: [PATCH 0830/1068] move CitationMarkerNumericEntryImpl.fromRaw to OOBibStyleTest.java --- .../oostyle/CitationMarkerNumericEntryImpl.java | 12 ------------ .../org/jabref/logic/oostyle/OOBibStyleTest.java | 14 +++++++++++++- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java index eeb9b5a780d..55d677f24f3 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java @@ -40,16 +40,4 @@ public Optional getNumber() { public Optional getPageInfo() { return pageInfo; } - - public static CitationMarkerNumericEntry from(Tuple3> x) { - return new CitationMarkerNumericEntryImpl(x.a, x.b, x.c); - } - - /* - * pageInfo is String and may be null - */ - public static CitationMarkerNumericEntry fromRaw(Tuple3 x) { - Optional pageInfo = Optional.ofNullable(OOText.fromString(x.c)); - return new CitationMarkerNumericEntryImpl(x.a, x.b, pageInfo); - } } diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index d17dbecf343..639d40ea393 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -94,11 +94,20 @@ void testNumerical() throws IOException { assertTrue(style.isSortByPosition()); } + /* + * Helpers for testing style.getNumCitationMarker2 + */ + private static CitationMarkerNumericEntry + CitationMarkerNumericEntryFromTuple(Tuple3 x) { + Optional pageInfo = Optional.ofNullable(OOText.fromString(x.c)); + return new CitationMarkerNumericEntryImpl(x.a, x.b, pageInfo); + } + static String mkNum(OOBibStyle style, int minGroupingCount, Tuple3... s) { List input = (Stream.of(s) - .map(CitationMarkerNumericEntryImpl::fromRaw) + .map(OOBibStyleTest::CitationMarkerNumericEntryFromTuple) .collect(Collectors.toList())); OOText res = style.getNumCitationMarker2(input, minGroupingCount); return OOText.toString(res); @@ -108,6 +117,9 @@ static Tuple3 tup3(String a,Integer b, String c) { return new Tuple3(a,b,c); } + /* + * For testing getNumCitationMarkerForBibliography + */ static class CitationMarkerNumericBibEntryImpl implements CitationMarkerNumericBibEntry { String key; Optional number; From 09c9b224ce2e35bc8005cdced4f08d52f49c9a11 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 00:13:31 +0200 Subject: [PATCH 0831/1068] move CitationMarkerNumericEntryImpl into OOBibStyleTest.java --- .../CitationMarkerNumericEntryImpl.java | 43 ------------------- .../jabref/logic/oostyle/OOBibStyleTest.java | 40 ++++++++++++++++- 2 files changed, 39 insertions(+), 44 deletions(-) delete mode 100644 src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java deleted file mode 100644 index 55d677f24f3..00000000000 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntryImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.jabref.model.oostyle; - -import java.util.Optional; - -import org.jabref.model.openoffice.Tuple3; - -/* - * Minimal implementation for CitationMarkerNumericEntry - */ -public class CitationMarkerNumericEntryImpl implements CitationMarkerNumericEntry { - - /* - * The number encoding "this entry is unresolved" for the constructor. - */ - public final static int UNRESOLVED_ENTRY_NUMBER = 0; - - private String citationKey; - private Optional num; - private Optional pageInfo; - - public CitationMarkerNumericEntryImpl(String citationKey, int num, Optional pageInfo) { - this.citationKey = citationKey; - this.num = (num == UNRESOLVED_ENTRY_NUMBER - ? Optional.empty() - : Optional.of(num)); - this.pageInfo = Citation.normalizePageInfo(pageInfo); - } - - @Override - public String getCitationKey() { - return citationKey; - } - - @Override - public Optional getNumber() { - return num; - } - - @Override - public Optional getPageInfo() { - return pageInfo; - } -} diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 639d40ea393..3ea1d74e708 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -30,7 +30,6 @@ import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerNumericBibEntry; import org.jabref.model.oostyle.CitationMarkerNumericEntry; -import org.jabref.model.oostyle.CitationMarkerNumericEntryImpl; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.Tuple3; @@ -97,6 +96,45 @@ void testNumerical() throws IOException { /* * Helpers for testing style.getNumCitationMarker2 */ + + /* + * Minimal implementation for CitationMarkerNumericEntry + */ + static class CitationMarkerNumericEntryImpl implements CitationMarkerNumericEntry { + + /* + * The number encoding "this entry is unresolved" for the constructor. + */ + public final static int UNRESOLVED_ENTRY_NUMBER = 0; + + private String citationKey; + private Optional num; + private Optional pageInfo; + + public CitationMarkerNumericEntryImpl(String citationKey, int num, Optional pageInfo) { + this.citationKey = citationKey; + this.num = (num == UNRESOLVED_ENTRY_NUMBER + ? Optional.empty() + : Optional.of(num)); + this.pageInfo = Citation.normalizePageInfo(pageInfo); + } + + @Override + public String getCitationKey() { + return citationKey; + } + + @Override + public Optional getNumber() { + return num; + } + + @Override + public Optional getPageInfo() { + return pageInfo; + } + } + private static CitationMarkerNumericEntry CitationMarkerNumericEntryFromTuple(Tuple3 x) { Optional pageInfo = Optional.ofNullable(OOText.fromString(x.c)); From 351edd2b8cfa00c6d050c08d0697f91742ff25ec Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 09:52:12 +0200 Subject: [PATCH 0832/1068] CitationGroups.unresolvedKeys() can work without a bibliography --- .../org/jabref/model/oostyle/CitationGroups.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index d0cda6dd653..f5e284b221b 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -176,14 +176,15 @@ public Optional getBibliography() { return bibliography; } + /** + * @return Citation keys where lookupCitations() failed. + */ public List getUnresolvedKeys() { - Optional bib = getBibliography(); - if (bib.isEmpty()) { - throw new RuntimeException("getUnresolvedKeys:" - + " CitationGroups does not have a bibliography"); - } + + CitedKeys bib = getBibliography().orElse(getCitedKeysUnordered()); + List unresolvedKeys = new ArrayList<>(); - for (CitedKey ck : bib.get().values()) { + for (CitedKey ck : bib.values()) { if (ck.getLookupResult().isEmpty()) { unresolvedKeys.add(ck.citationKey); } From 99c1fe8247c8c3b921a7dc004e5b31c8ea7c878e Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 10:39:13 +0200 Subject: [PATCH 0833/1068] comment on Consistency --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index bac09a83d11..eb7edaf07f4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -514,6 +514,11 @@ public void guiActionApplyCitationEntries(List citationEntries) { * @param database The database the entries belong to (all of them). * Used when creating the citation mark. * + * Consistency: for each entry in {@entries} looking it up in + * {@code syncOptions.get().databases} should yield {@code database}. + * Otherwise we may get a different entry + * with and without synchronization. + * * @param style The bibliography style we are using. * * @param citationType Indicates whether it is an in-text From 1c93f085d03afaae355c055250d7e41bbd5fc63d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 10:39:53 +0200 Subject: [PATCH 0834/1068] Support direct lookup of citations, but use old version --- .../jabref/model/oostyle/CitationGroups.java | 70 +++++++++++++------ .../model/oostyle/CitationLookupResult.java | 30 ++++++++ .../org/jabref/model/oostyle/CitedKey.java | 8 ++- 3 files changed, 84 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index f5e284b221b..d33f7d4b831 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -24,21 +24,10 @@ public class CitationGroups { private static final Logger LOGGER = LoggerFactory.getLogger(CitationGroups.class); - /** - * Original CitationGroups Data - */ private Map citationGroupsUnordered; - /* - * Extra Data - */ - /** * Provides order of appearance for the citation groups. - * - * Background: just getting the reference marks does not provide - * this. Citation groups in footnotes, frames etc make getting - * this order right tricky. {@see class RangeSortVisual} */ private Optional> globalOrder; @@ -81,13 +70,39 @@ public void distributeToCitations(Set where, } } - public CitedKeys lookupCitations(List databases) { + /* + * Look up each Citation in databases. + */ + public void lookupCitations(List databases) { CitationGroups cgs = this; - CitedKeys cks = cgs.getCitedKeysUnordered(); - - cks.lookupInDatabases(databases); - cks.distributeLookupResults(cgs); - return cks; + /* + * It is not clear which of the two solutions below is better. + */ + if (true) { + // collect-lookup-distribute + // + // CitationDatabaseLookupResult for the same citation key + // is the same object. Until we insert a new citation from the GUI. + CitedKeys cks = cgs.getCitedKeysUnordered(); + cks.lookupInDatabases(databases); + cks.distributeLookupResults(cgs); + } else { + // 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 cg : getCitationGroupsUnordered()) { + for (Citation cit : cg.citationsInStorageOrder) { + cit.lookupInDatabases(databases); + } + } + } } public List getCitationGroupsUnordered() { @@ -104,6 +119,12 @@ public List getCitationGroupsInGlobalOrder() { return OOListUtil.map(globalOrder.get(), cgid -> citationGroupsUnordered.get(cgid)); } + /** + * Impose an order of citation groups by providing the order + * of their citation group idendifiers. + * + * Also set indexInGlobalOrder for each citation group. + */ public void setGlobalOrder(List globalOrder) { Objects.requireNonNull(globalOrder); if (globalOrder.size() != numberOfCitationGroups()) { @@ -120,12 +141,23 @@ public void setGlobalOrder(List globalOrder) { } } + public boolean hasGlobalOrder() { + return globalOrder.isPresent(); + } + + /** + * Impose an order for citations within each group. + */ public void imposeLocalOrder(Comparator entryComparator) { for (CitationGroup cg : citationGroupsUnordered.values()) { cg.imposeLocalOrder(entryComparator); } } + /** + * Collect citations into a list of cited sources using neither + * CitationGroup.globalOrder or Citation.localOrder + */ public CitedKeys getCitedKeysUnordered() { LinkedHashMap res = new LinkedHashMap<>(); for (CitationGroup cg : citationGroupsUnordered.values()) { @@ -144,10 +176,6 @@ public CitedKeys getCitedKeysUnordered() { return new CitedKeys(res); } - public boolean hasGlobalOrder() { - return globalOrder.isPresent(); - } - /** * CitedKeys created iterating citations in (globalOrder,localOrder) */ diff --git a/src/main/java/org/jabref/model/oostyle/CitationLookupResult.java b/src/main/java/org/jabref/model/oostyle/CitationLookupResult.java index f234a4cc848..82c886a9037 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationLookupResult.java +++ b/src/main/java/org/jabref/model/oostyle/CitationLookupResult.java @@ -16,4 +16,34 @@ public CitationLookupResult(BibEntry entry, BibDatabase database) { this.entry = entry; this.database = database; } + + /** + * Note: BibEntry overrides Object.equals, but BibDatabase does not. + * + * Consequently, {@code this.database.equals(that.database)} below + * is equivalent to {@code this.database == that.database}. + * + * Since within each GUI call we use a fixed list of + * databases, it is OK. + */ + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof CitationLookupResult)) { + return false; + } + CitationLookupResult that = (CitationLookupResult) o; + return this.entry.equals(that.entry) && this.database.equals(that.database); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + entry.hashCode(); + result = prime * result + database.hashCode(); + return result; + } } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index 4bd2507ac2b..a9bc7a4b5e5 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -102,13 +102,15 @@ public void setNormalizedCitationMarker(Optional normCitMarker) { */ void addPath(CitationPath p, Citation cit) { this.where.add(p); - if (cit.getLookupResult() != this.db) { + + // Check consistency + if (!cit.getLookupResult().equals(this.db)) { throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); } - if (cit.getNumber() != this.number) { + if (!cit.getNumber().equals(this.number)) { throw new RuntimeException("CitedKey.addPath: mismatch on cit.number"); } - if (cit.getUniqueLetter() != this.uniqueLetter) { + if (!cit.getUniqueLetter().equals(this.uniqueLetter)) { throw new RuntimeException("CitedKey.addPath: mismatch on cit.uniqueLetter"); } } From a6b752a72af87677557b5fa9a007e67c9cbba5b5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 14:03:22 +0200 Subject: [PATCH 0835/1068] comments --- .../logic/oostyle/OOFormatBibliography.java | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index affd5037f6c..aeab5cc4f3a 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -26,7 +26,7 @@ private OOFormatBibliography() { } /** - * Format the bibliography, including its title. + * @return The formatted bibliography, including its title. */ public static OOText formatBibliography(CitationGroups cgs, CitedKeys bibliography, @@ -39,7 +39,7 @@ public static OOText formatBibliography(CitationGroups cgs, } /** - * Format the body of bibliography. Excludes the title. + * @return Formatted body of the bibliography. Excludes the title. */ public static OOText formatBibliographyBody(CitationGroups cgs, CitedKeys bibliography, @@ -56,8 +56,8 @@ public static OOText formatBibliographyBody(CitationGroups cgs, return OOText.fromString(stringBuilder.toString()); } - /* - * @return a paragraph. Includes label and "Cited on pages". + /** + * @return A paragraph. Includes label and "Cited on pages". */ public static OOText formatBibliographyEntry(CitationGroups cgs, CitedKey ck, @@ -87,8 +87,8 @@ public static OOText formatBibliographyEntry(CitationGroups cgs, return OOFormat.paragraph(entryText, parStyle); } - /* - * @return just the body. No label, "Cited on pages" or paragraph. + /** + * @return just the body of a bibliography entry. No label, "Cited on pages" or paragraph. */ public static OOText formatBibliographyEntryBody(CitedKey ck, OOBibStyle style) { if (ck.getLookupResult().isEmpty()) { @@ -145,15 +145,16 @@ private static OOText formatFullReferenceOfBibEntry(Layout layout, return formattedText; } - /* + /** * Format links to citations of the source (ck). * - * Requires reference marks for citation groups. + * Requires reference marks for the citation groups. * * - The links are created as references that show page numbers of the reference marks. * - We do not control the text shown, that is provided by OpenOffice. */ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { + if (!cgs.citationGroupsProvideReferenceMarkNameForLinking()) { return OOText.fromString(""); } From 241039cd8b99df05361139475e3b7be3e5b7bfb4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 14:03:54 +0200 Subject: [PATCH 0836/1068] afterCreateCitationGroup resets bibliography --- .../jabref/model/oostyle/CitationGroups.java | 26 +++---------------- 1 file changed, 3 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index d33f7d4b831..91841c06c39 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -308,37 +308,17 @@ public boolean citationGroupsProvideReferenceMarkNameForLinking() { } public void afterCreateCitationGroup(CitationGroup cg) { - // add to our data this.citationGroupsUnordered.put(cg.cgid, cg); - // invalidate globalOrder. + this.globalOrder = Optional.empty(); - // Note: we cannot impose localOrder, since we do not know - // how it was imposed. We leave it to an upper level. + this.bibliography = Optional.empty(); } - /* - * Note: we invalidate the extra data we are storing - * (bibliography). - * - * Update would be complicated, since we do not know how the - * bibliography was generated: it was partially done outside - * CitationGroups, and we did not store how. - * - * So we stay with invalidating. - * Note: localOrder, numbering, uniqueLetters are not adjusted, - * it is easier to reread everything for a refresh. - * - */ public void afterRemoveCitationGroup(CitationGroup cg) { - this.citationGroupsUnordered.remove(cg.cgid); - - // Update what we can. this.globalOrder.map(l -> l.remove(cg.cgid)); - // Invalidate what we cannot + this.bibliography = Optional.empty(); - // Could also: reset citation.number, citation.uniqueLetter. - // Proper update would need style, we do not do it here. } } From 014fb0f849f71e534eca71a2e97c1c296e39c455 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 16:41:26 +0200 Subject: [PATCH 0837/1068] drop some unused methods --- .../jabref/model/oostyle/CitationGroups.java | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 91841c06c39..f656e8ac378 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -262,6 +262,10 @@ public void createNumberedBibliographySortedByComparator(Comparator en this.bibliography = Optional.of(citedKeys); } + /* + * Query by CitationGroupID + */ + public Optional getCitationGroup(CitationGroupID cgid) { CitationGroup cg = citationGroupsUnordered.get(cgid); return Optional.ofNullable(cg); @@ -279,22 +283,6 @@ public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { return cg; } - private Optional getCitationType(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.citationType); - } - - public Optional> getCitationsInStorageOrder(CitationGroupID cgid) { - return getCitationGroup(cgid).map(cg -> cg.citationsInStorageOrder); - } - - public List getCitationsInLocalOrder(CitationGroupID cgid) { - Optional cg = getCitationGroup(cgid); - if (cg.isEmpty()) { - throw new RuntimeException("getCitationsInLocalOrder: invalid cgid"); - } - return cg.get().getCitationsInLocalOrder(); - } - /* * @return true if all citation groups have referenceMarkNameForLinking */ @@ -307,6 +295,10 @@ public boolean citationGroupsProvideReferenceMarkNameForLinking() { return true; } + /* + * Callbacks. + */ + public void afterCreateCitationGroup(CitationGroup cg) { this.citationGroupsUnordered.put(cg.cgid, cg); From 0364418ffe15cf6cb6ba585305f9ffe8f88cfb58 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 16:47:45 +0200 Subject: [PATCH 0838/1068] OOFrontend.getMarkRange accepts CitationGroup --- src/main/java/org/jabref/logic/openoffice/EditMerge.java | 2 +- .../java/org/jabref/logic/openoffice/EditSeparate.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 8 +++----- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index c954218f612..66d48227551 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -257,7 +257,7 @@ private static List scan(XTextDocument doc, OOFrontend fr) for (CitationGroupID cgid : cgids) { CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); - XTextRange currentRange = (fr.getMarkRange(doc, cgid) + XTextRange currentRange = (fr.getMarkRange(doc, cg) .orElseThrow(RuntimeException::new)); /* diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 173961c0d9d..6678925971b 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -61,7 +61,7 @@ public static boolean separateCitations(XTextDocument doc, for (CitationGroup cg : cgs) { XTextRange range1 = (fr - .getMarkRange(doc, cg.cgid) + .getMarkRange(doc, cg) .orElseThrow(RuntimeException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 7b328b15548..d2f1a282232 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -120,7 +120,7 @@ public Optional healthReport(XTextDocument doc) List sortables = new ArrayList<>(); for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { XTextRange range = (this - .getMarkRange(doc, cg.cgid) + .getMarkRange(doc, cg) .orElseThrow(RuntimeException::new)); sortables.add(new RangeSortEntry(range, 0, cg.cgid)); } @@ -314,15 +314,13 @@ public void removeCitationGroups(List cgs, XTextDocument doc) /** * ranges controlled by citation groups should not overlap with each other. * - * @param cgid : Must be known, throws if not. * @return Optional.empty() if the reference mark is missing. * */ - public Optional getMarkRange(XTextDocument doc, CitationGroupID cgid) + public Optional getMarkRange(XTextDocument doc, CitationGroup cg) throws NoDocumentException, WrappedTargetException { - CitationGroup cg = this.citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); return backend.getMarkRange(cg, doc); } @@ -365,7 +363,7 @@ private List> citationRanges(XTextDocument new ArrayList<>(citationGroups.numberOfCitationGroups()); for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { - XTextRange range = this.getMarkRange(doc, cg.cgid).orElseThrow(RuntimeException::new); + XTextRange range = this.getMarkRange(doc, cg).orElseThrow(RuntimeException::new); String description = cg.cgid.asString(); // cg.cgRangeStorage.nrGetRangeName(); result.add(new RangeForOverlapCheck(range, cg.cgid, From 015e63b6f09fe8f725b281d3ece307fb66a8a22e Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 16:54:03 +0200 Subject: [PATCH 0839/1068] OOFrontend.getFillCursorForCitationGroup accepts CitationGroup --- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 4 +--- .../org/jabref/logic/openoffice/UpdateCitationMarkers.java | 5 +++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index d2f1a282232..03cf2510398 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -324,13 +324,11 @@ public Optional getMarkRange(XTextDocument doc, CitationGroup cg) return backend.getMarkRange(cg, doc); } - public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGroupID cgid) + public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGroup cg) throws NoDocumentException, WrappedTargetException, CreationException { - - CitationGroup cg = this.citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); return backend.getFillCursorForCitationGroup(cg, doc); } diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index e9f461c3f5c..ac4f68bfebd 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -73,7 +73,7 @@ static void applyNewCitationMarkers(XTextDocument doc, if (withText && marker.isPresent()) { - XTextCursor cursor = fr.getFillCursorForCitationGroup(doc, cg.cgid); + XTextCursor cursor = fr.getFillCursorForCitationGroup(doc, cg); fillCitationMarkInCursor(doc, cursor, marker.get(), withText, style); @@ -164,7 +164,8 @@ public static void createAndFillCitationGroup(OOFrontend fr, final boolean withText = citationType.withText(); if (withText) { - XTextCursor c2 = fr.getFillCursorForCitationGroup(doc, cgid); + CitationGroup cg = fr.citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); + XTextCursor c2 = fr.getFillCursorForCitationGroup(doc, cg); UpdateCitationMarkers.fillCitationMarkInCursor(doc, c2, citationText, withText, style); From 504776723011bdda26acfb3ad7e3461475552b95 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 16:56:57 +0200 Subject: [PATCH 0840/1068] OOFrontend.createCitationGroup returns CitationGroup --- .../org/jabref/logic/openoffice/OOFrontend.java | 14 +++++++------- .../logic/openoffice/UpdateCitationMarkers.java | 16 +++++++--------- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 03cf2510398..d5956d2d018 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -251,12 +251,12 @@ public Optional healthReport(XTextDocument doc) * carries on format of characters from * the original position. */ - public CitationGroupID createCitationGroup(XTextDocument doc, - List citationKeys, - List> pageInfos, - InTextCitationType citationType, - XTextCursor position, - boolean insertSpaceAfter) + public CitationGroup createCitationGroup(XTextDocument doc, + List citationKeys, + List> pageInfos, + InTextCitationType citationType, + XTextCursor position, + boolean insertSpaceAfter) throws CreationException, NoDocumentException, @@ -278,7 +278,7 @@ public CitationGroupID createCitationGroup(XTextDocument doc, insertSpaceAfter); this.citationGroups.afterCreateCitationGroup(cg); - return cg.cgid; + return cg; } /** diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index ac4f68bfebd..76a9877af08 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -7,7 +7,6 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOText; @@ -154,22 +153,21 @@ public static void createAndFillCitationGroup(OOFrontend fr, if (pageInfos.size() != citationKeys.size()) { throw new RuntimeException("pageInfos.size != citationKeys.size"); } - CitationGroupID cgid = fr.createCitationGroup(doc, - citationKeys, - pageInfos, - citationType, - position, - insertSpaceAfter); + CitationGroup cg = fr.createCitationGroup(doc, + citationKeys, + pageInfos, + citationType, + position, + insertSpaceAfter); final boolean withText = citationType.withText(); if (withText) { - CitationGroup cg = fr.citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); XTextCursor c2 = fr.getFillCursorForCitationGroup(doc, cg); UpdateCitationMarkers.fillCitationMarkInCursor(doc, c2, citationText, withText, style); - fr.cleanFillCursorForCitationGroup(doc, cgid); + fr.cleanFillCursorForCitationGroup(doc, cg.cgid); } position.collapseToEnd(); } From 080c9fefde82e6dc901f4f71098c9ec5e17632de Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 17:05:41 +0200 Subject: [PATCH 0841/1068] OOFrontend.cleanFillCursorForCitationGroup accepts CitationGroup --- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 5 +---- .../org/jabref/logic/openoffice/UpdateCitationMarkers.java | 4 ++-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index d5956d2d018..212937a227c 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -334,16 +334,13 @@ public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGrou /** * Remove brackets added by getFillCursorForCitationGroup. - * - * @param cgid : Must be known, throws if not. */ - public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroupID cgid) + public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroup cg) throws NoDocumentException, WrappedTargetException, CreationException { - CitationGroup cg = this.citationGroups.getCitationGroup(cgid).orElseThrow(RuntimeException::new); backend.cleanFillCursorForCitationGroup(cg, doc); } diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 76a9877af08..4118675a0cc 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -76,7 +76,7 @@ static void applyNewCitationMarkers(XTextDocument doc, fillCitationMarkInCursor(doc, cursor, marker.get(), withText, style); - fr.cleanFillCursorForCitationGroup(doc, cg.cgid); + fr.cleanFillCursorForCitationGroup(doc, cg); } } @@ -167,7 +167,7 @@ public static void createAndFillCitationGroup(OOFrontend fr, UpdateCitationMarkers.fillCitationMarkInCursor(doc, c2, citationText, withText, style); - fr.cleanFillCursorForCitationGroup(doc, cg.cgid); + fr.cleanFillCursorForCitationGroup(doc, cg); } position.collapseToEnd(); } From bc67c967724d3c37400af912071934d3d9305971 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 17:11:12 +0200 Subject: [PATCH 0842/1068] use getCitationGroupsInGlobalOrder() --- src/main/java/org/jabref/model/oostyle/CitationGroups.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index f656e8ac378..fbdece0e237 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -184,8 +184,7 @@ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { if (!hasGlobalOrder()) { throw new RuntimeException("getSortedCitedKeys: no globalOrder"); } - for (CitationGroupID cgid : globalOrder.get()) { - CitationGroup cg = getCitationGroup(cgid).orElseThrow(RuntimeException::new); + for (CitationGroup cg : getCitationGroupsInGlobalOrder()) { for (int i : cg.getLocalOrder()) { Citation cit = cg.citationsInStorageOrder.get(i); String citationKey = cit.citationKey; From dfc03a0d661b00fc7010dbe4be0f14e4b45fa21d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 17:26:23 +0200 Subject: [PATCH 0843/1068] getCitationGroupIDsSortedWithinPartitions returns List --- .../jabref/logic/openoffice/EditMerge.java | 10 +++---- .../jabref/logic/openoffice/OOFrontend.java | 30 ++++++++++--------- .../jabref/model/oostyle/CitationGroups.java | 2 +- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 66d48227551..d787f1ff644 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -10,7 +10,6 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; @@ -245,17 +244,16 @@ private static List scan(XTextDocument doc, OOFrontend fr) WrappedTargetException { List result = new ArrayList<>(); - List cgids = + List cgs = fr.getCitationGroupIDsSortedWithinPartitions(doc, false /* mapFootnotesToFootnoteMarks */); - if (cgids.isEmpty()) { + if (cgs.isEmpty()) { return result; } ScanState state = new ScanState(); - for (CitationGroupID cgid : cgids) { - CitationGroup cg = fr.citationGroups.getCitationGroupOrThrow(cgid); + for (CitationGroup cg : cgs) { XTextRange currentRange = (fr.getMarkRange(doc, cg) .orElseThrow(RuntimeException::new)); @@ -285,7 +283,7 @@ private static List scan(XTextDocument doc, OOFrontend fr) if (addToGroup || canStartGroup) { addToCurrentGroup(state, cg, currentRange); } - } // for cgid + } // close currentGroup if (state.currentGroup.size() > 1) { diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 212937a227c..f7b9855e4e8 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -16,6 +16,7 @@ import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OODataModel; +import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; @@ -92,7 +93,7 @@ public Optional healthReport(XTextDocument doc) } /** - * Creates a list of {@code RangeSortable} values for + * Creates a list of {@code RangeSortable} values for * our {@code CitationGroup} values. Originally designed to be * passed to {@code visualSort}. * @@ -111,7 +112,7 @@ public Optional healthReport(XTextDocument doc) * mark. This is used for numbering the citations. * */ - private List> + private List> createVisualSortInput(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) throws NoDocumentException, @@ -122,7 +123,7 @@ public Optional healthReport(XTextDocument doc) XTextRange range = (this .getMarkRange(doc, cg) .orElseThrow(RuntimeException::new)); - sortables.add(new RangeSortEntry(range, 0, cg.cgid)); + sortables.add(new RangeSortEntry(range, 0, cg)); } /* @@ -146,16 +147,16 @@ public Optional healthReport(XTextDocument doc) */ // Sort within partitions - RangeKeyedMapList> rangeSorter = + RangeKeyedMapList> rangeSorter = new RangeKeyedMapList<>(); for (RangeSortEntry sortable : sortables) { rangeSorter.add(sortable.getRange(), sortable); } // build final list - List> result = new ArrayList<>(); + List> result = new ArrayList<>(); - for (TreeMap>> + for (TreeMap>> partition : rangeSorter.partitionValues()) { List orderedRanges = new ArrayList<>(partition.keySet()); @@ -163,8 +164,8 @@ public Optional healthReport(XTextDocument doc) int indexInPartition = 0; for (int i = 0; i < orderedRanges.size(); i++) { XTextRange aRange = orderedRanges.get(i); - List> sortablesAtARange = partition.get(aRange); - for (RangeSortEntry sortable : sortablesAtARange) { + List> sortablesAtARange = partition.get(aRange); + for (RangeSortEntry sortable : sortablesAtARange) { sortable.indexInPosition = indexInPartition++; if (mapFootnotesToFootnoteMarks) { Optional footnoteMarkRange = @@ -195,7 +196,7 @@ public Optional healthReport(XTextDocument doc) * order. * */ - private List + private List getVisuallySortedCitationGroupIDs(XTextDocument doc, boolean mapFootnotesToFootnoteMarks, FunctionalTextViewCursor fcursor) @@ -204,10 +205,10 @@ public Optional healthReport(XTextDocument doc) NoDocumentException, JabRefException { - List> sortables = + List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); - List> sorted = + List> sorted = RangeSortVisual.visualSort(sortables, doc, fcursor); @@ -223,14 +224,14 @@ public Optional healthReport(XTextDocument doc) * consecutive XTextRanges within each XText, (2) not confused by * multicolumn layout or multipage display. */ - public List + public List getCitationGroupIDsSortedWithinPartitions(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) throws NoDocumentException, WrappedTargetException { // This is like getVisuallySortedCitationGroupIDs, // but we skip the visualSort part. - List> sortables = + List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); return (sortables.stream().map(e -> e.getContent()).collect(Collectors.toList())); @@ -525,7 +526,8 @@ public void imposeGlobalOrder(XTextDocument doc, FunctionalTextViewCursor fcurso boolean mapFootnotesToFootnoteMarks = true; List sortedCitationGroupIDs = - getVisuallySortedCitationGroupIDs(doc, mapFootnotesToFootnoteMarks, fcursor); + OOListUtil.map(getVisuallySortedCitationGroupIDs(doc, mapFootnotesToFootnoteMarks, fcursor), + cg -> cg.cgid); citationGroups.setGlobalOrder(sortedCitationGroupIDs); } } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index fbdece0e237..5bd543f5317 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -188,7 +188,7 @@ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { for (int i : cg.getLocalOrder()) { Citation cit = cg.citationsInStorageOrder.get(i); String citationKey = cit.citationKey; - CitationPath p = new CitationPath(cgid, i); + CitationPath p = new CitationPath(cg.cgid, i); if (res.containsKey(citationKey)) { res.get(citationKey).addPath(p, cit); } else { From d5a9e67f2545a919008fda86e2084582f2b1dc1e Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 17:41:41 +0200 Subject: [PATCH 0844/1068] rename methods according their result types --- .../jabref/logic/openoffice/EditMerge.java | 4 ++-- .../jabref/logic/openoffice/OOFrontend.java | 23 +++++++++---------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index d787f1ff644..4279ca6c927 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -245,8 +245,8 @@ private static List scan(XTextDocument doc, OOFrontend fr) List result = new ArrayList<>(); List cgs = - fr.getCitationGroupIDsSortedWithinPartitions(doc, - false /* mapFootnotesToFootnoteMarks */); + fr.getCitationGroupsSortedWithinPartitions(doc, + false /* mapFootnotesToFootnoteMarks */); if (cgs.isEmpty()) { return result; } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index f7b9855e4e8..18b3bd580ac 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -183,13 +183,11 @@ public Optional healthReport(XTextDocument doc) } /** - * Return JabRef reference mark names sorted by their visual positions. - * * @param mapFootnotesToFootnoteMarks If true, sort reference * marks in footnotes as if they appeared at the * corresponding footnote mark. * - * @return JabRef reference mark names sorted by these positions. + * @return citation groups sorted by their visual positions. * * Limitation: for two column layout visual (top-down, * left-right) order does not match the expected (textual) @@ -197,9 +195,9 @@ public Optional healthReport(XTextDocument doc) * */ private List - getVisuallySortedCitationGroupIDs(XTextDocument doc, - boolean mapFootnotesToFootnoteMarks, - FunctionalTextViewCursor fcursor) + getVisuallySortedCitationGroups(XTextDocument doc, + boolean mapFootnotesToFootnoteMarks, + FunctionalTextViewCursor fcursor) throws WrappedTargetException, NoDocumentException, @@ -217,19 +215,19 @@ public Optional healthReport(XTextDocument doc) } /** - * Calculate and return citation group IDs in visual order within - * (but not across) XText partitions. + * Return citation groups in visual order within (but not across) + * XText partitions. * * This is (1) sufficient for combineCiteMarkers which looks for * consecutive XTextRanges within each XText, (2) not confused by * multicolumn layout or multipage display. */ public List - getCitationGroupIDsSortedWithinPartitions(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) + getCitationGroupsSortedWithinPartitions(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) throws NoDocumentException, WrappedTargetException { - // This is like getVisuallySortedCitationGroupIDs, + // This is like getVisuallySortedCitationGroups, // but we skip the visualSort part. List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); @@ -525,9 +523,10 @@ public void imposeGlobalOrder(XTextDocument doc, FunctionalTextViewCursor fcurso JabRefException { boolean mapFootnotesToFootnoteMarks = true; + List sortedCitationGroups = + getVisuallySortedCitationGroups(doc, mapFootnotesToFootnoteMarks, fcursor); List sortedCitationGroupIDs = - OOListUtil.map(getVisuallySortedCitationGroupIDs(doc, mapFootnotesToFootnoteMarks, fcursor), - cg -> cg.cgid); + OOListUtil.map(sortedCitationGroups, cg -> cg.cgid); citationGroups.setGlobalOrder(sortedCitationGroupIDs); } } From 30ffb53ab6b3c22d2c6f58c92af72fc7e4e754e9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 21:09:20 +0200 Subject: [PATCH 0845/1068] check attempt to cite in protected parts --- .../org/jabref/gui/openoffice/OOBibBase.java | 100 +++++++++++++++--- .../jabref/logic/openoffice/OOFrontend.java | 52 ++++++++- .../logic/openoffice/UpdateBibliography.java | 19 ++-- .../openoffice/RangeForOverlapCheck.java | 2 + src/main/resources/l10n/JabRef_en.properties | 1 + 5 files changed, 151 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index eb7edaf07f4..5ce71b865d1 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -29,10 +29,12 @@ import org.jabref.logic.openoffice.Update; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.RangeForOverlapCheck; import org.jabref.model.openoffice.Result; import org.jabref.model.openoffice.VoidResult; @@ -237,6 +239,65 @@ Result getFunctionalTextViewCursor(XTextDocum return result.mapError(e -> OOError.from(e).setTitle(title)); } + private static VoidResult + checkRangeOverlaps(XTextDocument doc, OOFrontend fr) { + final String title = "checkRangeOverlaps"; + boolean requireSeparation = false; + int maxReportedOverlaps = 10; + try { + return (fr.checkRangeOverlaps(doc, + new ArrayList<>(), + requireSeparation, + maxReportedOverlaps) + .mapError(OOError::fromJabRefException)); + } catch (NoDocumentException ex) { + return VoidResult.error(OOError.from(ex).setTitle(title)); + } catch (WrappedTargetException ex) { + return VoidResult.error(OOError.fromMisc(ex).setTitle(title)); + } + } + + private static VoidResult + checkRangeOverlapsWithCursor(XTextDocument doc, OOFrontend fr) { + final String title = "checkRangeOverlapsWithCursor"; + + VoidResult precheck = checkRangeOverlaps(doc, fr); + if (precheck.isError()) { + return precheck; + } + + List> userRanges; + try { + userRanges = fr.viewCursorRanges(doc); + } catch (NoDocumentException ex) { + return VoidResult.error(OOError.from(ex).setTitle(title)); + } catch (WrappedTargetException ex) { + return VoidResult.error(OOError.fromMisc(ex).setTitle(title)); + } + + boolean requireSeparation = false; + int maxReportedOverlaps = 10; + VoidResult res; + try { + res = fr.checkRangeOverlaps(doc, + userRanges, + requireSeparation, + maxReportedOverlaps); + } catch (NoDocumentException ex) { + return VoidResult.error(OOError.from(ex).setTitle(title)); + } catch (WrappedTargetException ex) { + return VoidResult.error(OOError.fromMisc(ex).setTitle(title)); + } + + if (res.isError()) { + final String xtitle = Localization.lang("The cursor is in protected area."); + return VoidResult.error(new OOError(xtitle, + xtitle + "\n" + + res.getError().getLocalizedMessage() + "\n")); + } + return res.mapError(OOError::fromJabRefException); + } + /* * * Tests for preconditions. @@ -283,6 +344,18 @@ VoidResult styleIsRequired(OOBibStyle style) { } } + Result getFrontend(XTextDocument doc) { + final String title = "getFrontend"; + try { + return Result.ok(new OOFrontend(doc)); + } catch (NoDocumentException ex) { + return Result.error(OOError.from(ex).setTitle(title)); + } catch (WrappedTargetException + | RuntimeException ex) { + return Result.error(OOError.fromMisc(ex).setTitle(title)); + } + } + VoidResult databaseIsRequired(List databases, Supplier fun) { if (databases == null || databases.isEmpty()) { @@ -568,12 +641,24 @@ public void guiActionInsertEntry(List entries, selectedBibEntryIsRequired(entries, OOError::noEntriesSelectedForCitation))) { return; } - XTextDocument doc = odoc.get(); + + Result ofr = getFrontend(doc); + if (testDialog(title, ofr.asVoidResult())) { + return; + } + OOFrontend fr = ofr.get(); + Result cursor = getUserCursorForTextInsertion(doc, title); + if (testDialog(title, cursor.asVoidResult())) { + return; + } + + if (testDialog(title, checkRangeOverlapsWithCursor(doc, fr))) { + return; + } if (testDialog(title, - cursor.asVoidResult(), checkStylesExistInTheDocument(style, doc), checkIfOpenOfficeIsRecordingChanges(doc))) { return; @@ -604,8 +689,6 @@ public void guiActionInsertEntry(List entries, try { UnoUndo.enterUndoContext(doc, "Insert citation"); - OOFrontend fr = new OOFrontend(doc); - EditInsert.insertCitationGroup(doc, fr, cursor.get(), @@ -876,14 +959,7 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl } OOFrontend fr = new OOFrontend(doc); - // Check Range overlaps - boolean requireSeparation = false; - int maxReportedOverlaps = 10; - VoidResult ee = (fr.checkRangeOverlaps(doc, - requireSeparation, - maxReportedOverlaps) - .mapError(OOError::fromJabRefException)); - if (testDialog(title, ee)) { + if (testDialog(title, checkRangeOverlaps(doc, fr))) { return; } diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 18b3bd580ac..792d9288571 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -97,7 +97,8 @@ public Optional healthReport(XTextDocument doc) * our {@code CitationGroup} values. Originally designed to be * passed to {@code visualSort}. * - * The elements of the returned list are actually of type {@code RangeSortEntry}. + * The elements of the returned list are actually of type + * {@code RangeSortEntry}. * * The result is sorted within {@code XTextRange.getText()} * partitions of the citation groups according to their {@code XTextRange} @@ -367,6 +368,42 @@ private List> citationRanges(XTextDocument return result; } + private List> bibliographyRanges(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException { + + List> result = new ArrayList<>(); + + Optional range = UpdateBibliography.getBibliographyRange(doc); + if (range.isPresent()) { + String description = "bibliography"; + result.add(new RangeForOverlapCheck(range.get(), + new CitationGroupID("bibliography"), + RangeForOverlapCheck.BIBLIOGRAPHY_MARK_KIND, + description)); + } + return result; + } + + public List> viewCursorRanges(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException { + + List> result = new ArrayList<>(); + + Optional range = UnoCursor.getViewCursor(doc).map(e -> e); + if (range.isPresent()) { + String description = "cursor"; + result.add(new RangeForOverlapCheck(range.get(), + new CitationGroupID("cursor"), + RangeForOverlapCheck.CURSOR_MARK_KIND, + description)); + } + return result; + } + /** * @return A range for each footnote mark where the footnote * contains at least one citation group. @@ -419,14 +456,19 @@ private List> footnoteMarkRanges(XTextDocu * @param reportAtMost Limit number of overlaps reported (0 for no limit) * */ - public VoidResult checkRangeOverlaps(XTextDocument doc, - boolean requireSeparation, - int reportAtMost) + public VoidResult + checkRangeOverlaps(XTextDocument doc, + List> userRanges, + boolean requireSeparation, + int reportAtMost) throws NoDocumentException, WrappedTargetException { - List> ranges = citationRanges(doc); + List> ranges = new ArrayList<>(); + ranges.addAll(userRanges); + ranges.addAll(bibliographyRanges(doc)); + ranges.addAll(citationRanges(doc)); ranges.addAll(footnoteMarkRanges(doc)); RangeKeyedMapList> sorted = new RangeKeyedMapList<>(); diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java index 10799c83e37..5da8d065d67 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -16,7 +16,6 @@ import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; -import com.sun.star.text.XTextSection; /* * Update document: citation marks and bibliography @@ -26,6 +25,14 @@ public class UpdateBibliography { private static final String BIB_SECTION_NAME = "JR_bib"; private static final String BIB_SECTION_END_NAME = "JR_bib_end"; + static Optional getBibliographyRange(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException { + Optional sectionRange = UnoTextSection.getAnchor(doc, BIB_SECTION_NAME); + return sectionRange; + } + /** * Rebuilds the bibliography. */ @@ -83,7 +90,8 @@ private static void clearBibTextSectionContent2(XTextDocument doc) NoDocumentException, WrappedTargetException { - Optional sectionRange = UnoTextSection.getAnchor(doc, BIB_SECTION_NAME); + // Optional sectionRange = UnoTextSection.getAnchor(doc, BIB_SECTION_NAME); + Optional sectionRange = getBibliographyRange(doc); if (sectionRange.isEmpty()) { createBibTextSection2(doc); return; @@ -113,10 +121,9 @@ private static void populateBibTextSection(XTextDocument doc, UnknownPropertyException, WrappedTargetException { - XTextSection section = (UnoTextSection.getByName(doc, BIB_SECTION_NAME) - .orElseThrow(RuntimeException::new)); + XTextRange sectionRange = getBibliographyRange(doc).orElseThrow(RuntimeException::new); - XTextCursor cursor = doc.getText().createTextCursorByRange(section.getAnchor()); + XTextCursor cursor = doc.getText().createTextCursorByRange(sectionRange); // emit the title of the bibliography OOTextIntoOO.removeDirectFormatting(cursor); @@ -128,7 +135,7 @@ private static void populateBibTextSection(XTextDocument doc, cursor.collapseToEnd(); // remove the inital empty paragraph from the section. - XTextCursor initialParagraph = doc.getText().createTextCursorByRange(section.getAnchor()); + XTextCursor initialParagraph = doc.getText().createTextCursorByRange(sectionRange); initialParagraph.collapseToStart(); initialParagraph.goRight((short) 1, true); initialParagraph.setString(""); diff --git a/src/main/java/org/jabref/model/openoffice/RangeForOverlapCheck.java b/src/main/java/org/jabref/model/openoffice/RangeForOverlapCheck.java index 8c15931422d..9d15f8c5fd5 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeForOverlapCheck.java +++ b/src/main/java/org/jabref/model/openoffice/RangeForOverlapCheck.java @@ -19,6 +19,8 @@ public class RangeForOverlapCheck { public final static int REFERENCE_MARK_KIND = 0; public final static int FOOTNOTE_MARK_KIND = 1; + public final static int CURSOR_MARK_KIND = 2; + public final static int BIBLIOGRAPHY_MARK_KIND = 3; public final XTextRange range; public final int kind; diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 2a060589c54..e8a1c354826 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1555,6 +1555,7 @@ Export\ cited=Export cited Unable\ to\ generate\ new\ library=Unable to generate new library Could\ not\ get\ the\ cursor.=Could not get the cursor. +The\ cursor\ is\ in\ protected\ area.=The cursor is in protected area. JabRefException=JabRefException No\ bibliography\ database\ is\ open\ for\ citation.=No bibliography database is open for citation. From db53c866aab9020a2060715739cdd843faea7e05 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 24 May 2021 21:26:42 +0200 Subject: [PATCH 0846/1068] reorder OOError, drop fromJabRefException --- .../org/jabref/gui/openoffice/OOBibBase.java | 4 +-- .../org/jabref/gui/openoffice/OOError.java | 25 +++++++++++-------- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 5ce71b865d1..693424453fc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -249,7 +249,7 @@ Result getFunctionalTextViewCursor(XTextDocum new ArrayList<>(), requireSeparation, maxReportedOverlaps) - .mapError(OOError::fromJabRefException)); + .mapError(OOError::from)); } catch (NoDocumentException ex) { return VoidResult.error(OOError.from(ex).setTitle(title)); } catch (WrappedTargetException ex) { @@ -295,7 +295,7 @@ Result getFunctionalTextViewCursor(XTextDocum xtitle + "\n" + res.getError().getLocalizedMessage() + "\n")); } - return res.mapError(OOError::fromJabRefException); + return res.mapError(OOError::from); } /* diff --git a/src/main/java/org/jabref/gui/openoffice/OOError.java b/src/main/java/org/jabref/gui/openoffice/OOError.java index ef0138d2d82..e5b9d493bf4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOError.java +++ b/src/main/java/org/jabref/gui/openoffice/OOError.java @@ -35,14 +35,10 @@ public void showErrorDialog(DialogService dialogService) { dialogService.showErrorDialogAndWait(getTitle(), getLocalizedMessage()); } - public static OOError fromMisc(Exception ex) { - return new OOError( - "Exception", - ex.getMessage(), - ex); - } + /* + * Conversions from exception caught + */ - // For JabRefException public static OOError from(JabRefException ex) { return new OOError( Localization.lang("JabRefException"), @@ -50,10 +46,6 @@ public static OOError from(JabRefException ex) { ex); } - public static OOError fromJabRefException(JabRefException ex) { - return from(ex); - } - // For DisposedException public static OOError from(DisposedException ex) { return new OOError( @@ -86,6 +78,17 @@ public static OOError from(NoDocumentFoundException ex) { ex); } + public static OOError fromMisc(Exception ex) { + return new OOError( + "Exception", + ex.getMessage(), + ex); + } + + /* + * Messages for error dialog. These are not thrown. + */ + // noDataBaseIsOpenForCiting public static OOError noDataBaseIsOpenForCiting() { return new OOError( From bfc1be4bf3c50286e9dea9ec0450133cf24d2d0e Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 25 May 2021 08:08:34 +0200 Subject: [PATCH 0847/1068] getBibliographyRange(doc) again beore removing initial para --- .../java/org/jabref/logic/openoffice/UpdateBibliography.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java index 5da8d065d67..1caf2bf814c 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -135,6 +135,7 @@ private static void populateBibTextSection(XTextDocument doc, cursor.collapseToEnd(); // remove the inital empty paragraph from the section. + sectionRange = getBibliographyRange(doc).orElseThrow(RuntimeException::new); XTextCursor initialParagraph = doc.getText().createTextCursorByRange(sectionRange); initialParagraph.collapseToStart(); initialParagraph.goRight((short) 1, true); From 0ee4d5b89d411d892a6c8068f10bdd381957d358 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 25 May 2021 10:53:19 +0200 Subject: [PATCH 0848/1068] comments --- .../org/jabref/gui/openoffice/OOBibBase.java | 47 ++++--------------- .../org/jabref/logic/openoffice/Codec52.java | 2 +- .../jabref/logic/openoffice/EditSeparate.java | 2 +- .../model/oostyle/CitationMarkerEntry.java | 8 ---- .../org/jabref/model/oostyle/OODataModel.java | 6 +-- 5 files changed, 13 insertions(+), 52 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 693424453fc..909a4240249 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -568,62 +568,35 @@ public void guiActionApplyCitationEntries(List citationEntries) { /** * - * Creates a citation group from {@code entries} at the cursor, - * and (if sync is true) refreshes the citation markers and the - * bibliography. - * - * - * Called from: OpenOfficePanel.pushEntries, a GUI action for - * "Cite", "Cite in-text", "Cite special" and "Insert empty - * citation". + * Creates a citation group from {@code entries} at the cursor. * * Uses LO undo context "Insert citation". * - * Note: Undo does not remove custom properties. Presumably - * neither does it reestablish them. + * Note: Undo does not remove or reestablish custom properties. * * @param entries The entries to cite. * * @param database The database the entries belong to (all of them). * Used when creating the citation mark. * - * Consistency: for each entry in {@entries} looking it up in - * {@code syncOptions.get().databases} should yield {@code database}. - * Otherwise we may get a different entry - * with and without synchronization. + * Consistency: for each entry in {@entries}: looking it up in + * {@code syncOptions.get().databases} (if present) + * should yield {@code database}. * * @param style The bibliography style we are using. * * @param citationType Indicates whether it is an in-text * citation, a citation in parenthesis or * an invisible citation. - * The in-text/in-parenthesis distionction is not relevant if - * numbered citations are used. - * - * @param pageInfo A single page-info for these entries. Stored in custom property - * with the same name as the reference mark. - * - * This is a GUI call, and we are not ready - * to get multiple pageInfo values there. - * - * In case of multiple entries, pageInfo goes - * to the last citation (as apparently did in JabRef52). * - * Related https://latex.org/forum/viewtopic.php?t=14331 - * """ - * Q: What I would like is something like this: - * (Jones, 2010, p. 12; Smith, 2003, pp. 21 - 23) - * A: Not in a single \citep, no. - * Use \citetext{\citealp[p.~12]{jones2010}; - * \citealp[pp.~21--23]{smith2003}} - * """ + * @param pageInfo A single page-info for these entries. + * Attributed to the last entry. * * @param syncOptions Indicates whether in-text citations * should be refreshed in the document. * Optional.empty() indicates no refresh. - * Otherwise provides options for refreshing the reference list. - * - * + * Otherwise provides options for refreshing + * the reference list. */ public void guiActionInsertEntry(List entries, BibDatabase database, @@ -742,7 +715,6 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle databaseIsRequired(databases, OOError::noDataBaseIsOpen))) { return; } - XTextDocument doc = odoc.get(); Result fcursor = getFunctionalTextViewCursor(doc, title); @@ -872,7 +844,6 @@ public Optional exportCitedHelper(List databases, databaseIsRequired(databases, OOError::noDataBaseIsOpenForExport))) { return FAIL; } - XTextDocument doc = odoc.get(); try { diff --git a/src/main/java/org/jabref/logic/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/Codec52.java index 26d48ec27db..427b00568f0 100644 --- a/src/main/java/org/jabref/logic/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/Codec52.java @@ -48,7 +48,7 @@ public static class ParsedMarkName { /* * Integer representation was written into the document in - * JabRef52, must keep it for compatibility. + * JabRef52, keep it for compatibility. */ public static InTextCitationType InTextCitationTypeFromInt(int i) { switch (i) { diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 6678925971b..ae1ce5da652 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -47,7 +47,7 @@ public static boolean separateCitations(XTextDocument doc, boolean madeModifications = false; // To reduce surprises in JabRef52 mode, impose localOrder to - // decide the visually last Citation i the group. Unless the + // decide the visually last Citation in the group. Unless the // style changed since refresh this is the last on the screen // as well. fr.citationGroups.lookupCitations(databases); diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java index b5dc641fcf7..005f2464cb7 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java @@ -5,14 +5,6 @@ /** * This is what we need for getCitationMarker2 to produce author-year * citation markers. - * - * Citation misses two things - * - isFirstAppearanceOfSource : could be extended to provide this. - * - pageInfo under DataModel JabRef52 needs CitationGroup - * - * CitedKey is used for creating normalizedCitationMarker, so we do - * not need pageInfo, uniqueLetter and isFirstAppearanceOfSource. - * */ public interface CitationMarkerEntry extends CitationMarkerNormEntry { diff --git a/src/main/java/org/jabref/model/oostyle/OODataModel.java b/src/main/java/org/jabref/model/oostyle/OODataModel.java index ed735db81ee..76383f3e954 100644 --- a/src/main/java/org/jabref/model/oostyle/OODataModel.java +++ b/src/main/java/org/jabref/model/oostyle/OODataModel.java @@ -8,14 +8,12 @@ public enum OODataModel { /** - * JabRef52: - * pageInfo belongs to CitationGroup, not Citation. + * JabRef52: pageInfo belongs to CitationGroup, not Citation. */ JabRef52, /** - * JabRef53: - * pageInfo belongs to Citation. + * JabRef53: pageInfo belongs to Citation. */ JabRef53; From 91d0dc81a844b44eaf0ec39da3a7a3f840cffeaf Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 25 May 2021 20:50:27 +0200 Subject: [PATCH 0849/1068] comments --- .../jabref/model/oostyle/CitationMarkerNormEntry.java | 3 ++- .../model/oostyle/CitationMarkerNumericBibEntry.java | 10 ++++++---- .../model/oostyle/CitationMarkerNumericEntry.java | 6 ++++-- src/main/java/org/jabref/model/oostyle/CitedKey.java | 7 +++++++ src/main/java/org/jabref/model/oostyle/CitedKeys.java | 6 ++---- .../org/jabref/model/oostyle/ComparableCitation.java | 2 +- .../org/jabref/model/oostyle/ComparableCitedKey.java | 2 +- 7 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java index 91f7fc55b75..a8b9685ae3f 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java @@ -12,12 +12,13 @@ public interface CitationMarkerNormEntry { * * Used if getBibEntry() and/or getDatabase() returns * empty, which indicates failure to lookup in the databases. - * The marker created is "Unresolved({citationKey})". * */ String getCitationKey(); /** Result of looking up citation key in databases. + * + * Optional.empty() indicates unresolved citation. */ Optional getLookupResult(); } diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java index d30a2767340..3c5e3f1e4d4 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java @@ -4,14 +4,16 @@ /** * This is for the numeric bibliography labels. - * - * getNumber() returning Optional.empty() indicates unresolved - * citation. In this case we also show the citation key to help - * finding the problematic citations. */ public interface CitationMarkerNumericBibEntry { + /** + * For unresolved citation we show the citation key. + */ String getCitationKey(); + /** + * @return Optional.empty() for unresolved + */ Optional getNumber(); } diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java index 7f83c470b10..b23ab17a988 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java @@ -3,13 +3,15 @@ import java.util.Optional; /** - * This is what we need for getCitationMarker to produce numeric - * citation markers. + * This is what we need for numeric citation markers. */ public interface CitationMarkerNumericEntry { String getCitationKey(); + /** + * @return Optional.empty() for unresolved + */ Optional getNumber(); Optional getPageInfo(); diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index a9bc7a4b5e5..f63a695a470 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -115,6 +115,9 @@ void addPath(CitationPath p, Citation cit) { } } + /* + * Lookup + */ void lookupInDatabases(List databases) { this.db = Citation.lookup(databases, this.citationKey); } @@ -123,6 +126,10 @@ void distributeLookupResult(CitationGroups cgs) { cgs.distributeToCitations(where, Citation::setLookupResult, db); } + /* + * Make unique using a letter or by numbering + */ + void distributeNumber(CitationGroups cgs) { cgs.distributeToCitations(where, Citation::setNumber, number); } diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeys.java b/src/main/java/org/jabref/model/oostyle/CitedKeys.java index ffea786a257..642fb07193a 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKeys.java @@ -44,9 +44,6 @@ void sortByComparator(Comparator entryComparator) { data = newData; } - /** - * Unresolved citations do not get a number. - */ void numberCitedKeysInCurrentOrder() { int i = 1; for (CitedKey ck : data.values()) { @@ -54,6 +51,7 @@ void numberCitedKeysInCurrentOrder() { ck.setNumber(Optional.of(i)); i++; } else { + // Unresolved citations do not get a number. ck.setNumber(Optional.empty()); } } @@ -83,4 +81,4 @@ public void distributeUniqueLetters(CitationGroups cgs) { } } -} // class CitedKeys +} diff --git a/src/main/java/org/jabref/model/oostyle/ComparableCitation.java b/src/main/java/org/jabref/model/oostyle/ComparableCitation.java index 06250c2e7b0..09df46110fd 100644 --- a/src/main/java/org/jabref/model/oostyle/ComparableCitation.java +++ b/src/main/java/org/jabref/model/oostyle/ComparableCitation.java @@ -2,7 +2,7 @@ import java.util.Optional; -/* +/** * When sorting citations (in a group), we also consider pageInfo. * Otherwise we sort citations as cited keys. */ diff --git a/src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java b/src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java index 17f2e8c1e8a..6c04d560dcc 100644 --- a/src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java @@ -4,7 +4,7 @@ import org.jabref.model.entry.BibEntry; -/* +/** * This is what we need to sort bibliography entries. */ public interface ComparableCitedKey { From ab9523f1e6275f84ba80bdcd650b7dcfaf87adf4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 25 May 2021 21:00:59 +0200 Subject: [PATCH 0850/1068] CitedKey.where can be a List --- src/main/java/org/jabref/model/oostyle/CitationGroups.java | 2 +- src/main/java/org/jabref/model/oostyle/CitedKey.java | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 5bd543f5317..ad47611ff59 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -55,7 +55,7 @@ public int numberOfCitationGroups() { * For each citation in {@code where} * call {@code fun.accept(new Pair(citation, value));} */ - public void distributeToCitations(Set where, + public void distributeToCitations(List where, Consumer> fun, T value) { diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index f63a695a470..eb3d4be964c 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -1,7 +1,6 @@ package org.jabref.model.oostyle; import java.util.ArrayList; -import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; @@ -21,7 +20,7 @@ public class CitedKey implements CitationMarkerNumericBibEntry { public final String citationKey; - private final LinkedHashSet where; + private final List where; private Optional db; private Optional number; // For Numbered citation styles. @@ -31,7 +30,7 @@ public class CitedKey implements CitedKey(String citationKey, CitationPath p, Citation cit) { this.citationKey = citationKey; - this.where = new LinkedHashSet<>(); // remember order + this.where = new ArrayList<>(); // remember order this.where.add(p); // sync with citations From fdd00f42fdc53097160cfa326897aa21691dcec8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 25 May 2021 21:05:07 +0200 Subject: [PATCH 0851/1068] comments --- src/main/java/org/jabref/model/oostyle/CitedKey.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/oostyle/CitedKey.java index eb3d4be964c..0afc9c35ba6 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/oostyle/CitedKey.java @@ -33,11 +33,12 @@ public class CitedKey implements this.where = new ArrayList<>(); // remember order this.where.add(p); - // sync with citations + // synchronized with Citation this.db = cit.getLookupResult(); this.number = cit.getNumber(); this.uniqueLetter = cit.getUniqueLetter(); + // CitedKey only this.normCitMarker = Optional.empty(); } From 6785712253fce47e7b22038d517a9f476b489b18 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 25 May 2021 21:35:48 +0200 Subject: [PATCH 0852/1068] add PageInfo.java --- .../org/jabref/logic/oostyle/OOBibStyle.java | 4 +- .../oostyle/OOBibStyleGetCitationMarker.java | 8 ++-- .../OOBibStyleGetNumCitationMarker.java | 4 +- .../jabref/logic/openoffice/Backend52.java | 9 ++-- .../org/jabref/model/oostyle/Citation.java | 15 +------ .../jabref/model/oostyle/CitationGroups.java | 1 - .../jabref/model/oostyle/CompareCitation.java | 26 +---------- .../org/jabref/model/oostyle/OODataModel.java | 2 +- .../org/jabref/model/oostyle/PageInfo.java | 45 +++++++++++++++++++ .../jabref/logic/oostyle/OOBibStyleTest.java | 5 ++- 10 files changed, 65 insertions(+), 54 deletions(-) create mode 100644 src/main/java/org/jabref/model/oostyle/PageInfo.java diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index bb1717fbe94..857afde3e79 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -30,7 +30,6 @@ 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.oostyle.Citation; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerNormEntry; import org.jabref.model.oostyle.CitationMarkerNumericBibEntry; @@ -38,6 +37,7 @@ import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; +import org.jabref.model.oostyle.PageInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -976,7 +976,7 @@ public OOText getNumCitationMarkerForBibliography(CitationMarkerNumericBibEntry } // not null, normalize elementwise - return OOListUtil.map(pageInfos, Citation::normalizePageInfo); + return OOListUtil.map(pageInfos, PageInfo::normalizePageInfo); } public OOText getNormalizedCitationMarker(CitationMarkerNormEntry ce) { diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 978219d9a75..732608230f3 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -12,12 +12,12 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; -import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationLookupResult; import org.jabref.model.oostyle.CitationMarkerEntry; import org.jabref.model.oostyle.CitationMarkerNormEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOText; +import org.jabref.model.oostyle.PageInfo; import org.jabref.model.strings.StringUtil; class OOBibStyleGetCitationMarker { @@ -436,7 +436,7 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, StringBuilder pageInfoPart = new StringBuilder(""); if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { Optional pageInfo = - Citation.normalizePageInfo(ce.getPageInfo()); + PageInfo.normalizePageInfo(ce.getPageInfo()); if (pageInfo.isPresent()) { pageInfoPart.append(pageInfoSeparator); pageInfoPart.append(OOText.toString(pageInfo.get())); @@ -708,8 +708,8 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, final boolean citationKeysDiffer = !ce2.getCitationKey().equals(ce1.getCitationKey()); final boolean normalizedMarkersDiffer = !nm2.equals(nm1); - Optional pageInfo2 = Citation.normalizePageInfo(ce2.getPageInfo()); - Optional pageInfo1 = Citation.normalizePageInfo(ce1.getPageInfo()); + Optional pageInfo2 = PageInfo.normalizePageInfo(ce2.getPageInfo()); + Optional pageInfo1 = PageInfo.normalizePageInfo(ce1.getPageInfo()); final boolean bothPageInfosAreEmpty = pageInfo2.isEmpty() && pageInfo1.isEmpty(); final boolean pageInfosDiffer = !pageInfo2.equals(pageInfo1); diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index 8669de8dafb..3d2cfaccd68 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -6,9 +6,9 @@ import org.jabref.model.oostyle.CitationMarkerNumericBibEntry; import org.jabref.model.oostyle.CitationMarkerNumericEntry; -import org.jabref.model.oostyle.CompareCitation; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; +import org.jabref.model.oostyle.PageInfo; class OOBibStyleGetNumCitationMarker { @@ -26,7 +26,7 @@ private static int compareCitationMarkerNumericEntry(CitationMarkerNumericEntry int nb = b.getNumber().orElse(UNRESOLVED_ENTRY_NUMBER); int res = Integer.compare(na, nb); if (res == 0) { - res = CompareCitation.comparePageInfo(a.getPageInfo(), b.getPageInfo()); + res = PageInfo.comparePageInfo(a.getPageInfo(), b.getPageInfo()); } return res; } diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 2b75f1471a2..ee7406b9838 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -17,6 +17,7 @@ import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OODataModel; import org.jabref.model.oostyle.OOText; +import org.jabref.model.oostyle.PageInfo; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NamedRange; @@ -154,7 +155,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str Optional pageInfo = (UnoUserDefinedProperty.getStringValue(doc, refMarkName) .map(OOText::fromString)); - pageInfo = Citation.normalizePageInfo(pageInfo); + pageInfo = PageInfo.normalizePageInfo(pageInfo); setPageInfoInDataInitial(citations, pageInfo); @@ -223,7 +224,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, Citation cit = new Citation(citationKeys.get(i)); citations.add(cit); - Optional pageInfo = Citation.normalizePageInfo(pageInfos.get(i)); + Optional pageInfo = PageInfo.normalizePageInfo(pageInfos.get(i)); switch (dataModel) { case JabRef52: if (i == last) { @@ -252,7 +253,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, switch (dataModel) { case JabRef52: Optional pageInfo = - Citation.normalizePageInfo(pageInfos.get(last)); + PageInfo.normalizePageInfo(pageInfos.get(last)); if (pageInfo.isPresent()) { String pageInfoString = OOText.toString(pageInfo.get()); @@ -447,7 +448,7 @@ public void applyCitationEntries(XTextDocument doc, List citation case JabRef52: for (CitationEntry entry : citationEntries) { Optional pageInfo = entry.getPageInfo().map(OOText::fromString); - pageInfo = Citation.normalizePageInfo(pageInfo); + pageInfo = PageInfo.normalizePageInfo(pageInfo); if (pageInfo.isPresent()) { String name = entry.getRefMarkName(); UnoUserDefinedProperty.createStringProperty(doc, name, pageInfo.get().asString()); diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index b58e7ea04cf..e2e1e412d15 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -109,7 +109,7 @@ public void setUniqueLetter(Optional uniqueLetter) { } public void setPageInfo(Optional v) { - Optional vv = normalizePageInfo(v); + Optional vv = PageInfo.normalizePageInfo(v); if (!vv.equals(v)) { throw new RuntimeException("setPageInfo argument is not normalized"); } @@ -138,17 +138,4 @@ public static void setUniqueLetter(Pair> x) { cit.uniqueLetter = x.b; } - /* - * pageInfo normalization - */ - public static Optional normalizePageInfo(Optional o) { - if (o == null || o.isEmpty() || "".equals(OOText.toString(o.get()))) { - return Optional.empty(); - } - String s = OOText.toString(o.get()); - if (s.trim().equals("")) { - return Optional.empty(); - } - return Optional.of(OOText.fromString(s.trim())); - } } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index ad47611ff59..7ede2e9e021 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -7,7 +7,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.Set; import java.util.function.Consumer; import org.jabref.model.database.BibDatabase; diff --git a/src/main/java/org/jabref/model/oostyle/CompareCitation.java b/src/main/java/org/jabref/model/oostyle/CompareCitation.java index 6e922f83d58..46e276a965e 100644 --- a/src/main/java/org/jabref/model/oostyle/CompareCitation.java +++ b/src/main/java/org/jabref/model/oostyle/CompareCitation.java @@ -1,7 +1,6 @@ package org.jabref.model.oostyle; import java.util.Comparator; -import java.util.Optional; import org.jabref.model.entry.BibEntry; @@ -11,7 +10,7 @@ */ public class CompareCitation implements Comparator { - CompareCitedKey citedKeyComparator; + private CompareCitedKey citedKeyComparator; CompareCitation(Comparator entryComparator, boolean unresolvedComesFirst) { this.citedKeyComparator = new CompareCitedKey(entryComparator, unresolvedComesFirst); @@ -22,31 +21,10 @@ public int compare(ComparableCitation a, ComparableCitation b) { // Also consider pageInfo if (res == 0) { - res = CompareCitation.comparePageInfo(a.getPageInfo(), b.getPageInfo()); + res = PageInfo.comparePageInfo(a.getPageInfo(), b.getPageInfo()); } return res; } - - /** - * Defines sort order for pageInfo strings. - * - * Optional.empty comes before non-empty. - */ - public static int comparePageInfo(Optional a, Optional b) { - - Optional aa = Citation.normalizePageInfo(a); - Optional bb = Citation.normalizePageInfo(b); - if (aa.isEmpty() && bb.isEmpty()) { - return 0; - } - if (aa.isEmpty()) { - return -1; - } - if (bb.isEmpty()) { - return +1; - } - return aa.get().asString().compareTo(bb.get().asString()); - } } diff --git a/src/main/java/org/jabref/model/oostyle/OODataModel.java b/src/main/java/org/jabref/model/oostyle/OODataModel.java index 76383f3e954..ee223b9dbc2 100644 --- a/src/main/java/org/jabref/model/oostyle/OODataModel.java +++ b/src/main/java/org/jabref/model/oostyle/OODataModel.java @@ -29,7 +29,7 @@ public static List> fakePageInfos(String pageInfo, int nCitatio if (pageInfo != null) { final int last = nCitations - 1; Optional pi = Optional.ofNullable(OOText.fromString(pageInfo)); - pageInfos.set(last, Citation.normalizePageInfo(pi)); + pageInfos.set(last, PageInfo.normalizePageInfo(pi)); } return pageInfos; } diff --git a/src/main/java/org/jabref/model/oostyle/PageInfo.java b/src/main/java/org/jabref/model/oostyle/PageInfo.java new file mode 100644 index 00000000000..8b5fd4ddf94 --- /dev/null +++ b/src/main/java/org/jabref/model/oostyle/PageInfo.java @@ -0,0 +1,45 @@ +package org.jabref.model.oostyle; + +import java.util.Optional; + +public class PageInfo { + + private PageInfo() { + // + } + + /* + * pageInfo normalization + */ + public static Optional normalizePageInfo(Optional o) { + if (o == null || o.isEmpty() || "".equals(OOText.toString(o.get()))) { + return Optional.empty(); + } + String s = OOText.toString(o.get()); + if (s.trim().equals("")) { + return Optional.empty(); + } + return Optional.of(OOText.fromString(s.trim())); + } + + /** + * Defines sort order for pageInfo strings. + * + * Optional.empty comes before non-empty. + */ + public static int comparePageInfo(Optional a, Optional b) { + + Optional aa = PageInfo.normalizePageInfo(a); + Optional bb = PageInfo.normalizePageInfo(b); + if (aa.isEmpty() && bb.isEmpty()) { + return 0; + } + if (aa.isEmpty()) { + return -1; + } + if (bb.isEmpty()) { + return +1; + } + return aa.get().asString().compareTo(bb.get().asString()); + } +} diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 3ea1d74e708..7c92504c746 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -32,6 +32,7 @@ import org.jabref.model.oostyle.CitationMarkerNumericEntry; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOText; +import org.jabref.model.oostyle.PageInfo; import org.jabref.model.openoffice.Tuple3; import org.junit.jupiter.api.BeforeEach; @@ -116,7 +117,7 @@ public CitationMarkerNumericEntryImpl(String citationKey, int num, Optional pageInfo = Optional.ofNullable(OOText.fromString(pageInfoQ)); - result.setPageInfo(Citation.normalizePageInfo(pageInfo)); + result.setPageInfo(PageInfo.normalizePageInfo(pageInfo)); result.setIsFirstAppearanceOfSource(isFirstAppearanceOfSource); return result; } From 9fe181ce104cce52eaba57b2bb2fa6773c951fad Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 25 May 2021 22:04:10 +0200 Subject: [PATCH 0853/1068] use OOListUtil.map --- src/main/java/org/jabref/logic/openoffice/Backend52.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index ee7406b9838..028298fa53f 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -16,6 +16,7 @@ import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.OODataModel; +import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; import org.jabref.model.oostyle.PageInfo; import org.jabref.model.openoffice.CitationEntry; @@ -252,8 +253,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, switch (dataModel) { case JabRef52: - Optional pageInfo = - PageInfo.normalizePageInfo(pageInfos.get(last)); + Optional pageInfo = PageInfo.normalizePageInfo(pageInfos.get(last)); if (pageInfo.isPresent()) { String pageInfoString = OOText.toString(pageInfo.get()); @@ -286,9 +286,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, case JabRef52: // collect to cgPageInfos List> cgPageInfos = - (joinableGroup.stream() - .map(cg -> getPageInfoFromData(cg)) - .collect(Collectors.toList())); + OOListUtil.map(joinableGroup, Backend52::getPageInfoFromData); // Try to do something of the cgPageInfos. String cgPageInfo = (cgPageInfos.stream() From 23a1fcb8d0bacb5052ef6d8e9a8a8c04ae91ae1c Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 25 May 2021 22:05:07 +0200 Subject: [PATCH 0854/1068] requireNonNull --- src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 7a348ac7613..524317fc569 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -520,6 +520,10 @@ public static void write(XTextDocument doc, final boolean debugThisFun = false; + Objects.requireNonNull(doc); + Objects.requireNonNull(ootext); + Objects.requireNonNull(position); + String lText = OOText.toString(ootext); if (debugThisFun) { From 00558328b9b52becded2b7f1be29d704aa9bb0e0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 25 May 2021 22:33:21 +0200 Subject: [PATCH 0855/1068] comments --- src/main/java/org/jabref/logic/openoffice/Backend52.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 028298fa53f..38b8127ef26 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -169,7 +169,6 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str CitationGroup cg = new CitationGroup(OODataModel.JabRef52, cgid, - // namedRange.get(), ov.citationType, citations, Optional.of(refMarkName)); @@ -461,5 +460,5 @@ public void applyCitationEntries(XTextDocument doc, List citation } } -} // end Backend52 +} From fa1d1b647ae27e78fccbf4b8e3d44055289da9d6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 09:28:23 +0200 Subject: [PATCH 0856/1068] bring public methods forward --- .../jabref/logic/openoffice/OOTextIntoOO.java | 663 +++++++----------- 1 file changed, 259 insertions(+), 404 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 524317fc569..f230863eae0 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -45,20 +45,6 @@ /** * Interpret OOText into an OpenOffice or LibreOffice writer * document. - * - * On the question of what should it understand: apart from what - * it can do now, probably whatever a CSL style with HTML output - * emits. - * - * Seems slow with approx 40 citations. - * - * Idea: - * - * - Use setString, not insertString. This removes character formats, - * probably no need for workaround about setPropertyToDefault. - * - Calculate current set of character properties in java. - * - Use interface allowing to set multiple properties in a single call. - * */ @AllowedToUseAwt("Requires AWT for changing document properties") public class OOTextIntoOO { @@ -91,373 +77,24 @@ public class OOTextIntoOO { private static final String TAG_NAME_REGEXP = "(?:b|i|em|tt|smallcaps|sup|sub|u|s|p|span|oo:referenceToPageNumberOfReferenceMark)"; + private static final String ATTRIBUTE_NAME_REGEXP = "(?:oo:ParaStyleName|oo:CharStyleName|lang|style|target)"; + private static final String ATTRIBUTE_VALUE_REGEXP = "\"([^\"]*)\""; + private static final Pattern HTML_TAG = Pattern.compile("<(/" + TAG_NAME_REGEXP + ")>" + "|" + "<(" + TAG_NAME_REGEXP + ")" + "((?:\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP + ")*)" + ">"); + private static final Pattern ATTRIBUTE_PATTERN = Pattern.compile("\\s+(" + ATTRIBUTE_NAME_REGEXP + ")=" + ATTRIBUTE_VALUE_REGEXP); private OOTextIntoOO() { - // Just to hide the public constructor - } - - static class MyPropertyStack { - - // Only try to control these. In particular, leave paragraph - // properties alone. - static final Set CONTROLLED_PROPERTIES = Set.of( - - /* Used for SuperScript, SubScript. - * - * These three are interdependent: changing one may change others. - */ - "CharEscapement", "CharEscapementHeight", "CharAutoEscapement", - - /* used for Bold */ - "CharWeight", - - /* Used for Italic */ - "CharPosture", - - /* CharWordMode : If this property is TRUE, the underline - * and strike-through properties are not applied to white - * spaces. - */ - // "CharWordMode", - - /* Used for strikeout. These two are interdependent. */ - "CharStrikeout", "CharCrossedOut", - - /* Used for underline */ - "CharUnderline", // "CharUnderlineColor", "CharUnderlineHasColor", - - // "CharOverline", "CharOverlineColor", "CharOverlineHasColor", - - /* Used for lang="zxx" to shut spellchecker. */ - "CharLocale", - - /* Used for CitationCharacterFormat */ - "CharStyleName", // "CharStyleNames", "CharAutoStyleName", - - /* Used for and */ - "CharCaseMap" - - /* HyperLink */ - // "HyperLinkName", /* ??? */ - // "HyperLinkURL", /* empty for thisDocument */ - // "HyperLinkTarget", - /* HyperLinkTarget : What comes after '#' (location in doc). - * Can be a bookmark name. - */ - /* character style names for unvisited and visited links */ - // "UnvisitedCharStyleName", "VisitedCharStyleName", - // "HyperLinkEvents", - - // "CharColor", - // "CharHighlight", - // "CharBackColor", "CharBackTransparent", - - // "CharScaleWidth", /* Allows to reduce font width */ - - // "CharKerning", "CharAutoKerning", - - // "CharFontCharSet", - // "CharFontFamily", - // "CharFontName", - // "CharFontPitch", - // "CharFontStyleName", - // "CharHeight", - - // "CharHidden", - - /* - * CharInteropGrabBag : **Since LibreOffice 4.3** - * - * Grab bag of character properties, used as a string-any - * map for interim interop purposes. - * - * This property is intentionally not handled by the ODF - * filter. Any member that should be handled there should - * be first moved out from this grab bag to a separate - * property. - */ - // "CharInteropGrabBag", - - // "CharNoHyphenation", - - // "CharContoured", "CharFlash", "CharRelief", - - // "CharRotation", "CharRotationIsFitToLine", - - // "CharShadingValue", "CharShadowFormat", "CharShadowed", - - /* CharBorder */ - // "CharBorderDistance", - // "CharBottomBorder", "CharBottomBorderDistance", - // "CharTopBorder", "CharTopBorderDistance", - // "CharRightBorder", "CharRightBorderDistance", - // "CharLeftBorder", "CharLeftBorderDistance", - - // "IsSkipHiddenText", - // "IsSkipProtectedText", - - /* TextUserDefinedAttributes: Saved into doc, but lost on Load. - * - * They might be usable within a session to invisibly attach info - * available elsewhere, but costly to get to. - * - */ - // "TextUserDefinedAttributes", - - // "WritingMode" - - // "CharCombineIsOn", "CharCombinePrefix", "CharCombineSuffix", - - /* Ruby */ - // "RubyAdjust", "RubyCharStyleName", "RubyIsAbove", "RubyPosition", "RubyText", - - // "CharEmphasis", /* emphasis mark in asian texts */ - - /* Asian */ - // "CharWeightAsian", - // "CharPostureAsian", - // "CharLocaleAsian", - // "CharFontCharSetAsian", - // "CharFontFamilyAsian", - // "CharFontNameAsian", - // "CharFontPitchAsian", - // "CharFontStyleNameAsian", - // "CharHeightAsian", - - /* Complex */ - // "CharWeightComplex", - // "CharPostureComplex", - // "CharLocaleComplex", - // "CharFontCharSetComplex", - // "CharFontFamilyComplex", - // "CharFontNameComplex", - // "CharFontPitchComplex", - // "CharFontStyleNameComplex", - // "CharHeightComplex", - - /* - * Non-character properties - */ - // "SnapToGrid", - // "BreakType" - // - // "BorderDistance" - // "BottomBorder" "BottomBorderDistance" - // "LeftBorder" "LeftBorderDistance" - // "RightBorder" "RightBorderDistance" - // "TopBorder" "TopBorderDistance" - // - // "ParaBottomMargin" - // "ParaLeftMargin" - // "ParaTopMargin" - // "ParaRightMargin" - // "ParaContextMargin" - // - // "DropCapCharStyleName" - // "DropCapFormat" - // "DropCapWholeWord" - // - // "ListAutoFormat" "ListId" - // - // "NumberingIsNumber" - // "NumberingLevel" - // "NumberingRules" - // "NumberingStartValue" - // "NumberingStyleName" - // "OutlineLevel" - // "ParaChapterNumberingLevel" - // - // "PageDescName" "PageNumberOffset" - // - // "Rsid" "ParRsid" - // - // "ParaAdjust" "ParaAutoStyleName" - // - // "ParaBackColor" - // "ParaBackGraphic" - // "ParaBackGraphicFilter" - // "ParaBackGraphicLocation" - // "ParaBackGraphicURL" - // "ParaBackTransparent" - // - // "ParaExpandSingleWord" - // "ParaFirstLineIndent" - // - // "ParaIsHyphenation" - // "ParaHyphenationMaxHyphens" - // "ParaHyphenationMaxLeadingChars" - // "ParaHyphenationMaxTrailingChars" - // "ParaHyphenationNoCaps" - // - // "ParaInteropGrabBag" - // "ParaIsAutoFirstLineIndent" - // "ParaIsCharacterDistance" - // "ParaIsConnectBorder" - // "ParaIsForbiddenRules" - // "ParaIsHangingPunctuation" - // "ParaIsNumberingRestart" - // "ParaKeepTogether" - // "ParaLastLineAdjust" - // "ParaLineNumberCount" "ParaLineNumberStartValue" - // "ParaLineSpacing" "ParaOrphans" "ParaRegisterModeActive" - // "ParaShadowFormat" "ParaSplit" - // "ParaStyleName" "ParaTabStops" - // "ParaUserDefinedAttributes" "ParaVertAlignment" - // "ParaWidows" - - /**/); - final int goodSize; - final Map goodNameToIndex; - final String[] goodNames; - final Stack>> layers; - - MyPropertyStack(XTextCursor cursor) - throws UnknownPropertyException { - - XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - XPropertySetInfo psi = propertySet.getPropertySetInfo(); - - this.goodNameToIndex = new HashMap<>(); - int nextIndex = 0; - for (Property p : psi.getProperties()) { - if ((p.Attributes & PropertyAttribute.READONLY) != 0) { - continue; - } - if (!CONTROLLED_PROPERTIES.contains(p.Name)) { - continue; - } - this.goodNameToIndex.put(p.Name, nextIndex); - nextIndex++; - } - - this.goodSize = nextIndex; - - this.goodNames = new String[goodSize]; - for (Map.Entry kv : goodNameToIndex.entrySet()) { - goodNames[ kv.getValue() ] = kv.getKey(); - } - - // XMultiPropertySet.setPropertyValues() - // requires alphabetically sorted property names. - Arrays.sort(goodNames); - for (int i = 0; i < goodSize; i++) { - this.goodNameToIndex.put(goodNames[i], i); - } - - /* - for (int i = 0; i < goodSize; i++) { - System.out.printf(" '%s'", goodNames[i]); - } - System.out.printf("%n"); - */ - - // This throws: - // XPropertyAccess xPropertyAccess = UnoCast.unoQI(XPropertyAccess.class, cursor); - // if (xPropertyAccess == null) { - // throw new RuntimeException("MyPropertyStack: xPropertyAccess is null"); - // } - - // we could use: - // import com.sun.star.beans.XMultiPropertyStates; - XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); - PropertyState[] propertyStates = mpss.getPropertyStates(goodNames); - - XMultiPropertySet mps = UnoCast.unoQI(XMultiPropertySet.class, cursor); - Object[] initialValues = mps.getPropertyValues(goodNames); - - ArrayList> initialValuesOpt = new ArrayList<>(goodSize); - - for (int i = 0; i < goodSize; i++) { - if (propertyStates[i] == PropertyState.DIRECT_VALUE) { - initialValuesOpt.add(Optional.of(initialValues[i])); - } else { - initialValuesOpt.add(Optional.empty()); - } - } - - this.layers = new Stack<>(); - this.layers.push(initialValuesOpt); - } - - void pushLayer(List> settings) { - ArrayList> oldLayer = layers.peek(); - ArrayList> newLayer = new ArrayList<>(oldLayer); - for (Pair kv : settings) { - String name = kv.a; - Integer i = goodNameToIndex.get(name); - if (i == null) { - LOGGER.warn(String.format("pushLayer: '%s' is not in goodNameToIndex", name)); - continue; - } - Object newValue = kv.b; - newLayer.set(i, Optional.ofNullable(newValue)); - } - layers.push(newLayer); - } - - void popLayer() { - if (layers.size() <= 1) { - LOGGER.warn("popLayer: underflow"); - return; - } - layers.pop(); - } - - void apply(XTextCursor cursor) { - // removeDirectFormatting(cursor); - XMultiPropertySet mps = UnoCast.unoQI(XMultiPropertySet.class, cursor); - XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); - ArrayList> topLayer = layers.peek(); - try { - // select values to be set - ArrayList names = new ArrayList<>(goodSize); - ArrayList values = new ArrayList<>(goodSize); - ArrayList delNames = new ArrayList<>(goodSize); - for (int i = 0; i < goodSize; i++) { - if (topLayer.get(i).isPresent()) { - names.add(goodNames[i]); - values.add(topLayer.get(i).get()); - } else { - delNames.add(goodNames[i]); - } - } - // namesArray must be alphabetically sorted. - String[] namesArray = names.toArray(new String[names.size()]); - String[] delNamesArray = delNames.toArray(new String[names.size()]); - mpss.setPropertiesToDefault(delNamesArray); - mps.setPropertyValues(namesArray, values.toArray()); - } catch (UnknownPropertyException ex) { - LOGGER.warn("UnknownPropertyException in MyPropertyStack.apply"); - } catch (PropertyVetoException ex) { - LOGGER.warn("PropertyVetoException in MyPropertyStack.apply"); - } catch (IllegalArgumentException ex) { - LOGGER.warn("IllegalArgumentException in MyPropertyStack.apply"); - } catch (WrappedTargetException ex) { - LOGGER.warn("WrappedTargetException in MyPropertyStack.apply"); - } - } - - // Relative CharEscapement needs to know current values. - Optional getPropertyValue(String name) { - if (goodNameToIndex.containsKey(name)) { - int i = goodNameToIndex.get(name); - ArrayList> topLayer = layers.peek(); - Optional value = topLayer.get(i); - return value; - } - return Optional.empty(); - } + // Hide the public constructor } /** @@ -468,7 +105,7 @@ Optional getPropertyValue(String name) { * the user provides it. * * To limit the damage {@code TAG_NAME_REGEXP} and {@code ATTRIBUTE_NAME_REGEXP} - * explicitly lists the values we care about. + * explicitly lists the names we care about. * * Notable changes w.r.t insertOOFormattedTextAtCurrentLocation: * @@ -491,25 +128,23 @@ Optional getPropertyValue(String name) { * - now: equivalent to <span oo:CharStyleName="Example"> * - <oo:referenceToPageNumberOfReferenceMark> (self-closing) * - * - closing tags try to properly restore state instead of dictating - * an "off" state. + * - closing tags try to properly restore state (in particular, the "not directly set" state) + * instead of dictating an "off" state. This makes a difference when the value inherited from + * another level (for example the paragraph) is not the "off" state. * - * - The practical consequence: the user can format - * citation marks (it is enough to format its start) and the - * properties not dictated by the style are preserved. + * An example: a style with + * ReferenceParagraphFormat="JR_bibentry" + * Assume JR_bibentry in LibreOffice is a paragraph style that prescribes "bold" font. + * LAYOUT only prescribes bold around year. + * Which parts of the bibliography entries should come out as bold? * - * A comparable example: a style with - * ReferenceParagraphFormat="JR_bibentry" - * JR_bibentry in LibreOffice, paragraph style prescribes "bold" font. - * LAYOUT only mentions bold around year. - * Which parts of the bibliography entries should come out as bold? + * - The user can format citation marks (it is enough to format their start) and the + * properties not (everywhere) dictated by the style are preserved (where they are not). * * @param position The cursor giving the insert location. Not modified. * @param ootext The marked-up text to insert. */ - public static void write(XTextDocument doc, - XTextCursor position, - OOText ootext) + public static void write(XTextDocument doc, XTextCursor position, OOText ootext) throws UnknownPropertyException, PropertyVetoException, @@ -557,6 +192,7 @@ public static void write(XTextDocument doc, String tagName = isStartTag ? startTagName : endTagName; Objects.requireNonNull(tagName); + // Attibutes parsed into (name,value) pairs. List> attributes = parseAttributes(attributeListPart); // Handle tags: @@ -575,11 +211,11 @@ public static void write(XTextDocument doc, expectEnd.push("/" + tagName); break; case "sup": - formatStack.pushLayer(SuperScript(formatStack)); + formatStack.pushLayer(setSuperScript(formatStack)); expectEnd.push("/" + tagName); break; case "sub": - formatStack.pushLayer(SubScript(formatStack)); + formatStack.pushLayer(setSubScript(formatStack)); expectEnd.push("/" + tagName); break; case "u": @@ -603,7 +239,6 @@ public static void write(XTextDocument doc, case "oo:ParaStyleName": //

if (value != null && !value.equals("")) { - // LOGGER.warn(String.format("oo:ParaStyleName=\"%s\" found", value)); if (setParagraphStyle(cursor, value)) { if (debugThisFun) { // Presumably tested already: @@ -657,7 +292,7 @@ public static void write(XTextDocument doc, settings.addAll(setCharLocale(value)); break; case "style": - // In general we may need to parse value + // HTML-style small-caps if (value.equals("font-variant: small-caps")) { settings.addAll(setCharCaseMap(CaseMap.SMALLCAPS)); break; @@ -737,7 +372,6 @@ public static void removeDirectFormatting(XTextCursor cursor) { try { // Special handling propertySet.setPropertyValue(CHAR_STYLE_NAME, "Standard"); - // propertySet.setPropertyValue("CharCaseMap", CaseMap.NONE); propertyState.setPropertyToDefault("CharCaseMap"); } catch (UnknownPropertyException | PropertyVetoException | @@ -778,11 +412,225 @@ public static void removeDirectFormatting(XTextCursor cursor) { if (knownToFail.contains(p.Name)) { continue; } - LOGGER.warn(String.format("OOTextIntoOO.removeDirectFormatting failed on '%s'", - p.Name)); + LOGGER.warn(String.format("OOTextIntoOO.removeDirectFormatting failed on '%s'", p.Name)); + } + } + + static class MyPropertyStack { + + /* + * We only try to control these. Should include all character + * properties we set, and maybe their interdependencies. + * + * For a list of properties see: + * https://www.openoffice.org/api/docs/common/ref/com/sun/star/style/CharacterProperties.html + * + * For interdependencies between properties: + * https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Formatting + * (at the end, under "Interdependencies between Properties") + * + */ + static final Set CONTROLLED_PROPERTIES = Set.of( + + /* Used for SuperScript, SubScript. + * + * These three are interdependent: changing one may change others. + */ + "CharEscapement", "CharEscapementHeight", "CharAutoEscapement", + + /* used for Bold */ + "CharWeight", + + /* Used for Italic */ + "CharPosture", + + /* Used for strikeout. These two are interdependent. */ + "CharStrikeout", "CharCrossedOut", + + /* Used for underline. These three are interdependent, but apparently + * we can leave out the last two. + */ + "CharUnderline", // "CharUnderlineColor", "CharUnderlineHasColor", + + /* Used for lang="zxx", to silence spellchecker. */ + "CharLocale", + + /* Used for CitationCharacterFormat. */ + "CharStyleName", + + /* Used for and */ + "CharCaseMap"); + + /** + * The number of properties actually controlled. + */ + final int goodSize; + + /** + * From property name to index in goodNames. + */ + final Map goodNameToIndex; + + /** + * From index to property name. + */ + final String[] goodNames; + + /** + * Maintain a stack of layers, each containing a description + * of the desired state of properties. Each description is an + * ArrayList of property values, Optional.empty() encoding + * "not directly set". + */ + final Stack>> layers; + + MyPropertyStack(XTextCursor cursor) + throws UnknownPropertyException { + + XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); + XPropertySetInfo psi = propertySet.getPropertySetInfo(); + + /* + * On creation, initialize the property name -- index mapping. + */ + this.goodNameToIndex = new HashMap<>(); + int nextIndex = 0; + for (Property p : psi.getProperties()) { + if ((p.Attributes & PropertyAttribute.READONLY) != 0) { + continue; + } + if (!CONTROLLED_PROPERTIES.contains(p.Name)) { + continue; + } + this.goodNameToIndex.put(p.Name, nextIndex); + nextIndex++; + } + + this.goodSize = nextIndex; + + this.goodNames = new String[goodSize]; + for (Map.Entry kv : goodNameToIndex.entrySet()) { + goodNames[ kv.getValue() ] = kv.getKey(); + } + + // XMultiPropertySet.setPropertyValues() + // requires alphabetically sorted property names. + // We adjust here: + Arrays.sort(goodNames); + for (int i = 0; i < goodSize; i++) { + this.goodNameToIndex.put(goodNames[i], i); + } + + /* + * Get the initial state of the properties and add add the first layer. + */ + XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); + PropertyState[] propertyStates = mpss.getPropertyStates(goodNames); + + XMultiPropertySet mps = UnoCast.unoQI(XMultiPropertySet.class, cursor); + Object[] initialValues = mps.getPropertyValues(goodNames); + + ArrayList> initialValuesOpt = new ArrayList<>(goodSize); + + for (int i = 0; i < goodSize; i++) { + if (propertyStates[i] == PropertyState.DIRECT_VALUE) { + initialValuesOpt.add(Optional.of(initialValues[i])); + } else { + initialValuesOpt.add(Optional.empty()); + } + } + + this.layers = new Stack<>(); + this.layers.push(initialValuesOpt); + } + + /** + * Given a list of property name, property value pairs, + * construct and push a new layer describing the intended + * state after these have been applied. + * + * Opening tags usually call this. + */ + void pushLayer(List> settings) { + ArrayList> oldLayer = layers.peek(); + ArrayList> newLayer = new ArrayList<>(oldLayer); + for (Pair kv : settings) { + String name = kv.a; + Integer i = goodNameToIndex.get(name); + if (i == null) { + LOGGER.warn(String.format("pushLayer: '%s' is not in goodNameToIndex", name)); + continue; + } + Object newValue = kv.b; + newLayer.set(i, Optional.ofNullable(newValue)); + } + layers.push(newLayer); + } + + /** + * Closing tags just pop a layer. + */ + void popLayer() { + if (layers.size() <= 1) { + LOGGER.warn("popLayer: underflow"); + return; + } + layers.pop(); + } + + /** + * Apply the current desired formatting state to a cursor. + * The idea is to minimize the number of calls to OpenOffice. + */ + void apply(XTextCursor cursor) { + XMultiPropertySet mps = UnoCast.unoQI(XMultiPropertySet.class, cursor); + XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); + ArrayList> topLayer = layers.peek(); + try { + // select values to be set + ArrayList names = new ArrayList<>(goodSize); + ArrayList values = new ArrayList<>(goodSize); + // and those to be cleared + ArrayList delNames = new ArrayList<>(goodSize); + for (int i = 0; i < goodSize; i++) { + if (topLayer.get(i).isPresent()) { + names.add(goodNames[i]); + values.add(topLayer.get(i).get()); + } else { + delNames.add(goodNames[i]); + } + } + // namesArray must be alphabetically sorted. + String[] namesArray = names.toArray(new String[names.size()]); + String[] delNamesArray = delNames.toArray(new String[names.size()]); + mpss.setPropertiesToDefault(delNamesArray); + mps.setPropertyValues(namesArray, values.toArray()); + } catch (UnknownPropertyException ex) { + LOGGER.warn("UnknownPropertyException in MyPropertyStack.apply"); + } catch (PropertyVetoException ex) { + LOGGER.warn("PropertyVetoException in MyPropertyStack.apply"); + } catch (IllegalArgumentException ex) { + LOGGER.warn("IllegalArgumentException in MyPropertyStack.apply"); + } catch (WrappedTargetException ex) { + LOGGER.warn("WrappedTargetException in MyPropertyStack.apply"); + } + } + + // Relative CharEscapement needs to know current values. + Optional getPropertyValue(String name) { + if (goodNameToIndex.containsKey(name)) { + int i = goodNameToIndex.get(name); + ArrayList> topLayer = layers.peek(); + Optional value = topLayer.get(i); + return value; + } + return Optional.empty(); } } + /** + * Parse HTML-like attributes to a list of (name,value) pairs. + */ private static List> parseAttributes(String s) { List> res = new ArrayList<>(); if (s == null) { @@ -814,6 +662,10 @@ private static boolean isPropertyDefault(XTextCursor cursor, String propertyName return pst == PropertyState.DEFAULT_VALUE; } + /* + * Various property change requests. Their results are passed to MyPropertyStack.pushLayer() + */ + private static List> setCharWeight(float value) { List> settings = new ArrayList<>(); settings.add(new Pair("CharWeight", (Float) value)); @@ -880,12 +732,15 @@ private static List> setCharLocale(String value) { } /* - * SuperScript and SubScript + * SuperScript and SubScript. + * + * @param relative If true, calculate the new values relative to + * the current values. This allows subscript-in-superscript. */ - private static List> CharEscapement(Optional value, - Optional height, - boolean relative, - MyPropertyStack formatStack) { + private static List> setCharEscapement(Optional value, + Optional height, + boolean relative, + MyPropertyStack formatStack) { List> settings = new ArrayList<>(); Optional oldValue = (formatStack .getPropertyValue(CHAR_ESCAPEMENT) @@ -919,18 +774,18 @@ private static List> CharEscapement(Optional value, return settings; } - private static List> SubScript(MyPropertyStack formatStack) { - return CharEscapement(Optional.of(SUBSCRIPT_VALUE), - Optional.of(SUBSCRIPT_HEIGHT), - true, - formatStack); + private static List> setSubScript(MyPropertyStack formatStack) { + return setCharEscapement(Optional.of(SUBSCRIPT_VALUE), + Optional.of(SUBSCRIPT_HEIGHT), + true, + formatStack); } - private static List> SuperScript(MyPropertyStack formatStack) { - return CharEscapement(Optional.of(SUPERSCRIPT_VALUE), - Optional.of(SUPERSCRIPT_HEIGHT), - true, - formatStack); + private static List> setSuperScript(MyPropertyStack formatStack) { + return setCharEscapement(Optional.of(SUPERSCRIPT_VALUE), + Optional.of(SUPERSCRIPT_HEIGHT), + true, + formatStack); } /* From 737828d59452dab354f2b6fa1920337a76b3b1e1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 09:41:58 +0200 Subject: [PATCH 0857/1068] rename: InTextCitationType -> CitationType --- .../org/jabref/gui/openoffice/OOBibBase.java | 4 +-- .../gui/openoffice/OpenOfficePanel.java | 20 +++++++------- .../oostyle/OOProcessAuthorYearMarkers.java | 4 +-- .../jabref/logic/openoffice/Backend52.java | 6 ++--- .../org/jabref/logic/openoffice/Codec52.java | 26 +++++++++---------- .../jabref/logic/openoffice/EditInsert.java | 4 +-- .../jabref/logic/openoffice/EditMerge.java | 8 +++--- .../jabref/logic/openoffice/OOFrontend.java | 4 +-- .../openoffice/UpdateCitationMarkers.java | 6 ++--- .../jabref/model/oostyle/CitationGroup.java | 4 +-- ...extCitationType.java => CitationType.java} | 5 ++-- 11 files changed, 46 insertions(+), 45 deletions(-) rename src/main/java/org/jabref/model/oostyle/{InTextCitationType.java => CitationType.java} (82%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 909a4240249..3870191e277 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -30,7 +30,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.CitationGroupID; -import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.CitationType; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -601,7 +601,7 @@ public void guiActionApplyCitationEntries(List citationEntries) { public void guiActionInsertEntry(List entries, BibDatabase database, OOBibStyle style, - InTextCitationType citationType, + CitationType citationType, String pageInfo, Optional syncOptions) { diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index e3ea20f2a03..7b482ea1d67 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -51,7 +51,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.CitationType; import org.jabref.model.openoffice.CreationException; import org.jabref.preferences.PreferencesService; @@ -185,16 +185,16 @@ private void initPanel() { }); pushEntries.setTooltip(new Tooltip(Localization.lang("Cite selected entries between parenthesis"))); - pushEntries.setOnAction(e -> pushEntries(InTextCitationType.AUTHORYEAR_PAR, false)); + pushEntries.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_PAR, false)); pushEntries.setMaxWidth(Double.MAX_VALUE); pushEntriesInt.setTooltip(new Tooltip(Localization.lang("Cite selected entries with in-text citation"))); - pushEntriesInt.setOnAction(e -> pushEntries(InTextCitationType.AUTHORYEAR_INTEXT, false)); + pushEntriesInt.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_INTEXT, false)); pushEntriesInt.setMaxWidth(Double.MAX_VALUE); pushEntriesEmpty.setTooltip(new Tooltip(Localization.lang("Insert a citation without text (the entry will appear in the reference list)"))); - pushEntriesEmpty.setOnAction(e -> pushEntries(InTextCitationType.INVISIBLE_CIT, false)); + pushEntriesEmpty.setOnAction(e -> pushEntries(CitationType.INVISIBLE_CIT, false)); pushEntriesEmpty.setMaxWidth(Double.MAX_VALUE); pushEntriesAdvanced.setTooltip(new Tooltip(Localization.lang("Cite selected entries with extra information"))); - pushEntriesAdvanced.setOnAction(e -> pushEntries(InTextCitationType.AUTHORYEAR_INTEXT, true)); + pushEntriesAdvanced.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_INTEXT, true)); pushEntriesAdvanced.setMaxWidth(Double.MAX_VALUE); update.setTooltip(new Tooltip(Localization.lang("Ensure that the bibliography is up-to-date"))); @@ -429,16 +429,16 @@ private OOBibBase createBibBase(Path loPath) throws IOException, InvocationTarge * @param inParenthesis True means "(Au and Thor 2000)". * False means "Au and Thor (2000)". */ - private static InTextCitationType citationTypeFromOptions(boolean withText, boolean inParenthesis) { + private static CitationType citationTypeFromOptions(boolean withText, boolean inParenthesis) { if (!withText) { - return InTextCitationType.INVISIBLE_CIT; + return CitationType.INVISIBLE_CIT; } return (inParenthesis - ? InTextCitationType.AUTHORYEAR_PAR - : InTextCitationType.AUTHORYEAR_INTEXT); + ? CitationType.AUTHORYEAR_PAR + : CitationType.AUTHORYEAR_INTEXT); } - private void pushEntries(InTextCitationType citationType, boolean addPageInfo) { + private void pushEntries(CitationType citationType, boolean addPageInfo) { final String title = Localization.lang("Error pushing entries"); LibraryTab libraryTab = frame.getCurrentLibraryTab(); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java index 13a986134be..c8a1cc9c09b 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java @@ -12,9 +12,9 @@ import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.CitationMarkerEntry; +import org.jabref.model.oostyle.CitationType; import org.jabref.model.oostyle.CitedKey; import org.jabref.model.oostyle.CitedKeys; -import org.jabref.model.oostyle.InTextCitationType; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; @@ -148,7 +148,7 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { - final boolean inParenthesis = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); + final boolean inParenthesis = (cg.citationType == CitationType.AUTHORYEAR_PAR); final NonUniqueCitationMarker strictlyUnique = NonUniqueCitationMarker.THROWS; List cits = cg.getCitationsInLocalOrder(); diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 38b8127ef26..76da6c1a038 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -14,7 +14,7 @@ import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.CitationType; import org.jabref.model.oostyle.OODataModel; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; @@ -191,7 +191,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, List> pageInfos, - InTextCitationType citationType, + CitationType citationType, XTextCursor position, boolean insertSpaceAfter) throws @@ -245,7 +245,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, /* * Apply to document */ - boolean withoutBrackets = (citationType == InTextCitationType.INVISIBLE_CIT); + boolean withoutBrackets = (citationType == CitationType.INVISIBLE_CIT); NamedRange namedRange = this.citationStorageManager.nrmCreate(doc, refMarkName, position, insertSpaceAfter, withoutBrackets); diff --git a/src/main/java/org/jabref/logic/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/Codec52.java index 427b00568f0..01560ac2fa0 100644 --- a/src/main/java/org/jabref/logic/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/Codec52.java @@ -9,7 +9,7 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; -import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.CitationType; import org.jabref.model.openoffice.NoDocumentException; /** @@ -33,11 +33,11 @@ public static class ParsedMarkName { /** "", "0", "1" ... */ public final String i; /** in-text-citation type */ - public final InTextCitationType citationType; + public final CitationType citationType; /** Citation keys embedded in the reference mark. */ public final List citationKeys; - ParsedMarkName(String i, InTextCitationType citationType, List citationKeys) { + ParsedMarkName(String i, CitationType citationType, List citationKeys) { Objects.requireNonNull(i); Objects.requireNonNull(citationKeys); this.i = i; @@ -50,20 +50,20 @@ public static class ParsedMarkName { * Integer representation was written into the document in * JabRef52, keep it for compatibility. */ - public static InTextCitationType InTextCitationTypeFromInt(int i) { + public static CitationType CitationTypeFromInt(int i) { switch (i) { case 1: - return InTextCitationType.AUTHORYEAR_PAR; + return CitationType.AUTHORYEAR_PAR; case 2: - return InTextCitationType.AUTHORYEAR_INTEXT; + return CitationType.AUTHORYEAR_INTEXT; case 3: - return InTextCitationType.INVISIBLE_CIT; + return CitationType.INVISIBLE_CIT; default: - throw new RuntimeException("Invalid InTextCitationType code"); + throw new RuntimeException("Invalid CitationType code"); } } - public static int InTextCitationTypeToInt(InTextCitationType i) { + public static int CitationTypeToInt(CitationType i) { switch (i) { case AUTHORYEAR_PAR: return 1; @@ -72,7 +72,7 @@ public static int InTextCitationTypeToInt(InTextCitationType i) { case INVISIBLE_CIT: return 3; default: - throw new RuntimeException("Invalid InTextCitationType"); + throw new RuntimeException("Invalid CitationType"); } } @@ -92,12 +92,12 @@ public static int InTextCitationTypeToInt(InTextCitationType i) { */ public static String getUniqueMarkName(Set usedNames, String bibtexKey, - InTextCitationType citationType) + CitationType citationType) throws NoDocumentException { int i = 0; - int j = InTextCitationTypeToInt(citationType); + int j = CitationTypeToInt(citationType); String name = BIB_CITATION + '_' + j + '_' + bibtexKey; while (usedNames.contains(name)) { name = BIB_CITATION + i + '_' + j + '_' + bibtexKey; @@ -122,7 +122,7 @@ public static Optional parseMarkName(String refMarkName) { List keys = Arrays.asList(citeMatcher.group(3).split(",")); String i = citeMatcher.group(1); int j = Integer.parseInt(citeMatcher.group(2)); - InTextCitationType citationType = InTextCitationTypeFromInt(j); + CitationType citationType = CitationTypeFromInt(j); return (Optional.of(new Codec52.ParsedMarkName(i, citationType, keys))); } diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index f3614ecaf9b..61269dabc03 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -11,7 +11,7 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.CitationType; import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OODataModel; import org.jabref.model.oostyle.OOListUtil; @@ -69,7 +69,7 @@ public static void insertCitationGroup(XTextDocument doc, List entries, BibDatabase database, OOBibStyle style, - InTextCitationType citationType, + CitationType citationType, String pageInfo) throws UnknownPropertyException, diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 4279ca6c927..3c00bbfb24a 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -10,7 +10,7 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.CitationType; import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -107,7 +107,7 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR Objects.requireNonNull(state.prevRange); // Only combine (Author 2000) type citations - if (cg.citationType != InTextCitationType.AUTHORYEAR_PAR) { + if (cg.citationType != CitationType.AUTHORYEAR_PAR) { return false; } @@ -269,7 +269,7 @@ private static List scan(XTextDocument doc, OOFrontend fr) * * Can it start a new group? */ - boolean canStartGroup = (cg.citationType == InTextCitationType.AUTHORYEAR_PAR); + boolean canStartGroup = (cg.citationType == CitationType.AUTHORYEAR_PAR); if (!addToGroup) { // close currentGroup @@ -328,7 +328,7 @@ public static boolean mergeCitationGroups(XTextDocument doc, newGroupCitations.addAll(cg.citationsInStorageOrder); } - InTextCitationType citationType = cgs.get(0).citationType; + CitationType citationType = cgs.get(0).citationType; List> pageInfos = fr.backend.combinePageInfos(cgs); fr.removeCitationGroups(cgs, doc); diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 792d9288571..950a5d9130e 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -14,7 +14,7 @@ import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroupID; import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.CitationType; import org.jabref.model.oostyle.OODataModel; import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; @@ -254,7 +254,7 @@ public Optional healthReport(XTextDocument doc) public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, List> pageInfos, - InTextCitationType citationType, + CitationType citationType, XTextCursor position, boolean insertSpaceAfter) throws diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 4118675a0cc..6cd9cae2f82 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -8,7 +8,7 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.InTextCitationType; +import org.jabref.model.oostyle.CitationType; import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -60,7 +60,7 @@ static void applyNewCitationMarkers(XTextDocument doc, for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { - boolean withText = (cg.citationType != InTextCitationType.INVISIBLE_CIT); + boolean withText = (cg.citationType != CitationType.INVISIBLE_CIT); Optional marker = cg.getCitationMarker(); if (!marker.isPresent()) { @@ -131,7 +131,7 @@ public static void createAndFillCitationGroup(OOFrontend fr, XTextDocument doc, List citationKeys, List> pageInfos, - InTextCitationType citationType, + CitationType citationType, OOText citationText, XTextCursor position, OOBibStyle style, diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index 559514d3921..3e6baa533b7 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -23,7 +23,7 @@ public class CitationGroup { * The core data, stored in the document: * The type of citation and citations in storage order. */ - public final InTextCitationType citationType; + public final CitationType citationType; public final List citationsInStorageOrder; /* @@ -60,7 +60,7 @@ public class CitationGroup { public CitationGroup(OODataModel dataModel, CitationGroupID cgid, - InTextCitationType citationType, + CitationType citationType, List citationsInStorageOrder, Optional referenceMarkNameForLinking) { this.dataModel = dataModel; diff --git a/src/main/java/org/jabref/model/oostyle/InTextCitationType.java b/src/main/java/org/jabref/model/oostyle/CitationType.java similarity index 82% rename from src/main/java/org/jabref/model/oostyle/InTextCitationType.java rename to src/main/java/org/jabref/model/oostyle/CitationType.java index 8b6423c27ca..b2451f7d928 100644 --- a/src/main/java/org/jabref/model/oostyle/InTextCitationType.java +++ b/src/main/java/org/jabref/model/oostyle/CitationType.java @@ -1,9 +1,10 @@ package org.jabref.model.oostyle; /* - * Types of in-text citation. (citationType) + * Presentation types of citation groups. */ -public enum InTextCitationType { +public enum CitationType { + AUTHORYEAR_PAR, AUTHORYEAR_INTEXT, INVISIBLE_CIT; From 8c73d5aac5e1640b911e63cd856bc97dbe83228b Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 09:45:01 +0200 Subject: [PATCH 0858/1068] rename: createNormalizedCitationMarkersForNormalStyle -> createNormalizedCitationMarkers --- .../org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java index c8a1cc9c09b..1c6b939df5d 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java @@ -24,8 +24,7 @@ class OOProcessAuthorYearMarkers { /** * Fills {@code sortedCitedKeys//normCitMarker} */ - private static void createNormalizedCitationMarkersForNormalStyle(CitedKeys sortedCitedKeys, - OOBibStyle style) { + private static void createNormalizedCitationMarkers(CitedKeys sortedCitedKeys, OOBibStyle style) { for (CitedKey ck : sortedCitedKeys.values()) { ck.setNormalizedCitationMarker(Optional.of(style.getNormalizedCitationMarker(ck))); @@ -139,7 +138,7 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { CitedKeys citedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); - createNormalizedCitationMarkersForNormalStyle(citedKeys, style); + createNormalizedCitationMarkers(citedKeys, style); createUniqueLetters(citedKeys, cgs); cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); From d66bf79b383ae468ccfdd0685a227bbe8d17fedf Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 10:02:23 +0200 Subject: [PATCH 0859/1068] rename: OOBibStyle.getCitationMarker2 -> createCitationMarker --- .../org/jabref/logic/oostyle/OOBibStyle.java | 14 +- .../oostyle/OOBibStyleGetCitationMarker.java | 12 +- .../oostyle/OOProcessAuthorYearMarkers.java | 6 +- .../jabref/logic/openoffice/EditInsert.java | 6 +- .../jabref/model/oostyle/CitationGroup.java | 2 +- .../model/oostyle/CitationMarkerEntry.java | 2 +- .../jabref/model/oostyle/CompareCitation.java | 2 +- .../oostyle/NonUniqueCitationMarker.java | 2 +- .../jabref/logic/oostyle/OOBibStyleTest.java | 146 +++++++++--------- 9 files changed, 96 insertions(+), 96 deletions(-) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 857afde3e79..12448479dfc 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -1014,13 +1014,13 @@ public OOText getNormalizedCitationMarker(CitationMarkerNormEntry ce) { * OOFormat.setLocaleNone() and OOFormat.setCharStyle(). * These are added by decorateCitationMarker() */ - public OOText getCitationMarker2(List citationMarkerEntries, - boolean inParenthesis, - NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { - return OOBibStyleGetCitationMarker.getCitationMarker2(this, - citationMarkerEntries, - inParenthesis, - nonUniqueCitationMarkerHandling); + public OOText createCitationMarker(List citationMarkerEntries, + boolean inParenthesis, + NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { + return OOBibStyleGetCitationMarker.createCitationMarker(this, + citationMarkerEntries, + inParenthesis, + nonUniqueCitationMarkerHandling); } /** diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 732608230f3..484799ea36f 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -600,10 +600,10 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, * */ public static OOText - getCitationMarker2(OOBibStyle style, - List citationMarkerEntries, - boolean inParenthesis, - NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { + createCitationMarker(OOBibStyle style, + List citationMarkerEntries, + boolean inParenthesis, + NonUniqueCitationMarker nonUniqueCitationMarkerHandling) { final int nEntries = citationMarkerEntries.size(); @@ -623,8 +623,8 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, // List normalizedMarkers = getNormalizedCitationMarkers(style, - citationMarkerEntries, - Optional.empty()); + citationMarkerEntries, + Optional.empty()); // How many authors would be emitted without grouping. int[] nAuthorsToEmit = new int[nEntries]; diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java index 1c6b939df5d..683450c5da6 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java @@ -152,9 +152,9 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { List cits = cg.getCitationsInLocalOrder(); List citationMarkerEntries = OOListUtil.map(cits, e -> e); - OOText citMarker = style.getCitationMarker2(citationMarkerEntries, - inParenthesis, - strictlyUnique); + OOText citMarker = style.createCitationMarker(citationMarkerEntries, + inParenthesis, + strictlyUnique); cg.setCitationMarker(Optional.of(citMarker)); } } diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 61269dabc03..c4ab7852f75 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -100,9 +100,9 @@ public static void insertCitationGroup(XTextDocument doc, OOText citeText = (style.isNumberEntries() ? OOText.fromString("[-]") // A dash only. Only refresh later. - : style.getCitationMarker2(citations, - citationType.inParenthesis(), - NonUniqueCitationMarker.FORGIVEN)); + : style.createCitationMarker(citations, + citationType.inParenthesis(), + NonUniqueCitationMarker.FORGIVEN)); if ("".equals(OOText.toString(citeText))) { citeText = OOText.fromString("[?]"); diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index 3e6baa533b7..e511b67cbb1 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -7,7 +7,7 @@ import org.jabref.model.entry.BibEntry; -/* +/** * A CitationGroup describes a group of citations. */ public class CitationGroup { diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java index 005f2464cb7..abe38ed2081 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java @@ -3,7 +3,7 @@ import java.util.Optional; /** - * This is what we need for getCitationMarker2 to produce author-year + * This is what we need for createCitationMarker to produce author-year * citation markers. */ public interface CitationMarkerEntry extends CitationMarkerNormEntry { diff --git a/src/main/java/org/jabref/model/oostyle/CompareCitation.java b/src/main/java/org/jabref/model/oostyle/CompareCitation.java index 46e276a965e..220b123e5df 100644 --- a/src/main/java/org/jabref/model/oostyle/CompareCitation.java +++ b/src/main/java/org/jabref/model/oostyle/CompareCitation.java @@ -6,7 +6,7 @@ /* * Given a Comparator provide a Comparator - * that can handle unresolved citation keys and take pageInfo into account. + * that can handle unresolved citation keys and takes pageInfo into account. */ public class CompareCitation implements Comparator { diff --git a/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java b/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java index ddfea3aaa64..0fd29fb75f3 100644 --- a/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java +++ b/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java @@ -1,7 +1,7 @@ package org.jabref.model.oostyle; /** - * What should getCitationMarker do if it discovers that + * What should createCitationMarker do if it discovers that * uniqueLetters provided are not sufficient for unique presentation? */ public enum NonUniqueCitationMarker { diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index 7c92504c746..bd9f060e6f4 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -454,14 +454,14 @@ void testGetCitationMarker() throws IOException { * author's name before "et al." */ assertEquals("[Boström et al., 2006]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Boström et al. [2006]", - style.getCitationMarker2(citationMarkerEntries, - false, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + false, + NonUniqueCitationMarker.THROWS).asString()); /* * Currently there is no way override for getMaxAuthors(), except @@ -472,9 +472,9 @@ void testGetCitationMarker() throws IOException { citationMarkerEntries.add(cm); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -549,15 +549,15 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" +"; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Boström, Wäyrynen, Bodén, Beznosov & Kruchten [2006a,b]" + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten [2006c]", - style.getCitationMarker2(citationMarkerEntries, - false, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + false, + NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the first is isFirstAppearanceOfSource. @@ -577,9 +577,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" +"; Boström et al., 2006c]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the second is isFirstAppearanceOfSource. @@ -601,9 +601,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a" + "; Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006b" + "; Boström et al., 2006c]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } // Without pageInfo, only the neither is isFirstAppearanceOfSource. @@ -623,9 +623,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a,b,c]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: different entries with identical non-null pageInfo: not joined. @@ -645,9 +645,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a; p1" + "; Boström et al., 2006b; p1" + "; Boström et al., 2006c; p1]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: same entries with identical non-null pageInfo: collapsed. @@ -666,9 +666,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Boström et al., 2006a; p1]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } // With pageInfo: same entries with different pageInfo: kept separate. // Empty ("") and null pageInfos considered equal her, collapsed. @@ -690,9 +690,9 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a; p1" + "; Boström et al., 2006a; p2" + "; Boström et al., 2006a]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } } @@ -780,9 +780,9 @@ void testInstitutionAuthorMarker() throws IOException { makeCitationMarkerEntry("JabRef2016", entry, database, null, null, false); citationMarkerEntries.add(cm); assertEquals("[JabRef Development Team, 2016]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -805,9 +805,9 @@ void testVonAuthorMarker() throws IOException { citationMarkerEntries.add(cm); assertEquals("[von Beta, 2016]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -828,9 +828,9 @@ void testNullAuthorMarker() throws IOException { citationMarkerEntries.add(cm); assertEquals("[, 2016]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -851,9 +851,9 @@ void testNullYearMarker() throws IOException { citationMarkerEntries.add(cm); assertEquals("[von Beta, ]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -872,9 +872,9 @@ void testEmptyEntryMarker() throws IOException { makeCitationMarkerEntry("Empty", entry, database, null, null, false); citationMarkerEntries.add(cm); - assertEquals("[, ]", style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS) + assertEquals("[, ]", style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS) .asString()); } @@ -905,7 +905,7 @@ void testGetCitationMarkerUniquefiers() throws IOException { database.insertEntry(entry2); - // Without uniquefiers this is a problem getCitationMarker cannot + // Without uniquefiers this is a problem createCitationMarker cannot // solve, since it does not see the whole picture (citations outside its scope). // It can throw a RuntimeException or forgive and provide a flawed presentation. // @@ -927,9 +927,9 @@ void testGetCitationMarkerUniquefiers() throws IOException { // can throw a RuntimeException. boolean doesItThrow = false; try { - style.getCitationMarker2(citationMarkerEntriesA, - false, - NonUniqueCitationMarker.THROWS); + style.createCitationMarker(citationMarkerEntriesA, + false, + NonUniqueCitationMarker.THROWS); } catch (RuntimeException ex) { doesItThrow = true; } @@ -937,14 +937,14 @@ void testGetCitationMarkerUniquefiers() throws IOException { // Or can just emit a presentation with repeated marks. assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", - style.getCitationMarker2(citationMarkerEntriesA, - true, - NonUniqueCitationMarker.FORGIVEN).asString()); + style.createCitationMarker(citationMarkerEntriesA, + true, + NonUniqueCitationMarker.FORGIVEN).asString()); assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", - style.getCitationMarker2(citationMarkerEntriesA, - false, - NonUniqueCitationMarker.FORGIVEN).asString()); + style.createCitationMarker(citationMarkerEntriesA, + false, + NonUniqueCitationMarker.FORGIVEN).asString()); // With uniquefiers @@ -959,14 +959,14 @@ void testGetCitationMarkerUniquefiers() throws IOException { citationMarkerEntriesB.add(cm2); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", - style.getCitationMarker2(citationMarkerEntriesB, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntriesB, + true, + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Beta [2000a,b]; Epsilon [2001]", - style.getCitationMarker2(citationMarkerEntriesB, - false, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntriesB, + false, + NonUniqueCitationMarker.THROWS).asString()); } @@ -1008,14 +1008,14 @@ void testGetCitationMarkerUniquefiersThreeSameAuthor() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Beta, 2000a,b,c]", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); assertEquals("Beta [2000a,b,c]", - style.getCitationMarker2(citationMarkerEntries, - false, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + false, + NonUniqueCitationMarker.THROWS).asString()); } @Test @@ -1076,9 +1076,9 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { makeCitationMarkerEntry("Beta2016", entry, database, null, null, false)); assertEquals("von Beta, Epsilon, & Tau, 2016", - style.getCitationMarker2(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); } @Test From 9407ec06a8afa0a2fcb4b32c78a35555cee7451d Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 10:03:30 +0200 Subject: [PATCH 0860/1068] format --- .../java/org/jabref/model/oostyle/NonUniqueCitationMarker.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java b/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java index 0fd29fb75f3..40eccf87c7c 100644 --- a/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java +++ b/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java @@ -5,8 +5,10 @@ * uniqueLetters provided are not sufficient for unique presentation? */ public enum NonUniqueCitationMarker { + /** Give an insufficient representation anyway. */ FORGIVEN, + /** Throw a RuntimeException */ THROWS } From 24ee74e8624c1b8245781714cc3f091ab53706f8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 10:08:51 +0200 Subject: [PATCH 0861/1068] srip unused methods: zipWith, zip3 --- .../org/jabref/model/oostyle/OOListUtil.java | 31 ------------------- 1 file changed, 31 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/OOListUtil.java b/src/main/java/org/jabref/model/oostyle/OOListUtil.java index a3ebcc626e1..b7c11e1269e 100644 --- a/src/main/java/org/jabref/model/oostyle/OOListUtil.java +++ b/src/main/java/org/jabref/model/oostyle/OOListUtil.java @@ -1,49 +1,18 @@ package org.jabref.model.oostyle; -import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; -import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.jabref.model.openoffice.Tuple3; - public class OOListUtil { public static List map(List list, Function fun) { return list.stream().map(e -> fun.apply(e)).collect(Collectors.toList()); } - public static List zipWith(List a, - List b, - BiFunction fun) { - if (a.size() != b.size()) { - throw new RuntimeException("a.size != b.size"); - } - List result = new ArrayList<>(a.size()); - for (int i = 0; i < a.size(); i++) { - result.add(fun.apply(a.get(i), b.get(i))); - } - return result; - } - - public static List> zip3(List a, List b, List c) { - if (a.size() != b.size()) { - throw new RuntimeException("a.size != b.size"); - } - if (a.size() != c.size()) { - throw new RuntimeException("a.size != c.size"); - } - List> result = new ArrayList<>(a.size()); - for (int i = 0; i < a.size(); i++) { - result.add(new Tuple3(a.get(i), b.get(i), c.get(i))); - } - return result; - } - /** Integers 0..(n-1) */ public static List makeIndices(int n) { return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); From 77ac5a5befd0f351721ec383da618b7569326fb4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 10:13:49 +0200 Subject: [PATCH 0862/1068] Tuple3 is only used in OOBibStyleTest.java --- .../java/org/jabref/model/openoffice/Tuple3.java | 13 ------------- .../org/jabref/logic/oostyle/OOBibStyleTest.java | 14 ++++++++++++-- 2 files changed, 12 insertions(+), 15 deletions(-) delete mode 100644 src/main/java/org/jabref/model/openoffice/Tuple3.java diff --git a/src/main/java/org/jabref/model/openoffice/Tuple3.java b/src/main/java/org/jabref/model/openoffice/Tuple3.java deleted file mode 100644 index d15f0006b49..00000000000 --- a/src/main/java/org/jabref/model/openoffice/Tuple3.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.jabref.model.openoffice; - -public class Tuple3 { - public final A a; - public final B b; - public final C c; - public Tuple3(A a, B b, C c) { - this.a = a; - this.b = b; - this.c = c; - } -} - diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index bd9f060e6f4..af7f01aae43 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -33,7 +33,6 @@ import org.jabref.model.oostyle.NonUniqueCitationMarker; import org.jabref.model.oostyle.OOText; import org.jabref.model.oostyle.PageInfo; -import org.jabref.model.openoffice.Tuple3; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -136,6 +135,17 @@ public Optional getPageInfo() { } } + public class Tuple3 { + public final A a; + public final B b; + public final C c; + public Tuple3(A a, B b, C c) { + this.a = a; + this.b = b; + this.c = c; + } + } + private static CitationMarkerNumericEntry CitationMarkerNumericEntryFromTuple(Tuple3 x) { Optional pageInfo = Optional.ofNullable(OOText.fromString(x.c)); @@ -152,7 +162,7 @@ static String mkNum(OOBibStyle style, return OOText.toString(res); } - static Tuple3 tup3(String a,Integer b, String c) { + static Tuple3 tup3(String a, Integer b, String c) { return new Tuple3(a,b,c); } From b9836a757aa0889cad94cb536576879b5f4884ff Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 10:22:54 +0200 Subject: [PATCH 0863/1068] comment --- src/main/java/org/jabref/model/oostyle/PageInfo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/oostyle/PageInfo.java b/src/main/java/org/jabref/model/oostyle/PageInfo.java index 8b5fd4ddf94..6ac269d31e1 100644 --- a/src/main/java/org/jabref/model/oostyle/PageInfo.java +++ b/src/main/java/org/jabref/model/oostyle/PageInfo.java @@ -5,7 +5,7 @@ public class PageInfo { private PageInfo() { - // + // hide public constructor } /* From 9d46033374d7cb25a504ab184eb16ddf46e8d971 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 10:23:09 +0200 Subject: [PATCH 0864/1068] rename: CitationGroupID.asString -> citationGroupIdAsString --- src/main/java/org/jabref/logic/openoffice/Backend52.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 2 +- .../org/jabref/logic/openoffice/UpdateCitationMarkers.java | 6 ++---- src/main/java/org/jabref/model/oostyle/CitationGroupID.java | 5 +++-- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 76da6c1a038..baa35459b81 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -406,7 +406,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups int n = cgs.numberOfCitationGroups(); List citations = new ArrayList<>(n); for (CitationGroup cg : cgs.getCitationGroupsUnordered()) { - String name = cg.cgid.asString(); + String name = cg.cgid.citationGroupIdAsString(); XTextCursor cursor = (this .getRawCursorForCitationGroup(cg, doc) .orElseThrow(RuntimeException::new)); diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 950a5d9130e..9a23b085b7a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -359,7 +359,7 @@ private List> citationRanges(XTextDocument for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { XTextRange range = this.getMarkRange(doc, cg).orElseThrow(RuntimeException::new); - String description = cg.cgid.asString(); // cg.cgRangeStorage.nrGetRangeName(); + String description = cg.cgid.citationGroupIdAsString(); // cg.cgRangeStorage.nrGetRangeName(); result.add(new RangeForOverlapCheck(range, cg.cgid, RangeForOverlapCheck.REFERENCE_MARK_KIND, diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 6cd9cae2f82..38a884c861d 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -44,9 +44,7 @@ public class UpdateCitationMarkers { * @param style Bibliography style to use. * */ - static void applyNewCitationMarkers(XTextDocument doc, - OOFrontend fr, - OOBibStyle style) + static void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, OOBibStyle style) throws NoDocumentException, UnknownPropertyException, @@ -65,7 +63,7 @@ static void applyNewCitationMarkers(XTextDocument doc, if (!marker.isPresent()) { String msg = String.format("applyNewCitationMarkers: no marker for %s", - cg.cgid.asString()); + cg.cgid.citationGroupIdAsString()); LOGGER.warn(msg); continue; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroupID.java b/src/main/java/org/jabref/model/oostyle/CitationGroupID.java index 569fb0bd8ba..74c88b8cab3 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroupID.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroupID.java @@ -10,9 +10,10 @@ public CitationGroupID(String id) { } /** - * CitationEntry needs refMark or other identifying string + * CitationEntry needs some string identifying the group + * that it can pass back later. */ - public String asString() { + public String citationGroupIdAsString() { return id; } } From e111d82de833dc5289495c8081de0e8e0f2e7174 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 10:30:38 +0200 Subject: [PATCH 0865/1068] rename: CitationGroupID -> CitationGroupId --- .../org/jabref/gui/openoffice/OOBibBase.java | 4 +- .../logic/oostyle/OOFormatBibliography.java | 4 +- .../jabref/logic/openoffice/Backend52.java | 8 ++-- .../jabref/logic/openoffice/OOFrontend.java | 46 +++++++++---------- .../logic/openoffice/RangeSortVisual.java | 2 +- .../jabref/model/oostyle/CitationGroup.java | 4 +- ...ationGroupID.java => CitationGroupId.java} | 4 +- .../jabref/model/oostyle/CitationGroups.java | 16 +++---- .../jabref/model/oostyle/CitationPath.java | 4 +- 9 files changed, 46 insertions(+), 46 deletions(-) rename src/main/java/org/jabref/model/oostyle/{CitationGroupID.java => CitationGroupId.java} (81%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3870191e277..416dc5e52c4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -29,7 +29,7 @@ import org.jabref.logic.openoffice.Update; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroupId; import org.jabref.model.oostyle.CitationType; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; @@ -266,7 +266,7 @@ Result getFunctionalTextViewCursor(XTextDocum return precheck; } - List> userRanges; + List> userRanges; try { userRanges = fr.viewCursorRanges(doc); } catch (NoDocumentException ex) { diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index aeab5cc4f3a..e91f65d1ef5 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -11,7 +11,7 @@ import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroupId; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.CitationPath; import org.jabref.model.oostyle.CitedKey; @@ -167,7 +167,7 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { List citationGroups = new ArrayList(); for (CitationPath p : ck.getCitationPaths()) { - CitationGroupID cgid = p.group; + CitationGroupId cgid = p.group; CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); citationGroups.add(cg); } diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index baa35459b81..55d52770cdb 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -12,7 +12,7 @@ import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroupId; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.CitationType; import org.jabref.model.oostyle.OODataModel; @@ -42,7 +42,7 @@ public class Backend52 { private static final Logger LOGGER = LoggerFactory.getLogger(Backend52.class); public final OODataModel dataModel; private final NamedRangeManager citationStorageManager; - private final Map cgidToNamedRange; + private final Map cgidToNamedRange; // uses: Codec52 public Backend52() { @@ -148,7 +148,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str + " found unparsable referenceMarkName"); } Codec52.ParsedMarkName ov = op.get(); - CitationGroupID cgid = new CitationGroupID(refMarkName); + CitationGroupId cgid = new CitationGroupId(refMarkName); List citations = (ov.citationKeys.stream() .map(Citation::new) .collect(Collectors.toList())); @@ -213,7 +213,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, String xkey = (citationKeys.stream().collect(Collectors.joining(","))); String refMarkName = Codec52.getUniqueMarkName(usedNames, xkey, citationType); - CitationGroupID cgid = new CitationGroupID(refMarkName); + CitationGroupId cgid = new CitationGroupId(refMarkName); final int nCitations = citationKeys.size(); final int last = nCitations - 1; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 9a23b085b7a..d11170dd00c 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -12,7 +12,7 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupID; +import org.jabref.model.oostyle.CitationGroupId; import org.jabref.model.oostyle.CitationGroups; import org.jabref.model.oostyle.CitationType; import org.jabref.model.oostyle.OODataModel; @@ -60,7 +60,7 @@ public OOFrontend(XTextDocument doc) // Get the citationGroupNames List citationGroupNames = this.backend.getJabRefReferenceMarkNames(doc); - Map citationGroups = + Map citationGroups = readCitationGroupsFromDocument(this.backend, doc, citationGroupNames); this.citationGroups = new CitationGroups(citationGroups); } @@ -75,7 +75,7 @@ public Optional healthReport(XTextDocument doc) return backend.healthReport(doc); } - private static Map + private static Map readCitationGroupsFromDocument(Backend52 backend, XTextDocument doc, List citationGroupNames) @@ -83,7 +83,7 @@ public Optional healthReport(XTextDocument doc) WrappedTargetException, NoDocumentException { - Map citationGroups = new HashMap<>(); + Map citationGroups = new HashMap<>(); for (int i = 0; i < citationGroupNames.size(); i++) { final String name = citationGroupNames.get(i); CitationGroup cg = backend.readCitationGroupFromDocumentOrThrow(doc, name); @@ -349,12 +349,12 @@ public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroup cg) * * result.size() == nRefMarks */ - private List> citationRanges(XTextDocument doc) + private List> citationRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - List> result = + List> result = new ArrayList<>(citationGroups.numberOfCitationGroups()); for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { @@ -368,36 +368,36 @@ private List> citationRanges(XTextDocument return result; } - private List> bibliographyRanges(XTextDocument doc) + private List> bibliographyRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - List> result = new ArrayList<>(); + List> result = new ArrayList<>(); Optional range = UpdateBibliography.getBibliographyRange(doc); if (range.isPresent()) { String description = "bibliography"; result.add(new RangeForOverlapCheck(range.get(), - new CitationGroupID("bibliography"), + new CitationGroupId("bibliography"), RangeForOverlapCheck.BIBLIOGRAPHY_MARK_KIND, description)); } return result; } - public List> viewCursorRanges(XTextDocument doc) + public List> viewCursorRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - List> result = new ArrayList<>(); + List> result = new ArrayList<>(); Optional range = UnoCursor.getViewCursor(doc).map(e -> e); if (range.isPresent()) { String description = "cursor"; result.add(new RangeForOverlapCheck(range.get(), - new CitationGroupID("cursor"), + new CitationGroupId("cursor"), RangeForOverlapCheck.CURSOR_MARK_KIND, description)); } @@ -418,7 +418,7 @@ public List> viewCursorRanges(XTextDocumen * footnote marks does not depend on how do we mark or * structure those ranges. */ - private List> footnoteMarkRanges(XTextDocument doc) + private List> footnoteMarkRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { @@ -427,9 +427,9 @@ private List> footnoteMarkRanges(XTextDocu // Could use RangeSet if we had that. RangeKeyedMap seen = new RangeKeyedMap<>(); - List> result = new ArrayList<>(); + List> result = new ArrayList<>(); - for (RangeForOverlapCheck citationRange : citationRanges(doc)) { + for (RangeForOverlapCheck citationRange : citationRanges(doc)) { Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(citationRange.range); @@ -458,30 +458,30 @@ private List> footnoteMarkRanges(XTextDocu */ public VoidResult checkRangeOverlaps(XTextDocument doc, - List> userRanges, + List> userRanges, boolean requireSeparation, int reportAtMost) throws NoDocumentException, WrappedTargetException { - List> ranges = new ArrayList<>(); + List> ranges = new ArrayList<>(); ranges.addAll(userRanges); ranges.addAll(bibliographyRanges(doc)); ranges.addAll(citationRanges(doc)); ranges.addAll(footnoteMarkRanges(doc)); - RangeKeyedMapList> sorted = new RangeKeyedMapList<>(); - for (RangeForOverlapCheck aRange : ranges) { + RangeKeyedMapList> sorted = new RangeKeyedMapList<>(); + for (RangeForOverlapCheck aRange : ranges) { sorted.add(aRange.range, aRange); } - List>> overlaps = + List>> overlaps = RangeOverlapFinder.findOverlappingRanges(sorted, reportAtMost, requireSeparation); if (overlaps.size() > 0) { StringBuilder msg = new StringBuilder(); - for (RangeOverlap> overlap : overlaps) { + for (RangeOverlap> overlap : overlaps) { String listOfRanges = (overlap.valuesForOverlappingRanges.stream() .map(v -> String.format("'%s'", v.format())) .collect(Collectors.joining(", "))); @@ -567,8 +567,8 @@ public void imposeGlobalOrder(XTextDocument doc, FunctionalTextViewCursor fcurso boolean mapFootnotesToFootnoteMarks = true; List sortedCitationGroups = getVisuallySortedCitationGroups(doc, mapFootnotesToFootnoteMarks, fcursor); - List sortedCitationGroupIDs = + List sortedCitationGroupIds = OOListUtil.map(sortedCitationGroups, cg -> cg.cgid); - citationGroups.setGlobalOrder(sortedCitationGroupIDs); + citationGroups.setGlobalOrder(sortedCitationGroupIds); } } diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index a76a8645c35..2c9abdcc324 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -173,7 +173,7 @@ public int hashCode() { throw new RuntimeException("visualSort: set.size() != inputSize"); } - // collect CitationGroupIDs in order + // collect ordered result List> result = new ArrayList<>(set.size()); for (ComparableMark> mark : set) { result.add(mark.getContent()); diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/oostyle/CitationGroup.java index e511b67cbb1..778864cac96 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroup.java @@ -17,7 +17,7 @@ public class CitationGroup { /* * Identifies this citation group. */ - public final CitationGroupID cgid; + public final CitationGroupId cgid; /* * The core data, stored in the document: @@ -59,7 +59,7 @@ public class CitationGroup { private Optional citationMarker; public CitationGroup(OODataModel dataModel, - CitationGroupID cgid, + CitationGroupId cgid, CitationType citationType, List citationsInStorageOrder, Optional referenceMarkNameForLinking) { diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroupID.java b/src/main/java/org/jabref/model/oostyle/CitationGroupId.java similarity index 81% rename from src/main/java/org/jabref/model/oostyle/CitationGroupID.java rename to src/main/java/org/jabref/model/oostyle/CitationGroupId.java index 74c88b8cab3..1c26696bf09 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroupID.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroupId.java @@ -3,9 +3,9 @@ /** * Identifies a citation group in a document. */ -public class CitationGroupID { +public class CitationGroupId { String id; - public CitationGroupID(String id) { + public CitationGroupId(String id) { this.id = id; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 7ede2e9e021..a835e1b5137 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -23,12 +23,12 @@ public class CitationGroups { private static final Logger LOGGER = LoggerFactory.getLogger(CitationGroups.class); - private Map citationGroupsUnordered; + private Map citationGroupsUnordered; /** * Provides order of appearance for the citation groups. */ - private Optional> globalOrder; + private Optional> globalOrder; /** * This is going to be the bibliography @@ -38,7 +38,7 @@ public class CitationGroups { /** * Constructor */ - public CitationGroups(Map citationGroups) { + public CitationGroups(Map citationGroups) { this.citationGroupsUnordered = citationGroups; @@ -124,7 +124,7 @@ public List getCitationGroupsInGlobalOrder() { * * Also set indexInGlobalOrder for each citation group. */ - public void setGlobalOrder(List globalOrder) { + public void setGlobalOrder(List globalOrder) { Objects.requireNonNull(globalOrder); if (globalOrder.size() != numberOfCitationGroups()) { throw new RuntimeException("setGlobalOrder:" @@ -134,7 +134,7 @@ public void setGlobalOrder(List globalOrder) { // Propagate to each CitationGroup int i = 0; - for (CitationGroupID cgid : globalOrder) { + for (CitationGroupId cgid : globalOrder) { citationGroupsUnordered.get(cgid).setIndexInGlobalOrder(Optional.of(i)); i++; } @@ -261,10 +261,10 @@ public void createNumberedBibliographySortedByComparator(Comparator en } /* - * Query by CitationGroupID + * Query by CitationGroupId */ - public Optional getCitationGroup(CitationGroupID cgid) { + public Optional getCitationGroup(CitationGroupId cgid) { CitationGroup cg = citationGroupsUnordered.get(cgid); return Optional.ofNullable(cg); } @@ -272,7 +272,7 @@ public Optional getCitationGroup(CitationGroupID cgid) { /** * Call this when the citation group is unquestionably there. */ - public CitationGroup getCitationGroupOrThrow(CitationGroupID cgid) { + public CitationGroup getCitationGroupOrThrow(CitationGroupId cgid) { CitationGroup cg = citationGroupsUnordered.get(cgid); if (cg == null) { throw new RuntimeException("getCitationGroupOrThrow:" diff --git a/src/main/java/org/jabref/model/oostyle/CitationPath.java b/src/main/java/org/jabref/model/oostyle/CitationPath.java index eb295e615c5..628fcba6d97 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationPath.java +++ b/src/main/java/org/jabref/model/oostyle/CitationPath.java @@ -6,11 +6,11 @@ */ public class CitationPath { - public final CitationGroupID group; + public final CitationGroupId group; public final int storageIndexInGroup; - CitationPath(CitationGroupID group, int storageIndexInGroup) { + CitationPath(CitationGroupId group, int storageIndexInGroup) { this.group = group; this.storageIndexInGroup = storageIndexInGroup; } From 539e4b8286023625d2e5b1f900ee6a0a574d3b07 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 10:36:26 +0200 Subject: [PATCH 0866/1068] comment --- src/main/java/org/jabref/model/oostyle/CitationGroups.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index a835e1b5137..62d29386a2d 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -18,6 +18,10 @@ /** * CitationGroups : the set of citation groups in the document. + * + * This is the main input (as well as output) for creating citation + * markers and bibliography. + * */ public class CitationGroups { From 8c95a83d60f326da6bd593f45f8928be564a6062 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 10:40:10 +0200 Subject: [PATCH 0867/1068] use this instead of cgs --- .../jabref/model/oostyle/CitationGroups.java | 44 +++++++++---------- 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index 62d29386a2d..c26ee38e73e 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -63,7 +63,7 @@ public void distributeToCitations(List where, T value) { for (CitationPath p : where) { - CitationGroup cg = this.citationGroupsUnordered.get(p.group); + CitationGroup cg = citationGroupsUnordered.get(p.group); if (cg == null) { LOGGER.warn("CitationGroups.distributeToCitations: group missing"); continue; @@ -77,7 +77,6 @@ public void distributeToCitations(List where, * Look up each Citation in databases. */ public void lookupCitations(List databases) { - CitationGroups cgs = this; /* * It is not clear which of the two solutions below is better. */ @@ -86,9 +85,9 @@ public void lookupCitations(List databases) { // // CitationDatabaseLookupResult for the same citation key // is the same object. Until we insert a new citation from the GUI. - CitedKeys cks = cgs.getCitedKeysUnordered(); + CitedKeys cks = getCitedKeysUnordered(); cks.lookupInDatabases(databases); - cks.distributeLookupResults(cgs); + cks.distributeLookupResults(this); } else { // lookup each citation directly // @@ -223,45 +222,42 @@ public List getUnresolvedKeys() { } public void createNumberedBibliographySortedInOrderOfAppearance() { - CitationGroups cgs = this; - if (!cgs.bibliography.isEmpty()) { + if (!bibliography.isEmpty()) { throw new RuntimeException("createNumberedBibliographySortedInOrderOfAppearance:" + " already have a bibliography"); } - CitedKeys citedKeys = cgs.getCitedKeysSortedInOrderOfAppearance(); + CitedKeys citedKeys = getCitedKeysSortedInOrderOfAppearance(); citedKeys.numberCitedKeysInCurrentOrder(); - citedKeys.distributeNumbers(cgs); - cgs.bibliography = Optional.of(citedKeys); + citedKeys.distributeNumbers(this); + bibliography = Optional.of(citedKeys); } /** * precondition: database lookup already performed (otherwise we just sort citation keys) */ public void createPlainBibliographySortedByComparator(Comparator entryComparator) { - CitationGroups cgs = this; - if (!this.bibliography.isEmpty()) { + if (!bibliography.isEmpty()) { throw new RuntimeException("createPlainBibliographySortedByComparator:" + " already have a bibliography"); } - CitedKeys citedKeys = cgs.getCitedKeysUnordered(); + CitedKeys citedKeys = getCitedKeysUnordered(); citedKeys.sortByComparator(entryComparator); - this.bibliography = Optional.of(citedKeys); + bibliography = Optional.of(citedKeys); } /** * precondition: database lookup already performed (otherwise we just sort citation keys) */ public void createNumberedBibliographySortedByComparator(Comparator entryComparator) { - CitationGroups cgs = this; - if (!cgs.bibliography.isEmpty()) { + if (!bibliography.isEmpty()) { throw new RuntimeException("createNumberedBibliographySortedByComparator:" + " already have a bibliography"); } - CitedKeys citedKeys = cgs.getCitedKeysUnordered(); + CitedKeys citedKeys = getCitedKeysUnordered(); citedKeys.sortByComparator(entryComparator); citedKeys.numberCitedKeysInCurrentOrder(); - citedKeys.distributeNumbers(cgs); - this.bibliography = Optional.of(citedKeys); + citedKeys.distributeNumbers(this); + bibliography = Optional.of(citedKeys); } /* @@ -302,17 +298,17 @@ public boolean citationGroupsProvideReferenceMarkNameForLinking() { */ public void afterCreateCitationGroup(CitationGroup cg) { - this.citationGroupsUnordered.put(cg.cgid, cg); + citationGroupsUnordered.put(cg.cgid, cg); - this.globalOrder = Optional.empty(); - this.bibliography = Optional.empty(); + globalOrder = Optional.empty(); + bibliography = Optional.empty(); } public void afterRemoveCitationGroup(CitationGroup cg) { - this.citationGroupsUnordered.remove(cg.cgid); - this.globalOrder.map(l -> l.remove(cg.cgid)); + citationGroupsUnordered.remove(cg.cgid); + globalOrder.map(l -> l.remove(cg.cgid)); - this.bibliography = Optional.empty(); + bibliography = Optional.empty(); } } From 7d2f0507e740eb144d8c07dc955844eb26a66538 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 11:21:46 +0200 Subject: [PATCH 0868/1068] move model/openoffice/Pair.java to model/oostyle/OOPair.java --- .../jabref/logic/openoffice/OOTextIntoOO.java | 82 +++++++++---------- .../org/jabref/model/oostyle/Citation.java | 7 +- .../jabref/model/oostyle/CitationGroups.java | 5 +- .../Pair.java => oostyle/OOPair.java} | 6 +- 4 files changed, 49 insertions(+), 51 deletions(-) rename src/main/java/org/jabref/model/{openoffice/Pair.java => oostyle/OOPair.java} (50%) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index f230863eae0..a11c8297f52 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -13,9 +13,9 @@ import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseAwt; +import org.jabref.model.oostyle.OOPair; import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.Pair; import com.sun.star.awt.FontSlant; import com.sun.star.awt.FontStrikeout; @@ -193,7 +193,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) Objects.requireNonNull(tagName); // Attibutes parsed into (name,value) pairs. - List> attributes = parseAttributes(attributeListPart); + List> attributes = parseAttributes(attributeListPart); // Handle tags: switch (tagName) { @@ -232,7 +232,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) case "p": OOUtil.insertParagraphBreak(text, cursor); cursor.collapseToEnd(); - for (Pair kv : attributes) { + for (OOPair kv : attributes) { String key = kv.a; String value = kv.b; switch (key) { @@ -258,7 +258,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) } break; case "oo:referenceToPageNumberOfReferenceMark": - for (Pair kv : attributes) { + for (OOPair kv : attributes) { String key = kv.a; String value = kv.b; switch (key) { @@ -277,8 +277,8 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) expectEnd.push("/" + tagName); break; case "span": - List> settings = new ArrayList<>(); - for (Pair kv : attributes) { + List> settings = new ArrayList<>(); + for (OOPair kv : attributes) { String key = kv.a; String value = kv.b; switch (key) { @@ -551,10 +551,10 @@ static class MyPropertyStack { * * Opening tags usually call this. */ - void pushLayer(List> settings) { + void pushLayer(List> settings) { ArrayList> oldLayer = layers.peek(); ArrayList> newLayer = new ArrayList<>(oldLayer); - for (Pair kv : settings) { + for (OOPair kv : settings) { String name = kv.a; Integer i = goodNameToIndex.get(name); if (i == null) { @@ -631,8 +631,8 @@ Optional getPropertyValue(String name) { /** * Parse HTML-like attributes to a list of (name,value) pairs. */ - private static List> parseAttributes(String s) { - List> res = new ArrayList<>(); + private static List> parseAttributes(String s) { + List> res = new ArrayList<>(); if (s == null) { return res; } @@ -640,7 +640,7 @@ private static List> parseAttributes(String s) { while (m.find()) { String key = m.group(1); String value = m.group(2); - res.add(new Pair(key, value)); + res.add(new OOPair(key, value)); } return res; } @@ -666,43 +666,43 @@ private static boolean isPropertyDefault(XTextCursor cursor, String propertyName * Various property change requests. Their results are passed to MyPropertyStack.pushLayer() */ - private static List> setCharWeight(float value) { - List> settings = new ArrayList<>(); - settings.add(new Pair("CharWeight", (Float) value)); + private static List> setCharWeight(float value) { + List> settings = new ArrayList<>(); + settings.add(new OOPair("CharWeight", (Float) value)); return settings; } - private static List> setCharPosture(FontSlant value) { - List> settings = new ArrayList<>(); - settings.add(new Pair("CharPosture", (Object) value)); + private static List> setCharPosture(FontSlant value) { + List> settings = new ArrayList<>(); + settings.add(new OOPair("CharPosture", (Object) value)); return settings; } - private static List> setCharCaseMap(short value) { - List> settings = new ArrayList<>(); - settings.add(new Pair("CharCaseMap", (Short) value)); + private static List> setCharCaseMap(short value) { + List> settings = new ArrayList<>(); + settings.add(new OOPair("CharCaseMap", (Short) value)); return settings; } // com.sun.star.awt.FontUnderline - private static List> setCharUnderline(short value) { - List> settings = new ArrayList<>(); - settings.add(new Pair(CHAR_UNDERLINE, (Short) value)); + private static List> setCharUnderline(short value) { + List> settings = new ArrayList<>(); + settings.add(new OOPair(CHAR_UNDERLINE, (Short) value)); return settings; } // com.sun.star.awt.FontStrikeout - private static List> setCharStrikeout(short value) { - List> settings = new ArrayList<>(); - settings.add(new Pair(CHAR_STRIKEOUT, (Short) value)); + private static List> setCharStrikeout(short value) { + List> settings = new ArrayList<>(); + settings.add(new OOPair(CHAR_STRIKEOUT, (Short) value)); return settings; } // CharStyleName - private static List> setCharStyleName(String value) { - List> settings = new ArrayList<>(); + private static List> setCharStyleName(String value) { + List> settings = new ArrayList<>(); if (value != null && value != "") { - settings.add(new Pair(CHAR_STYLE_NAME, value)); + settings.add(new OOPair(CHAR_STYLE_NAME, value)); } else { LOGGER.warn("setCharStyleName: received null or empty value"); } @@ -710,16 +710,16 @@ private static List> setCharStyleName(String value) { } // Locale - private static List> setCharLocale(Locale value) { - List> settings = new ArrayList<>(); - settings.add(new Pair("CharLocale", (Object) value)); + private static List> setCharLocale(Locale value) { + List> settings = new ArrayList<>(); + settings.add(new OOPair("CharLocale", (Object) value)); return settings; } /** * Locale from string encoding: language, language-country or language-country-variant */ - private static List> setCharLocale(String value) { + private static List> setCharLocale(String value) { if (value == null || "".equals(value)) { throw new RuntimeException("setCharLocale \"\" or null"); } @@ -737,11 +737,11 @@ private static List> setCharLocale(String value) { * @param relative If true, calculate the new values relative to * the current values. This allows subscript-in-superscript. */ - private static List> setCharEscapement(Optional value, + private static List> setCharEscapement(Optional value, Optional height, boolean relative, MyPropertyStack formatStack) { - List> settings = new ArrayList<>(); + List> settings = new ArrayList<>(); Optional oldValue = (formatStack .getPropertyValue(CHAR_ESCAPEMENT) .map(e -> (short) e)); @@ -758,30 +758,30 @@ private static List> setCharEscapement(Optional valu short newValue = (short) Math.round(xValue); byte newHeight = (byte) Math.round(xHeight); if (value.isPresent()) { - settings.add(new Pair(CHAR_ESCAPEMENT, (Short) newValue)); + settings.add(new OOPair(CHAR_ESCAPEMENT, (Short) newValue)); } if (height.isPresent()) { - settings.add(new Pair(CHAR_ESCAPEMENT_HEIGHT, (Byte) newHeight)); + settings.add(new OOPair(CHAR_ESCAPEMENT_HEIGHT, (Byte) newHeight)); } } else { if (value.isPresent()) { - settings.add(new Pair(CHAR_ESCAPEMENT, (Short) value.get())); + settings.add(new OOPair(CHAR_ESCAPEMENT, (Short) value.get())); } if (height.isPresent()) { - settings.add(new Pair(CHAR_ESCAPEMENT_HEIGHT, (Byte) height.get())); + settings.add(new OOPair(CHAR_ESCAPEMENT_HEIGHT, (Byte) height.get())); } } return settings; } - private static List> setSubScript(MyPropertyStack formatStack) { + private static List> setSubScript(MyPropertyStack formatStack) { return setCharEscapement(Optional.of(SUBSCRIPT_VALUE), Optional.of(SUBSCRIPT_HEIGHT), true, formatStack); } - private static List> setSuperScript(MyPropertyStack formatStack) { + private static List> setSuperScript(MyPropertyStack formatStack) { return setCharEscapement(Optional.of(SUPERSCRIPT_VALUE), Optional.of(SUPERSCRIPT_HEIGHT), true, diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/oostyle/Citation.java index e2e1e412d15..e8eda6ffd07 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/oostyle/Citation.java @@ -5,7 +5,6 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.openoffice.Pair; public class Citation implements ComparableCitation, CitationMarkerEntry, CitationMarkerNumericEntry { @@ -123,17 +122,17 @@ public void setIsFirstAppearanceOfSource(boolean value) { /* * Setters for CitationGroups.distribute() */ - public static void setLookupResult(Pair> x) { + public static void setLookupResult(OOPair> x) { Citation cit = x.a; cit.db = x.b; } - public static void setNumber(Pair> x) { + public static void setNumber(OOPair> x) { Citation cit = x.a; cit.number = x.b; } - public static void setUniqueLetter(Pair> x) { + public static void setUniqueLetter(OOPair> x) { Citation cit = x.a; cit.uniqueLetter = x.b; } diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/oostyle/CitationGroups.java index c26ee38e73e..038e6514962 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/oostyle/CitationGroups.java @@ -11,7 +11,6 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.openoffice.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,7 +58,7 @@ public int numberOfCitationGroups() { * call {@code fun.accept(new Pair(citation, value));} */ public void distributeToCitations(List where, - Consumer> fun, + Consumer> fun, T value) { for (CitationPath p : where) { @@ -69,7 +68,7 @@ public void distributeToCitations(List where, continue; } Citation cit = cg.citationsInStorageOrder.get(p.storageIndexInGroup); - fun.accept(new Pair(cit, value)); + fun.accept(new OOPair(cit, value)); } } diff --git a/src/main/java/org/jabref/model/openoffice/Pair.java b/src/main/java/org/jabref/model/oostyle/OOPair.java similarity index 50% rename from src/main/java/org/jabref/model/openoffice/Pair.java rename to src/main/java/org/jabref/model/oostyle/OOPair.java index de53f6d2965..ec50bd4417c 100644 --- a/src/main/java/org/jabref/model/openoffice/Pair.java +++ b/src/main/java/org/jabref/model/oostyle/OOPair.java @@ -1,9 +1,9 @@ -package org.jabref.model.openoffice; +package org.jabref.model.oostyle; -public class Pair { +public class OOPair { public final A a; public final B b; - public Pair(A a, B b) { + public OOPair(A a, B b) { this.a = a; this.b = b; } From c6865dd0bac4e323cda760c1db2ccde416d39f91 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 11:41:08 +0200 Subject: [PATCH 0869/1068] prefix Result and VoidResult -> OOResult, OOVoidResult --- .../org/jabref/gui/openoffice/OOBibBase.java | 142 +++++++++--------- .../gui/openoffice/OOBibBaseConnect.java | 8 +- .../openoffice/FunctionalTextViewCursor.java | 16 +- .../jabref/logic/openoffice/OOFrontend.java | 10 +- .../openoffice/{Result.java => OOResult.java} | 28 ++-- .../{VoidResult.java => OOVoidResult.java} | 16 +- 6 files changed, 110 insertions(+), 110 deletions(-) rename src/main/java/org/jabref/model/openoffice/{Result.java => OOResult.java} (71%) rename src/main/java/org/jabref/model/openoffice/{VoidResult.java => OOVoidResult.java} (63%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 416dc5e52c4..d4ee109a804 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -34,9 +34,9 @@ import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.OOResult; +import org.jabref.model.openoffice.OOVoidResult; import org.jabref.model.openoffice.RangeForOverlapCheck; -import org.jabref.model.openoffice.Result; -import org.jabref.model.openoffice.VoidResult; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -137,7 +137,7 @@ public boolean isDocumentConnectionMissing() { /** * Either return an XTextDocument or return JabRefException. */ - public Result getXTextDocument() { + public OOResult getXTextDocument() { return this.connection.getXTextDocument(); } @@ -162,32 +162,32 @@ void showDialog(String title, OOError ex) { ex.setTitle(title).showErrorDialog(dialogService); } - VoidResult collectResults(String title, List> results) { + OOVoidResult collectResults(String title, List> results) { String msg = (results.stream() .filter(e -> e.isError()) .map(e -> e.getError().getLocalizedMessage()) .collect(Collectors.joining("\n\n"))); if (msg.isEmpty()) { - return VoidResult.ok(); + return OOVoidResult.ok(); } else { - return VoidResult.error(new OOError(title, msg)); + return OOVoidResult.error(new OOError(title, msg)); } } - boolean testDialog(VoidResult res) { + boolean testDialog(OOVoidResult res) { return res.ifError(ex -> ex.showErrorDialog(dialogService)).isError(); } - boolean testDialog(String title, VoidResult res) { + boolean testDialog(String title, OOVoidResult res) { return res.ifError(e -> showDialog(e.setTitle(title))).isError(); } - boolean testDialog(String title, List> results) { + boolean testDialog(String title, List> results) { return testDialog(title, collectResults(title, results)); } - boolean testDialog(String title, VoidResult... results) { - List> rs = Arrays.asList(results); + boolean testDialog(String title, OOVoidResult... results) { + List> rs = Arrays.asList(results); return testDialog(collectResults(title, rs)); } @@ -196,16 +196,16 @@ boolean testDialog(String title, VoidResult... results) { * Get the cursor positioned by the user for inserting text. * */ - Result getUserCursorForTextInsertion(XTextDocument doc, String title) { + OOResult getUserCursorForTextInsertion(XTextDocument doc, String title) { XTextCursor cursor; // Get the cursor positioned by the user. try { cursor = UnoCursor.getViewCursor(doc).orElse(null); } catch (RuntimeException ex) { - return Result.error(new OOError(title, - Localization.lang("Could not get the cursor."), - ex)); + return OOResult.error(new OOError(title, + Localization.lang("Could not get the cursor."), + ex)); } // Check for crippled XTextViewCursor @@ -218,15 +218,15 @@ Result getUserCursorForTextInsertion(XTextDocument doc, St + " to the location for the new citation.") + "\n" + Localization.lang("I cannot insert to the cursors current location."); - return Result.error(new OOError(title, msg, ex)); + return OOResult.error(new OOError(title, msg, ex)); } - return Result.ok(cursor); + return OOResult.ok(cursor); } /** * This may move the view cursor. */ - Result getFunctionalTextViewCursor(XTextDocument doc, + OOResult getFunctionalTextViewCursor(XTextDocument doc, String title) { String messageOnFailureToObtain = Localization.lang("Please move the cursor into the document text.") @@ -234,12 +234,12 @@ Result getFunctionalTextViewCursor(XTextDocum + Localization.lang("To get the visual positions of your citations" + " I need to move the cursor around," + " but could not get it."); - Result result = + OOResult result = FunctionalTextViewCursor.get(doc, messageOnFailureToObtain); return result.mapError(e -> OOError.from(e).setTitle(title)); } - private static VoidResult + private static OOVoidResult checkRangeOverlaps(XTextDocument doc, OOFrontend fr) { final String title = "checkRangeOverlaps"; boolean requireSeparation = false; @@ -251,17 +251,17 @@ Result getFunctionalTextViewCursor(XTextDocum maxReportedOverlaps) .mapError(OOError::from)); } catch (NoDocumentException ex) { - return VoidResult.error(OOError.from(ex).setTitle(title)); + return OOVoidResult.error(OOError.from(ex).setTitle(title)); } catch (WrappedTargetException ex) { - return VoidResult.error(OOError.fromMisc(ex).setTitle(title)); + return OOVoidResult.error(OOError.fromMisc(ex).setTitle(title)); } } - private static VoidResult + private static OOVoidResult checkRangeOverlapsWithCursor(XTextDocument doc, OOFrontend fr) { final String title = "checkRangeOverlapsWithCursor"; - VoidResult precheck = checkRangeOverlaps(doc, fr); + OOVoidResult precheck = checkRangeOverlaps(doc, fr); if (precheck.isError()) { return precheck; } @@ -270,30 +270,30 @@ Result getFunctionalTextViewCursor(XTextDocum try { userRanges = fr.viewCursorRanges(doc); } catch (NoDocumentException ex) { - return VoidResult.error(OOError.from(ex).setTitle(title)); + return OOVoidResult.error(OOError.from(ex).setTitle(title)); } catch (WrappedTargetException ex) { - return VoidResult.error(OOError.fromMisc(ex).setTitle(title)); + return OOVoidResult.error(OOError.fromMisc(ex).setTitle(title)); } boolean requireSeparation = false; int maxReportedOverlaps = 10; - VoidResult res; + OOVoidResult res; try { res = fr.checkRangeOverlaps(doc, userRanges, requireSeparation, maxReportedOverlaps); } catch (NoDocumentException ex) { - return VoidResult.error(OOError.from(ex).setTitle(title)); + return OOVoidResult.error(OOError.from(ex).setTitle(title)); } catch (WrappedTargetException ex) { - return VoidResult.error(OOError.fromMisc(ex).setTitle(title)); + return OOVoidResult.error(OOError.fromMisc(ex).setTitle(title)); } if (res.isError()) { final String xtitle = Localization.lang("The cursor is in protected area."); - return VoidResult.error(new OOError(xtitle, - xtitle + "\n" - + res.getError().getLocalizedMessage() + "\n")); + return OOVoidResult.error(new OOError(xtitle, + xtitle + "\n" + + res.getError().getLocalizedMessage() + "\n")); } return res.mapError(OOError::from); } @@ -304,7 +304,7 @@ Result getFunctionalTextViewCursor(XTextDocum * */ - private static VoidResult checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) { + private static OOVoidResult checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) { String title = Localization.lang("Recording and/or Recorded changes"); try { @@ -326,58 +326,58 @@ private static VoidResult checkIfOpenOfficeIsRecordingChanges(XTextDocu msg += "\n"; msg += Localization.lang("Use [Edit]/[Track Changes]/[Manage] to resolve them first."); } - return VoidResult.error(new OOError(title, msg)); + return OOVoidResult.error(new OOError(title, msg)); } } catch (UnknownPropertyException | WrappedTargetException ex) { String msg = Localization.lang("Error while checking if Writer" + " is recording changes or has recorded changes."); - return VoidResult.error(new OOError(title, msg, ex)); + return OOVoidResult.error(new OOError(title, msg, ex)); } - return VoidResult.ok(); + return OOVoidResult.ok(); } - VoidResult styleIsRequired(OOBibStyle style) { + OOVoidResult styleIsRequired(OOBibStyle style) { if (style == null) { - return VoidResult.error(OOError.noValidStyleSelected()); + return OOVoidResult.error(OOError.noValidStyleSelected()); } else { - return VoidResult.ok(); + return OOVoidResult.ok(); } } - Result getFrontend(XTextDocument doc) { + OOResult getFrontend(XTextDocument doc) { final String title = "getFrontend"; try { - return Result.ok(new OOFrontend(doc)); + return OOResult.ok(new OOFrontend(doc)); } catch (NoDocumentException ex) { - return Result.error(OOError.from(ex).setTitle(title)); + return OOResult.error(OOError.from(ex).setTitle(title)); } catch (WrappedTargetException | RuntimeException ex) { - return Result.error(OOError.fromMisc(ex).setTitle(title)); + return OOResult.error(OOError.fromMisc(ex).setTitle(title)); } } - VoidResult databaseIsRequired(List databases, + OOVoidResult databaseIsRequired(List databases, Supplier fun) { if (databases == null || databases.isEmpty()) { - return VoidResult.error(fun.get()); + return OOVoidResult.error(fun.get()); } else { - return VoidResult.ok(); + return OOVoidResult.ok(); } } - VoidResult selectedBibEntryIsRequired(List entries, + OOVoidResult selectedBibEntryIsRequired(List entries, Supplier fun) { if (entries == null || entries.isEmpty()) { - return VoidResult.error(fun.get()); + return OOVoidResult.error(fun.get()); } else { - return VoidResult.ok(); + return OOVoidResult.ok(); } } /* * Checks existence and also checks if it is not an internal name. */ - private VoidResult checkStyleExistsInTheDocument(String familyName, + private OOVoidResult checkStyleExistsInTheDocument(String familyName, String styleName, XTextDocument doc, String labelInJstyleFile, @@ -408,7 +408,7 @@ private VoidResult checkStyleExistsInTheDocument(String familyName, + Localization.lang("Please create it in the document or change in the file:") + "\n" + pathToStyleFile; - return VoidResult.error(new OOError("StyleIsNotKnown", msg)); + return OOVoidResult.error(new OOError("StyleIsNotKnown", msg)); } if (!internalName.get().equals(styleName)) { @@ -434,16 +434,16 @@ private VoidResult checkStyleExistsInTheDocument(String familyName, + " to avoid localization problems.") + "\n" + pathToStyleFile; - return VoidResult.error(new OOError("StyleNameIsNotInternal", msg)); + return OOVoidResult.error(new OOError("StyleNameIsNotInternal", msg)); } - return VoidResult.ok(); + return OOVoidResult.ok(); } - public VoidResult checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) { + public OOVoidResult checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) { String pathToStyleFile = style.getPath(); - List> results = new ArrayList<>(); + List> results = new ArrayList<>(); try { results.add(checkStyleExistsInTheDocument(UnoStyle.PARAGRAPH_STYLES, style.getReferenceHeaderParagraphFormat(), @@ -464,9 +464,9 @@ public VoidResult checkStylesExistInTheDocument(OOBibStyle style, XText } } catch (NoSuchElementException | WrappedTargetException ex) { - results.add(VoidResult.error(new OOError("Other error in checkStyleExistsInTheDocument", - ex.getMessage(), - ex))); + results.add(OOVoidResult.error(new OOError("Other error in checkStyleExistsInTheDocument", + ex.getMessage(), + ex))); } return collectResults("checkStyleExistsInTheDocument failed", results); @@ -482,7 +482,7 @@ public Optional> guiActionGetCitationEntries() { final Optional> FAIL = Optional.empty(); final String title = Localization.lang("Problem collecting citations"); - Result odoc = getXTextDocument(); + OOResult odoc = getXTextDocument(); if (testDialog(title, odoc.asVoidResult())) { return FAIL; } @@ -540,7 +540,7 @@ public void guiActionApplyCitationEntries(List citationEntries) { final String title = Localization.lang("Problem modifying citation"); - Result odoc = getXTextDocument(); + OOResult odoc = getXTextDocument(); if (testDialog(title, odoc.asVoidResult())) { return; } @@ -607,7 +607,7 @@ public void guiActionInsertEntry(List entries, final String title = "Could not insert citation"; - Result odoc = getXTextDocument(); + OOResult odoc = getXTextDocument(); if (testDialog(title, odoc.asVoidResult(), styleIsRequired(style), @@ -616,13 +616,13 @@ public void guiActionInsertEntry(List entries, } XTextDocument doc = odoc.get(); - Result ofr = getFrontend(doc); + OOResult ofr = getFrontend(doc); if (testDialog(title, ofr.asVoidResult())) { return; } OOFrontend fr = ofr.get(); - Result cursor = getUserCursorForTextInsertion(doc, title); + OOResult cursor = getUserCursorForTextInsertion(doc, title); if (testDialog(title, cursor.asVoidResult())) { return; } @@ -640,7 +640,7 @@ public void guiActionInsertEntry(List entries, /* * For sync we need a FunctionalTextViewCursor. */ - Result fcursor = null; + OOResult fcursor = null; if (syncOptions.isPresent()) { fcursor = getFunctionalTextViewCursor(doc, title); if (testDialog(title, fcursor.asVoidResult())) { @@ -708,7 +708,7 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle final String title = Localization.lang("Problem combining cite markers"); - Result odoc = getXTextDocument(); + OOResult odoc = getXTextDocument(); if (testDialog(title, odoc.asVoidResult(), styleIsRequired(style), @@ -717,7 +717,7 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle } XTextDocument doc = odoc.get(); - Result fcursor = getFunctionalTextViewCursor(doc, title); + OOResult fcursor = getFunctionalTextViewCursor(doc, title); if (testDialog(title, fcursor.asVoidResult(), @@ -771,7 +771,7 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s final String title = Localization.lang("Problem during separating cite markers"); - Result odoc = getXTextDocument(); + OOResult odoc = getXTextDocument(); if (testDialog(title, odoc.asVoidResult(), styleIsRequired(style), @@ -780,7 +780,7 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s } XTextDocument doc = odoc.get(); - Result fcursor = getFunctionalTextViewCursor(doc, title); + OOResult fcursor = getFunctionalTextViewCursor(doc, title); if (testDialog(title, fcursor.asVoidResult(), @@ -838,7 +838,7 @@ public Optional exportCitedHelper(List databases, final Optional FAIL = Optional.empty(); final String title = Localization.lang("Unable to generate new library"); - Result odoc = getXTextDocument(); + OOResult odoc = getXTextDocument(); if (testDialog(title, odoc.asVoidResult(), databaseIsRequired(databases, OOError::noDataBaseIsOpenForExport))) { @@ -911,7 +911,7 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl try { - Result odoc = getXTextDocument(); + OOResult odoc = getXTextDocument(); if (testDialog(title, odoc.asVoidResult(), styleIsRequired(style))) { @@ -920,7 +920,7 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl XTextDocument doc = odoc.get(); - Result fcursor = getFunctionalTextViewCursor(doc, title); + OOResult fcursor = getFunctionalTextViewCursor(doc, title); if (testDialog(title, fcursor.asVoidResult(), diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 7bf7dd23008..7aae4fe4345 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -13,7 +13,7 @@ import org.jabref.logic.openoffice.UnoTextDocument; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; -import org.jabref.model.openoffice.Result; +import org.jabref.model.openoffice.OOResult; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; @@ -239,11 +239,11 @@ public XTextDocument getXTextDocumentOrThrow() return this.xTextDocument; } - public Result getXTextDocument() { + public OOResult getXTextDocument() { if (isDocumentConnectionMissing()) { - return Result.error(OOError.from(new NoDocumentException())); + return OOResult.error(OOError.from(new NoDocumentException())); } - return Result.ok(this.xTextDocument); + return OOResult.ok(this.xTextDocument); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java index a93bcc5617d..f26bf3174d9 100644 --- a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java @@ -4,7 +4,7 @@ import java.util.Objects; import org.jabref.logic.JabRefException; -import org.jabref.model.openoffice.Result; +import org.jabref.model.openoffice.OOResult; import com.sun.star.lang.XServiceInfo; import com.sun.star.text.XTextDocument; @@ -32,7 +32,7 @@ * * Usage: * - * Result fcursor = FunctionalTextViewCursor.get(doc, msg); + * OOResult fcursor = FunctionalTextViewCursor.get(doc, msg); * if (fcursor.isError()) { * ... * } else { @@ -80,7 +80,7 @@ private FunctionalTextViewCursor(XTextRange initialPosition, * The cursor position may differ from the location * provided by the user. */ - public static Result get(XTextDocument doc, + public static OOResult get(XTextDocument doc, String messageOnFailure) { Objects.requireNonNull(doc); @@ -93,7 +93,7 @@ public static Result get(XTextDocumen try { initialPosition = UnoCursor.createTextCursorByRange(viewCursor); viewCursor.getStart(); - return Result.ok(new FunctionalTextViewCursor(initialPosition, + return OOResult.ok(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); } catch (com.sun.star.uno.RuntimeException ex) { @@ -106,7 +106,7 @@ public static Result get(XTextDocumen if (initialSelection == null) { String errorMessage = ("Selection is not available:" + " cannot provide a functional view cursor"); - return Result.error(new JabRefException(errorMessage, messageOnFailure)); + return OOResult.error(new JabRefException(errorMessage, messageOnFailure)); } else if (!Arrays.stream(initialSelection.getSupportedServiceNames()) .anyMatch("com.sun.star.text.TextRanges"::equals)) { // initialSelection does not support TextRanges. @@ -119,7 +119,7 @@ public static Result get(XTextDocumen if (viewCursor == null) { restore(doc, initialPosition, initialSelection); String errorMessage = "Could not get the view cursor"; - return Result.error(new JabRefException(errorMessage, messageOnFailure)); + return OOResult.error(new JabRefException(errorMessage, messageOnFailure)); } try { @@ -127,10 +127,10 @@ public static Result get(XTextDocumen } catch (com.sun.star.uno.RuntimeException ex) { restore(doc, initialPosition, initialSelection); String errorMessage = "The view cursor failed the functionality test"; - return Result.error(new JabRefException(errorMessage, messageOnFailure)); + return OOResult.error(new JabRefException(errorMessage, messageOnFailure)); } - return Result.ok(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); + return OOResult.ok(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); } public XTextViewCursor getViewCursor() { diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index d11170dd00c..716629ec021 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -21,13 +21,13 @@ import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.OOVoidResult; import org.jabref.model.openoffice.RangeForOverlapCheck; import org.jabref.model.openoffice.RangeKeyedMap; import org.jabref.model.openoffice.RangeKeyedMapList; import org.jabref.model.openoffice.RangeOverlap; import org.jabref.model.openoffice.RangeSortEntry; import org.jabref.model.openoffice.RangeSortable; -import org.jabref.model.openoffice.VoidResult; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -456,7 +456,7 @@ private List> footnoteMarkRanges(XTextDocu * @param reportAtMost Limit number of overlaps reported (0 for no limit) * */ - public VoidResult + public OOVoidResult checkRangeOverlaps(XTextDocument doc, List> userRanges, boolean requireSeparation, @@ -496,10 +496,10 @@ private List> footnoteMarkRanges(XTextDocu msg.append(listOfRanges); msg.append("\n"); } - return VoidResult.error(new JabRefException("Found overlapping or touching ranges", - msg.toString())); + return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges", + msg.toString())); } else { - return VoidResult.ok(); + return OOVoidResult.ok(); } } diff --git a/src/main/java/org/jabref/model/openoffice/Result.java b/src/main/java/org/jabref/model/openoffice/OOResult.java similarity index 71% rename from src/main/java/org/jabref/model/openoffice/Result.java rename to src/main/java/org/jabref/model/openoffice/OOResult.java index 600df3a15ad..e6807407a50 100644 --- a/src/main/java/org/jabref/model/openoffice/Result.java +++ b/src/main/java/org/jabref/model/openoffice/OOResult.java @@ -8,11 +8,11 @@ * error cannot be null * result cannot be null * - * Void is not allowed for R, use VoidResult instead. + * Void is not allowed for R, use OOVoidResult instead. * * Out of `isPresent()` and `isError()` exactly one is true. */ -public class Result { +public class OOResult { private final Optional result; private final Optional error; @@ -22,7 +22,7 @@ public class Result { * @param result * @param error */ - private Result(Optional result, Optional error) { + private OOResult(Optional result, Optional error) { this.result = result; this.error = error; } @@ -30,15 +30,15 @@ private Result(Optional result, Optional error) { /** * @param result Null is not allowed. */ - public static Result ok(R result) { - return new Result(Optional.of(result), Optional.empty()); + public static OOResult ok(R result) { + return new OOResult(Optional.of(result), Optional.empty()); } /** * @param error Null is not allowed. */ - public static Result error(E error) { - return new Result(Optional.empty(), Optional.of(error)); + public static OOResult error(E error) { + return new OOResult(Optional.empty(), Optional.of(error)); } /* @@ -80,21 +80,21 @@ public E getError() { * Conditionals */ - public Result ifPresent(Consumer fun) { + public OOResult ifPresent(Consumer fun) { if (isPresent()) { fun.accept(get()); } return this; } - public Result ifError(Consumer fun) { + public OOResult ifError(Consumer fun) { if (isError()) { fun.accept(getError()); } return this; } - public Result map(Function fun) { + public OOResult map(Function fun) { if (isError()) { return error(getError()); } else { @@ -102,7 +102,7 @@ public Result map(Function fun) { } } - public Result mapError(Function fun) { + public OOResult mapError(Function fun) { if (isError()) { return error(fun.apply(getError())); } else { @@ -116,11 +116,11 @@ public Optional getOptional() { } /** Throw away the result part. */ - public VoidResult asVoidResult() { + public OOVoidResult asVoidResult() { if (isError()) { - return VoidResult.error(getError()); + return OOVoidResult.error(getError()); } else { - return VoidResult.ok(); + return OOVoidResult.ok(); } } diff --git a/src/main/java/org/jabref/model/openoffice/VoidResult.java b/src/main/java/org/jabref/model/openoffice/OOVoidResult.java similarity index 63% rename from src/main/java/org/jabref/model/openoffice/VoidResult.java rename to src/main/java/org/jabref/model/openoffice/OOVoidResult.java index f1eff235f60..5a8ee600682 100644 --- a/src/main/java/org/jabref/model/openoffice/VoidResult.java +++ b/src/main/java/org/jabref/model/openoffice/OOVoidResult.java @@ -7,19 +7,19 @@ /* * error cannot be null */ -public class VoidResult { +public class OOVoidResult { private final Optional error; - private VoidResult(Optional error) { + private OOVoidResult(Optional error) { this.error = error; } - public static VoidResult ok() { - return new VoidResult(Optional.empty()); + public static OOVoidResult ok() { + return new OOVoidResult(Optional.empty()); } - public static VoidResult error(E error) { - return new VoidResult(Optional.of(error)); + public static OOVoidResult error(E error) { + return new OOVoidResult(Optional.of(error)); } public boolean isError() { @@ -34,14 +34,14 @@ public E getError() { return error.get(); } - public VoidResult ifError(Consumer fun) { + public OOVoidResult ifError(Consumer fun) { if (isError()) { fun.accept(getError()); } return this; } - public VoidResult mapError(Function fun) { + public OOVoidResult mapError(Function fun) { if (isError()) { return error(fun.apply(getError())); } else { From 8edb55612c48e35466122c59239ab61d6782c351 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 11:50:29 +0200 Subject: [PATCH 0870/1068] drop unused: flatListOfValues --- .../model/openoffice/RangeKeyedMapList.java | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java index dfde0c37b2e..58b51a098e7 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java @@ -39,19 +39,4 @@ public List>> partitionValues() { return this.partitions.partitionValues(); } - /** - * Lis of all values: partitions in arbitrary order, ranges are - * sorted within partitions, values under the same range are in - * the order they were added. - */ - public List flatListOfValues() { - List result = new ArrayList<>(); - for (TreeMap> partition : partitionValues()) { - for (List valuesUnderARange : partition.values()) { - result.addAll(valuesUnderARange); - } - } - return result; - } - } From ab5b6fe8caaece653926bab7ac7dd39453f002f7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 11:51:07 +0200 Subject: [PATCH 0871/1068] RangeKeyedMapList.partitions is private --- .../java/org/jabref/logic/openoffice/RangeOverlapFinder.java | 2 +- .../java/org/jabref/model/openoffice/RangeKeyedMapList.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java b/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java index f88a56997a9..e78fd60c3ab 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java @@ -24,7 +24,7 @@ public static List> findOverlappingRanges(RangeKeyedMapList< int atMost, boolean includeTouching) { List> result = new ArrayList<>(); - for (TreeMap> partition : input.partitions.partitionValues()) { + for (TreeMap> partition : input.partitionValues()) { List orderedRanges = new ArrayList<>(partition.keySet()); for (int i = 0; i < orderedRanges.size(); i++) { XTextRange aRange = orderedRanges.get(i); diff --git a/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java index 58b51a098e7..13353442205 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java @@ -7,7 +7,8 @@ import com.sun.star.text.XTextRange; public class RangeKeyedMapList { - public RangeKeyedMap> partitions; + + private RangeKeyedMap> partitions; public RangeKeyedMapList() { this.partitions = new RangeKeyedMap<>(); From afbc9bfe732474035559dea406076a759aed964c Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 11:57:38 +0200 Subject: [PATCH 0872/1068] comments --- src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java | 2 +- .../java/org/jabref/model/openoffice/RangeOverlapKind.java | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java index c1da3c94b69..4f36fbae9cc 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java +++ b/src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java @@ -21,7 +21,7 @@ * range.getText(), we group them by these. * * Within such groups (partitions) we may define comparison, here - * based on (range.getStart(),range.getEnd()), thus equality means identical + * based on (range.getStart(),range.getEnd()), where equality means identical * ranges. * * For finding overlapping ranges this class proved insufficient, diff --git a/src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java b/src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java index 79b1acac3fe..1c172d7da3f 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java +++ b/src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java @@ -1,8 +1,13 @@ package org.jabref.model.openoffice; public enum RangeOverlapKind { + /** They share a boundary */ TOUCH, + + /** They share some characters */ OVERLAP, + + /** They cover the same XTextRange */ EQUAL_RANGE } From 0600163147e42ecd7584284e6141476884d71f02 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 12:05:37 +0200 Subject: [PATCH 0873/1068] comments --- .../org/jabref/model/openoffice/RangeSortable.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/java/org/jabref/model/openoffice/RangeSortable.java b/src/main/java/org/jabref/model/openoffice/RangeSortable.java index d72736cb1c6..938cb1cdd0f 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeSortable.java +++ b/src/main/java/org/jabref/model/openoffice/RangeSortable.java @@ -10,8 +10,18 @@ * */ public interface RangeSortable { + + /** The XTextRange + * + * For citation marks in footnotes this may be the range of the + * footnote mark. + */ public XTextRange getRange(); + /** + * For citation marks in footnotes this may provide order within + * the footnote. + */ public int getIndexInPosition(); public T getContent(); From 155f75ec2131b1e72c493e314ca839621fa8b4fb Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 12:15:36 +0200 Subject: [PATCH 0874/1068] RangeSortEntry fields are private --- .../jabref/logic/openoffice/OOFrontend.java | 4 ++-- .../model/openoffice/RangeSortEntry.java | 19 +++++++++++++------ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 716629ec021..d51fbbb4af5 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -167,13 +167,13 @@ public Optional healthReport(XTextDocument doc) XTextRange aRange = orderedRanges.get(i); List> sortablesAtARange = partition.get(aRange); for (RangeSortEntry sortable : sortablesAtARange) { - sortable.indexInPosition = indexInPartition++; + sortable.setIndexInPosition(indexInPartition++); if (mapFootnotesToFootnoteMarks) { Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(sortable.getRange()); // Adjust range if we are inside a footnote: if (footnoteMarkRange.isPresent()) { - sortable.range = footnoteMarkRange.get(); + sortable.setRange(footnoteMarkRange.get()); } } result.add(sortable); diff --git a/src/main/java/org/jabref/model/openoffice/RangeSortEntry.java b/src/main/java/org/jabref/model/openoffice/RangeSortEntry.java index 9141bbbaef3..e7a55bf4d54 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeSortEntry.java +++ b/src/main/java/org/jabref/model/openoffice/RangeSortEntry.java @@ -6,13 +6,12 @@ * A simple implementation of {@code RangeSortable} */ public class RangeSortEntry implements RangeSortable { - public XTextRange range; - public int indexInPosition; - public T content; - public RangeSortEntry(XTextRange range, - int indexInPosition, - T content) { + private XTextRange range; + private int indexInPosition; + private T content; + + public RangeSortEntry(XTextRange range, int indexInPosition, T content) { this.range = range; this.indexInPosition = indexInPosition; this.content = content; @@ -32,4 +31,12 @@ public int getIndexInPosition() { public T getContent() { return content; } + + public void setRange(XTextRange r) { + range = r; + } + + public void setIndexInPosition(int i) { + indexInPosition = i; + } } From cae3ac03ee91edfcbf613a13bfa0ce5a5dd013b0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 12:19:25 +0200 Subject: [PATCH 0875/1068] bring public methods to the front --- .../jabref/logic/openoffice/EditMerge.java | 139 +++++++++--------- 1 file changed, 71 insertions(+), 68 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 3c00bbfb24a..78b39896b8a 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -33,6 +33,77 @@ public class EditMerge { private static final Logger LOGGER = LoggerFactory.getLogger(EditMerge.class); + private EditMerge() { + // hide constructor + } + + /* + * @return true if modified document + */ + public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBibStyle style) + throws + CreationException, + IllegalArgumentException, + IllegalTypeException, + InvalidStateException, + JabRefException, + NoDocumentException, + NoSuchElementException, + NotRemoveableException, + PropertyExistException, + PropertyVetoException, + UnknownPropertyException, + WrappedTargetException { + + boolean madeModifications = false; + + try { + UnoScreenRefresh.lockControllers(doc); + + List joinableGroups = EditMerge.scan(doc, fr); + + for (JoinableGroupData joinableGroupData : joinableGroups) { + + List cgs = joinableGroupData.group; + + List newGroupCitations = new ArrayList<>(); + for (CitationGroup cg : cgs) { + newGroupCitations.addAll(cg.citationsInStorageOrder); + } + + CitationType citationType = cgs.get(0).citationType; + List> pageInfos = fr.backend.combinePageInfos(cgs); + + fr.removeCitationGroups(cgs, doc); + XTextCursor textCursor = joinableGroupData.groupCursor; + textCursor.setString(""); // Also remove the spaces between. + + List citationKeys = (newGroupCitations.stream() + .map(cit -> cit.citationKey) + .collect(Collectors.toList())); + + /* insertSpaceAfter: no, it is already there (or could be) */ + boolean insertSpaceAfter = false; + UpdateCitationMarkers.createAndFillCitationGroup(fr, + doc, + citationKeys, + pageInfos, + citationType, + OOText.fromString("tmp"), + textCursor, + style, + insertSpaceAfter); + } + + madeModifications = !joinableGroups.isEmpty(); + + } finally { + UnoScreenRefresh.unlockControllers(doc); + } + + return madeModifications; + } + private static class JoinableGroupData { /* * A list of consecutive citation groups only separated by spaces. @@ -292,72 +363,4 @@ private static List scan(XTextDocument doc, OOFrontend fr) return result; } - /* - * @return true if modified document - */ - public static boolean mergeCitationGroups(XTextDocument doc, - OOFrontend fr, - OOBibStyle style) - throws - CreationException, - IllegalArgumentException, - IllegalTypeException, - InvalidStateException, - JabRefException, - NoDocumentException, - NoSuchElementException, - NotRemoveableException, - PropertyExistException, - PropertyVetoException, - UnknownPropertyException, - WrappedTargetException { - - boolean madeModifications = false; - - try { - UnoScreenRefresh.lockControllers(doc); - - List joinableGroups = EditMerge.scan(doc, fr); - - for (JoinableGroupData joinableGroupData : joinableGroups) { - - List cgs = joinableGroupData.group; - - List newGroupCitations = new ArrayList<>(); - for (CitationGroup cg : cgs) { - newGroupCitations.addAll(cg.citationsInStorageOrder); - } - - CitationType citationType = cgs.get(0).citationType; - List> pageInfos = fr.backend.combinePageInfos(cgs); - - fr.removeCitationGroups(cgs, doc); - XTextCursor textCursor = joinableGroupData.groupCursor; - textCursor.setString(""); // Also remove the spaces between. - - List citationKeys = (newGroupCitations.stream() - .map(cit -> cit.citationKey) - .collect(Collectors.toList())); - - /* insertSpaceAfter: no, it is already there (or could be) */ - boolean insertSpaceAfter = false; - UpdateCitationMarkers.createAndFillCitationGroup(fr, - doc, - citationKeys, - pageInfos, - citationType, - OOText.fromString("tmp"), - textCursor, - style, - insertSpaceAfter); - } - - madeModifications = !joinableGroups.isEmpty(); - - } finally { - UnoScreenRefresh.unlockControllers(doc); - } - - return madeModifications; - } } From f979fdf5d2bdabad227a48d294fcfac40eb29cd6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 12:38:09 +0200 Subject: [PATCH 0876/1068] add OOListUtil.flatMap --- src/main/java/org/jabref/logic/openoffice/EditMerge.java | 9 +++------ src/main/java/org/jabref/model/oostyle/OOListUtil.java | 4 ++++ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 78b39896b8a..005bbfb9781 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -11,6 +11,7 @@ import org.jabref.model.oostyle.Citation; import org.jabref.model.oostyle.CitationGroup; import org.jabref.model.oostyle.CitationType; +import org.jabref.model.oostyle.OOListUtil; import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -66,11 +67,7 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBi List cgs = joinableGroupData.group; - List newGroupCitations = new ArrayList<>(); - for (CitationGroup cg : cgs) { - newGroupCitations.addAll(cg.citationsInStorageOrder); - } - + List newCitations = OOListUtil.flatMap(cgs, cg -> cg.citationsInStorageOrder); CitationType citationType = cgs.get(0).citationType; List> pageInfos = fr.backend.combinePageInfos(cgs); @@ -78,7 +75,7 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBi XTextCursor textCursor = joinableGroupData.groupCursor; textCursor.setString(""); // Also remove the spaces between. - List citationKeys = (newGroupCitations.stream() + List citationKeys = (newCitations.stream() .map(cit -> cit.citationKey) .collect(Collectors.toList())); diff --git a/src/main/java/org/jabref/model/oostyle/OOListUtil.java b/src/main/java/org/jabref/model/oostyle/OOListUtil.java index b7c11e1269e..47e37fb3c14 100644 --- a/src/main/java/org/jabref/model/oostyle/OOListUtil.java +++ b/src/main/java/org/jabref/model/oostyle/OOListUtil.java @@ -13,6 +13,10 @@ public static List map(List list, Function fun) { return list.stream().map(e -> fun.apply(e)).collect(Collectors.toList()); } + public static List flatMap(List list, Function> fun) { + return list.stream().flatMap(e -> fun.apply(e).stream()).collect(Collectors.toList()); + } + /** Integers 0..(n-1) */ public static List makeIndices(int n) { return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); From fc0faa64afc65f4b52f205c7c50c2076bfe97249 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 12:52:08 +0200 Subject: [PATCH 0877/1068] use OOListUtil.flatMap and map --- .../java/org/jabref/logic/openoffice/Backend52.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 55d52770cdb..8657bcb67f9 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -284,8 +284,8 @@ public CitationGroup createCitationGroup(XTextDocument doc, switch (dataModel) { case JabRef52: // collect to cgPageInfos - List> cgPageInfos = - OOListUtil.map(joinableGroup, Backend52::getPageInfoFromData); + List> cgPageInfos = OOListUtil.map(joinableGroup, + Backend52::getPageInfoFromData); // Try to do something of the cgPageInfos. String cgPageInfo = (cgPageInfos.stream() @@ -303,10 +303,9 @@ public CitationGroup createCitationGroup(XTextDocument doc, return OODataModel.fakePageInfos(cgPageInfo, nCitations); case JabRef53: - return (joinableGroup.stream() - .flatMap(cg -> (cg.citationsInStorageOrder.stream() - .map(cit -> cit.getPageInfo()))) - .collect(Collectors.toList())); + return OOListUtil.flatMap(joinableGroup, + cg -> OOListUtil.map(cg.citationsInStorageOrder, + cit -> cit.getPageInfo())); default: throw new RuntimeException("unhandled dataModel here"); } From ed3f5c505f9ab8ad306dae3831cc4b6a20de6003 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 12:56:10 +0200 Subject: [PATCH 0878/1068] rename: ps -> propertySet, xPropertyContainer -> container, psi -> propertySetInfo --- .../openoffice/UnoUserDefinedProperty.java | 42 +++++++++---------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java b/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java index 5b2b65ec407..c0d21bd73b4 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java @@ -55,13 +55,13 @@ public static List getListOfNames(XTextDocument doc) { public static Optional getStringValue(XTextDocument doc, String property) throws WrappedTargetException { - Optional ps = (UnoUserDefinedProperty.getPropertyContainer(doc) - .flatMap(UnoProperties::asPropertySet)); - if (ps.isEmpty()) { + Optional propertySet = (UnoUserDefinedProperty.getPropertyContainer(doc) + .flatMap(UnoProperties::asPropertySet)); + if (propertySet.isEmpty()) { throw new RuntimeException("getting UserDefinedProperties as XPropertySet failed"); } try { - String v = ps.get().getPropertyValue(property).toString(); + String v = propertySet.get().getPropertyValue(property).toString(); return Optional.ofNullable(v); } catch (UnknownPropertyException ex) { return Optional.empty(); @@ -86,33 +86,31 @@ public static void createStringProperty(XTextDocument doc, String property, Stri Objects.requireNonNull(property); Objects.requireNonNull(value); - Optional xPropertyContainer = - UnoUserDefinedProperty.getPropertyContainer(doc); + Optional container = UnoUserDefinedProperty.getPropertyContainer(doc); - if (xPropertyContainer.isEmpty()) { + if (container.isEmpty()) { throw new RuntimeException("UnoUserDefinedProperty.getPropertyContainer failed"); } - Optional ps = - xPropertyContainer.flatMap(UnoProperties::asPropertySet); - if (ps.isEmpty()) { + Optional propertySet = container.flatMap(UnoProperties::asPropertySet); + if (propertySet.isEmpty()) { throw new RuntimeException("asPropertySet failed"); } - XPropertySetInfo psi = ps.get().getPropertySetInfo(); + XPropertySetInfo propertySetInfo = propertySet.get().getPropertySetInfo(); - if (psi.hasPropertyByName(property)) { + if (propertySetInfo.hasPropertyByName(property)) { try { - ps.get().setPropertyValue(property, value); + propertySet.get().setPropertyValue(property, value); return; } catch (UnknownPropertyException ex) { // fall through to addProperty } } - xPropertyContainer.get().addProperty(property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value)); + container.get().addProperty(property, + com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value)); } /** @@ -130,14 +128,14 @@ public static void remove(XTextDocument doc, String property) Objects.requireNonNull(property); - Optional xPropertyContainer = UnoUserDefinedProperty.getPropertyContainer(doc); + Optional container = UnoUserDefinedProperty.getPropertyContainer(doc); - if (xPropertyContainer.isEmpty()) { + if (container.isEmpty()) { throw new RuntimeException("getUserDefinedPropertiesAsXPropertyContainer failed"); } try { - xPropertyContainer.get().removeProperty(property); + container.get().removeProperty(property); } catch (UnknownPropertyException ex) { LOGGER.warn(String.format("UnoUserDefinedProperty.remove(%s)" + " This property was not there to remove", @@ -160,14 +158,14 @@ public static void removeIfExists(XTextDocument doc, String property) Objects.requireNonNull(property); - Optional xPropertyContainer = UnoUserDefinedProperty.getPropertyContainer(doc); + Optional container = UnoUserDefinedProperty.getPropertyContainer(doc); - if (xPropertyContainer.isEmpty()) { + if (container.isEmpty()) { throw new RuntimeException("getUserDefinedPropertiesAsXPropertyContainer failed"); } try { - xPropertyContainer.get().removeProperty(property); + container.get().removeProperty(property); } catch (UnknownPropertyException ex) { // did not exist } From 8da865eee0ad6b8df9b5c432e3ebc95dc27634ab Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 13:01:17 +0200 Subject: [PATCH 0879/1068] rename: psi -> propertySetInfo --- .../java/org/jabref/logic/openoffice/OOTextIntoOO.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index a11c8297f52..07454121924 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -395,10 +395,10 @@ public static void removeDirectFormatting(XTextCursor cursor) { // query again, just in case it matters propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - XPropertySetInfo psi = propertySet.getPropertySetInfo(); + XPropertySetInfo propertySetInfo = propertySet.getPropertySetInfo(); // check the result - for (Property p : psi.getProperties()) { + for (Property p : propertySetInfo.getProperties()) { if ((p.Attributes & PropertyAttribute.READONLY) != 0) { continue; } @@ -488,14 +488,14 @@ static class MyPropertyStack { throws UnknownPropertyException { XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - XPropertySetInfo psi = propertySet.getPropertySetInfo(); + XPropertySetInfo propertySetInfo = propertySet.getPropertySetInfo(); /* * On creation, initialize the property name -- index mapping. */ this.goodNameToIndex = new HashMap<>(); int nextIndex = 0; - for (Property p : psi.getProperties()) { + for (Property p : propertySetInfo.getProperties()) { if ((p.Attributes & PropertyAttribute.READONLY) != 0) { continue; } From 754e8a43cd4e001917b1b3d0194e064969dd7640 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 13:08:16 +0200 Subject: [PATCH 0880/1068] use longer names --- .../jabref/logic/openoffice/OOTextIntoOO.java | 12 ++++++------ .../jabref/logic/openoffice/UnoRedlines.java | 18 ++++++++++-------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 07454121924..14a62f40612 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -367,12 +367,12 @@ public static void removeDirectFormatting(XTextCursor cursor) { */ XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); + XPropertyState xPropertyState = UnoCast.unoQI(XPropertyState.class, cursor); try { // Special handling propertySet.setPropertyValue(CHAR_STYLE_NAME, "Standard"); - propertyState.setPropertyToDefault("CharCaseMap"); + xPropertyState.setPropertyToDefault("CharCaseMap"); } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | @@ -653,13 +653,13 @@ private static List> parseAttributes(String s) { private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) throws UnknownPropertyException { - XPropertyState propertyState = UnoCast.unoQI(XPropertyState.class, cursor); - PropertyState pst = propertyState.getPropertyState(propertyName); - if (pst == PropertyState.AMBIGUOUS_VALUE) { + XPropertyState xPropertyState = UnoCast.unoQI(XPropertyState.class, cursor); + PropertyState state = xPropertyState.getPropertyState(propertyName); + if (state == PropertyState.AMBIGUOUS_VALUE) { throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE" + " (expected properties for a homogeneous cursor)"); } - return pst == PropertyState.DEFAULT_VALUE; + return state == PropertyState.DEFAULT_VALUE; } /* diff --git a/src/main/java/org/jabref/logic/openoffice/UnoRedlines.java b/src/main/java/org/jabref/logic/openoffice/UnoRedlines.java index 8ec36f6a85c..4589182d30a 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoRedlines.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoRedlines.java @@ -22,8 +22,10 @@ public static boolean getRecordChanges(XTextDocument doc) // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Settings // "Properties of com.sun.star.text.TextDocument" - XPropertySet ps = UnoCast.optUnoQI(XPropertySet.class, doc).orElseThrow(RuntimeException::new); - return (boolean) ps.getPropertyValue("RecordChanges"); + XPropertySet propertySet = (UnoCast.optUnoQI(XPropertySet.class, doc) + .orElseThrow(RuntimeException::new)); + + return (boolean) propertySet.getPropertyValue("RecordChanges"); } private static XRedlinesSupplier getRedlinesSupplier(XTextDocument doc) { @@ -31,16 +33,16 @@ private static XRedlinesSupplier getRedlinesSupplier(XTextDocument doc) { } public static int countRedlines(XTextDocument doc) { - XRedlinesSupplier rs = getRedlinesSupplier(doc); - XEnumerationAccess ea = rs.getRedlines(); - XEnumeration e = ea.createEnumeration(); - if (e == null) { + XRedlinesSupplier supplier = getRedlinesSupplier(doc); + XEnumerationAccess enumerationAccess = supplier.getRedlines(); + XEnumeration enumeration = enumerationAccess.createEnumeration(); + if (enumeration == null) { return 0; } else { int count = 0; - while (e.hasMoreElements()) { + while (enumeration.hasMoreElements()) { try { - e.nextElement(); + enumeration.nextElement(); count++; } catch (NoSuchElementException | WrappedTargetException ex) { break; From 2eb3766072b1581bddcca48b2da68f33297d0243 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 13:12:16 +0200 Subject: [PATCH 0881/1068] drop local variable 'l' --- src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 14a62f40612..485da1748fd 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -727,8 +727,7 @@ private static List> setCharLocale(String value) { String language = (parts.length > 0) ? parts[0] : ""; String country = (parts.length > 1) ? parts[1] : ""; String variant = (parts.length > 2) ? parts[2] : ""; - Locale l = new Locale(language, country, variant); - return setCharLocale(l); + return setCharLocale(new Locale(language, country, variant)); } /* From b07c7571784a3889862247a0a5ca5bf46c7590f7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 13:12:37 +0200 Subject: [PATCH 0882/1068] format --- src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 485da1748fd..cd4623bf236 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -737,9 +737,9 @@ private static List> setCharLocale(String value) { * the current values. This allows subscript-in-superscript. */ private static List> setCharEscapement(Optional value, - Optional height, - boolean relative, - MyPropertyStack formatStack) { + Optional height, + boolean relative, + MyPropertyStack formatStack) { List> settings = new ArrayList<>(); Optional oldValue = (formatStack .getPropertyValue(CHAR_ESCAPEMENT) From 118067b29256c8b5ac2e2d41d07c70943bdac118 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 13:20:21 +0200 Subject: [PATCH 0883/1068] use longer names --- .../org/jabref/logic/openoffice/OOTextIntoOO.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index cd4623bf236..24c6685d870 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -750,12 +750,12 @@ private static List> setCharEscapement(Optional va .map(e -> (byte) e)); if (relative && (value.isPresent() || height.isPresent())) { - double oh = oldHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * 0.01; - double xHeight = height.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * oh; - double ov = oldValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT); - double xValue = value.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT) * oh + ov; - short newValue = (short) Math.round(xValue); - byte newHeight = (byte) Math.round(xHeight); + double oldHeightFloat = oldHeight.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT) * 0.01; + double oldValueFloat = oldValue.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT); + double heightFloat = height.orElse(CHAR_ESCAPEMENT_HEIGHT_DEFAULT); + double valueFloat = value.orElse(CHAR_ESCAPEMENT_VALUE_DEFAULT); + byte newHeight = (byte) Math.round(heightFloat * oldHeightFloat); + short newValue = (short) Math.round(valueFloat * oldHeightFloat + oldValueFloat); if (value.isPresent()) { settings.add(new OOPair(CHAR_ESCAPEMENT, (Short) newValue)); } From 638c0ffb5ce7d5d9aecb69d0cf71926cefae60c2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 13:22:44 +0200 Subject: [PATCH 0884/1068] use longer names --- .../java/org/jabref/logic/openoffice/OOTextIntoOO.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 24c6685d870..d0e90fc6fa0 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -790,14 +790,14 @@ private static List> setSuperScript(MyPropertyStack forma /* * @return true on failure */ - public static boolean setParagraphStyle(XTextCursor cursor, String parStyle) { + public static boolean setParagraphStyle(XTextCursor cursor, String paragraphStyle) { final boolean FAIL = true; final boolean PASS = false; - XParagraphCursor parCursor = UnoCast.unoQI(XParagraphCursor.class, cursor); - XPropertySet props = UnoCast.unoQI(XPropertySet.class, parCursor); + XParagraphCursor paragraphCursor = UnoCast.unoQI(XParagraphCursor.class, cursor); + XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, paragraphCursor); try { - props.setPropertyValue(PARA_STYLE_NAME, parStyle); + propertySet.setPropertyValue(PARA_STYLE_NAME, paragraphStyle); return PASS; } catch (UnknownPropertyException | PropertyVetoException From 46d653b5e9bcb50d72ac5d9e3efcbd7783b059fa Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 16:53:32 +0200 Subject: [PATCH 0885/1068] rename: kv -> pair --- .../jabref/logic/openoffice/OOTextIntoOO.java | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index d0e90fc6fa0..bf9c187eec8 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -232,9 +232,9 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) case "p": OOUtil.insertParagraphBreak(text, cursor); cursor.collapseToEnd(); - for (OOPair kv : attributes) { - String key = kv.a; - String value = kv.b; + for (OOPair pair : attributes) { + String key = pair.a; + String value = pair.b; switch (key) { case "oo:ParaStyleName": //

@@ -258,9 +258,9 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) } break; case "oo:referenceToPageNumberOfReferenceMark": - for (OOPair kv : attributes) { - String key = kv.a; - String value = kv.b; + for (OOPair pair : attributes) { + String key = pair.a; + String value = pair.b; switch (key) { case "target": UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); @@ -278,9 +278,9 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) break; case "span": List> settings = new ArrayList<>(); - for (OOPair kv : attributes) { - String key = kv.a; - String value = kv.b; + for (OOPair pair : attributes) { + String key = pair.a; + String value = pair.b; switch (key) { case "oo:CharStyleName": // @@ -509,8 +509,8 @@ static class MyPropertyStack { this.goodSize = nextIndex; this.goodNames = new String[goodSize]; - for (Map.Entry kv : goodNameToIndex.entrySet()) { - goodNames[ kv.getValue() ] = kv.getKey(); + for (Map.Entry entry : goodNameToIndex.entrySet()) { + goodNames[ entry.getValue() ] = entry.getKey(); } // XMultiPropertySet.setPropertyValues() @@ -554,14 +554,14 @@ static class MyPropertyStack { void pushLayer(List> settings) { ArrayList> oldLayer = layers.peek(); ArrayList> newLayer = new ArrayList<>(oldLayer); - for (OOPair kv : settings) { - String name = kv.a; + for (OOPair pair : settings) { + String name = pair.a; Integer i = goodNameToIndex.get(name); if (i == null) { LOGGER.warn(String.format("pushLayer: '%s' is not in goodNameToIndex", name)); continue; } - Object newValue = kv.b; + Object newValue = pair.b; newLayer.set(i, Optional.ofNullable(newValue)); } layers.push(newLayer); From f80447c0e105ae6bf10dbc1f094de621f03fa3de Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 17:37:44 +0200 Subject: [PATCH 0886/1068] drop OOListUtil.flatMap --- src/main/java/org/jabref/logic/openoffice/Backend52.java | 7 ++++--- src/main/java/org/jabref/logic/openoffice/EditMerge.java | 5 ++++- src/main/java/org/jabref/model/oostyle/OOListUtil.java | 4 ---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 8657bcb67f9..5482efbe0f7 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -303,9 +303,10 @@ public CitationGroup createCitationGroup(XTextDocument doc, return OODataModel.fakePageInfos(cgPageInfo, nCitations); case JabRef53: - return OOListUtil.flatMap(joinableGroup, - cg -> OOListUtil.map(cg.citationsInStorageOrder, - cit -> cit.getPageInfo())); + return (joinableGroup.stream() + .flatMap(cg -> (cg.citationsInStorageOrder.stream() + .map(Citation::getPageInfo))) + .collect(Collectors.toList())); default: throw new RuntimeException("unhandled dataModel here"); } diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 005bbfb9781..d89d29c5a61 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -67,7 +67,10 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBi List cgs = joinableGroupData.group; - List newCitations = OOListUtil.flatMap(cgs, cg -> cg.citationsInStorageOrder); + List newCitations = (cgs.stream() + .flatMap(cg -> cg.citationsInStorageOrder.stream()) + .collect(Collectors.toList())); + CitationType citationType = cgs.get(0).citationType; List> pageInfos = fr.backend.combinePageInfos(cgs); diff --git a/src/main/java/org/jabref/model/oostyle/OOListUtil.java b/src/main/java/org/jabref/model/oostyle/OOListUtil.java index 47e37fb3c14..b7c11e1269e 100644 --- a/src/main/java/org/jabref/model/oostyle/OOListUtil.java +++ b/src/main/java/org/jabref/model/oostyle/OOListUtil.java @@ -13,10 +13,6 @@ public static List map(List list, Function fun) { return list.stream().map(e -> fun.apply(e)).collect(Collectors.toList()); } - public static List flatMap(List list, Function> fun) { - return list.stream().flatMap(e -> fun.apply(e).stream()).collect(Collectors.toList()); - } - /** Integers 0..(n-1) */ public static List makeIndices(int n) { return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); From 42463e8d492d0851b7d631350fbcd7b6539bef98 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 17:51:34 +0200 Subject: [PATCH 0887/1068] use OOListUtil.map --- src/main/java/org/jabref/logic/openoffice/EditMerge.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index d89d29c5a61..50d098d8fe0 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -78,9 +78,7 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBi XTextCursor textCursor = joinableGroupData.groupCursor; textCursor.setString(""); // Also remove the spaces between. - List citationKeys = (newCitations.stream() - .map(cit -> cit.citationKey) - .collect(Collectors.toList())); + List citationKeys = OOListUtil.map(newCitations, Citation::getCitationKey); /* insertSpaceAfter: no, it is already there (or could be) */ boolean insertSpaceAfter = false; From 8c971a2637450a2cdc6bf46ad0319754efc807a8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 18:38:39 +0200 Subject: [PATCH 0888/1068] move model.oostyle to model.openoffice.style --- .../org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- .../gui/openoffice/OpenOfficePanel.java | 2 +- .../org/jabref/logic/oostyle/OOBibStyle.java | 16 +++++++-------- .../oostyle/OOBibStyleGetCitationMarker.java | 12 +++++------ .../OOBibStyleGetNumCitationMarker.java | 10 +++++----- .../org/jabref/logic/oostyle/OOFormat.java | 2 +- .../logic/oostyle/OOFormatBibliography.java | 14 ++++++------- .../org/jabref/logic/oostyle/OOProcess.java | 2 +- .../oostyle/OOProcessAuthorYearMarkers.java | 20 +++++++++---------- .../oostyle/OOProcessCitationKeyMarkers.java | 10 +++++----- .../oostyle/OOProcessNumericMarkers.java | 10 +++++----- .../jabref/logic/openoffice/Backend52.java | 18 ++++++++--------- .../org/jabref/logic/openoffice/Codec52.java | 2 +- .../jabref/logic/openoffice/EditInsert.java | 14 ++++++------- .../jabref/logic/openoffice/EditMerge.java | 10 +++++----- .../jabref/logic/openoffice/EditSeparate.java | 6 +++--- .../jabref/logic/openoffice/ExportCited.java | 4 ++-- .../jabref/logic/openoffice/OOFrontend.java | 14 ++++++------- .../jabref/logic/openoffice/OOTextIntoOO.java | 4 ++-- .../logic/openoffice/UpdateBibliography.java | 4 ++-- .../openoffice/UpdateCitationMarkers.java | 8 ++++---- .../style}/Citation.java | 2 +- .../style}/CitationGroup.java | 2 +- .../style}/CitationGroupId.java | 2 +- .../style}/CitationGroups.java | 2 +- .../style}/CitationLookupResult.java | 2 +- .../style}/CitationMarkerEntry.java | 2 +- .../style}/CitationMarkerNormEntry.java | 2 +- .../style}/CitationMarkerNumericBibEntry.java | 2 +- .../style}/CitationMarkerNumericEntry.java | 2 +- .../style}/CitationPath.java | 2 +- .../style}/CitationType.java | 2 +- .../style}/CitedKey.java | 2 +- .../style}/CitedKeys.java | 2 +- .../style}/ComparableCitation.java | 2 +- .../style}/ComparableCitedKey.java | 2 +- .../style}/CompareCitation.java | 2 +- .../style}/CompareCitedKey.java | 2 +- .../style}/NonUniqueCitationMarker.java | 2 +- .../style}/OODataModel.java | 2 +- .../style}/OOListUtil.java | 2 +- .../{oostyle => openoffice/style}/OOPair.java | 2 +- .../{oostyle => openoffice/style}/OOText.java | 2 +- .../style}/PageInfo.java | 2 +- .../jabref/logic/oostyle/OOBibStyleTest.java | 16 +++++++-------- 45 files changed, 124 insertions(+), 124 deletions(-) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/Citation.java (98%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitationGroup.java (99%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitationGroupId.java (89%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitationGroups.java (99%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitationLookupResult.java (96%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitationMarkerEntry.java (94%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitationMarkerNormEntry.java (93%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitationMarkerNumericBibEntry.java (88%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitationMarkerNumericEntry.java (87%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitationPath.java (89%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitationType.java (90%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitedKey.java (98%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CitedKeys.java (98%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/ComparableCitation.java (85%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/ComparableCitedKey.java (85%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CompareCitation.java (95%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/CompareCitedKey.java (96%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/NonUniqueCitationMarker.java (87%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/OODataModel.java (95%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/OOListUtil.java (96%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/OOPair.java (77%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/OOText.java (95%) rename src/main/java/org/jabref/model/{oostyle => openoffice/style}/PageInfo.java (96%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index d4ee109a804..11cc7d1c9a3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -29,14 +29,14 @@ import org.jabref.logic.openoffice.Update; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.CitationGroupId; -import org.jabref.model.oostyle.CitationType; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.OOResult; import org.jabref.model.openoffice.OOVoidResult; import org.jabref.model.openoffice.RangeForOverlapCheck; +import org.jabref.model.openoffice.style.CitationGroupId; +import org.jabref.model.openoffice.style.CitationType; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 7b482ea1d67..300cb405e8b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -51,8 +51,8 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.CitationType; import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.style.CitationType; import org.jabref.preferences.PreferencesService; import com.sun.star.comp.helper.BootstrapException; diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 12448479dfc..97d869be386 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -30,14 +30,14 @@ 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.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.CitationMarkerNormEntry; -import org.jabref.model.oostyle.CitationMarkerNumericBibEntry; -import org.jabref.model.oostyle.CitationMarkerNumericEntry; -import org.jabref.model.oostyle.NonUniqueCitationMarker; -import org.jabref.model.oostyle.OOListUtil; -import org.jabref.model.oostyle.OOText; -import org.jabref.model.oostyle.PageInfo; +import org.jabref.model.openoffice.style.CitationMarkerEntry; +import org.jabref.model.openoffice.style.CitationMarkerNormEntry; +import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; +import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; +import org.jabref.model.openoffice.style.NonUniqueCitationMarker; +import org.jabref.model.openoffice.style.OOListUtil; +import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.style.PageInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java index 484799ea36f..af5736b0819 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java @@ -12,12 +12,12 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; -import org.jabref.model.oostyle.CitationLookupResult; -import org.jabref.model.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.CitationMarkerNormEntry; -import org.jabref.model.oostyle.NonUniqueCitationMarker; -import org.jabref.model.oostyle.OOText; -import org.jabref.model.oostyle.PageInfo; +import org.jabref.model.openoffice.style.CitationLookupResult; +import org.jabref.model.openoffice.style.CitationMarkerEntry; +import org.jabref.model.openoffice.style.CitationMarkerNormEntry; +import org.jabref.model.openoffice.style.NonUniqueCitationMarker; +import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.style.PageInfo; import org.jabref.model.strings.StringUtil; class OOBibStyleGetCitationMarker { diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index 3d2cfaccd68..da7f12a438b 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -4,11 +4,11 @@ import java.util.List; import java.util.Optional; -import org.jabref.model.oostyle.CitationMarkerNumericBibEntry; -import org.jabref.model.oostyle.CitationMarkerNumericEntry; -import org.jabref.model.oostyle.OOListUtil; -import org.jabref.model.oostyle.OOText; -import org.jabref.model.oostyle.PageInfo; +import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; +import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; +import org.jabref.model.openoffice.style.OOListUtil; +import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.style.PageInfo; class OOBibStyleGetNumCitationMarker { diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/oostyle/OOFormat.java index d45be75b20f..ddcec9ebb31 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormat.java @@ -1,6 +1,6 @@ package org.jabref.logic.oostyle; -import org.jabref.model.oostyle.OOText; +import org.jabref.model.openoffice.style.OOText; public class OOFormat { diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java index e91f65d1ef5..0322dfd2b7e 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java @@ -10,13 +10,13 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.UnknownField; -import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupId; -import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.CitationPath; -import org.jabref.model.oostyle.CitedKey; -import org.jabref.model.oostyle.CitedKeys; -import org.jabref.model.oostyle.OOText; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.CitationGroupId; +import org.jabref.model.openoffice.style.CitationGroups; +import org.jabref.model.openoffice.style.CitationPath; +import org.jabref.model.openoffice.style.CitedKey; +import org.jabref.model.openoffice.style.CitedKeys; +import org.jabref.model.openoffice.style.OOText; public class OOFormatBibliography { private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/oostyle/OOProcess.java index 9899d306fb6..b34e60a8833 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcess.java @@ -9,7 +9,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; -import org.jabref.model.oostyle.CitationGroups; +import org.jabref.model.openoffice.style.CitationGroups; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java index 683450c5da6..ed5fe729df6 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java @@ -8,16 +8,16 @@ import java.util.Optional; import java.util.Set; -import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.CitationType; -import org.jabref.model.oostyle.CitedKey; -import org.jabref.model.oostyle.CitedKeys; -import org.jabref.model.oostyle.NonUniqueCitationMarker; -import org.jabref.model.oostyle.OOListUtil; -import org.jabref.model.oostyle.OOText; +import org.jabref.model.openoffice.style.Citation; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.CitationGroups; +import org.jabref.model.openoffice.style.CitationMarkerEntry; +import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.style.CitedKey; +import org.jabref.model.openoffice.style.CitedKeys; +import org.jabref.model.openoffice.style.NonUniqueCitationMarker; +import org.jabref.model.openoffice.style.OOListUtil; +import org.jabref.model.openoffice.style.OOText; class OOProcessAuthorYearMarkers { diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java index 70a7118f43c..d6e4d13906f 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java @@ -2,11 +2,11 @@ import java.util.Optional; -import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.OOListUtil; -import org.jabref.model.oostyle.OOText; +import org.jabref.model.openoffice.style.Citation; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.CitationGroups; +import org.jabref.model.openoffice.style.OOListUtil; +import org.jabref.model.openoffice.style.OOText; class OOProcessCitationKeyMarkers { /** diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java index d8f964d6656..1a3802a4020 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java @@ -3,11 +3,11 @@ import java.util.List; import java.util.Optional; -import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.CitationMarkerNumericEntry; -import org.jabref.model.oostyle.OOListUtil; -import org.jabref.model.oostyle.OOText; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.CitationGroups; +import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; +import org.jabref.model.openoffice.style.OOListUtil; +import org.jabref.model.openoffice.style.OOText; class OOProcessNumericMarkers { diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 5482efbe0f7..f05e563931b 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -10,20 +10,20 @@ import java.util.Set; import java.util.stream.Collectors; -import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupId; -import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.CitationType; -import org.jabref.model.oostyle.OODataModel; -import org.jabref.model.oostyle.OOListUtil; -import org.jabref.model.oostyle.OOText; -import org.jabref.model.oostyle.PageInfo; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NamedRange; import org.jabref.model.openoffice.NamedRangeManager; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.style.Citation; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.CitationGroupId; +import org.jabref.model.openoffice.style.CitationGroups; +import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.style.OODataModel; +import org.jabref.model.openoffice.style.OOListUtil; +import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.style.PageInfo; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/Codec52.java index 01560ac2fa0..47004cecc3f 100644 --- a/src/main/java/org/jabref/logic/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/Codec52.java @@ -9,8 +9,8 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; -import org.jabref.model.oostyle.CitationType; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.style.CitationType; /** * How and what is encoded in a mark names. diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index c4ab7852f75..41e84b7a46c 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -9,15 +9,15 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.CitationType; -import org.jabref.model.oostyle.NonUniqueCitationMarker; -import org.jabref.model.oostyle.OODataModel; -import org.jabref.model.oostyle.OOListUtil; -import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.style.Citation; +import org.jabref.model.openoffice.style.CitationMarkerEntry; +import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.style.NonUniqueCitationMarker; +import org.jabref.model.openoffice.style.OODataModel; +import org.jabref.model.openoffice.style.OOListUtil; +import org.jabref.model.openoffice.style.OOText; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 50d098d8fe0..fe9b51f6cfe 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -8,13 +8,13 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationType; -import org.jabref.model.oostyle.OOListUtil; -import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.style.Citation; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.style.OOListUtil; +import org.jabref.model.openoffice.style.OOText; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index ae1ce5da652..27cb6e23132 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -6,11 +6,11 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOProcess; import org.jabref.model.database.BibDatabase; -import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.style.Citation; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.OOText; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/ExportCited.java index 5b14e78d645..362a4a2957c 100644 --- a/src/main/java/org/jabref/logic/openoffice/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/ExportCited.java @@ -8,9 +8,9 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; -import org.jabref.model.oostyle.CitedKey; -import org.jabref.model.oostyle.CitedKeys; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.style.CitedKey; +import org.jabref.model.openoffice.style.CitedKeys; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index d51fbbb4af5..3d8a73caabe 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -11,13 +11,6 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroupId; -import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.CitationType; -import org.jabref.model.oostyle.OODataModel; -import org.jabref.model.oostyle.OOListUtil; -import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; @@ -28,6 +21,13 @@ import org.jabref.model.openoffice.RangeOverlap; import org.jabref.model.openoffice.RangeSortEntry; import org.jabref.model.openoffice.RangeSortable; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.CitationGroupId; +import org.jabref.model.openoffice.style.CitationGroups; +import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.style.OODataModel; +import org.jabref.model.openoffice.style.OOListUtil; +import org.jabref.model.openoffice.style.OOText; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index bf9c187eec8..084a8139d55 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -13,9 +13,9 @@ import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.model.oostyle.OOPair; -import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.style.OOPair; +import org.jabref.model.openoffice.style.OOText; import com.sun.star.awt.FontSlant; import com.sun.star.awt.FontStrikeout; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java index 1caf2bf814c..70d534c9ba7 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -4,10 +4,10 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOFormatBibliography; -import org.jabref.model.oostyle.CitedKeys; -import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.style.CitedKeys; +import org.jabref.model.openoffice.style.OOText; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 38a884c861d..33ff9766db5 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -6,12 +6,12 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.model.oostyle.CitationGroup; -import org.jabref.model.oostyle.CitationGroups; -import org.jabref.model.oostyle.CitationType; -import org.jabref.model.oostyle.OOText; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.CitationGroups; +import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.style.OOText; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/model/oostyle/Citation.java b/src/main/java/org/jabref/model/openoffice/style/Citation.java similarity index 98% rename from src/main/java/org/jabref/model/oostyle/Citation.java rename to src/main/java/org/jabref/model/openoffice/style/Citation.java index e8eda6ffd07..27bf7729c17 100644 --- a/src/main/java/org/jabref/model/oostyle/Citation.java +++ b/src/main/java/org/jabref/model/openoffice/style/Citation.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.List; import java.util.Optional; diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroup.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java similarity index 99% rename from src/main/java/org/jabref/model/oostyle/CitationGroup.java rename to src/main/java/org/jabref/model/openoffice/style/CitationGroup.java index 778864cac96..c6eced80502 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroup.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Collections; import java.util.Comparator; diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroupId.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java similarity index 89% rename from src/main/java/org/jabref/model/oostyle/CitationGroupId.java rename to src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java index 1c26696bf09..bac1e3c1387 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroupId.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; /** * Identifies a citation group in a document. diff --git a/src/main/java/org/jabref/model/oostyle/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java similarity index 99% rename from src/main/java/org/jabref/model/oostyle/CitationGroups.java rename to src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index 038e6514962..658c5067821 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.ArrayList; import java.util.Comparator; diff --git a/src/main/java/org/jabref/model/oostyle/CitationLookupResult.java b/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java similarity index 96% rename from src/main/java/org/jabref/model/oostyle/CitationLookupResult.java rename to src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java index 82c886a9037..866a0de34c3 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationLookupResult.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Objects; diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java similarity index 94% rename from src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java rename to src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java index abe38ed2081..108e8b72217 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Optional; diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNormEntry.java similarity index 93% rename from src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java rename to src/main/java/org/jabref/model/openoffice/style/CitationMarkerNormEntry.java index a8b9685ae3f..e9df5ec961f 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNormEntry.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNormEntry.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Optional; diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericBibEntry.java similarity index 88% rename from src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java rename to src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericBibEntry.java index 3c5e3f1e4d4..398282113b8 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericBibEntry.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericBibEntry.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Optional; diff --git a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericEntry.java similarity index 87% rename from src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java rename to src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericEntry.java index b23ab17a988..aba47a7f902 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationMarkerNumericEntry.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericEntry.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Optional; diff --git a/src/main/java/org/jabref/model/oostyle/CitationPath.java b/src/main/java/org/jabref/model/openoffice/style/CitationPath.java similarity index 89% rename from src/main/java/org/jabref/model/oostyle/CitationPath.java rename to src/main/java/org/jabref/model/openoffice/style/CitationPath.java index 628fcba6d97..05aeb6547f6 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationPath.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationPath.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; /** * Identifies a citation with the citation group containing it and diff --git a/src/main/java/org/jabref/model/oostyle/CitationType.java b/src/main/java/org/jabref/model/openoffice/style/CitationType.java similarity index 90% rename from src/main/java/org/jabref/model/oostyle/CitationType.java rename to src/main/java/org/jabref/model/openoffice/style/CitationType.java index b2451f7d928..14189e903e3 100644 --- a/src/main/java/org/jabref/model/oostyle/CitationType.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationType.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; /* * Presentation types of citation groups. diff --git a/src/main/java/org/jabref/model/oostyle/CitedKey.java b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java similarity index 98% rename from src/main/java/org/jabref/model/oostyle/CitedKey.java rename to src/main/java/org/jabref/model/openoffice/style/CitedKey.java index 0afc9c35ba6..70410abcd4f 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/org/jabref/model/oostyle/CitedKeys.java b/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java similarity index 98% rename from src/main/java/org/jabref/model/oostyle/CitedKeys.java rename to src/main/java/org/jabref/model/openoffice/style/CitedKeys.java index 642fb07193a..898fadbebe9 100644 --- a/src/main/java/org/jabref/model/oostyle/CitedKeys.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.ArrayList; import java.util.Comparator; diff --git a/src/main/java/org/jabref/model/oostyle/ComparableCitation.java b/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java similarity index 85% rename from src/main/java/org/jabref/model/oostyle/ComparableCitation.java rename to src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java index 09df46110fd..14fe74743f1 100644 --- a/src/main/java/org/jabref/model/oostyle/ComparableCitation.java +++ b/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Optional; diff --git a/src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java b/src/main/java/org/jabref/model/openoffice/style/ComparableCitedKey.java similarity index 85% rename from src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java rename to src/main/java/org/jabref/model/openoffice/style/ComparableCitedKey.java index 6c04d560dcc..0d4c8e2efce 100644 --- a/src/main/java/org/jabref/model/oostyle/ComparableCitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/ComparableCitedKey.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Optional; diff --git a/src/main/java/org/jabref/model/oostyle/CompareCitation.java b/src/main/java/org/jabref/model/openoffice/style/CompareCitation.java similarity index 95% rename from src/main/java/org/jabref/model/oostyle/CompareCitation.java rename to src/main/java/org/jabref/model/openoffice/style/CompareCitation.java index 220b123e5df..916f8ec610c 100644 --- a/src/main/java/org/jabref/model/oostyle/CompareCitation.java +++ b/src/main/java/org/jabref/model/openoffice/style/CompareCitation.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Comparator; diff --git a/src/main/java/org/jabref/model/oostyle/CompareCitedKey.java b/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java similarity index 96% rename from src/main/java/org/jabref/model/oostyle/CompareCitedKey.java rename to src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java index a02341339ac..439d0556c2d 100644 --- a/src/main/java/org/jabref/model/oostyle/CompareCitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Comparator; import java.util.Optional; diff --git a/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java b/src/main/java/org/jabref/model/openoffice/style/NonUniqueCitationMarker.java similarity index 87% rename from src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java rename to src/main/java/org/jabref/model/openoffice/style/NonUniqueCitationMarker.java index 40eccf87c7c..e7d988ee216 100644 --- a/src/main/java/org/jabref/model/oostyle/NonUniqueCitationMarker.java +++ b/src/main/java/org/jabref/model/openoffice/style/NonUniqueCitationMarker.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; /** * What should createCitationMarker do if it discovers that diff --git a/src/main/java/org/jabref/model/oostyle/OODataModel.java b/src/main/java/org/jabref/model/openoffice/style/OODataModel.java similarity index 95% rename from src/main/java/org/jabref/model/oostyle/OODataModel.java rename to src/main/java/org/jabref/model/openoffice/style/OODataModel.java index ee223b9dbc2..c693b64e74a 100644 --- a/src/main/java/org/jabref/model/oostyle/OODataModel.java +++ b/src/main/java/org/jabref/model/openoffice/style/OODataModel.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/org/jabref/model/oostyle/OOListUtil.java b/src/main/java/org/jabref/model/openoffice/style/OOListUtil.java similarity index 96% rename from src/main/java/org/jabref/model/oostyle/OOListUtil.java rename to src/main/java/org/jabref/model/openoffice/style/OOListUtil.java index b7c11e1269e..9f193ae6725 100644 --- a/src/main/java/org/jabref/model/oostyle/OOListUtil.java +++ b/src/main/java/org/jabref/model/openoffice/style/OOListUtil.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Collections; import java.util.Comparator; diff --git a/src/main/java/org/jabref/model/oostyle/OOPair.java b/src/main/java/org/jabref/model/openoffice/style/OOPair.java similarity index 77% rename from src/main/java/org/jabref/model/oostyle/OOPair.java rename to src/main/java/org/jabref/model/openoffice/style/OOPair.java index ec50bd4417c..c77e81b08e3 100644 --- a/src/main/java/org/jabref/model/oostyle/OOPair.java +++ b/src/main/java/org/jabref/model/openoffice/style/OOPair.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; public class OOPair { public final A a; diff --git a/src/main/java/org/jabref/model/oostyle/OOText.java b/src/main/java/org/jabref/model/openoffice/style/OOText.java similarity index 95% rename from src/main/java/org/jabref/model/oostyle/OOText.java rename to src/main/java/org/jabref/model/openoffice/style/OOText.java index aca69dd9474..62d5b534f86 100644 --- a/src/main/java/org/jabref/model/oostyle/OOText.java +++ b/src/main/java/org/jabref/model/openoffice/style/OOText.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Objects; diff --git a/src/main/java/org/jabref/model/oostyle/PageInfo.java b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java similarity index 96% rename from src/main/java/org/jabref/model/oostyle/PageInfo.java rename to src/main/java/org/jabref/model/openoffice/style/PageInfo.java index 6ac269d31e1..e3e193632fa 100644 --- a/src/main/java/org/jabref/model/oostyle/PageInfo.java +++ b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java @@ -1,4 +1,4 @@ -package org.jabref.model.oostyle; +package org.jabref.model.openoffice.style; import java.util.Optional; diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index af7f01aae43..f0fd58e34e3 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -25,14 +25,14 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; -import org.jabref.model.oostyle.Citation; -import org.jabref.model.oostyle.CitationLookupResult; -import org.jabref.model.oostyle.CitationMarkerEntry; -import org.jabref.model.oostyle.CitationMarkerNumericBibEntry; -import org.jabref.model.oostyle.CitationMarkerNumericEntry; -import org.jabref.model.oostyle.NonUniqueCitationMarker; -import org.jabref.model.oostyle.OOText; -import org.jabref.model.oostyle.PageInfo; +import org.jabref.model.openoffice.style.Citation; +import org.jabref.model.openoffice.style.CitationLookupResult; +import org.jabref.model.openoffice.style.CitationMarkerEntry; +import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; +import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; +import org.jabref.model.openoffice.style.NonUniqueCitationMarker; +import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.style.PageInfo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; From 77eb551cb3e6a91f58fc0e8be9864bf247b4d442 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 18:44:41 +0200 Subject: [PATCH 0889/1068] drop unused insertTextAtCurrentLocation --- .../java/org/jabref/logic/openoffice/OOUtil.java | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 1a09c083e49..c07b045eb63 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -28,18 +28,6 @@ public static void insertParagraphBreak(XText text, XTextCursor cursor) text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); } - public static void insertTextAtCurrentLocation(XTextCursor cursor, String string) - throws - UnknownPropertyException, - PropertyVetoException, - WrappedTargetException, - IllegalArgumentException, - NoSuchElementException { - XText text = cursor.getText(); - text.insertString(cursor, string, true); - cursor.collapseToEnd(); - } - /** * Get the text belonging to cursor with up to * charBefore and charAfter characters of context. From a504eb9fc03a84c94341281056cf15e82844aa95 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 19:56:25 +0200 Subject: [PATCH 0890/1068] move insertParagraphBreak where it is used --- .../java/org/jabref/logic/openoffice/OOTextIntoOO.java | 8 +++++++- src/main/java/org/jabref/logic/openoffice/OOUtil.java | 10 ---------- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 084a8139d55..fc672362938 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -35,6 +35,7 @@ import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.style.CaseMap; +import com.sun.star.text.ControlCharacter; import com.sun.star.text.XParagraphCursor; import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; @@ -230,7 +231,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) // nop break; case "p": - OOUtil.insertParagraphBreak(text, cursor); + insertParagraphBreak(text, cursor); cursor.collapseToEnd(); for (OOPair pair : attributes) { String key = pair.a; @@ -807,4 +808,9 @@ public static boolean setParagraphStyle(XTextCursor cursor, String paragraphStyl } } + private static void insertParagraphBreak(XText text, XTextCursor cursor) + throws IllegalArgumentException { + text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); + } + } diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index c07b045eb63..4dc5b89c884 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -2,12 +2,7 @@ import org.jabref.model.openoffice.NoDocumentException; -import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.ControlCharacter; -import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,11 +18,6 @@ private OOUtil() { // Just to hide the public constructor } - public static void insertParagraphBreak(XText text, XTextCursor cursor) - throws IllegalArgumentException { - text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); - } - /** * Get the text belonging to cursor with up to * charBefore and charAfter characters of context. From 46e6c06a146bfee0008661f93566903fc9ef65e9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 20:05:27 +0200 Subject: [PATCH 0891/1068] move OOListUtil to model/openoffice/util --- src/main/java/org/jabref/logic/oostyle/OOBibStyle.java | 2 +- .../jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java | 2 +- .../org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java | 2 +- .../org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java | 2 +- .../java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java | 2 +- src/main/java/org/jabref/logic/openoffice/Backend52.java | 2 +- src/main/java/org/jabref/logic/openoffice/EditInsert.java | 2 +- src/main/java/org/jabref/logic/openoffice/EditMerge.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 2 +- .../java/org/jabref/model/openoffice/style/CitationGroup.java | 1 + .../java/org/jabref/model/openoffice/style/CitationGroups.java | 1 + .../org/jabref/model/openoffice/{style => util}/OOListUtil.java | 2 +- 12 files changed, 12 insertions(+), 10 deletions(-) rename src/main/java/org/jabref/model/openoffice/{style => util}/OOListUtil.java (96%) diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java index 97d869be386..38cb049b388 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java @@ -35,9 +35,9 @@ import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; -import org.jabref.model.openoffice.style.OOListUtil; import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.style.PageInfo; +import org.jabref.model.openoffice.util.OOListUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java index da7f12a438b..df069c7d27b 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java @@ -6,9 +6,9 @@ import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; -import org.jabref.model.openoffice.style.OOListUtil; import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.style.PageInfo; +import org.jabref.model.openoffice.util.OOListUtil; class OOBibStyleGetNumCitationMarker { diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java index ed5fe729df6..11be85ee6b8 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java @@ -16,8 +16,8 @@ import org.jabref.model.openoffice.style.CitedKey; import org.jabref.model.openoffice.style.CitedKeys; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; -import org.jabref.model.openoffice.style.OOListUtil; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.util.OOListUtil; class OOProcessAuthorYearMarkers { diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java index d6e4d13906f..e9bdf8dfbb7 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java @@ -5,8 +5,8 @@ import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; -import org.jabref.model.openoffice.style.OOListUtil; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.util.OOListUtil; class OOProcessCitationKeyMarkers { /** diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java index 1a3802a4020..fc374548c43 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java @@ -6,8 +6,8 @@ import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; -import org.jabref.model.openoffice.style.OOListUtil; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.util.OOListUtil; class OOProcessNumericMarkers { diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index f05e563931b..626ca507704 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -21,9 +21,9 @@ import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.style.OODataModel; -import org.jabref.model.openoffice.style.OOListUtil; import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.style.PageInfo; +import org.jabref.model.openoffice.util.OOListUtil; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 41e84b7a46c..5d78aaa3402 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -16,8 +16,8 @@ import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.jabref.model.openoffice.style.OODataModel; -import org.jabref.model.openoffice.style.OOListUtil; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.util.OOListUtil; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index fe9b51f6cfe..59450d257d5 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -13,8 +13,8 @@ import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationType; -import org.jabref.model.openoffice.style.OOListUtil; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.util.OOListUtil; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 3d8a73caabe..39a5e5308c4 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -26,8 +26,8 @@ import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.style.OODataModel; -import org.jabref.model.openoffice.style.OOListUtil; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.util.OOListUtil; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java index c6eced80502..0755b7be024 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java @@ -6,6 +6,7 @@ import java.util.Optional; import org.jabref.model.entry.BibEntry; +import org.jabref.model.openoffice.util.OOListUtil; /** * A CitationGroup describes a group of citations. diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index 658c5067821..048229a1835 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -11,6 +11,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.openoffice.util.OOListUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/model/openoffice/style/OOListUtil.java b/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java similarity index 96% rename from src/main/java/org/jabref/model/openoffice/style/OOListUtil.java rename to src/main/java/org/jabref/model/openoffice/util/OOListUtil.java index 9f193ae6725..1fe617ed99a 100644 --- a/src/main/java/org/jabref/model/openoffice/style/OOListUtil.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.style; +package org.jabref.model.openoffice.util; import java.util.Collections; import java.util.Comparator; From b056fc31d751a115193ef3e5ff00588c9b7eb12c Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 20:10:02 +0200 Subject: [PATCH 0892/1068] move OOPair to model/openoffice/util --- src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java | 2 +- src/main/java/org/jabref/model/openoffice/style/Citation.java | 1 + .../java/org/jabref/model/openoffice/style/CitationGroups.java | 1 + .../org/jabref/model/openoffice/{style => util}/OOPair.java | 2 +- 4 files changed, 4 insertions(+), 2 deletions(-) rename src/main/java/org/jabref/model/openoffice/{style => util}/OOPair.java (77%) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index fc672362938..4cf488a9858 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -14,8 +14,8 @@ import org.jabref.architecture.AllowedToUseAwt; import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.style.OOPair; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.util.OOPair; import com.sun.star.awt.FontSlant; import com.sun.star.awt.FontStrikeout; diff --git a/src/main/java/org/jabref/model/openoffice/style/Citation.java b/src/main/java/org/jabref/model/openoffice/style/Citation.java index 27bf7729c17..7ce16a37352 100644 --- a/src/main/java/org/jabref/model/openoffice/style/Citation.java +++ b/src/main/java/org/jabref/model/openoffice/style/Citation.java @@ -5,6 +5,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.openoffice.util.OOPair; public class Citation implements ComparableCitation, CitationMarkerEntry, CitationMarkerNumericEntry { diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index 048229a1835..c2767c3108a 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -12,6 +12,7 @@ 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; diff --git a/src/main/java/org/jabref/model/openoffice/style/OOPair.java b/src/main/java/org/jabref/model/openoffice/util/OOPair.java similarity index 77% rename from src/main/java/org/jabref/model/openoffice/style/OOPair.java rename to src/main/java/org/jabref/model/openoffice/util/OOPair.java index c77e81b08e3..9d1596d19ef 100644 --- a/src/main/java/org/jabref/model/openoffice/style/OOPair.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOPair.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.style; +package org.jabref.model.openoffice.util; public class OOPair { public final A a; From 982ebf7cb42f7627c39813dbec1a1643753b210f Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 20:11:30 +0200 Subject: [PATCH 0893/1068] move comment --- .../org/jabref/logic/openoffice/OOTextIntoOO.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 4cf488a9858..26b4ed45ce2 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -360,13 +360,6 @@ public static void removeDirectFormatting(XTextCursor cursor) { XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); - /* - * Now that we have setAllPropertiesToDefault, check which properties - * are not set to default and try to correct what we can and seem necessary. - * - * Note: tested with LibreOffice : 6.4.6.2 - */ - XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); XPropertyState xPropertyState = UnoCast.unoQI(XPropertyState.class, cursor); @@ -383,6 +376,13 @@ public static void removeDirectFormatting(XTextCursor cursor) { mpss.setAllPropertiesToDefault(); + /* + * Now that we have called setAllPropertiesToDefault, check which properties + * are not set to default and try to correct what we can and seem necessary. + * + * Note: tested with LibreOffice : 6.4.6.2 + */ + // Only report those we do not yet know about final Set knownToFail = Set.of("ListAutoFormat", "ListId", From 8a909b00e751f7bcc857dbf0b715a2e2e3b61f8f Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 20:16:59 +0200 Subject: [PATCH 0894/1068] move OOResult, OOVoidResult to util --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 4 ++-- src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java | 2 +- .../org/jabref/logic/openoffice/FunctionalTextViewCursor.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 2 +- .../java/org/jabref/model/openoffice/{ => util}/OOResult.java | 2 +- .../org/jabref/model/openoffice/{ => util}/OOVoidResult.java | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) rename src/main/java/org/jabref/model/openoffice/{ => util}/OOResult.java (98%) rename src/main/java/org/jabref/model/openoffice/{ => util}/OOVoidResult.java (96%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 11cc7d1c9a3..007c85f0b70 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -32,11 +32,11 @@ import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; -import org.jabref.model.openoffice.OOResult; -import org.jabref.model.openoffice.OOVoidResult; import org.jabref.model.openoffice.RangeForOverlapCheck; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.util.OOResult; +import org.jabref.model.openoffice.util.OOVoidResult; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 7aae4fe4345..fd11cc7bb61 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -13,7 +13,7 @@ import org.jabref.logic.openoffice.UnoTextDocument; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; -import org.jabref.model.openoffice.OOResult; +import org.jabref.model.openoffice.util.OOResult; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; diff --git a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java index f26bf3174d9..7643f750f74 100644 --- a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java @@ -4,7 +4,7 @@ import java.util.Objects; import org.jabref.logic.JabRefException; -import org.jabref.model.openoffice.OOResult; +import org.jabref.model.openoffice.util.OOResult; import com.sun.star.lang.XServiceInfo; import com.sun.star.text.XTextDocument; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 39a5e5308c4..25bbe53a760 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -14,7 +14,6 @@ import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; -import org.jabref.model.openoffice.OOVoidResult; import org.jabref.model.openoffice.RangeForOverlapCheck; import org.jabref.model.openoffice.RangeKeyedMap; import org.jabref.model.openoffice.RangeKeyedMapList; @@ -28,6 +27,7 @@ import org.jabref.model.openoffice.style.OODataModel; import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.util.OOListUtil; +import org.jabref.model.openoffice.util.OOVoidResult; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/model/openoffice/OOResult.java b/src/main/java/org/jabref/model/openoffice/util/OOResult.java similarity index 98% rename from src/main/java/org/jabref/model/openoffice/OOResult.java rename to src/main/java/org/jabref/model/openoffice/util/OOResult.java index e6807407a50..1bc8cddcc13 100644 --- a/src/main/java/org/jabref/model/openoffice/OOResult.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOResult.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.util; import java.util.Optional; import java.util.function.Consumer; diff --git a/src/main/java/org/jabref/model/openoffice/OOVoidResult.java b/src/main/java/org/jabref/model/openoffice/util/OOVoidResult.java similarity index 96% rename from src/main/java/org/jabref/model/openoffice/OOVoidResult.java rename to src/main/java/org/jabref/model/openoffice/util/OOVoidResult.java index 5a8ee600682..a0bb0ebebe2 100644 --- a/src/main/java/org/jabref/model/openoffice/OOVoidResult.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOVoidResult.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.util; import java.util.Optional; import java.util.function.Consumer; From 5f060e5be74a23bdf38a898d2ce1dd17a862bb22 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 20:27:37 +0200 Subject: [PATCH 0895/1068] add model/openoffice/rangesort --- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 8 ++++---- .../org/jabref/logic/openoffice/RangeOverlapFinder.java | 2 +- .../java/org/jabref/logic/openoffice/RangeSortVisual.java | 2 +- .../model/openoffice/{ => rangesort}/RangeKeyedMap.java | 2 +- .../openoffice/{ => rangesort}/RangeKeyedMapList.java | 2 +- .../model/openoffice/{ => rangesort}/RangeSortEntry.java | 2 +- .../model/openoffice/{ => rangesort}/RangeSortable.java | 2 +- 7 files changed, 10 insertions(+), 10 deletions(-) rename src/main/java/org/jabref/model/openoffice/{ => rangesort}/RangeKeyedMap.java (98%) rename src/main/java/org/jabref/model/openoffice/{ => rangesort}/RangeKeyedMapList.java (95%) rename src/main/java/org/jabref/model/openoffice/{ => rangesort}/RangeSortEntry.java (94%) rename src/main/java/org/jabref/model/openoffice/{ => rangesort}/RangeSortable.java (92%) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 25bbe53a760..72dfa83bda8 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -15,11 +15,11 @@ import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.RangeForOverlapCheck; -import org.jabref.model.openoffice.RangeKeyedMap; -import org.jabref.model.openoffice.RangeKeyedMapList; import org.jabref.model.openoffice.RangeOverlap; -import org.jabref.model.openoffice.RangeSortEntry; -import org.jabref.model.openoffice.RangeSortable; +import org.jabref.model.openoffice.rangesort.RangeKeyedMap; +import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; +import org.jabref.model.openoffice.rangesort.RangeSortEntry; +import org.jabref.model.openoffice.rangesort.RangeSortable; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationGroups; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java b/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java index e78fd60c3ab..d0dec13faaa 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java @@ -4,9 +4,9 @@ import java.util.List; import java.util.TreeMap; -import org.jabref.model.openoffice.RangeKeyedMapList; import org.jabref.model.openoffice.RangeOverlap; import org.jabref.model.openoffice.RangeOverlapKind; +import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index 2c9abdcc324..c11b7f1a300 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -7,7 +7,7 @@ import java.util.TreeSet; import org.jabref.model.openoffice.NoDocumentException; -import org.jabref.model.openoffice.RangeSortable; +import org.jabref.model.openoffice.rangesort.RangeSortable; import com.sun.star.awt.Point; import com.sun.star.lang.WrappedTargetException; diff --git a/src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java similarity index 98% rename from src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java index 4f36fbae9cc..841b6f52355 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeKeyedMap.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java similarity index 95% rename from src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java index 13353442205..1c77986c35a 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/org/jabref/model/openoffice/RangeSortEntry.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java similarity index 94% rename from src/main/java/org/jabref/model/openoffice/RangeSortEntry.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java index e7a55bf4d54..4ed651e5396 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeSortEntry.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.rangesort; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/model/openoffice/RangeSortable.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java similarity index 92% rename from src/main/java/org/jabref/model/openoffice/RangeSortable.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java index 938cb1cdd0f..6b2c1fa9e8f 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeSortable.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.rangesort; import com.sun.star.text.XTextRange; From 3d47c16a87ec29f8e6abb7468787019b736696e0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 20:48:27 +0200 Subject: [PATCH 0896/1068] model/openoffice/rangeoverlap model/openoffice/uno --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- .../java/org/jabref/gui/openoffice/OOBibBaseConnect.java | 4 ++-- src/main/java/org/jabref/gui/openoffice/OOError.java | 2 +- .../java/org/jabref/gui/openoffice/OpenOfficePanel.java | 2 +- src/main/java/org/jabref/logic/openoffice/Backend52.java | 4 ++-- src/main/java/org/jabref/logic/openoffice/Codec52.java | 2 +- src/main/java/org/jabref/logic/openoffice/EditInsert.java | 4 ++-- src/main/java/org/jabref/logic/openoffice/EditMerge.java | 4 ++-- .../java/org/jabref/logic/openoffice/EditSeparate.java | 4 ++-- .../java/org/jabref/logic/openoffice/ExportCited.java | 2 +- .../java/org/jabref/logic/openoffice/ManageCitations.java | 2 +- .../logic/openoffice/NamedRangeManagerReferenceMark.java | 4 ++-- .../jabref/logic/openoffice/NamedRangeReferenceMark.java | 4 ++-- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 8 ++++---- .../java/org/jabref/logic/openoffice/OOTextIntoOO.java | 2 +- src/main/java/org/jabref/logic/openoffice/OOUtil.java | 2 +- .../org/jabref/logic/openoffice/RangeOverlapFinder.java | 4 ++-- .../java/org/jabref/logic/openoffice/RangeSortVisual.java | 2 +- .../java/org/jabref/logic/openoffice/UnoBookmark.java | 4 ++-- .../java/org/jabref/logic/openoffice/UnoCrossRef.java | 2 +- src/main/java/org/jabref/logic/openoffice/UnoNamed.java | 2 +- .../org/jabref/logic/openoffice/UnoReferenceMark.java | 4 ++-- .../java/org/jabref/logic/openoffice/UnoTextDocument.java | 2 +- .../java/org/jabref/logic/openoffice/UnoTextSection.java | 4 ++-- src/main/java/org/jabref/logic/openoffice/Update.java | 4 ++-- .../org/jabref/logic/openoffice/UpdateBibliography.java | 4 ++-- .../jabref/logic/openoffice/UpdateCitationMarkers.java | 4 ++-- src/main/java/org/jabref/model/openoffice/NamedRange.java | 3 +++ .../org/jabref/model/openoffice/NamedRangeManager.java | 3 +++ .../{ => rangeoverlap}/RangeForOverlapCheck.java | 2 +- .../model/openoffice/{ => rangeoverlap}/RangeOverlap.java | 2 +- .../openoffice/{ => rangeoverlap}/RangeOverlapKind.java | 2 +- .../model/openoffice/{ => uno}/CreationException.java | 2 +- .../model/openoffice/{ => uno}/NoDocumentException.java | 2 +- 34 files changed, 57 insertions(+), 51 deletions(-) rename src/main/java/org/jabref/model/openoffice/{ => rangeoverlap}/RangeForOverlapCheck.java (96%) rename src/main/java/org/jabref/model/openoffice/{ => rangeoverlap}/RangeOverlap.java (90%) rename src/main/java/org/jabref/model/openoffice/{ => rangeoverlap}/RangeOverlapKind.java (79%) rename src/main/java/org/jabref/model/openoffice/{ => uno}/CreationException.java (87%) rename src/main/java/org/jabref/model/openoffice/{ => uno}/NoDocumentException.java (84%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 007c85f0b70..3c1e4a73ba9 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -30,11 +30,11 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; -import org.jabref.model.openoffice.RangeForOverlapCheck; +import org.jabref.model.openoffice.rangeoverlap.RangeForOverlapCheck; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.util.OOResult; import org.jabref.model.openoffice.util.OOVoidResult; diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index fd11cc7bb61..ffbfa4d71e3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -11,8 +11,8 @@ import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.UnoCast; import org.jabref.logic.openoffice.UnoTextDocument; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.util.OOResult; import com.sun.star.comp.helper.BootstrapException; diff --git a/src/main/java/org/jabref/gui/openoffice/OOError.java b/src/main/java/org/jabref/gui/openoffice/OOError.java index e5b9d493bf4..44e70b3e975 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOError.java +++ b/src/main/java/org/jabref/gui/openoffice/OOError.java @@ -4,7 +4,7 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.NoDocumentFoundException; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.lang.DisposedException; diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 300cb405e8b..f9947a0dea8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -51,8 +51,8 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.uno.CreationException; import org.jabref.preferences.PreferencesService; import com.sun.star.comp.helper.BootstrapException; diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 626ca507704..820bb2d8ae3 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -11,10 +11,8 @@ import java.util.stream.Collectors; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NamedRange; import org.jabref.model.openoffice.NamedRangeManager; -import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroupId; @@ -23,6 +21,8 @@ import org.jabref.model.openoffice.style.OODataModel; import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.style.PageInfo; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.util.OOListUtil; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/logic/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/Codec52.java index 47004cecc3f..9df218c70e5 100644 --- a/src/main/java/org/jabref/logic/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/Codec52.java @@ -9,8 +9,8 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; -import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.uno.NoDocumentException; /** * How and what is encoded in a mark names. diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index 5d78aaa3402..e733f1103be 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -9,14 +9,14 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.jabref.model.openoffice.style.OODataModel; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.util.OOListUtil; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index 59450d257d5..beb1c5edbf1 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -8,12 +8,12 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.util.OOListUtil; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 27cb6e23132..0043094b024 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -6,11 +6,11 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOProcess; import org.jabref.model.database.BibDatabase; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/ExportCited.java index 362a4a2957c..efdb2a37ace 100644 --- a/src/main/java/org/jabref/logic/openoffice/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/ExportCited.java @@ -8,9 +8,9 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; -import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.style.CitedKey; import org.jabref.model.openoffice.style.CitedKeys; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; diff --git a/src/main/java/org/jabref/logic/openoffice/ManageCitations.java b/src/main/java/org/jabref/logic/openoffice/ManageCitations.java index 964e87d28f4..34f5de63ad3 100644 --- a/src/main/java/org/jabref/logic/openoffice/ManageCitations.java +++ b/src/main/java/org/jabref/logic/openoffice/ManageCitations.java @@ -3,7 +3,7 @@ import java.util.List; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java index 64011254e73..cdf3f4dea38 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java @@ -3,10 +3,10 @@ import java.util.List; import java.util.Optional; -import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NamedRange; import org.jabref.model.openoffice.NamedRangeManager; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java index 32ff32528d6..e9521114651 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java @@ -2,9 +2,9 @@ import java.util.Optional; -import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.NamedRange; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 72dfa83bda8..b13f9d437a8 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -12,10 +12,8 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; -import org.jabref.model.openoffice.RangeForOverlapCheck; -import org.jabref.model.openoffice.RangeOverlap; +import org.jabref.model.openoffice.rangeoverlap.RangeForOverlapCheck; +import org.jabref.model.openoffice.rangeoverlap.RangeOverlap; import org.jabref.model.openoffice.rangesort.RangeKeyedMap; import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; import org.jabref.model.openoffice.rangesort.RangeSortEntry; @@ -26,6 +24,8 @@ import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.style.OODataModel; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.util.OOListUtil; import org.jabref.model.openoffice.util.OOVoidResult; diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 26b4ed45ce2..5b2bb1638ff 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -13,8 +13,8 @@ import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.model.openoffice.CreationException; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.util.OOPair; import com.sun.star.awt.FontSlant; diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 4dc5b89c884..033c16e538a 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -1,6 +1,6 @@ package org.jabref.logic.openoffice; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java b/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java index d0dec13faaa..e493f513be3 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java @@ -4,8 +4,8 @@ import java.util.List; import java.util.TreeMap; -import org.jabref.model.openoffice.RangeOverlap; -import org.jabref.model.openoffice.RangeOverlapKind; +import org.jabref.model.openoffice.rangeoverlap.RangeOverlap; +import org.jabref.model.openoffice.rangeoverlap.RangeOverlapKind; import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index c11b7f1a300..24dbc86c606 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -6,8 +6,8 @@ import java.util.Set; import java.util.TreeSet; -import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.rangesort.RangeSortable; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.awt.Point; import com.sun.star.lang.WrappedTargetException; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java index 287a59eef9d..9803fdd439a 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java @@ -2,8 +2,8 @@ import java.util.Optional; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java b/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java index c7e8e09f1bb..e4cf2ff9702 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java @@ -1,6 +1,6 @@ package org.jabref.logic.openoffice; -import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.uno.CreationException; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoNamed.java b/src/main/java/org/jabref/logic/openoffice/UnoNamed.java index bd6459fa192..f12fab8807b 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoNamed.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoNamed.java @@ -1,6 +1,6 @@ package org.jabref.logic.openoffice; -import org.jabref.model.openoffice.CreationException; +import org.jabref.model.openoffice.uno.CreationException; import com.sun.star.container.XNamed; import com.sun.star.lang.XMultiServiceFactory; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java index 36c60d8f9d0..d90f2db0962 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java @@ -5,8 +5,8 @@ import java.util.List; import java.util.Optional; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java index 461b14fc26e..f60801d8a93 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java @@ -2,7 +2,7 @@ import java.util.Optional; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.beans.XPropertySet; import com.sun.star.document.XDocumentProperties; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java index fe02ccafebe..29d14f8d78d 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java +++ b/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java @@ -2,8 +2,8 @@ import java.util.Optional; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index 29eb5ce4638..8be0ff14e0e 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -6,8 +6,8 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOProcess; import org.jabref.model.database.BibDatabase; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java index 70d534c9ba7..77e79977c58 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -4,10 +4,10 @@ import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.oostyle.OOFormatBibliography; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.style.CitedKeys; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 33ff9766db5..7eea1441988 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -6,12 +6,12 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.model.openoffice.CreationException; -import org.jabref.model.openoffice.NoDocumentException; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/model/openoffice/NamedRange.java b/src/main/java/org/jabref/model/openoffice/NamedRange.java index 586a1e78141..c5f3d5afc1d 100644 --- a/src/main/java/org/jabref/model/openoffice/NamedRange.java +++ b/src/main/java/org/jabref/model/openoffice/NamedRange.java @@ -2,6 +2,9 @@ import java.util.Optional; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; + import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; diff --git a/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java b/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java index 06f27204475..53ef9b10f52 100644 --- a/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java +++ b/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java @@ -3,6 +3,9 @@ import java.util.List; import java.util.Optional; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; + import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; diff --git a/src/main/java/org/jabref/model/openoffice/RangeForOverlapCheck.java b/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeForOverlapCheck.java similarity index 96% rename from src/main/java/org/jabref/model/openoffice/RangeForOverlapCheck.java rename to src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeForOverlapCheck.java index 9d15f8c5fd5..6881db5a3d2 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeForOverlapCheck.java +++ b/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeForOverlapCheck.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.rangeoverlap; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/model/openoffice/RangeOverlap.java b/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlap.java similarity index 90% rename from src/main/java/org/jabref/model/openoffice/RangeOverlap.java rename to src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlap.java index 05e8b4251b3..fef6883d7e2 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeOverlap.java +++ b/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlap.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.rangeoverlap; import java.util.List; diff --git a/src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java b/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlapKind.java similarity index 79% rename from src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java rename to src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlapKind.java index 1c172d7da3f..d60d43a952d 100644 --- a/src/main/java/org/jabref/model/openoffice/RangeOverlapKind.java +++ b/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlapKind.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.rangeoverlap; public enum RangeOverlapKind { /** They share a boundary */ diff --git a/src/main/java/org/jabref/model/openoffice/CreationException.java b/src/main/java/org/jabref/model/openoffice/uno/CreationException.java similarity index 87% rename from src/main/java/org/jabref/model/openoffice/CreationException.java rename to src/main/java/org/jabref/model/openoffice/uno/CreationException.java index 5900f99c935..091d5469e2d 100644 --- a/src/main/java/org/jabref/model/openoffice/CreationException.java +++ b/src/main/java/org/jabref/model/openoffice/uno/CreationException.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.uno; /** * Exception used to indicate failure in either diff --git a/src/main/java/org/jabref/model/openoffice/NoDocumentException.java b/src/main/java/org/jabref/model/openoffice/uno/NoDocumentException.java similarity index 84% rename from src/main/java/org/jabref/model/openoffice/NoDocumentException.java rename to src/main/java/org/jabref/model/openoffice/uno/NoDocumentException.java index 09cc216fd12..20783e3a580 100644 --- a/src/main/java/org/jabref/model/openoffice/NoDocumentException.java +++ b/src/main/java/org/jabref/model/openoffice/uno/NoDocumentException.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.uno; public class NoDocumentException extends Exception { From 0b226e44eb88519c18c65b10a8ca1dadd9a2317a Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 20:54:37 +0200 Subject: [PATCH 0897/1068] model/openoffice/backend --- src/main/java/org/jabref/logic/openoffice/Backend52.java | 4 ++-- .../logic/openoffice/NamedRangeManagerReferenceMark.java | 4 ++-- .../org/jabref/logic/openoffice/NamedRangeReferenceMark.java | 2 +- .../org/jabref/model/openoffice/{ => backend}/NamedRange.java | 2 +- .../model/openoffice/{ => backend}/NamedRangeManager.java | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) rename src/main/java/org/jabref/model/openoffice/{ => backend}/NamedRange.java (97%) rename src/main/java/org/jabref/model/openoffice/{ => backend}/NamedRangeManager.java (95%) diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 820bb2d8ae3..6364eb8c2d8 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -11,8 +11,8 @@ import java.util.stream.Collectors; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.model.openoffice.NamedRange; -import org.jabref.model.openoffice.NamedRangeManager; +import org.jabref.model.openoffice.backend.NamedRange; +import org.jabref.model.openoffice.backend.NamedRangeManager; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroupId; diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java index cdf3f4dea38..fa6572a437d 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java @@ -3,8 +3,8 @@ import java.util.List; import java.util.Optional; -import org.jabref.model.openoffice.NamedRange; -import org.jabref.model.openoffice.NamedRangeManager; +import org.jabref.model.openoffice.backend.NamedRange; +import org.jabref.model.openoffice.backend.NamedRangeManager; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java index e9521114651..e2f0e67e5b9 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java @@ -2,7 +2,7 @@ import java.util.Optional; -import org.jabref.model.openoffice.NamedRange; +import org.jabref.model.openoffice.backend.NamedRange; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/model/openoffice/NamedRange.java b/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java similarity index 97% rename from src/main/java/org/jabref/model/openoffice/NamedRange.java rename to src/main/java/org/jabref/model/openoffice/backend/NamedRange.java index c5f3d5afc1d..e5c54773b07 100644 --- a/src/main/java/org/jabref/model/openoffice/NamedRange.java +++ b/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.backend; import java.util.Optional; diff --git a/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java b/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java similarity index 95% rename from src/main/java/org/jabref/model/openoffice/NamedRangeManager.java rename to src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java index 53ef9b10f52..f53fcc72527 100644 --- a/src/main/java/org/jabref/model/openoffice/NamedRangeManager.java +++ b/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice; +package org.jabref.model.openoffice.backend; import java.util.List; import java.util.Optional; From 4cd88ae62c24f54a52e9455511c623d1d2c2d927 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 20:59:29 +0200 Subject: [PATCH 0898/1068] OOBibStyleTest.java : Tuple23 class is static --- src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index f0fd58e34e3..fb9ec3a181c 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -135,7 +135,7 @@ public Optional getPageInfo() { } } - public class Tuple3 { + public static class Tuple3 { public final A a; public final B b; public final C c; From a277835182adb8987f15a84e4353250e01626a52 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 21:08:41 +0200 Subject: [PATCH 0899/1068] logic/openoffice/style --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 2 +- src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java | 4 ++-- .../java/org/jabref/gui/openoffice/StyleSelectDialogView.java | 4 ++-- .../org/jabref/gui/openoffice/StyleSelectDialogViewModel.java | 4 ++-- .../org/jabref/gui/openoffice/StyleSelectItemViewModel.java | 2 +- src/main/java/org/jabref/logic/layout/LayoutEntry.java | 2 +- src/main/java/org/jabref/logic/openoffice/EditInsert.java | 2 +- src/main/java/org/jabref/logic/openoffice/EditMerge.java | 2 +- src/main/java/org/jabref/logic/openoffice/EditSeparate.java | 4 ++-- src/main/java/org/jabref/logic/openoffice/Update.java | 4 ++-- .../java/org/jabref/logic/openoffice/UpdateBibliography.java | 4 ++-- .../org/jabref/logic/openoffice/UpdateCitationMarkers.java | 2 +- .../logic/{oostyle => openoffice/style}/OOBibStyle.java | 2 +- .../style}/OOBibStyleGetCitationMarker.java | 2 +- .../style}/OOBibStyleGetNumCitationMarker.java | 2 +- .../jabref/logic/{oostyle => openoffice/style}/OOFormat.java | 2 +- .../{oostyle => openoffice/style}/OOFormatBibliography.java | 2 +- .../logic/{oostyle => openoffice/style}/OOPreFormatter.java | 2 +- .../jabref/logic/{oostyle => openoffice/style}/OOProcess.java | 2 +- .../style}/OOProcessAuthorYearMarkers.java | 2 +- .../style}/OOProcessCitationKeyMarkers.java | 2 +- .../style}/OOProcessNumericMarkers.java | 2 +- .../logic/{oostyle => openoffice/style}/StyleLoader.java | 2 +- src/main/java/org/jabref/preferences/JabRefPreferences.java | 2 +- src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java | 2 +- .../java/org/jabref/logic/oostyle/OOPreFormatterTest.java | 2 +- src/test/java/org/jabref/logic/oostyle/StyleLoaderTest.java | 2 +- 27 files changed, 33 insertions(+), 33 deletions(-) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/OOBibStyle.java (99%) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/OOBibStyleGetCitationMarker.java (99%) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/OOBibStyleGetNumCitationMarker.java (99%) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/OOFormat.java (98%) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/OOFormatBibliography.java (99%) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/OOPreFormatter.java (99%) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/OOProcess.java (98%) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/OOProcessAuthorYearMarkers.java (99%) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/OOProcessCitationKeyMarkers.java (96%) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/OOProcessNumericMarkers.java (97%) rename src/main/java/org/jabref/logic/{oostyle => openoffice/style}/StyleLoader.java (99%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3c1e4a73ba9..388d43f6634 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -12,7 +12,6 @@ import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.oostyle.OOBibStyle; import org.jabref.logic.openoffice.EditInsert; import org.jabref.logic.openoffice.EditMerge; import org.jabref.logic.openoffice.EditSeparate; @@ -27,6 +26,7 @@ import org.jabref.logic.openoffice.UnoStyle; import org.jabref.logic.openoffice.UnoUndo; import org.jabref.logic.openoffice.Update; +import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index f9947a0dea8..437c51d7f56 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -43,11 +43,11 @@ import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.help.HelpFile; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.logic.oostyle.StyleLoader; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; import org.jabref.logic.openoffice.Update; +import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.logic.openoffice.style.StyleLoader; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java index 4570487d0ac..0465dfd0a41 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java @@ -20,8 +20,8 @@ import org.jabref.gui.util.ViewModelTableRowFactory; import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.TextBasedPreviewLayout; -import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.logic.oostyle.StyleLoader; +import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.logic.openoffice.style.StyleLoader; import org.jabref.logic.util.TestEntry; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.types.StandardEntryType; diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java index 4e93b2ffccf..abb37e87bd7 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java @@ -22,9 +22,9 @@ import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.logic.oostyle.StyleLoader; import org.jabref.logic.openoffice.OpenOfficePreferences; +import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.logic.openoffice.style.StyleLoader; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.PreferencesService; diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java index 1dc1c3bf1f3..af7390aeb65 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java @@ -9,7 +9,7 @@ import javafx.scene.Node; import org.jabref.gui.icon.IconTheme; -import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.openoffice.style.OOBibStyle; public class StyleSelectItemViewModel { diff --git a/src/main/java/org/jabref/logic/layout/LayoutEntry.java b/src/main/java/org/jabref/logic/layout/LayoutEntry.java index 2e1edd91103..8b3c98edb8d 100644 --- a/src/main/java/org/jabref/logic/layout/LayoutEntry.java +++ b/src/main/java/org/jabref/logic/layout/LayoutEntry.java @@ -80,7 +80,7 @@ import org.jabref.logic.layout.format.WrapContent; import org.jabref.logic.layout.format.WrapFileLinks; import org.jabref.logic.layout.format.XMLChars; -import org.jabref.logic.oostyle.OOPreFormatter; +import org.jabref.logic.openoffice.style.OOPreFormatter; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/EditInsert.java index e733f1103be..4173aaf5e11 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/EditInsert.java @@ -6,7 +6,7 @@ import java.util.Optional; import org.jabref.logic.JabRefException; -import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.style.Citation; diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index beb1c5edbf1..edb1118eafc 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -7,7 +7,7 @@ import java.util.stream.Collectors; import org.jabref.logic.JabRefException; -import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationType; diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 0043094b024..96bec047c05 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -3,8 +3,8 @@ import java.util.List; import org.jabref.logic.JabRefException; -import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.logic.oostyle.OOProcess; +import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.model.database.BibDatabase; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index 8be0ff14e0e..96309eea2d2 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -3,8 +3,8 @@ import java.util.List; import org.jabref.logic.JabRefException; -import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.logic.oostyle.OOProcess; +import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.model.database.BibDatabase; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java index 77e79977c58..96d3179b072 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -2,8 +2,8 @@ import java.util.Optional; -import org.jabref.logic.oostyle.OOBibStyle; -import org.jabref.logic.oostyle.OOFormatBibliography; +import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.logic.openoffice.style.OOFormatBibliography; import org.jabref.model.openoffice.style.CitedKeys; import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.uno.CreationException; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java index 7eea1441988..9578fa4e975 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java @@ -5,7 +5,7 @@ import java.util.Optional; import org.jabref.logic.JabRefException; -import org.jabref.logic.oostyle.OOBibStyle; +import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationType; diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java similarity index 99% rename from src/main/java/org/jabref/logic/oostyle/OOBibStyle.java rename to src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index 38cb049b388..fbc1d94a987 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java similarity index 99% rename from src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java rename to src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java index af5736b0819..d89c3e1a79a 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.util.ArrayList; import java.util.Collections; diff --git a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java similarity index 99% rename from src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java rename to src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java index df069c7d27b..2ceab557033 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormat.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormat.java similarity index 98% rename from src/main/java/org/jabref/logic/oostyle/OOFormat.java rename to src/main/java/org/jabref/logic/openoffice/style/OOFormat.java index ddcec9ebb31..67dc3102545 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormat.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormat.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import org.jabref.model.openoffice.style.OOText; diff --git a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java similarity index 99% rename from src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java rename to src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index 0322dfd2b7e..eae82cf7033 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/org/jabref/logic/oostyle/OOPreFormatter.java b/src/main/java/org/jabref/logic/openoffice/style/OOPreFormatter.java similarity index 99% rename from src/main/java/org/jabref/logic/oostyle/OOPreFormatter.java rename to src/main/java/org/jabref/logic/openoffice/style/OOPreFormatter.java index 1c413234c8f..dc02daf6ee9 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOPreFormatter.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOPreFormatter.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.util.Map; import java.util.Objects; diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcess.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java similarity index 98% rename from src/main/java/org/jabref/logic/oostyle/OOProcess.java rename to src/main/java/org/jabref/logic/openoffice/style/OOProcess.java index b34e60a8833..6f7709aac10 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcess.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.util.ArrayList; import java.util.Comparator; diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java similarity index 99% rename from src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java rename to src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index 11be85ee6b8..b909534a5cb 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java similarity index 96% rename from src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java rename to src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java index e9bdf8dfbb7..4986e03d058 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessCitationKeyMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java similarity index 97% rename from src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java rename to src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java index fc374548c43..dcbfec2c077 100644 --- a/src/main/java/org/jabref/logic/oostyle/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.util.List; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/oostyle/StyleLoader.java b/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java similarity index 99% rename from src/main/java/org/jabref/logic/oostyle/StyleLoader.java rename to src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java index 14f9710e4e8..727db88cbc4 100644 --- a/src/main/java/org/jabref/logic/oostyle/StyleLoader.java +++ b/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.io.File; import java.io.FileNotFoundException; diff --git a/src/main/java/org/jabref/preferences/JabRefPreferences.java b/src/main/java/org/jabref/preferences/JabRefPreferences.java index 7904745527a..ba5df0fa216 100644 --- a/src/main/java/org/jabref/preferences/JabRefPreferences.java +++ b/src/main/java/org/jabref/preferences/JabRefPreferences.java @@ -86,8 +86,8 @@ import org.jabref.logic.layout.format.FileLinkPreferences; import org.jabref.logic.layout.format.NameFormatterPreferences; import org.jabref.logic.net.ProxyPreferences; -import org.jabref.logic.oostyle.StyleLoader; import org.jabref.logic.openoffice.OpenOfficePreferences; +import org.jabref.logic.openoffice.style.StyleLoader; import org.jabref.logic.preferences.DOIPreferences; import org.jabref.logic.preferences.OwnerPreferences; import org.jabref.logic.preferences.TimestampPreferences; diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java index fb9ec3a181c..20095b5d16a 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.io.File; import java.io.IOException; diff --git a/src/test/java/org/jabref/logic/oostyle/OOPreFormatterTest.java b/src/test/java/org/jabref/logic/oostyle/OOPreFormatterTest.java index fb0ad8e5391..0478089a8dc 100644 --- a/src/test/java/org/jabref/logic/oostyle/OOPreFormatterTest.java +++ b/src/test/java/org/jabref/logic/oostyle/OOPreFormatterTest.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import org.junit.jupiter.api.Test; diff --git a/src/test/java/org/jabref/logic/oostyle/StyleLoaderTest.java b/src/test/java/org/jabref/logic/oostyle/StyleLoaderTest.java index 17f4104a001..9b5a58f4de5 100644 --- a/src/test/java/org/jabref/logic/oostyle/StyleLoaderTest.java +++ b/src/test/java/org/jabref/logic/oostyle/StyleLoaderTest.java @@ -1,4 +1,4 @@ -package org.jabref.logic.oostyle; +package org.jabref.logic.openoffice.style; import java.net.URISyntaxException; import java.nio.charset.Charset; From cffdf3cbdf1062163c94ab1f4da141d06164c07c Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 21:33:11 +0200 Subject: [PATCH 0900/1068] logic/openoffice/uno --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 10 +++++----- .../org/jabref/gui/openoffice/OOBibBaseConnect.java | 4 ++-- .../java/org/jabref/logic/openoffice/Backend52.java | 1 + .../java/org/jabref/logic/openoffice/EditMerge.java | 2 ++ .../java/org/jabref/logic/openoffice/EditSeparate.java | 1 + .../logic/openoffice/FunctionalTextViewCursor.java | 2 ++ .../openoffice/NamedRangeManagerReferenceMark.java | 1 + .../logic/openoffice/NamedRangeReferenceMark.java | 2 ++ .../java/org/jabref/logic/openoffice/OOFrontend.java | 2 ++ .../java/org/jabref/logic/openoffice/OOTextIntoOO.java | 2 ++ .../jabref/logic/openoffice/RangeOverlapFinder.java | 1 + .../org/jabref/logic/openoffice/RangeSortVisual.java | 1 + src/main/java/org/jabref/logic/openoffice/Update.java | 1 + .../jabref/logic/openoffice/UpdateBibliography.java | 2 ++ .../jabref/logic/openoffice/{ => uno}/UnoBookmark.java | 2 +- .../org/jabref/logic/openoffice/{ => uno}/UnoCast.java | 2 +- .../jabref/logic/openoffice/{ => uno}/UnoCrossRef.java | 2 +- .../jabref/logic/openoffice/{ => uno}/UnoCursor.java | 2 +- .../logic/openoffice/{ => uno}/UnoNameAccess.java | 2 +- .../jabref/logic/openoffice/{ => uno}/UnoNamed.java | 2 +- .../logic/openoffice/{ => uno}/UnoProperties.java | 2 +- .../jabref/logic/openoffice/{ => uno}/UnoRedlines.java | 2 +- .../logic/openoffice/{ => uno}/UnoReferenceMark.java | 2 +- .../logic/openoffice/{ => uno}/UnoScreenRefresh.java | 2 +- .../logic/openoffice/{ => uno}/UnoSelection.java | 2 +- .../jabref/logic/openoffice/{ => uno}/UnoStyle.java | 2 +- .../logic/openoffice/{ => uno}/UnoTextDocument.java | 2 +- .../logic/openoffice/{ => uno}/UnoTextRange.java | 2 +- .../logic/openoffice/{ => uno}/UnoTextSection.java | 2 +- .../org/jabref/logic/openoffice/{ => uno}/UnoUndo.java | 2 +- .../openoffice/{ => uno}/UnoUserDefinedProperty.java | 2 +- 31 files changed, 42 insertions(+), 24 deletions(-) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoBookmark.java (98%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoCast.java (93%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoCrossRef.java (98%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoCursor.java (97%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoNameAccess.java (94%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoNamed.java (98%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoProperties.java (98%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoRedlines.java (97%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoReferenceMark.java (99%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoScreenRefresh.java (95%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoSelection.java (99%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoStyle.java (98%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoTextDocument.java (98%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoTextRange.java (98%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoTextSection.java (98%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoUndo.java (97%) rename src/main/java/org/jabref/logic/openoffice/{ => uno}/UnoUserDefinedProperty.java (99%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 388d43f6634..e33fda62ed5 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -20,13 +20,13 @@ import org.jabref.logic.openoffice.ManageCitations; import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.OOFrontend; -import org.jabref.logic.openoffice.UnoCrossRef; -import org.jabref.logic.openoffice.UnoCursor; -import org.jabref.logic.openoffice.UnoRedlines; -import org.jabref.logic.openoffice.UnoStyle; -import org.jabref.logic.openoffice.UnoUndo; import org.jabref.logic.openoffice.Update; import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.logic.openoffice.uno.UnoCrossRef; +import org.jabref.logic.openoffice.uno.UnoCursor; +import org.jabref.logic.openoffice.uno.UnoRedlines; +import org.jabref.logic.openoffice.uno.UnoStyle; +import org.jabref.logic.openoffice.uno.UnoUndo; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index ffbfa4d71e3..31864e4212e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -9,8 +9,8 @@ import org.jabref.gui.DialogService; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.NoDocumentFoundException; -import org.jabref.logic.openoffice.UnoCast; -import org.jabref.logic.openoffice.UnoTextDocument; +import org.jabref.logic.openoffice.uno.UnoCast; +import org.jabref.logic.openoffice.uno.UnoTextDocument; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.util.OOResult; diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/Backend52.java index 6364eb8c2d8..8388222b0e8 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/Backend52.java @@ -10,6 +10,7 @@ import java.util.Set; import java.util.stream.Collectors; +import org.jabref.logic.openoffice.uno.UnoUserDefinedProperty; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.backend.NamedRange; import org.jabref.model.openoffice.backend.NamedRangeManager; diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/EditMerge.java index edb1118eafc..0c0a58da86a 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/EditMerge.java @@ -8,6 +8,8 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.logic.openoffice.uno.UnoScreenRefresh; +import org.jabref.logic.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationType; diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java index 96bec047c05..7200ba7e72d 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/EditSeparate.java @@ -5,6 +5,7 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; +import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.model.database.BibDatabase; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; diff --git a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java index 7643f750f74..77571611dcd 100644 --- a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java @@ -4,6 +4,8 @@ import java.util.Objects; import org.jabref.logic.JabRefException; +import org.jabref.logic.openoffice.uno.UnoCursor; +import org.jabref.logic.openoffice.uno.UnoSelection; import org.jabref.model.openoffice.util.OOResult; import com.sun.star.lang.XServiceInfo; diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java index fa6572a437d..1b72cf4e707 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java @@ -3,6 +3,7 @@ import java.util.List; import java.util.Optional; +import org.jabref.logic.openoffice.uno.UnoReferenceMark; import org.jabref.model.openoffice.backend.NamedRange; import org.jabref.model.openoffice.backend.NamedRangeManager; import org.jabref.model.openoffice.uno.CreationException; diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java index e2f0e67e5b9..ebfde136ef4 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java @@ -2,6 +2,8 @@ import java.util.Optional; +import org.jabref.logic.openoffice.uno.UnoCursor; +import org.jabref.logic.openoffice.uno.UnoReferenceMark; import org.jabref.model.openoffice.backend.NamedRange; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index b13f9d437a8..1684a48ea65 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -11,6 +11,8 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; +import org.jabref.logic.openoffice.uno.UnoCursor; +import org.jabref.logic.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.rangeoverlap.RangeForOverlapCheck; import org.jabref.model.openoffice.rangeoverlap.RangeOverlap; diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java index 5b2bb1638ff..a983d3b16ab 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java @@ -13,6 +13,8 @@ import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseAwt; +import org.jabref.logic.openoffice.uno.UnoCast; +import org.jabref.logic.openoffice.uno.UnoCrossRef; import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.util.OOPair; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java b/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java index e493f513be3..c05b043f22f 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.TreeMap; +import org.jabref.logic.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.rangeoverlap.RangeOverlap; import org.jabref.model.openoffice.rangeoverlap.RangeOverlapKind; import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java index 24dbc86c606..c5735c683b7 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java @@ -6,6 +6,7 @@ import java.util.Set; import java.util.TreeSet; +import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.model.openoffice.rangesort.RangeSortable; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/Update.java index 96309eea2d2..0a44cd78026 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/Update.java @@ -5,6 +5,7 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; +import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.model.database.BibDatabase; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java index 96d3179b072..f79db0c3455 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java @@ -4,6 +4,8 @@ import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOFormatBibliography; +import org.jabref.logic.openoffice.uno.UnoBookmark; +import org.jabref.logic.openoffice.uno.UnoTextSection; import org.jabref.model.openoffice.style.CitedKeys; import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.uno.CreationException; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoBookmark.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/UnoBookmark.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoBookmark.java index 9803fdd439a..784b4b1a4fb 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoBookmark.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoBookmark.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCast.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoCast.java similarity index 93% rename from src/main/java/org/jabref/logic/openoffice/UnoCast.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoCast.java index 77e1c8c7a1d..78acc423625 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoCast.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoCast.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoCrossRef.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoCrossRef.java index e4cf2ff9702..859b3a26b84 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoCrossRef.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoCrossRef.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import org.jabref.model.openoffice.uno.CreationException; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoCursor.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoCursor.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/UnoCursor.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoCursor.java index 2d5d6443b01..70fc8078a10 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoCursor.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoNameAccess.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoNameAccess.java similarity index 94% rename from src/main/java/org/jabref/logic/openoffice/UnoNameAccess.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoNameAccess.java index b8d26edfb0e..fd34b26f038 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoNameAccess.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoNameAccess.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoNamed.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoNamed.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/UnoNamed.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoNamed.java index f12fab8807b..19f7ad56f2d 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoNamed.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoNamed.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import org.jabref.model.openoffice.uno.CreationException; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoProperties.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoProperties.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/UnoProperties.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoProperties.java index b1d3c56a367..25ef7c75a9f 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoProperties.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoProperties.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoRedlines.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoRedlines.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/UnoRedlines.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoRedlines.java index 4589182d30a..94ec745cb73 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoRedlines.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoRedlines.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertySet; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoReferenceMark.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoReferenceMark.java index d90f2db0962..2c7e6db921e 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoReferenceMark.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoScreenRefresh.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoScreenRefresh.java similarity index 95% rename from src/main/java/org/jabref/logic/openoffice/UnoScreenRefresh.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoScreenRefresh.java index 92591f119b3..3212746cedc 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoScreenRefresh.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoScreenRefresh.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import com.sun.star.text.XTextDocument; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoSelection.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoSelection.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/UnoSelection.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoSelection.java index a5fb4290d0f..e4efad0ef5a 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoSelection.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoSelection.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.Objects; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoStyle.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoStyle.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/UnoStyle.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoStyle.java index 96f67e4dbe0..15b47c313d4 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoStyle.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoTextDocument.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoTextDocument.java index f60801d8a93..f23eb66adb1 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextDocument.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoTextDocument.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextRange.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoTextRange.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/UnoTextRange.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoTextRange.java index 8cd0d4fefe0..797007c1cc5 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextRange.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoTextRange.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoTextSection.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/UnoTextSection.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoTextSection.java index 29d14f8d78d..3d8c3279dc5 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoTextSection.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoTextSection.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoUndo.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoUndo.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/UnoUndo.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoUndo.java index 902b0eadf29..408ff2aa0f4 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoUndo.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoUndo.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java b/src/main/java/org/jabref/logic/openoffice/uno/UnoUserDefinedProperty.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java rename to src/main/java/org/jabref/logic/openoffice/uno/UnoUserDefinedProperty.java index c0d21bd73b4..1484706e6aa 100644 --- a/src/main/java/org/jabref/logic/openoffice/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/logic/openoffice/uno/UnoUserDefinedProperty.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.uno; import java.util.ArrayList; import java.util.List; From f85b2f75a268419d546ca4a135de6f3ed9a6cce5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 21:43:39 +0200 Subject: [PATCH 0901/1068] logic/openoffice/backend --- src/main/java/org/jabref/logic/openoffice/OOFrontend.java | 1 + .../org/jabref/logic/openoffice/{ => backend}/Backend52.java | 3 ++- .../org/jabref/logic/openoffice/{ => backend}/Codec52.java | 2 +- .../{ => backend}/NamedRangeManagerReferenceMark.java | 2 +- .../openoffice/{ => backend}/NamedRangeReferenceMark.java | 2 +- 5 files changed, 6 insertions(+), 4 deletions(-) rename src/main/java/org/jabref/logic/openoffice/{ => backend}/Backend52.java (99%) rename src/main/java/org/jabref/logic/openoffice/{ => backend}/Codec52.java (99%) rename src/main/java/org/jabref/logic/openoffice/{ => backend}/NamedRangeManagerReferenceMark.java (97%) rename src/main/java/org/jabref/logic/openoffice/{ => backend}/NamedRangeReferenceMark.java (99%) diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 1684a48ea65..72fe9c341a3 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -11,6 +11,7 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; +import org.jabref.logic.openoffice.backend.Backend52; import org.jabref.logic.openoffice.uno.UnoCursor; import org.jabref.logic.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.CitationEntry; diff --git a/src/main/java/org/jabref/logic/openoffice/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/Backend52.java rename to src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 8388222b0e8..68a7ebd4239 100644 --- a/src/main/java/org/jabref/logic/openoffice/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.backend; import java.util.ArrayList; import java.util.HashMap; @@ -10,6 +10,7 @@ import java.util.Set; import java.util.stream.Collectors; +import org.jabref.logic.openoffice.OOUtil; import org.jabref.logic.openoffice.uno.UnoUserDefinedProperty; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.backend.NamedRange; diff --git a/src/main/java/org/jabref/logic/openoffice/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/Codec52.java rename to src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index 9df218c70e5..352df27cdeb 100644 --- a/src/main/java/org/jabref/logic/openoffice/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.backend; import java.util.Arrays; import java.util.List; diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java rename to src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java index 1b72cf4e707..d53ae0b6685 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeManagerReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.backend; import java.util.List; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java rename to src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index ebfde136ef4..a4f9a6b68d8 100644 --- a/src/main/java/org/jabref/logic/openoffice/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.backend; import java.util.Optional; From 50f1438daac95235d80315e04edaace592871a0a Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 21:47:51 +0200 Subject: [PATCH 0902/1068] rename OOUtil -> backend/GetContext --- .../org/jabref/logic/openoffice/backend/Backend52.java | 3 +-- .../openoffice/{OOUtil.java => backend/GetContext.java} | 8 ++++---- 2 files changed, 5 insertions(+), 6 deletions(-) rename src/main/java/org/jabref/logic/openoffice/{OOUtil.java => backend/GetContext.java} (96%) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 68a7ebd4239..87d0c98e676 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -10,7 +10,6 @@ import java.util.Set; import java.util.stream.Collectors; -import org.jabref.logic.openoffice.OOUtil; import org.jabref.logic.openoffice.uno.UnoUserDefinedProperty; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.backend.NamedRange; @@ -412,7 +411,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups XTextCursor cursor = (this .getRawCursorForCitationGroup(cg, doc) .orElseThrow(RuntimeException::new)); - String context = OOUtil.getCursorStringWithContext(cursor, 30, 30, true); + String context = GetContext.getCursorStringWithContext(cursor, 30, 30, true); Optional pageInfo = (cg.numberOfCitations() > 0 ? (getPageInfoFromData(cg) .map(e -> OOText.toString(e))) diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/OOUtil.java rename to src/main/java/org/jabref/logic/openoffice/backend/GetContext.java index 033c16e538a..468d630e756 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.backend; import org.jabref.model.openoffice.uno.NoDocumentException; @@ -10,11 +10,11 @@ /** * Utility methods for processing OO Writer documents. */ -public class OOUtil { +public class GetContext { - private static final Logger LOGGER = LoggerFactory.getLogger(OOUtil.class); + private static final Logger LOGGER = LoggerFactory.getLogger(GetContext.class); - private OOUtil() { + private GetContext() { // Just to hide the public constructor } From dba71e3c0f172a03a2e88ff47a183822fae64d1a Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 22:10:55 +0200 Subject: [PATCH 0903/1068] adjust test and test/resources --- .../logic/{oostyle => openoffice/style}/OOBibStyleTest.java | 0 .../logic/{oostyle => openoffice/style}/OOPreFormatterTest.java | 0 .../logic/{oostyle => openoffice/style}/StyleLoaderTest.java | 0 .../org/jabref/logic/{oostyle => openoffice/style}/test.jstyle | 0 .../style}/testWithDefaultAtFirstLIne.jstyle | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename src/test/java/org/jabref/logic/{oostyle => openoffice/style}/OOBibStyleTest.java (100%) rename src/test/java/org/jabref/logic/{oostyle => openoffice/style}/OOPreFormatterTest.java (100%) rename src/test/java/org/jabref/logic/{oostyle => openoffice/style}/StyleLoaderTest.java (100%) rename src/test/resources/org/jabref/logic/{oostyle => openoffice/style}/test.jstyle (100%) rename src/test/resources/org/jabref/logic/{oostyle => openoffice/style}/testWithDefaultAtFirstLIne.jstyle (100%) diff --git a/src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java similarity index 100% rename from src/test/java/org/jabref/logic/oostyle/OOBibStyleTest.java rename to src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java diff --git a/src/test/java/org/jabref/logic/oostyle/OOPreFormatterTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOPreFormatterTest.java similarity index 100% rename from src/test/java/org/jabref/logic/oostyle/OOPreFormatterTest.java rename to src/test/java/org/jabref/logic/openoffice/style/OOPreFormatterTest.java diff --git a/src/test/java/org/jabref/logic/oostyle/StyleLoaderTest.java b/src/test/java/org/jabref/logic/openoffice/style/StyleLoaderTest.java similarity index 100% rename from src/test/java/org/jabref/logic/oostyle/StyleLoaderTest.java rename to src/test/java/org/jabref/logic/openoffice/style/StyleLoaderTest.java diff --git a/src/test/resources/org/jabref/logic/oostyle/test.jstyle b/src/test/resources/org/jabref/logic/openoffice/style/test.jstyle similarity index 100% rename from src/test/resources/org/jabref/logic/oostyle/test.jstyle rename to src/test/resources/org/jabref/logic/openoffice/style/test.jstyle diff --git a/src/test/resources/org/jabref/logic/oostyle/testWithDefaultAtFirstLIne.jstyle b/src/test/resources/org/jabref/logic/openoffice/style/testWithDefaultAtFirstLIne.jstyle similarity index 100% rename from src/test/resources/org/jabref/logic/oostyle/testWithDefaultAtFirstLIne.jstyle rename to src/test/resources/org/jabref/logic/openoffice/style/testWithDefaultAtFirstLIne.jstyle From abb0b0e50a7b64e686978bfb0c5f418d4c4fafc9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 22:41:30 +0200 Subject: [PATCH 0904/1068] logic/openoffice/action --- .../java/org/jabref/gui/openoffice/OOBibBase.java | 12 ++++++------ .../org/jabref/gui/openoffice/OpenOfficePanel.java | 2 +- .../java/org/jabref/logic/openoffice/OOFrontend.java | 1 + .../logic/openoffice/{ => action}/EditInsert.java | 3 ++- .../logic/openoffice/{ => action}/EditMerge.java | 3 ++- .../logic/openoffice/{ => action}/EditSeparate.java | 3 ++- .../logic/openoffice/{ => action}/ExportCited.java | 3 ++- .../openoffice/{ => action}/ManageCitations.java | 3 ++- .../jabref/logic/openoffice/{ => action}/Update.java | 4 +++- .../openoffice/{ => action}/UpdateBibliography.java | 6 ++++-- .../{ => action}/UpdateCitationMarkers.java | 4 +++- 11 files changed, 28 insertions(+), 16 deletions(-) rename src/main/java/org/jabref/logic/openoffice/{ => action}/EditInsert.java (98%) rename src/main/java/org/jabref/logic/openoffice/{ => action}/EditMerge.java (99%) rename src/main/java/org/jabref/logic/openoffice/{ => action}/EditSeparate.java (97%) rename src/main/java/org/jabref/logic/openoffice/{ => action}/ExportCited.java (97%) rename src/main/java/org/jabref/logic/openoffice/{ => action}/ManageCitations.java (93%) rename src/main/java/org/jabref/logic/openoffice/{ => action}/Update.java (97%) rename src/main/java/org/jabref/logic/openoffice/{ => action}/UpdateBibliography.java (96%) rename src/main/java/org/jabref/logic/openoffice/{ => action}/UpdateCitationMarkers.java (97%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index e33fda62ed5..bd3f65a3d94 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -12,15 +12,15 @@ import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.openoffice.EditInsert; -import org.jabref.logic.openoffice.EditMerge; -import org.jabref.logic.openoffice.EditSeparate; -import org.jabref.logic.openoffice.ExportCited; +import org.jabref.logic.openoffice.action.EditInsert; +import org.jabref.logic.openoffice.action.EditMerge; +import org.jabref.logic.openoffice.action.EditSeparate; +import org.jabref.logic.openoffice.action.ExportCited; import org.jabref.logic.openoffice.FunctionalTextViewCursor; -import org.jabref.logic.openoffice.ManageCitations; +import org.jabref.logic.openoffice.action.ManageCitations; import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.OOFrontend; -import org.jabref.logic.openoffice.Update; +import org.jabref.logic.openoffice.action.Update; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.uno.UnoCrossRef; import org.jabref.logic.openoffice.uno.UnoCursor; diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 437c51d7f56..0f3b2e2e902 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -45,7 +45,7 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; -import org.jabref.logic.openoffice.Update; +import org.jabref.logic.openoffice.action.Update; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.StyleLoader; import org.jabref.model.database.BibDatabase; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java index 72fe9c341a3..b8cbe8c2a6c 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/OOFrontend.java @@ -11,6 +11,7 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; +import org.jabref.logic.openoffice.action.UpdateBibliography; import org.jabref.logic.openoffice.backend.Backend52; import org.jabref.logic.openoffice.uno.UnoCursor; import org.jabref.logic.openoffice.uno.UnoTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/EditInsert.java rename to src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index 4173aaf5e11..a0f85fedcf4 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.action; import java.util.ArrayList; import java.util.Collections; @@ -6,6 +6,7 @@ import java.util.Optional; import org.jabref.logic.JabRefException; +import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; diff --git a/src/main/java/org/jabref/logic/openoffice/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/EditMerge.java rename to src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index 0c0a58da86a..3c6da1e1682 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.action; import java.util.ArrayList; import java.util.List; @@ -7,6 +7,7 @@ import java.util.stream.Collectors; import org.jabref.logic.JabRefException; +import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.logic.openoffice.uno.UnoTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/EditSeparate.java rename to src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index 7200ba7e72d..be82c229d48 100644 --- a/src/main/java/org/jabref/logic/openoffice/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -1,8 +1,9 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.action; import java.util.List; import org.jabref.logic.JabRefException; +import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; diff --git a/src/main/java/org/jabref/logic/openoffice/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/ExportCited.java rename to src/main/java/org/jabref/logic/openoffice/action/ExportCited.java index efdb2a37ace..fb479282640 100644 --- a/src/main/java/org/jabref/logic/openoffice/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java @@ -1,10 +1,11 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.action; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; +import org.jabref.logic.openoffice.OOFrontend; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; diff --git a/src/main/java/org/jabref/logic/openoffice/ManageCitations.java b/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java similarity index 93% rename from src/main/java/org/jabref/logic/openoffice/ManageCitations.java rename to src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java index 34f5de63ad3..6158307f008 100644 --- a/src/main/java/org/jabref/logic/openoffice/ManageCitations.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java @@ -1,7 +1,8 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.action; import java.util.List; +import org.jabref.logic.openoffice.OOFrontend; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/Update.java rename to src/main/java/org/jabref/logic/openoffice/action/Update.java index 0a44cd78026..4e080cc935c 100644 --- a/src/main/java/org/jabref/logic/openoffice/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -1,8 +1,10 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.action; import java.util.List; import org.jabref.logic.JabRefException; +import org.jabref.logic.openoffice.FunctionalTextViewCursor; +import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/action/UpdateBibliography.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java rename to src/main/java/org/jabref/logic/openoffice/action/UpdateBibliography.java index f79db0c3455..baefc49455f 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/action/UpdateBibliography.java @@ -1,7 +1,9 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.action; import java.util.Optional; +import org.jabref.logic.openoffice.OOFrontend; +import org.jabref.logic.openoffice.OOTextIntoOO; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOFormatBibliography; import org.jabref.logic.openoffice.uno.UnoBookmark; @@ -27,7 +29,7 @@ public class UpdateBibliography { private static final String BIB_SECTION_NAME = "JR_bib"; private static final String BIB_SECTION_END_NAME = "JR_bib_end"; - static Optional getBibliographyRange(XTextDocument doc) + public static Optional getBibliographyRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException { diff --git a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/action/UpdateCitationMarkers.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java rename to src/main/java/org/jabref/logic/openoffice/action/UpdateCitationMarkers.java index 9578fa4e975..1e49ad22f61 100644 --- a/src/main/java/org/jabref/logic/openoffice/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/action/UpdateCitationMarkers.java @@ -1,10 +1,12 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.action; import java.util.List; import java.util.Objects; import java.util.Optional; import org.jabref.logic.JabRefException; +import org.jabref.logic.openoffice.OOFrontend; +import org.jabref.logic.openoffice.OOTextIntoOO; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; From 410e0057fa9ac22d71de28a7e3b4df936347b011 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 22:54:26 +0200 Subject: [PATCH 0905/1068] logic/openoffice/frontend --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 6 +++--- .../java/org/jabref/logic/openoffice/action/EditInsert.java | 2 +- .../java/org/jabref/logic/openoffice/action/EditMerge.java | 2 +- .../org/jabref/logic/openoffice/action/EditSeparate.java | 2 +- .../org/jabref/logic/openoffice/action/ExportCited.java | 2 +- .../org/jabref/logic/openoffice/action/ManageCitations.java | 2 +- .../java/org/jabref/logic/openoffice/action/Update.java | 4 ++-- .../jabref/logic/openoffice/action/UpdateBibliography.java | 4 ++-- .../logic/openoffice/action/UpdateCitationMarkers.java | 4 ++-- .../openoffice/{ => frontend}/FunctionalTextViewCursor.java | 2 +- .../jabref/logic/openoffice/{ => frontend}/OOFrontend.java | 2 +- .../logic/openoffice/{ => frontend}/OOTextIntoOO.java | 2 +- .../logic/openoffice/{ => frontend}/RangeOverlapFinder.java | 2 +- .../logic/openoffice/{ => frontend}/RangeSortVisual.java | 4 ++-- 14 files changed, 20 insertions(+), 20 deletions(-) rename src/main/java/org/jabref/logic/openoffice/{ => frontend}/FunctionalTextViewCursor.java (99%) rename src/main/java/org/jabref/logic/openoffice/{ => frontend}/OOFrontend.java (99%) rename src/main/java/org/jabref/logic/openoffice/{ => frontend}/OOTextIntoOO.java (99%) rename src/main/java/org/jabref/logic/openoffice/{ => frontend}/RangeOverlapFinder.java (98%) rename src/main/java/org/jabref/logic/openoffice/{ => frontend}/RangeSortVisual.java (98%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index bd3f65a3d94..d01f52d8d7b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -12,15 +12,15 @@ import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; +import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.action.EditInsert; import org.jabref.logic.openoffice.action.EditMerge; import org.jabref.logic.openoffice.action.EditSeparate; import org.jabref.logic.openoffice.action.ExportCited; -import org.jabref.logic.openoffice.FunctionalTextViewCursor; import org.jabref.logic.openoffice.action.ManageCitations; -import org.jabref.logic.openoffice.NoDocumentFoundException; -import org.jabref.logic.openoffice.OOFrontend; import org.jabref.logic.openoffice.action.Update; +import org.jabref.logic.openoffice.frontend.FunctionalTextViewCursor; +import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.uno.UnoCrossRef; import org.jabref.logic.openoffice.uno.UnoCursor; diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index a0f85fedcf4..9546b9902ed 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -6,7 +6,7 @@ import java.util.Optional; import org.jabref.logic.JabRefException; -import org.jabref.logic.openoffice.OOFrontend; +import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index 3c6da1e1682..42f68e7d341 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -7,7 +7,7 @@ import java.util.stream.Collectors; import org.jabref.logic.JabRefException; -import org.jabref.logic.openoffice.OOFrontend; +import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.logic.openoffice.uno.UnoTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index be82c229d48..a165f62dca6 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -3,7 +3,7 @@ import java.util.List; import org.jabref.logic.JabRefException; -import org.jabref.logic.openoffice.OOFrontend; +import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; diff --git a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java index fb479282640..8d344688c68 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java @@ -5,7 +5,7 @@ import java.util.List; import java.util.Set; -import org.jabref.logic.openoffice.OOFrontend; +import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; diff --git a/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java b/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java index 6158307f008..4046cbbe11b 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java @@ -2,7 +2,7 @@ import java.util.List; -import org.jabref.logic.openoffice.OOFrontend; +import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index 4e080cc935c..a15db98e703 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -3,8 +3,8 @@ import java.util.List; import org.jabref.logic.JabRefException; -import org.jabref.logic.openoffice.FunctionalTextViewCursor; -import org.jabref.logic.openoffice.OOFrontend; +import org.jabref.logic.openoffice.frontend.FunctionalTextViewCursor; +import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; diff --git a/src/main/java/org/jabref/logic/openoffice/action/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/action/UpdateBibliography.java index baefc49455f..c1df4e0c877 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/action/UpdateBibliography.java @@ -2,8 +2,8 @@ import java.util.Optional; -import org.jabref.logic.openoffice.OOFrontend; -import org.jabref.logic.openoffice.OOTextIntoOO; +import org.jabref.logic.openoffice.frontend.OOFrontend; +import org.jabref.logic.openoffice.frontend.OOTextIntoOO; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOFormatBibliography; import org.jabref.logic.openoffice.uno.UnoBookmark; diff --git a/src/main/java/org/jabref/logic/openoffice/action/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/action/UpdateCitationMarkers.java index 1e49ad22f61..fa02b1f41dc 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/action/UpdateCitationMarkers.java @@ -5,8 +5,8 @@ import java.util.Optional; import org.jabref.logic.JabRefException; -import org.jabref.logic.openoffice.OOFrontend; -import org.jabref.logic.openoffice.OOTextIntoOO; +import org.jabref.logic.openoffice.frontend.OOFrontend; +import org.jabref.logic.openoffice.frontend.OOTextIntoOO; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; diff --git a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java b/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java rename to src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java index 77571611dcd..caf144a699e 100644 --- a/src/main/java/org/jabref/logic/openoffice/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.frontend; import java.util.Arrays; import java.util.Objects; diff --git a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/OOFrontend.java rename to src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index b8cbe8c2a6c..eb7cf443ef2 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.frontend; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOTextIntoOO.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java rename to src/main/java/org/jabref/logic/openoffice/frontend/OOTextIntoOO.java index a983d3b16ab..6e9e9a269d8 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOTextIntoOO.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.frontend; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java b/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java rename to src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java index c05b043f22f..bd7bbbfaa6d 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeOverlapFinder.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.frontend; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java rename to src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java index c5735c683b7..69f2fec2e6f 100644 --- a/src/main/java/org/jabref/logic/openoffice/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice; +package org.jabref.logic.openoffice.frontend; import java.util.ArrayList; import java.util.List; @@ -30,7 +30,7 @@ * of the first column of the first page. * */ -public class RangeSortVisual { +class RangeSortVisual { private static final Logger LOGGER = LoggerFactory.getLogger(RangeSortVisual.class); From 3d827b4ac0cc29e241b5a6e085c64c975abfc113 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 26 May 2021 23:12:57 +0200 Subject: [PATCH 0906/1068] move UpdateCitationMarkers and UpdateBibliography to frontend --- .../jabref/logic/openoffice/action/EditInsert.java | 1 + .../jabref/logic/openoffice/action/EditMerge.java | 1 + .../jabref/logic/openoffice/action/EditSeparate.java | 1 + .../org/jabref/logic/openoffice/action/Update.java | 2 ++ .../jabref/logic/openoffice/frontend/OOFrontend.java | 1 - .../{action => frontend}/UpdateBibliography.java | 12 ++++++------ .../{action => frontend}/UpdateCitationMarkers.java | 4 ++-- 7 files changed, 13 insertions(+), 9 deletions(-) rename src/main/java/org/jabref/logic/openoffice/{action => frontend}/UpdateBibliography.java (93%) rename src/main/java/org/jabref/logic/openoffice/{action => frontend}/UpdateCitationMarkers.java (97%) diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index 9546b9902ed..f18f5ac7d9b 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -7,6 +7,7 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.frontend.OOFrontend; +import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index 42f68e7d341..e0194df6e9a 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -8,6 +8,7 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.frontend.OOFrontend; +import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.logic.openoffice.uno.UnoTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index a165f62dca6..ee4e14960f0 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -4,6 +4,7 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.frontend.OOFrontend; +import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index a15db98e703..57f1b50697e 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -5,6 +5,8 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.frontend.FunctionalTextViewCursor; import org.jabref.logic.openoffice.frontend.OOFrontend; +import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; +import org.jabref.logic.openoffice.frontend.UpdateBibliography; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index eb7cf443ef2..ce9c2b1ffc7 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -11,7 +11,6 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; -import org.jabref.logic.openoffice.action.UpdateBibliography; import org.jabref.logic.openoffice.backend.Backend52; import org.jabref.logic.openoffice.uno.UnoCursor; import org.jabref.logic.openoffice.uno.UnoTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/action/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java similarity index 93% rename from src/main/java/org/jabref/logic/openoffice/action/UpdateBibliography.java rename to src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java index c1df4e0c877..e2df1f66d42 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.action; +package org.jabref.logic.openoffice.frontend; import java.util.Optional; @@ -40,11 +40,11 @@ public static Optional getBibliographyRange(XTextDocument doc) /** * Rebuilds the bibliography. */ - static void rebuildBibTextSection(XTextDocument doc, - OOFrontend fr, - CitedKeys bibliography, - OOBibStyle style, - boolean alwaysAddCitedOnPages) + public static void rebuildBibTextSection(XTextDocument doc, + OOFrontend fr, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) throws NoSuchElementException, WrappedTargetException, diff --git a/src/main/java/org/jabref/logic/openoffice/action/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/action/UpdateCitationMarkers.java rename to src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index fa02b1f41dc..c2c613ad58c 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.action; +package org.jabref.logic.openoffice.frontend; import java.util.List; import java.util.Objects; @@ -46,7 +46,7 @@ public class UpdateCitationMarkers { * @param style Bibliography style to use. * */ - static void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, OOBibStyle style) + public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, OOBibStyle style) throws NoDocumentException, UnknownPropertyException, From 66c40763f7e59875174fa9c5cab2fb4613afefca Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 27 May 2021 10:14:05 +0200 Subject: [PATCH 0907/1068] OOBibBase2, ootext --- .../gui/openoffice/ManageCitationsDialogView.java | 4 ++-- .../gui/openoffice/ManageCitationsDialogViewModel.java | 4 ++-- .../gui/openoffice/{OOBibBase.java => OOBibBase2.java} | 8 ++++---- .../org/jabref/gui/openoffice/OpenOfficePanel.java | 10 +++++----- .../org/jabref/logic/openoffice/action/EditInsert.java | 2 +- .../org/jabref/logic/openoffice/action/EditMerge.java | 2 +- .../jabref/logic/openoffice/action/EditSeparate.java | 2 +- .../org/jabref/logic/openoffice/action/Update.java | 2 +- .../org/jabref/logic/openoffice/backend/Backend52.java | 2 +- .../jabref/logic/openoffice/frontend/OOFrontend.java | 2 +- .../logic/openoffice/frontend/UpdateBibliography.java | 5 ++--- .../openoffice/frontend/UpdateCitationMarkers.java | 5 ++--- .../logic/openoffice/{style => ootext}/OOFormat.java | 4 ++-- .../openoffice/{frontend => ootext}/OOTextIntoOO.java | 4 ++-- .../org/jabref/logic/openoffice/style/OOBibStyle.java | 3 ++- .../openoffice/style/OOBibStyleGetCitationMarker.java | 2 +- .../style/OOBibStyleGetNumCitationMarker.java | 2 +- .../logic/openoffice/style/OOFormatBibliography.java | 5 +++-- .../openoffice/style/OOProcessAuthorYearMarkers.java | 2 +- .../openoffice/style/OOProcessCitationKeyMarkers.java | 2 +- .../openoffice/style/OOProcessNumericMarkers.java | 2 +- .../model/openoffice/{style => ootext}/OOText.java | 2 +- .../org/jabref/model/openoffice/style/Citation.java | 1 + .../jabref/model/openoffice/style/CitationGroup.java | 1 + .../model/openoffice/style/CitationMarkerEntry.java | 2 ++ .../openoffice/style/CitationMarkerNumericEntry.java | 2 ++ .../org/jabref/model/openoffice/style/CitedKey.java | 1 + .../model/openoffice/style/ComparableCitation.java | 2 ++ .../org/jabref/model/openoffice/style/OODataModel.java | 2 ++ .../org/jabref/model/openoffice/style/PageInfo.java | 2 ++ .../jabref/logic/openoffice/style/OOBibStyleTest.java | 2 +- 31 files changed, 52 insertions(+), 39 deletions(-) rename src/main/java/org/jabref/gui/openoffice/{OOBibBase.java => OOBibBase2.java} (99%) rename src/main/java/org/jabref/logic/openoffice/{style => ootext}/OOFormat.java (96%) rename src/main/java/org/jabref/logic/openoffice/{frontend => ootext}/OOTextIntoOO.java (99%) rename src/main/java/org/jabref/model/openoffice/{style => ootext}/OOText.java (95%) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index 588381cea3e..872d1f8adc0 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -25,7 +25,7 @@ public class ManageCitationsDialogView extends BaseDialog { private static final String HTML_BOLD_END_TAG = ""; private static final String HTML_BOLD_START_TAG = ""; - private final OOBibBase ooBase; + private final OOBibBase2 ooBase; @FXML private TableView citationsTableView; @FXML private TableColumn citation; @@ -35,7 +35,7 @@ public class ManageCitationsDialogView extends BaseDialog { private ManageCitationsDialogViewModel viewModel; - public ManageCitationsDialogView(OOBibBase ooBase) { + public ManageCitationsDialogView(OOBibBase2 ooBase) { this.ooBase = ooBase; ViewLoader.view(this) diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 3736cb3243c..b854a445fa9 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -15,10 +15,10 @@ public class ManageCitationsDialogViewModel { public final boolean failedToGetCitationEntries; private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList()); - private final OOBibBase ooBase; + private final OOBibBase2 ooBase; private final DialogService dialogService; - public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) { + public ManageCitationsDialogViewModel(OOBibBase2 ooBase, DialogService dialogService) { this.ooBase = ooBase; this.dialogService = dialogService; diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java similarity index 99% rename from src/main/java/org/jabref/gui/openoffice/OOBibBase.java rename to src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index d01f52d8d7b..eabc25f75d4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -57,9 +57,9 @@ * Class for manipulating the Bibliography of the currently started * document in OpenOffice. */ -class OOBibBase { +class OOBibBase2 { - private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase2.class); /* variables */ private final DialogService dialogService; @@ -80,7 +80,7 @@ class OOBibBase { /* * Constructor */ - public OOBibBase(Path loPath, DialogService dialogService) + public OOBibBase2(Path loPath, DialogService dialogService) throws BootstrapException, CreationException { @@ -976,4 +976,4 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl } } -} // end of OOBibBase +} diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 0f3b2e2e902..8b8f398c1ff 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -89,7 +89,7 @@ public class OpenOfficePanel { private final TaskExecutor taskExecutor; private final StyleLoader loader; private OpenOfficePreferences ooPrefs; - private OOBibBase ooBase; + private OOBibBase2 ooBase; private OOBibStyle style; public OpenOfficePanel(JabRefFrame frame, PreferencesService preferencesService, OpenOfficePreferences ooPrefs, KeyBindingRepository keyBindingRepository) { @@ -371,10 +371,10 @@ private void updateButtonAvailability() { private void connect() { ooPrefs = preferencesService.getOpenOfficePreferences(); - Task connectTask = new Task<>() { + Task connectTask = new Task<>() { @Override - protected OOBibBase call() throws Exception { + protected OOBibBase2 call() throws Exception { updateProgress(ProgressBar.INDETERMINATE_PROGRESS, ProgressBar.INDETERMINATE_PROGRESS); var path = Path.of(ooPrefs.getExecutablePath()); @@ -416,9 +416,9 @@ protected OOBibBase call() throws Exception { taskExecutor.execute(connectTask); } - private OOBibBase createBibBase(Path loPath) throws IOException, InvocationTargetException, IllegalAccessException, + private OOBibBase2 createBibBase(Path loPath) throws IOException, InvocationTargetException, IllegalAccessException, BootstrapException, CreationException, ClassNotFoundException { - return new OOBibBase(loPath, dialogService); + return new OOBibBase2(loPath, dialogService); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index f18f5ac7d9b..fdecec69c2c 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -11,12 +11,12 @@ import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.jabref.model.openoffice.style.OODataModel; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.util.OOListUtil; diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index e0194df6e9a..d4231491a0a 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -12,10 +12,10 @@ import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.logic.openoffice.uno.UnoTextRange; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationType; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.util.OOListUtil; diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index ee4e14960f0..4af8e19df14 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -9,9 +9,9 @@ import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.model.database.BibDatabase; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index 57f1b50697e..5c14a7ede95 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -5,8 +5,8 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.frontend.FunctionalTextViewCursor; import org.jabref.logic.openoffice.frontend.OOFrontend; -import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.frontend.UpdateBibliography; +import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 87d0c98e676..8f8609e6e06 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -14,13 +14,13 @@ import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.backend.NamedRange; import org.jabref.model.openoffice.backend.NamedRangeManager; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.style.OODataModel; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.style.PageInfo; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index ce9c2b1ffc7..8c3e3e59e85 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -15,6 +15,7 @@ import org.jabref.logic.openoffice.uno.UnoCursor; import org.jabref.logic.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.rangeoverlap.RangeForOverlapCheck; import org.jabref.model.openoffice.rangeoverlap.RangeOverlap; import org.jabref.model.openoffice.rangesort.RangeKeyedMap; @@ -26,7 +27,6 @@ import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.style.OODataModel; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.util.OOListUtil; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java index e2df1f66d42..7d468218d60 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java @@ -2,14 +2,13 @@ import java.util.Optional; -import org.jabref.logic.openoffice.frontend.OOFrontend; -import org.jabref.logic.openoffice.frontend.OOTextIntoOO; +import org.jabref.logic.openoffice.ootext.OOTextIntoOO; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOFormatBibliography; import org.jabref.logic.openoffice.uno.UnoBookmark; import org.jabref.logic.openoffice.uno.UnoTextSection; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitedKeys; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index c2c613ad58c..38ce092f971 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -5,13 +5,12 @@ import java.util.Optional; import org.jabref.logic.JabRefException; -import org.jabref.logic.openoffice.frontend.OOFrontend; -import org.jabref.logic.openoffice.frontend.OOTextIntoOO; +import org.jabref.logic.openoffice.ootext.OOTextIntoOO; import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationType; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOFormat.java b/src/main/java/org/jabref/logic/openoffice/ootext/OOFormat.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/style/OOFormat.java rename to src/main/java/org/jabref/logic/openoffice/ootext/OOFormat.java index 67dc3102545..588241c2ba8 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOFormat.java +++ b/src/main/java/org/jabref/logic/openoffice/ootext/OOFormat.java @@ -1,6 +1,6 @@ -package org.jabref.logic.openoffice.style; +package org.jabref.logic.openoffice.ootext; -import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.ootext.OOText; public class OOFormat { diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/ootext/OOTextIntoOO.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/frontend/OOTextIntoOO.java rename to src/main/java/org/jabref/logic/openoffice/ootext/OOTextIntoOO.java index 6e9e9a269d8..ab68c9c6f53 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/ootext/OOTextIntoOO.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.frontend; +package org.jabref.logic.openoffice.ootext; import java.util.ArrayList; import java.util.Arrays; @@ -15,7 +15,7 @@ import org.jabref.architecture.AllowedToUseAwt; import org.jabref.logic.openoffice.uno.UnoCast; import org.jabref.logic.openoffice.uno.UnoCrossRef; -import org.jabref.model.openoffice.style.OOText; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.util.OOPair; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index fbc1d94a987..a51e6e7cdb5 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -25,17 +25,18 @@ import org.jabref.logic.layout.LayoutFormatter; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.layout.LayoutHelper; +import org.jabref.logic.openoffice.ootext.OOFormat; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.OrFields; 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.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationMarkerNormEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.style.PageInfo; import org.jabref.model.openoffice.util.OOListUtil; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java index d89c3e1a79a..ee2bba27e7e 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java @@ -12,11 +12,11 @@ import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitationLookupResult; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationMarkerNormEntry; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.style.PageInfo; import org.jabref.model.strings.StringUtil; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java index 2ceab557033..376c4478421 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java @@ -4,9 +4,9 @@ import java.util.List; import java.util.Optional; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.style.PageInfo; import org.jabref.model.openoffice.util.OOListUtil; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index eae82cf7033..98ece8f20b0 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -6,17 +6,18 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; +import org.jabref.logic.openoffice.ootext.OOFormat; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.UnknownField; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationPath; import org.jabref.model.openoffice.style.CitedKey; import org.jabref.model.openoffice.style.CitedKeys; -import org.jabref.model.openoffice.style.OOText; public class OOFormatBibliography { private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); @@ -115,7 +116,7 @@ public static OOText formatBibliographyEntryBody(CitedKey ck, OOBibStyle style) * @param database The database the entry belongs to. * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. * - * @return OOText suitable for OOTextIntoOO.write() + * @return OOText The reference part of a bibliography entry formatted as OOText */ private static OOText formatFullReferenceOfBibEntry(Layout layout, BibEntry entry, diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index b909534a5cb..a55d59107a8 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -8,6 +8,7 @@ import java.util.Optional; import java.util.Set; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; @@ -16,7 +17,6 @@ import org.jabref.model.openoffice.style.CitedKey; import org.jabref.model.openoffice.style.CitedKeys; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.util.OOListUtil; class OOProcessAuthorYearMarkers { diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java index 4986e03d058..c63a4b3d0e4 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java @@ -2,10 +2,10 @@ import java.util.Optional; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.util.OOListUtil; class OOProcessCitationKeyMarkers { diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java index dcbfec2c077..4023ed0e028 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java @@ -3,10 +3,10 @@ import java.util.List; import java.util.Optional; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.util.OOListUtil; class OOProcessNumericMarkers { diff --git a/src/main/java/org/jabref/model/openoffice/style/OOText.java b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java similarity index 95% rename from src/main/java/org/jabref/model/openoffice/style/OOText.java rename to src/main/java/org/jabref/model/openoffice/ootext/OOText.java index 62d5b534f86..604f2c6c657 100644 --- a/src/main/java/org/jabref/model/openoffice/style/OOText.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.style; +package org.jabref.model.openoffice.ootext; import java.util.Objects; diff --git a/src/main/java/org/jabref/model/openoffice/style/Citation.java b/src/main/java/org/jabref/model/openoffice/style/Citation.java index 7ce16a37352..f0b732a9240 100644 --- a/src/main/java/org/jabref/model/openoffice/style/Citation.java +++ b/src/main/java/org/jabref/model/openoffice/style/Citation.java @@ -5,6 +5,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.util.OOPair; public class Citation implements ComparableCitation, CitationMarkerEntry, CitationMarkerNumericEntry { diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java index 0755b7be024..075c55cc2ef 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java @@ -6,6 +6,7 @@ import java.util.Optional; import org.jabref.model.entry.BibEntry; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.util.OOListUtil; /** diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java index 108e8b72217..4ab2c626b68 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java @@ -2,6 +2,8 @@ import java.util.Optional; +import org.jabref.model.openoffice.ootext.OOText; + /** * This is what we need for createCitationMarker to produce author-year * citation markers. diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericEntry.java b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericEntry.java index aba47a7f902..9c0c6081489 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericEntry.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericEntry.java @@ -2,6 +2,8 @@ import java.util.Optional; +import org.jabref.model.openoffice.ootext.OOText; + /** * This is what we need for numeric citation markers. */ diff --git a/src/main/java/org/jabref/model/openoffice/style/CitedKey.java b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java index 70410abcd4f..08b2ffb1bb8 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java @@ -6,6 +6,7 @@ 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. diff --git a/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java b/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java index 14fe74743f1..a6ac799b017 100644 --- a/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java +++ b/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java @@ -2,6 +2,8 @@ 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. diff --git a/src/main/java/org/jabref/model/openoffice/style/OODataModel.java b/src/main/java/org/jabref/model/openoffice/style/OODataModel.java index c693b64e74a..50c3a9e4842 100644 --- a/src/main/java/org/jabref/model/openoffice/style/OODataModel.java +++ b/src/main/java/org/jabref/model/openoffice/style/OODataModel.java @@ -4,6 +4,8 @@ import java.util.List; import java.util.Optional; +import org.jabref.model.openoffice.ootext.OOText; + /** What is the data stored? */ public enum OODataModel { diff --git a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java index e3e193632fa..6807ecf0753 100644 --- a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java +++ b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java @@ -2,6 +2,8 @@ import java.util.Optional; +import org.jabref.model.openoffice.ootext.OOText; + public class PageInfo { private PageInfo() { diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java index 20095b5d16a..58952633af8 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java @@ -25,13 +25,13 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; +import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationLookupResult; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; -import org.jabref.model.openoffice.style.OOText; import org.jabref.model.openoffice.style.PageInfo; import org.junit.jupiter.api.BeforeEach; From 2a02b6cb4c885c7fb7198c56f39496d0d79c7624 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 27 May 2021 10:24:00 +0200 Subject: [PATCH 0908/1068] model/frontend --- .../java/org/jabref/gui/openoffice/OOBibBase2.java | 2 +- .../jabref/logic/openoffice/frontend/OOFrontend.java | 12 ++++++------ .../openoffice/frontend/RangeOverlapFinder.java | 6 +++--- .../logic/openoffice/frontend/RangeSortVisual.java | 2 +- .../rangeoverlap/RangeForOverlapCheck.java | 2 +- .../{ => frontend}/rangeoverlap/RangeOverlap.java | 2 +- .../rangeoverlap/RangeOverlapKind.java | 2 +- .../{ => frontend}/rangesort/RangeKeyedMap.java | 2 +- .../{ => frontend}/rangesort/RangeKeyedMapList.java | 2 +- .../{ => frontend}/rangesort/RangeSortEntry.java | 2 +- .../{ => frontend}/rangesort/RangeSortable.java | 2 +- 11 files changed, 18 insertions(+), 18 deletions(-) rename src/main/java/org/jabref/model/openoffice/{ => frontend}/rangeoverlap/RangeForOverlapCheck.java (95%) rename src/main/java/org/jabref/model/openoffice/{ => frontend}/rangeoverlap/RangeOverlap.java (88%) rename src/main/java/org/jabref/model/openoffice/{ => frontend}/rangeoverlap/RangeOverlapKind.java (76%) rename src/main/java/org/jabref/model/openoffice/{ => frontend}/rangesort/RangeKeyedMap.java (98%) rename src/main/java/org/jabref/model/openoffice/{ => frontend}/rangesort/RangeKeyedMapList.java (94%) rename src/main/java/org/jabref/model/openoffice/{ => frontend}/rangesort/RangeSortEntry.java (93%) rename src/main/java/org/jabref/model/openoffice/{ => frontend}/rangesort/RangeSortable.java (91%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index eabc25f75d4..b46dd32d821 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -30,7 +30,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.model.openoffice.rangeoverlap.RangeForOverlapCheck; +import org.jabref.model.openoffice.frontend.rangeoverlap.RangeForOverlapCheck; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.uno.CreationException; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 8c3e3e59e85..c94a0fb8ba9 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -15,13 +15,13 @@ import org.jabref.logic.openoffice.uno.UnoCursor; import org.jabref.logic.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.frontend.rangeoverlap.RangeForOverlapCheck; +import org.jabref.model.openoffice.frontend.rangeoverlap.RangeOverlap; +import org.jabref.model.openoffice.frontend.rangesort.RangeKeyedMap; +import org.jabref.model.openoffice.frontend.rangesort.RangeKeyedMapList; +import org.jabref.model.openoffice.frontend.rangesort.RangeSortEntry; +import org.jabref.model.openoffice.frontend.rangesort.RangeSortable; import org.jabref.model.openoffice.ootext.OOText; -import org.jabref.model.openoffice.rangeoverlap.RangeForOverlapCheck; -import org.jabref.model.openoffice.rangeoverlap.RangeOverlap; -import org.jabref.model.openoffice.rangesort.RangeKeyedMap; -import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; -import org.jabref.model.openoffice.rangesort.RangeSortEntry; -import org.jabref.model.openoffice.rangesort.RangeSortable; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationGroups; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java b/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java index bd7bbbfaa6d..9150b9b789e 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java @@ -5,9 +5,9 @@ import java.util.TreeMap; import org.jabref.logic.openoffice.uno.UnoTextRange; -import org.jabref.model.openoffice.rangeoverlap.RangeOverlap; -import org.jabref.model.openoffice.rangeoverlap.RangeOverlapKind; -import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; +import org.jabref.model.openoffice.frontend.rangeoverlap.RangeOverlap; +import org.jabref.model.openoffice.frontend.rangeoverlap.RangeOverlapKind; +import org.jabref.model.openoffice.frontend.rangesort.RangeKeyedMapList; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java index 69f2fec2e6f..01e1bf58d3f 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java @@ -7,7 +7,7 @@ import java.util.TreeSet; import org.jabref.logic.openoffice.uno.UnoScreenRefresh; -import org.jabref.model.openoffice.rangesort.RangeSortable; +import org.jabref.model.openoffice.frontend.rangesort.RangeSortable; import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.awt.Point; diff --git a/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeForOverlapCheck.java b/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeForOverlapCheck.java similarity index 95% rename from src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeForOverlapCheck.java rename to src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeForOverlapCheck.java index 6881db5a3d2..20e416c4dec 100644 --- a/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeForOverlapCheck.java +++ b/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeForOverlapCheck.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.rangeoverlap; +package org.jabref.model.openoffice.frontend.rangeoverlap; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlap.java b/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlap.java similarity index 88% rename from src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlap.java rename to src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlap.java index fef6883d7e2..ebe75551b7c 100644 --- a/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlap.java +++ b/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlap.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.rangeoverlap; +package org.jabref.model.openoffice.frontend.rangeoverlap; import java.util.List; diff --git a/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlapKind.java b/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlapKind.java similarity index 76% rename from src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlapKind.java rename to src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlapKind.java index d60d43a952d..b6d5cf2efa8 100644 --- a/src/main/java/org/jabref/model/openoffice/rangeoverlap/RangeOverlapKind.java +++ b/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlapKind.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.rangeoverlap; +package org.jabref.model.openoffice.frontend.rangeoverlap; public enum RangeOverlapKind { /** They share a boundary */ diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java b/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMap.java similarity index 98% rename from src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java rename to src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMap.java index 841b6f52355..ce4c380e0a4 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java +++ b/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMap.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.rangesort; +package org.jabref.model.openoffice.frontend.rangesort; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java b/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMapList.java similarity index 94% rename from src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java rename to src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMapList.java index 1c77986c35a..1bcf564e155 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMapList.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.rangesort; +package org.jabref.model.openoffice.frontend.rangesort; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java b/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortEntry.java similarity index 93% rename from src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java rename to src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortEntry.java index 4ed651e5396..c1a27b13fd8 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java +++ b/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortEntry.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.rangesort; +package org.jabref.model.openoffice.frontend.rangesort; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java b/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortable.java similarity index 91% rename from src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java rename to src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortable.java index 6b2c1fa9e8f..bc78a982a75 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java +++ b/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortable.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.rangesort; +package org.jabref.model.openoffice.frontend.rangesort; import com.sun.star.text.XTextRange; From 030fd4e78a72e9b6c1bbd1ebf07496f7c013878e Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 27 May 2021 10:42:56 +0200 Subject: [PATCH 0909/1068] move all of uno to model --- .../java/org/jabref/gui/openoffice/OOBibBase2.java | 10 +++++----- .../org/jabref/gui/openoffice/OOBibBaseConnect.java | 4 ++-- .../org/jabref/logic/openoffice/action/EditMerge.java | 4 ++-- .../jabref/logic/openoffice/action/EditSeparate.java | 2 +- .../org/jabref/logic/openoffice/action/Update.java | 2 +- .../org/jabref/logic/openoffice/backend/Backend52.java | 2 +- .../backend/NamedRangeManagerReferenceMark.java | 2 +- .../openoffice/backend/NamedRangeReferenceMark.java | 4 ++-- .../openoffice/frontend/FunctionalTextViewCursor.java | 4 ++-- .../jabref/logic/openoffice/frontend/OOFrontend.java | 4 ++-- .../logic/openoffice/frontend/RangeOverlapFinder.java | 2 +- .../logic/openoffice/frontend/RangeSortVisual.java | 2 +- .../logic/openoffice/frontend/UpdateBibliography.java | 4 ++-- .../jabref/logic/openoffice/ootext/OOTextIntoOO.java | 4 ++-- .../{logic => model}/openoffice/uno/UnoBookmark.java | 5 +---- .../{logic => model}/openoffice/uno/UnoCast.java | 2 +- .../{logic => model}/openoffice/uno/UnoCrossRef.java | 4 +--- .../{logic => model}/openoffice/uno/UnoCursor.java | 2 +- .../{logic => model}/openoffice/uno/UnoNameAccess.java | 2 +- .../{logic => model}/openoffice/uno/UnoNamed.java | 4 +--- .../{logic => model}/openoffice/uno/UnoProperties.java | 2 +- .../{logic => model}/openoffice/uno/UnoRedlines.java | 2 +- .../openoffice/uno/UnoReferenceMark.java | 5 +---- .../openoffice/uno/UnoScreenRefresh.java | 2 +- .../{logic => model}/openoffice/uno/UnoSelection.java | 2 +- .../{logic => model}/openoffice/uno/UnoStyle.java | 2 +- .../openoffice/uno/UnoTextDocument.java | 4 +--- .../{logic => model}/openoffice/uno/UnoTextRange.java | 2 +- .../openoffice/uno/UnoTextSection.java | 5 +---- .../{logic => model}/openoffice/uno/UnoUndo.java | 2 +- .../openoffice/uno/UnoUserDefinedProperty.java | 2 +- 31 files changed, 42 insertions(+), 57 deletions(-) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoBookmark.java (95%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoCast.java (93%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoCrossRef.java (96%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoCursor.java (97%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoNameAccess.java (94%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoNamed.java (96%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoProperties.java (98%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoRedlines.java (97%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoReferenceMark.java (96%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoScreenRefresh.java (95%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoSelection.java (99%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoStyle.java (98%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoTextDocument.java (96%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoTextRange.java (98%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoTextSection.java (94%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoUndo.java (97%) rename src/main/java/org/jabref/{logic => model}/openoffice/uno/UnoUserDefinedProperty.java (99%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index b46dd32d821..3156dfe61f3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -22,11 +22,6 @@ import org.jabref.logic.openoffice.frontend.FunctionalTextViewCursor; import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.style.OOBibStyle; -import org.jabref.logic.openoffice.uno.UnoCrossRef; -import org.jabref.logic.openoffice.uno.UnoCursor; -import org.jabref.logic.openoffice.uno.UnoRedlines; -import org.jabref.logic.openoffice.uno.UnoStyle; -import org.jabref.logic.openoffice.uno.UnoUndo; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; @@ -35,6 +30,11 @@ import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoCrossRef; +import org.jabref.model.openoffice.uno.UnoCursor; +import org.jabref.model.openoffice.uno.UnoRedlines; +import org.jabref.model.openoffice.uno.UnoStyle; +import org.jabref.model.openoffice.uno.UnoUndo; import org.jabref.model.openoffice.util.OOResult; import org.jabref.model.openoffice.util.OOVoidResult; diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 31864e4212e..30c43c1097d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -9,10 +9,10 @@ import org.jabref.gui.DialogService; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.NoDocumentFoundException; -import org.jabref.logic.openoffice.uno.UnoCast; -import org.jabref.logic.openoffice.uno.UnoTextDocument; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoCast; +import org.jabref.model.openoffice.uno.UnoTextDocument; import org.jabref.model.openoffice.util.OOResult; import com.sun.star.comp.helper.BootstrapException; diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index d4231491a0a..ae9f13ddc0c 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -10,14 +10,14 @@ import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; -import org.jabref.logic.openoffice.uno.UnoScreenRefresh; -import org.jabref.logic.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoScreenRefresh; +import org.jabref.model.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.util.OOListUtil; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index 4af8e19df14..31c23ed52d0 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -7,13 +7,13 @@ import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; -import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.model.database.BibDatabase; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoScreenRefresh; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index 5c14a7ede95..69fbeb26415 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -9,10 +9,10 @@ import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; -import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.model.database.BibDatabase; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoScreenRefresh; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 8f8609e6e06..de2cfaec518 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -10,7 +10,6 @@ import java.util.Set; import java.util.stream.Collectors; -import org.jabref.logic.openoffice.uno.UnoUserDefinedProperty; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.backend.NamedRange; import org.jabref.model.openoffice.backend.NamedRangeManager; @@ -24,6 +23,7 @@ import org.jabref.model.openoffice.style.PageInfo; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoUserDefinedProperty; import org.jabref.model.openoffice.util.OOListUtil; import com.sun.star.beans.IllegalTypeException; diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java index d53ae0b6685..157dd87cf0c 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java @@ -3,11 +3,11 @@ import java.util.List; import java.util.Optional; -import org.jabref.logic.openoffice.uno.UnoReferenceMark; import org.jabref.model.openoffice.backend.NamedRange; import org.jabref.model.openoffice.backend.NamedRangeManager; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoReferenceMark; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index a4f9a6b68d8..ae4a3e1caaa 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -2,11 +2,11 @@ import java.util.Optional; -import org.jabref.logic.openoffice.uno.UnoCursor; -import org.jabref.logic.openoffice.uno.UnoReferenceMark; import org.jabref.model.openoffice.backend.NamedRange; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoCursor; +import org.jabref.model.openoffice.uno.UnoReferenceMark; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java b/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java index caf144a699e..c47503ec546 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java @@ -4,8 +4,8 @@ import java.util.Objects; import org.jabref.logic.JabRefException; -import org.jabref.logic.openoffice.uno.UnoCursor; -import org.jabref.logic.openoffice.uno.UnoSelection; +import org.jabref.model.openoffice.uno.UnoCursor; +import org.jabref.model.openoffice.uno.UnoSelection; import org.jabref.model.openoffice.util.OOResult; import com.sun.star.lang.XServiceInfo; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index c94a0fb8ba9..1a033b8dbb7 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -12,8 +12,6 @@ import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.backend.Backend52; -import org.jabref.logic.openoffice.uno.UnoCursor; -import org.jabref.logic.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.frontend.rangeoverlap.RangeForOverlapCheck; import org.jabref.model.openoffice.frontend.rangeoverlap.RangeOverlap; @@ -29,6 +27,8 @@ import org.jabref.model.openoffice.style.OODataModel; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoCursor; +import org.jabref.model.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.util.OOListUtil; import org.jabref.model.openoffice.util.OOVoidResult; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java b/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java index 9150b9b789e..2651ed2f72d 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java @@ -4,10 +4,10 @@ import java.util.List; import java.util.TreeMap; -import org.jabref.logic.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.frontend.rangeoverlap.RangeOverlap; import org.jabref.model.openoffice.frontend.rangeoverlap.RangeOverlapKind; import org.jabref.model.openoffice.frontend.rangesort.RangeKeyedMapList; +import org.jabref.model.openoffice.uno.UnoTextRange; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java b/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java index 01e1bf58d3f..b4d7212622a 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java @@ -6,9 +6,9 @@ import java.util.Set; import java.util.TreeSet; -import org.jabref.logic.openoffice.uno.UnoScreenRefresh; import org.jabref.model.openoffice.frontend.rangesort.RangeSortable; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoScreenRefresh; import com.sun.star.awt.Point; import com.sun.star.lang.WrappedTargetException; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java index 7d468218d60..93631261e08 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java @@ -5,12 +5,12 @@ import org.jabref.logic.openoffice.ootext.OOTextIntoOO; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOFormatBibliography; -import org.jabref.logic.openoffice.uno.UnoBookmark; -import org.jabref.logic.openoffice.uno.UnoTextSection; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitedKeys; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoBookmark; +import org.jabref.model.openoffice.uno.UnoTextSection; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; diff --git a/src/main/java/org/jabref/logic/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/logic/openoffice/ootext/OOTextIntoOO.java index ab68c9c6f53..4ee4d58aa61 100644 --- a/src/main/java/org/jabref/logic/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/logic/openoffice/ootext/OOTextIntoOO.java @@ -13,10 +13,10 @@ import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.logic.openoffice.uno.UnoCast; -import org.jabref.logic.openoffice.uno.UnoCrossRef; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.UnoCast; +import org.jabref.model.openoffice.uno.UnoCrossRef; import org.jabref.model.openoffice.util.OOPair; import com.sun.star.awt.FontSlant; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoBookmark.java b/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java similarity index 95% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoBookmark.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java index 784b4b1a4fb..b97618a3231 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoBookmark.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java @@ -1,10 +1,7 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.Optional; -import org.jabref.model.openoffice.uno.CreationException; -import org.jabref.model.openoffice.uno.NoDocumentException; - import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoCast.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCast.java similarity index 93% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoCast.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoCast.java index 78acc423625..df5be51db36 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoCast.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCast.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoCrossRef.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoCrossRef.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java index 859b3a26b84..0e8b84e8d22 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoCrossRef.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java @@ -1,6 +1,4 @@ -package org.jabref.logic.openoffice.uno; - -import org.jabref.model.openoffice.uno.CreationException; +package org.jabref.model.openoffice.uno; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoCursor.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoCursor.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java index 70fc8078a10..b7115feb8e1 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoCursor.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoNameAccess.java b/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java similarity index 94% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoNameAccess.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java index fd34b26f038..3d172d11f14 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoNameAccess.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoNamed.java b/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoNamed.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java index 19f7ad56f2d..d99b6702153 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoNamed.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java @@ -1,6 +1,4 @@ -package org.jabref.logic.openoffice.uno; - -import org.jabref.model.openoffice.uno.CreationException; +package org.jabref.model.openoffice.uno; import com.sun.star.container.XNamed; import com.sun.star.lang.XMultiServiceFactory; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoProperties.java b/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoProperties.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java index 25ef7c75a9f..07a6de1374d 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoProperties.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoRedlines.java b/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoRedlines.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java index 94ec745cb73..a5f5ce7c6d1 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoRedlines.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertySet; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoReferenceMark.java b/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoReferenceMark.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java index 2c7e6db921e..8185c1ffbe3 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoReferenceMark.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java @@ -1,13 +1,10 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; -import org.jabref.model.openoffice.uno.CreationException; -import org.jabref.model.openoffice.uno.NoDocumentException; - import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoScreenRefresh.java b/src/main/java/org/jabref/model/openoffice/uno/UnoScreenRefresh.java similarity index 95% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoScreenRefresh.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoScreenRefresh.java index 3212746cedc..e5c27fcbb5c 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoScreenRefresh.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoScreenRefresh.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import com.sun.star.text.XTextDocument; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoSelection.java b/src/main/java/org/jabref/model/openoffice/uno/UnoSelection.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoSelection.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoSelection.java index e4efad0ef5a..0ef750b9983 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoSelection.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoSelection.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.Objects; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoStyle.java b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoStyle.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java index 15b47c313d4..86222872597 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoStyle.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoTextDocument.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoTextDocument.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java index f23eb66adb1..188a092465a 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoTextDocument.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java @@ -1,9 +1,7 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.Optional; -import org.jabref.model.openoffice.uno.NoDocumentException; - import com.sun.star.beans.XPropertySet; import com.sun.star.document.XDocumentProperties; import com.sun.star.document.XDocumentPropertiesSupplier; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoTextRange.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java similarity index 98% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoTextRange.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java index 797007c1cc5..1559c55d490 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoTextRange.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoTextSection.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java similarity index 94% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoTextSection.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java index 3d8c3279dc5..107e7a0e018 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoTextSection.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java @@ -1,10 +1,7 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.Optional; -import org.jabref.model.openoffice.uno.CreationException; -import org.jabref.model.openoffice.uno.NoDocumentException; - import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoUndo.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java similarity index 97% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoUndo.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java index 408ff2aa0f4..7f41515dd1c 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoUndo.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.Optional; diff --git a/src/main/java/org/jabref/logic/openoffice/uno/UnoUserDefinedProperty.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/uno/UnoUserDefinedProperty.java rename to src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java index 1484706e6aa..78e8b8acb23 100644 --- a/src/main/java/org/jabref/logic/openoffice/uno/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.uno; +package org.jabref.model.openoffice.uno; import java.util.ArrayList; import java.util.List; From 57084d0ccba2295f826c3134eaa4e8443efc8664 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 27 May 2021 10:50:09 +0200 Subject: [PATCH 0910/1068] move all of ootext to model --- .../jabref/logic/openoffice/frontend/UpdateBibliography.java | 2 +- .../logic/openoffice/frontend/UpdateCitationMarkers.java | 2 +- .../java/org/jabref/logic/openoffice/style/OOBibStyle.java | 2 +- .../jabref/logic/openoffice/style/OOFormatBibliography.java | 2 +- .../jabref/{logic => model}/openoffice/ootext/OOFormat.java | 4 +--- .../{logic => model}/openoffice/ootext/OOTextIntoOO.java | 3 +-- 6 files changed, 6 insertions(+), 9 deletions(-) rename src/main/java/org/jabref/{logic => model}/openoffice/ootext/OOFormat.java (96%) rename src/main/java/org/jabref/{logic => model}/openoffice/ootext/OOTextIntoOO.java (99%) diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java index 93631261e08..ef1a4c42dc5 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java @@ -2,10 +2,10 @@ import java.util.Optional; -import org.jabref.logic.openoffice.ootext.OOTextIntoOO; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOFormatBibliography; import org.jabref.model.openoffice.ootext.OOText; +import org.jabref.model.openoffice.ootext.OOTextIntoOO; import org.jabref.model.openoffice.style.CitedKeys; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index 38ce092f971..7d864ab1063 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -5,9 +5,9 @@ import java.util.Optional; import org.jabref.logic.JabRefException; -import org.jabref.logic.openoffice.ootext.OOTextIntoOO; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.openoffice.ootext.OOText; +import org.jabref.model.openoffice.ootext.OOTextIntoOO; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroups; import org.jabref.model.openoffice.style.CitationType; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index a51e6e7cdb5..3b9cfa012dd 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -25,12 +25,12 @@ import org.jabref.logic.layout.LayoutFormatter; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.layout.LayoutHelper; -import org.jabref.logic.openoffice.ootext.OOFormat; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.OrFields; 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.openoffice.ootext.OOFormat; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationMarkerNormEntry; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index 98ece8f20b0..93988aa4770 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -6,11 +6,11 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; -import org.jabref.logic.openoffice.ootext.OOFormat; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.UnknownField; +import org.jabref.model.openoffice.ootext.OOFormat; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroupId; diff --git a/src/main/java/org/jabref/logic/openoffice/ootext/OOFormat.java b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java similarity index 96% rename from src/main/java/org/jabref/logic/openoffice/ootext/OOFormat.java rename to src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java index 588241c2ba8..ca0d5b01832 100644 --- a/src/main/java/org/jabref/logic/openoffice/ootext/OOFormat.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java @@ -1,6 +1,4 @@ -package org.jabref.logic.openoffice.ootext; - -import org.jabref.model.openoffice.ootext.OOText; +package org.jabref.model.openoffice.ootext; public class OOFormat { diff --git a/src/main/java/org/jabref/logic/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/ootext/OOTextIntoOO.java rename to src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index 4ee4d58aa61..e1983823870 100644 --- a/src/main/java/org/jabref/logic/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.ootext; +package org.jabref.model.openoffice.ootext; import java.util.ArrayList; import java.util.Arrays; @@ -13,7 +13,6 @@ import java.util.regex.Pattern; import org.jabref.architecture.AllowedToUseAwt; -import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoCrossRef; From 46d28822d6e4a3d417dda9c0233e5ab56fcc4f3b Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 27 May 2021 11:23:22 +0200 Subject: [PATCH 0911/1068] FunctionalTextViewCursor.java now does not depend on JabRef --- .../org/jabref/gui/openoffice/OOBibBase2.java | 16 ++++++++-------- .../frontend/FunctionalTextViewCursor.java | 13 +++++-------- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index 3156dfe61f3..516827b3e47 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -227,20 +227,21 @@ OOResult getUserCursorForTextInsertion(XTextDocument doc, * This may move the view cursor. */ OOResult getFunctionalTextViewCursor(XTextDocument doc, - String title) { + String title) { String messageOnFailureToObtain = Localization.lang("Please move the cursor into the document text.") + "\n" + Localization.lang("To get the visual positions of your citations" + " I need to move the cursor around," + " but could not get it."); - OOResult result = - FunctionalTextViewCursor.get(doc, messageOnFailureToObtain); - return result.mapError(e -> OOError.from(e).setTitle(title)); + OOResult result = FunctionalTextViewCursor.get(doc); + if (result.isError()) { + LOGGER.warn(result.getError()); + } + return result.mapError(detail -> new OOError(title, messageOnFailureToObtain)); } - private static OOVoidResult - checkRangeOverlaps(XTextDocument doc, OOFrontend fr) { + private static OOVoidResult checkRangeOverlaps(XTextDocument doc, OOFrontend fr) { final String title = "checkRangeOverlaps"; boolean requireSeparation = false; int maxReportedOverlaps = 10; @@ -257,8 +258,7 @@ OOResult getFunctionalTextViewCursor(XTextDoc } } - private static OOVoidResult - checkRangeOverlapsWithCursor(XTextDocument doc, OOFrontend fr) { + private static OOVoidResult checkRangeOverlapsWithCursor(XTextDocument doc, OOFrontend fr) { final String title = "checkRangeOverlapsWithCursor"; OOVoidResult precheck = checkRangeOverlaps(doc, fr); diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java b/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java index c47503ec546..95250bdccc5 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java @@ -3,7 +3,6 @@ import java.util.Arrays; import java.util.Objects; -import org.jabref.logic.JabRefException; import org.jabref.model.openoffice.uno.UnoCursor; import org.jabref.model.openoffice.uno.UnoSelection; import org.jabref.model.openoffice.util.OOResult; @@ -34,7 +33,7 @@ * * Usage: * - * OOResult fcursor = FunctionalTextViewCursor.get(doc, msg); + * OOResult fcursor = FunctionalTextViewCursor.get(doc, msg); * if (fcursor.isError()) { * ... * } else { @@ -82,11 +81,9 @@ private FunctionalTextViewCursor(XTextRange initialPosition, * The cursor position may differ from the location * provided by the user. */ - public static OOResult get(XTextDocument doc, - String messageOnFailure) { + public static OOResult get(XTextDocument doc) { Objects.requireNonNull(doc); - Objects.requireNonNull(messageOnFailure); XTextRange initialPosition = null; XServiceInfo initialSelection = UnoSelection.getSelectionAsXServiceInfo(doc).orElse(null); @@ -108,7 +105,7 @@ public static OOResult get(XTextDocum if (initialSelection == null) { String errorMessage = ("Selection is not available:" + " cannot provide a functional view cursor"); - return OOResult.error(new JabRefException(errorMessage, messageOnFailure)); + return OOResult.error(errorMessage); } else if (!Arrays.stream(initialSelection.getSupportedServiceNames()) .anyMatch("com.sun.star.text.TextRanges"::equals)) { // initialSelection does not support TextRanges. @@ -121,7 +118,7 @@ public static OOResult get(XTextDocum if (viewCursor == null) { restore(doc, initialPosition, initialSelection); String errorMessage = "Could not get the view cursor"; - return OOResult.error(new JabRefException(errorMessage, messageOnFailure)); + return OOResult.error(errorMessage); } try { @@ -129,7 +126,7 @@ public static OOResult get(XTextDocum } catch (com.sun.star.uno.RuntimeException ex) { restore(doc, initialPosition, initialSelection); String errorMessage = "The view cursor failed the functionality test"; - return OOResult.error(new JabRefException(errorMessage, messageOnFailure)); + return OOResult.error(errorMessage); } return OOResult.ok(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); From 9e6e083604c1fbc961ff0191bf26f32c1089c6b3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 27 May 2021 11:50:47 +0200 Subject: [PATCH 0912/1068] move rangesort stuff to model --- .../org/jabref/gui/openoffice/OOBibBase2.java | 4 +- .../logic/openoffice/action/Update.java | 2 +- .../logic/openoffice/frontend/OOFrontend.java | 14 +- .../frontend}/RangeForOverlapCheck.java | 2 +- .../rangesort}/FunctionalTextViewCursor.java | 2 +- .../rangesort/RangeKeyedMap.java | 2 +- .../rangesort/RangeKeyedMapList.java | 2 +- .../RangeOverlap.java | 2 +- .../rangesort}/RangeOverlapFinder.java | 7 +- .../RangeOverlapKind.java | 2 +- .../rangesort/RangeSortEntry.java | 2 +- .../rangesort}/RangeSortVisual.java | 134 +++++++++--------- .../rangesort/RangeSortable.java | 2 +- 13 files changed, 86 insertions(+), 91 deletions(-) rename src/main/java/org/jabref/{model/openoffice/frontend/rangeoverlap => logic/openoffice/frontend}/RangeForOverlapCheck.java (95%) rename src/main/java/org/jabref/{logic/openoffice/frontend => model/openoffice/rangesort}/FunctionalTextViewCursor.java (99%) rename src/main/java/org/jabref/model/openoffice/{frontend => }/rangesort/RangeKeyedMap.java (98%) rename src/main/java/org/jabref/model/openoffice/{frontend => }/rangesort/RangeKeyedMapList.java (94%) rename src/main/java/org/jabref/model/openoffice/{frontend/rangeoverlap => rangesort}/RangeOverlap.java (88%) rename src/main/java/org/jabref/{logic/openoffice/frontend => model/openoffice/rangesort}/RangeOverlapFinder.java (89%) rename src/main/java/org/jabref/model/openoffice/{frontend/rangeoverlap => rangesort}/RangeOverlapKind.java (76%) rename src/main/java/org/jabref/model/openoffice/{frontend => }/rangesort/RangeSortEntry.java (93%) rename src/main/java/org/jabref/{logic/openoffice/frontend => model/openoffice/rangesort}/RangeSortVisual.java (88%) rename src/main/java/org/jabref/model/openoffice/{frontend => }/rangesort/RangeSortable.java (91%) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index 516827b3e47..706f09c8e0d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -19,13 +19,13 @@ import org.jabref.logic.openoffice.action.ExportCited; import org.jabref.logic.openoffice.action.ManageCitations; import org.jabref.logic.openoffice.action.Update; -import org.jabref.logic.openoffice.frontend.FunctionalTextViewCursor; import org.jabref.logic.openoffice.frontend.OOFrontend; +import org.jabref.logic.openoffice.frontend.RangeForOverlapCheck; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.model.openoffice.frontend.rangeoverlap.RangeForOverlapCheck; +import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.uno.CreationException; diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index 69fbeb26415..17ffff5a210 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -3,13 +3,13 @@ import java.util.List; import org.jabref.logic.JabRefException; -import org.jabref.logic.openoffice.frontend.FunctionalTextViewCursor; import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.frontend.UpdateBibliography; import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.model.database.BibDatabase; +import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.uno.UnoScreenRefresh; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 1a033b8dbb7..507a7244899 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -13,13 +13,15 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.backend.Backend52; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.model.openoffice.frontend.rangeoverlap.RangeForOverlapCheck; -import org.jabref.model.openoffice.frontend.rangeoverlap.RangeOverlap; -import org.jabref.model.openoffice.frontend.rangesort.RangeKeyedMap; -import org.jabref.model.openoffice.frontend.rangesort.RangeKeyedMapList; -import org.jabref.model.openoffice.frontend.rangesort.RangeSortEntry; -import org.jabref.model.openoffice.frontend.rangesort.RangeSortable; import org.jabref.model.openoffice.ootext.OOText; +import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; +import org.jabref.model.openoffice.rangesort.RangeKeyedMap; +import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; +import org.jabref.model.openoffice.rangesort.RangeOverlap; +import org.jabref.model.openoffice.rangesort.RangeOverlapFinder; +import org.jabref.model.openoffice.rangesort.RangeSortEntry; +import org.jabref.model.openoffice.rangesort.RangeSortVisual; +import org.jabref.model.openoffice.rangesort.RangeSortable; import org.jabref.model.openoffice.style.CitationGroup; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationGroups; diff --git a/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeForOverlapCheck.java b/src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java similarity index 95% rename from src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeForOverlapCheck.java rename to src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java index 20e416c4dec..02dd98636be 100644 --- a/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeForOverlapCheck.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.frontend.rangeoverlap; +package org.jabref.logic.openoffice.frontend; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java b/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java similarity index 99% rename from src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java rename to src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java index 95250bdccc5..039be4537ac 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.frontend; +package org.jabref.model.openoffice.rangesort; import java.util.Arrays; import java.util.Objects; diff --git a/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMap.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java similarity index 98% rename from src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMap.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java index ce4c380e0a4..841b6f52355 100644 --- a/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMap.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.frontend.rangesort; +package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMapList.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java similarity index 94% rename from src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMapList.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java index 1bcf564e155..1c77986c35a 100644 --- a/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.frontend.rangesort; +package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlap.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlap.java similarity index 88% rename from src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlap.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlap.java index ebe75551b7c..849f0e0405b 100644 --- a/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlap.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlap.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.frontend.rangeoverlap; +package org.jabref.model.openoffice.rangesort; import java.util.List; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java similarity index 89% rename from src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java index 2651ed2f72d..59fdf59592c 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/RangeOverlapFinder.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java @@ -1,17 +1,14 @@ -package org.jabref.logic.openoffice.frontend; +package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; -import org.jabref.model.openoffice.frontend.rangeoverlap.RangeOverlap; -import org.jabref.model.openoffice.frontend.rangeoverlap.RangeOverlapKind; -import org.jabref.model.openoffice.frontend.rangesort.RangeKeyedMapList; import org.jabref.model.openoffice.uno.UnoTextRange; import com.sun.star.text.XTextRange; -class RangeOverlapFinder { +public class RangeOverlapFinder { /** * Report identical, overlapping or touching ranges. * diff --git a/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlapKind.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapKind.java similarity index 76% rename from src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlapKind.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapKind.java index b6d5cf2efa8..98bf6df2b40 100644 --- a/src/main/java/org/jabref/model/openoffice/frontend/rangeoverlap/RangeOverlapKind.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapKind.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.frontend.rangeoverlap; +package org.jabref.model.openoffice.rangesort; public enum RangeOverlapKind { /** They share a boundary */ diff --git a/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortEntry.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java similarity index 93% rename from src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortEntry.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java index c1a27b13fd8..4ed651e5396 100644 --- a/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortEntry.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.frontend.rangesort; +package org.jabref.model.openoffice.rangesort; import com.sun.star.text.XTextRange; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java similarity index 88% rename from src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index b4d7212622a..7ed3b54ab32 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -1,4 +1,4 @@ -package org.jabref.logic.openoffice.frontend; +package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; import java.util.List; @@ -6,7 +6,6 @@ import java.util.Set; import java.util.TreeSet; -import org.jabref.model.openoffice.frontend.rangesort.RangeSortable; import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.uno.UnoScreenRefresh; @@ -30,11 +29,73 @@ * of the first column of the first page. * */ -class RangeSortVisual { +public class RangeSortVisual { private static final Logger LOGGER = LoggerFactory.getLogger(RangeSortVisual.class); - /* first appearance order, based on visual order */ + /** + * Sort the input {@code inputs} visually. + * + * Requires a functional {@code XTextViewCursor}. + * + * @return The input, sorted by the elements XTextRange and + * getIndexInPosition. + */ + public static List> visualSort(List> inputs, + XTextDocument doc, + FunctionalTextViewCursor fcursor) + throws + WrappedTargetException, + NoDocumentException { + + final int inputSize = inputs.size(); + + if (UnoScreenRefresh.hasControllersLocked(doc)) { + LOGGER.warn("visualSort:" + + " with ControllersLocked, viewCursor.gotoRange" + + " is probably useless"); + } + + XTextViewCursor viewCursor = fcursor.getViewCursor(); + + // find coordinates + List positions = new ArrayList<>(inputSize); + + for (RangeSortable v : inputs) { + positions.add(findPositionOfTextRange(v.getRange(), + viewCursor)); + } + + fcursor.restore(doc); + + if (positions.size() != inputSize) { + throw new RuntimeException("visualSort: positions.size() != inputSize"); + } + + // order by position + Set>> set = new TreeSet<>(); + for (int i = 0; i < inputSize; i++) { + set.add(new ComparableMark<>(positions.get(i), + inputs.get(i).getIndexInPosition(), + inputs.get(i))); + } + + if (set.size() != inputSize) { + throw new RuntimeException("visualSort: set.size() != inputSize"); + } + + // collect ordered result + List> result = new ArrayList<>(set.size()); + for (ComparableMark> mark : set) { + result.add(mark.getContent()); + } + + if (result.size() != inputSize) { + throw new RuntimeException("visualSort: result.size() != inputSize"); + } + + return result; + } /** * Given a location, return its position: coordinates relative to @@ -122,69 +183,4 @@ public int hashCode() { } } - /** - * Sort its input {@code vses} visually. - * - * Requires a functional {@code XTextViewCursor}. - * - * @return The input, sorted by the elements XTextRange and - * getIndexInPosition. - */ - public static List> - visualSort(List> vses, - XTextDocument doc, - FunctionalTextViewCursor fcursor) - throws - WrappedTargetException, - NoDocumentException { - - final int inputSize = vses.size(); - - if (UnoScreenRefresh.hasControllersLocked(doc)) { - LOGGER.warn("visualSort:" - + " with ControllersLocked, viewCursor.gotoRange" - + " is probably useless"); - } - - XTextViewCursor viewCursor = fcursor.getViewCursor(); - - // find coordinates - List positions = new ArrayList<>(vses.size()); - - for (RangeSortable v : vses) { - positions.add(findPositionOfTextRange(v.getRange(), - viewCursor)); - } - - fcursor.restore(doc); - - if (positions.size() != inputSize) { - throw new RuntimeException("visualSort: positions.size() != inputSize"); - } - - // order by position - Set>> set = new TreeSet<>(); - for (int i = 0; i < vses.size(); i++) { - set.add(new ComparableMark<>(positions.get(i), - vses.get(i).getIndexInPosition(), - vses.get(i))); - } - - if (set.size() != inputSize) { - throw new RuntimeException("visualSort: set.size() != inputSize"); - } - - // collect ordered result - List> result = new ArrayList<>(set.size()); - for (ComparableMark> mark : set) { - result.add(mark.getContent()); - } - - if (result.size() != inputSize) { - throw new RuntimeException("visualSort: result.size() != inputSize"); - } - - return result; - } - } diff --git a/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortable.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java similarity index 91% rename from src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortable.java rename to src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java index bc78a982a75..6b2c1fa9e8f 100644 --- a/src/main/java/org/jabref/model/openoffice/frontend/rangesort/RangeSortable.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java @@ -1,4 +1,4 @@ -package org.jabref.model.openoffice.frontend.rangesort; +package org.jabref.model.openoffice.rangesort; import com.sun.star.text.XTextRange; From a29a8b019d55927a1d62d2028e7bdea0e63692c9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 27 May 2021 13:51:07 +0200 Subject: [PATCH 0913/1068] rename OOBibStyleTest OOBibStyleTest2 --- .../style/{OOBibStyleTest.java => OOBibStyleTest2.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/test/java/org/jabref/logic/openoffice/style/{OOBibStyleTest.java => OOBibStyleTest2.java} (100%) diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest2.java similarity index 100% rename from src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java rename to src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest2.java From 1cf5c9a05e0ca888167d09cfb00c6d8cee0bec98 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 27 May 2021 13:54:25 +0200 Subject: [PATCH 0914/1068] restore OOBibStyleTest --- .../openoffice/style/OOBibStyleTest.java | 516 ++++++++++++++++++ 1 file changed, 516 insertions(+) create mode 100644 src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java new file mode 100644 index 00000000000..786e678324c --- /dev/null +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java @@ -0,0 +1,516 @@ +package org.jabref.logic.openoffice.style; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.jabref.logic.layout.Layout; +import org.jabref.logic.layout.LayoutFormatterPreferences; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.StandardField; +import org.jabref.model.entry.types.StandardEntryType; +import org.jabref.model.entry.types.UnknownEntryType; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +class OOBibStyleTest { + private LayoutFormatterPreferences layoutFormatterPreferences; + + @BeforeEach + void setUp() { + layoutFormatterPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); + } + + @Test + void testAuthorYear() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, layoutFormatterPreferences); + assertTrue(style.isValid()); + assertTrue(style.isInternalStyle()); + assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.isBoldCitations()); + assertFalse(style.isFormatCitations()); + assertFalse(style.isItalicCitations()); + assertFalse(style.isNumberEntries()); + assertFalse(style.isSortByPosition()); + } + + @Test + void testAuthorYearAsFile() throws URISyntaxException, IOException { + File defFile = Path.of(OOBibStyleTest.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) + .toFile(); + OOBibStyle style = new OOBibStyle(defFile, layoutFormatterPreferences, StandardCharsets.UTF_8); + assertTrue(style.isValid()); + assertFalse(style.isInternalStyle()); + assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.isBoldCitations()); + assertFalse(style.isFormatCitations()); + assertFalse(style.isItalicCitations()); + assertFalse(style.isNumberEntries()); + assertFalse(style.isSortByPosition()); + } + + @Test + void testNumerical() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + assertTrue(style.isValid()); + assertFalse(style.isCitationKeyCiteMarkers()); + assertFalse(style.isBoldCitations()); + assertFalse(style.isFormatCitations()); + assertFalse(style.isItalicCitations()); + assertTrue(style.isNumberEntries()); + assertTrue(style.isSortByPosition()); + } + + @Test + void testGetNumCitationMarker() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), -1, true)); + assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, false)); + assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), 0, true)); + assertEquals("[1-3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, true)); + assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, true)); + assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, true)); + assertEquals("[1; 3; 12] ", style.getNumCitationMarker(Arrays.asList(1, 12, 3), 1, true)); + assertEquals("[3-5; 7; 10-12] ", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, true)); + + String citation = style.getNumCitationMarker(Arrays.asList(1), -1, false); + assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); + } + + @Test + void testGetNumCitationMarkerUndefined() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4] ", + style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, true)); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", + style.getNumCitationMarker(Arrays.asList(0), 1, true)); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3] ", + style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, true)); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", + style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, true)); + } + + @Test + void testGetCitProperty() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + assertEquals(", ", style.getStringCitProperty("AuthorSeparator")); + assertEquals(3, style.getIntCitProperty("MaxAuthors")); + assertTrue(style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)); + assertEquals("Default", style.getCitationCharacterFormat()); + assertEquals("Default [number] style file.", style.getName()); + Set journals = style.getJournals(); + assertTrue(journals.contains("Journal name 1")); + } + + @Test + void testGetCitationMarker() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + BibEntry entry = new BibEntry() + .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m and Jaana W\\\"{a}yrynen and Marine Bod\\'{e}n and Konstantin Beznosov and Philippe Kruchten") + .withField(StandardField.YEAR, "2006") + .withField(StandardField.BOOKTITLE, "SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems") + .withField(StandardField.PUBLISHER, "ACM") + .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") + .withField(StandardField.PAGES, "11--18"); + BibDatabase database = new BibDatabase(); + database.insertEntry(entry); + Map entryDBMap = new HashMap<>(); + entryDBMap.put(entry, database); + + assertEquals("[Boström et al., 2006]", + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, null)); + assertEquals("Boström et al. [2006]", + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, false, null, new int[]{3})); + assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, new int[]{5})); + } + + @Test + void testLayout() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + + BibEntry entry = new BibEntry() + .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m and Jaana W\\\"{a}yrynen and Marine Bod\\'{e}n and Konstantin Beznosov and Philippe Kruchten") + .withField(StandardField.YEAR, "2006") + .withField(StandardField.BOOKTITLE, "SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems") + .withField(StandardField.PUBLISHER, "ACM") + .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") + .withField(StandardField.PAGES, "11--18"); + BibDatabase database = new BibDatabase(); + database.insertEntry(entry); + + Layout l = style.getReferenceFormat(new UnknownEntryType("default")); + l.setPostFormatter(new OOPreFormatter()); + assertEquals( + "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006). Extending XP practices to support security requirements engineering, : 11-18.", + l.doLayout(entry, database)); + + l = style.getReferenceFormat(StandardEntryType.InCollection); + l.setPostFormatter(new OOPreFormatter()); + assertEquals( + "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006). Extending XP practices to support security requirements engineering. In: (Ed.), SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems, ACM.", + l.doLayout(entry, database)); + } + + @Test + void testInstitutionAuthor() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + BibDatabase database = new BibDatabase(); + + Layout l = style.getReferenceFormat(StandardEntryType.Article); + l.setPostFormatter(new OOPreFormatter()); + + BibEntry entry = new BibEntry(); + entry.setType(StandardEntryType.Article); + entry.setField(StandardField.AUTHOR, "{JabRef Development Team}"); + entry.setField(StandardField.TITLE, "JabRef Manual"); + entry.setField(StandardField.YEAR, "2016"); + database.insertEntry(entry); + assertEquals("JabRef Development Team (2016). JabRef Manual, .", + l.doLayout(entry, database)); + } + + @Test + void testVonAuthor() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + BibDatabase database = new BibDatabase(); + + Layout l = style.getReferenceFormat(StandardEntryType.Article); + l.setPostFormatter(new OOPreFormatter()); + + BibEntry entry = new BibEntry(); + entry.setType(StandardEntryType.Article); + entry.setField(StandardField.AUTHOR, "Alpha von Beta"); + entry.setField(StandardField.TITLE, "JabRef Manual"); + entry.setField(StandardField.YEAR, "2016"); + database.insertEntry(entry); + assertEquals("von Beta, A. (2016). JabRef Manual, .", + l.doLayout(entry, database)); + } + + @Test + void testInstitutionAuthorMarker() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + + Map entryDBMap = new HashMap<>(); + List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); + + BibEntry entry = new BibEntry(); + entry.setType(StandardEntryType.Article); + entry.setField(StandardField.AUTHOR, "{JabRef Development Team}"); + entry.setField(StandardField.TITLE, "JabRef Manual"); + entry.setField(StandardField.YEAR, "2016"); + database.insertEntry(entry); + entries.add(entry); + entryDBMap.put(entry, database); + assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + } + + @Test + void testVonAuthorMarker() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + + Map entryDBMap = new HashMap<>(); + List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); + + BibEntry entry = new BibEntry(); + entry.setType(StandardEntryType.Article); + entry.setField(StandardField.AUTHOR, "Alpha von Beta"); + entry.setField(StandardField.TITLE, "JabRef Manual"); + entry.setField(StandardField.YEAR, "2016"); + database.insertEntry(entry); + entries.add(entry); + entryDBMap.put(entry, database); + assertEquals("[von Beta, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + } + + @Test + void testNullAuthorMarker() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + + Map entryDBMap = new HashMap<>(); + List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); + + BibEntry entry = new BibEntry(); + entry.setType(StandardEntryType.Article); + entry.setField(StandardField.YEAR, "2016"); + database.insertEntry(entry); + entries.add(entry); + entryDBMap.put(entry, database); + assertEquals("[, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + } + + @Test + void testNullYearMarker() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + + Map entryDBMap = new HashMap<>(); + List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); + + BibEntry entry = new BibEntry(); + entry.setType(StandardEntryType.Article); + entry.setField(StandardField.AUTHOR, "Alpha von Beta"); + database.insertEntry(entry); + entries.add(entry); + entryDBMap.put(entry, database); + assertEquals("[von Beta, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + } + + @Test + void testEmptyEntryMarker() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + + Map entryDBMap = new HashMap<>(); + List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); + + BibEntry entry = new BibEntry(); + entry.setType(StandardEntryType.Article); + database.insertEntry(entry); + entries.add(entry); + entryDBMap.put(entry, database); + assertEquals("[, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + } + + @Test + void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + + Map entryDBMap = new HashMap<>(); + List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); + + BibEntry entry1 = new BibEntry(); + entry1.setField(StandardField.AUTHOR, "Alpha Beta"); + entry1.setField(StandardField.TITLE, "Paper 1"); + entry1.setField(StandardField.YEAR, "2000"); + entries.add(entry1); + database.insertEntry(entry1); + BibEntry entry3 = new BibEntry(); + entry3.setField(StandardField.AUTHOR, "Alpha Beta"); + entry3.setField(StandardField.TITLE, "Paper 2"); + entry3.setField(StandardField.YEAR, "2000"); + entries.add(entry3); + database.insertEntry(entry3); + BibEntry entry2 = new BibEntry(); + entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); + entry2.setField(StandardField.YEAR, "2001"); + entries.add(entry2); + database.insertEntry(entry2); + for (BibEntry entry : database.getEntries()) { + entryDBMap.put(entry, database); + } + + assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", + style.getCitationMarker(entries, entryDBMap, true, null, null)); + assertEquals("[Beta, 2000a,b; Epsilon, 2001]", + style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); + } + + @Test + void testGetCitationMarkerInTextUniquefiers() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + + Map entryDBMap = new HashMap<>(); + List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); + + BibEntry entry1 = new BibEntry(); + entry1.setField(StandardField.AUTHOR, "Alpha Beta"); + entry1.setField(StandardField.TITLE, "Paper 1"); + entry1.setField(StandardField.YEAR, "2000"); + entries.add(entry1); + database.insertEntry(entry1); + BibEntry entry3 = new BibEntry(); + entry3.setField(StandardField.AUTHOR, "Alpha Beta"); + entry3.setField(StandardField.TITLE, "Paper 2"); + entry3.setField(StandardField.YEAR, "2000"); + entries.add(entry3); + database.insertEntry(entry3); + BibEntry entry2 = new BibEntry(); + entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); + entry2.setField(StandardField.YEAR, "2001"); + entries.add(entry2); + database.insertEntry(entry2); + for (BibEntry entry : database.getEntries()) { + entryDBMap.put(entry, database); + } + + assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", + style.getCitationMarker(entries, entryDBMap, false, null, null)); + assertEquals("Beta [2000a,b]; Epsilon [2001]", + style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); + } + + @Test + void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + + Map entryDBMap = new HashMap<>(); + List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); + + BibEntry entry1 = new BibEntry(); + entry1.setField(StandardField.AUTHOR, "Alpha Beta"); + entry1.setField(StandardField.TITLE, "Paper 1"); + entry1.setField(StandardField.YEAR, "2000"); + entries.add(entry1); + database.insertEntry(entry1); + BibEntry entry2 = new BibEntry(); + entry2.setField(StandardField.AUTHOR, "Alpha Beta"); + entry2.setField(StandardField.TITLE, "Paper 2"); + entry2.setField(StandardField.YEAR, "2000"); + entries.add(entry2); + database.insertEntry(entry2); + BibEntry entry3 = new BibEntry(); + entry3.setField(StandardField.AUTHOR, "Alpha Beta"); + entry3.setField(StandardField.TITLE, "Paper 3"); + entry3.setField(StandardField.YEAR, "2000"); + entries.add(entry3); + database.insertEntry(entry3); + for (BibEntry entry : database.getEntries()) { + entryDBMap.put(entry, database); + } + + assertEquals("[Beta, 2000a,b,c]", + style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); + } + + @Test + void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + + Map entryDBMap = new HashMap<>(); + List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); + + BibEntry entry1 = new BibEntry(); + entry1.setField(StandardField.AUTHOR, "Alpha Beta"); + entry1.setField(StandardField.TITLE, "Paper 1"); + entry1.setField(StandardField.YEAR, "2000"); + entries.add(entry1); + database.insertEntry(entry1); + BibEntry entry2 = new BibEntry(); + entry2.setField(StandardField.AUTHOR, "Alpha Beta"); + entry2.setField(StandardField.TITLE, "Paper 2"); + entry2.setField(StandardField.YEAR, "2000"); + entries.add(entry2); + database.insertEntry(entry2); + BibEntry entry3 = new BibEntry(); + entry3.setField(StandardField.AUTHOR, "Alpha Beta"); + entry3.setField(StandardField.TITLE, "Paper 3"); + entry3.setField(StandardField.YEAR, "2000"); + entries.add(entry3); + database.insertEntry(entry3); + for (BibEntry entry : database.getEntries()) { + entryDBMap.put(entry, database); + } + + assertEquals("Beta [2000a,b,c]", + style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); + } + + @Test + // TODO: equals only work when initialized from file, not from reader + void testEquals() throws IOException { + OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + assertEquals(style1, style2); + } + + @Test + // TODO: equals only work when initialized from file, not from reader + void testNotEquals() throws IOException { + OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, + layoutFormatterPreferences); + assertNotEquals(style1, style2); + } + + @Test + void testCompareToEqual() throws IOException { + OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + assertEquals(0, style1.compareTo(style2)); + } + + @Test + void testCompareToNotEqual() throws IOException { + OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, + layoutFormatterPreferences); + assertTrue(style1.compareTo(style2) > 0); + assertFalse(style2.compareTo(style1) > 0); + } + + @Test + void testEmptyStringPropertyAndOxfordComma() throws Exception { + OOBibStyle style = new OOBibStyle("test.jstyle", layoutFormatterPreferences); + Map entryDBMap = new HashMap<>(); + List entries = new ArrayList<>(); + BibDatabase database = new BibDatabase(); + + BibEntry entry = new BibEntry(); + entry.setType(StandardEntryType.Article); + entry.setField(StandardField.AUTHOR, "Alpha von Beta and Gamma Epsilon and Ypsilon Tau"); + entry.setField(StandardField.TITLE, "JabRef Manual"); + entry.setField(StandardField.YEAR, "2016"); + database.insertEntry(entry); + entries.add(entry); + entryDBMap.put(entry, database); + assertEquals("von Beta, Epsilon, & Tau, 2016", + style.getCitationMarker(entries, entryDBMap, true, null, null)); + } + + @Test + void testIsValidWithDefaultSectionAtTheStart() throws Exception { + OOBibStyle style = new OOBibStyle("testWithDefaultAtFirstLIne.jstyle", layoutFormatterPreferences); + assertTrue(style.isValid()); + } +} From 85b6c1d0e657a0e1fbcca9fa16334c472b51e2d5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 27 May 2021 15:37:58 +0200 Subject: [PATCH 0915/1068] uncomment old stuff --- .../logic/openoffice/style/OOBibStyle.java | 105 +++++++++++++++--- 1 file changed, 89 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index 3b9cfa012dd..47fb6c29224 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -441,6 +441,75 @@ public Layout getReferenceFormat(EntryType type) { } } + /* begin_old */ + /** + * Format a number-based citation marker for the given number. + * + * @param number The citation numbers. + * @return The text for the citation. + */ + public String getNumCitationMarker(List number, int minGroupingCount, boolean inList) { + String bracketBefore = getStringCitProperty(BRACKET_BEFORE); + if (inList && (citProperties.containsKey(BRACKET_BEFORE_IN_LIST))) { + bracketBefore = getStringCitProperty(BRACKET_BEFORE_IN_LIST); + } + String bracketAfter = getStringCitProperty(BRACKET_AFTER); + if (inList && (citProperties.containsKey(BRACKET_AFTER_IN_LIST))) { + bracketAfter = getStringCitProperty(BRACKET_AFTER_IN_LIST); + } + // Sort the numbers: + List lNum = new ArrayList<>(number); + Collections.sort(lNum); + StringBuilder sb = new StringBuilder(bracketBefore); + int combineFrom = -1; + int written = 0; + for (int i = 0; i < lNum.size(); i++) { + int i1 = lNum.get(i); + if (combineFrom < 0) { + // Check if next entry is the next in the ref list: + if ((i < (lNum.size() - 1)) && (lNum.get(i + 1) == (i1 + 1)) && (i1 > 0)) { + combineFrom = i1; + } else { + // Add single entry: + if (i > 0) { + sb.append(getStringCitProperty(CITATION_SEPARATOR)); + } + sb.append(lNum.get(i) > 0 ? String.valueOf(lNum.get(i)) : OOBibStyle.UNDEFINED_CITATION_MARKER); + written++; + } + } else { + // We are building a list of combined entries. + // Check if it ends here: + if ((i == (lNum.size() - 1)) || (lNum.get(i + 1) != (i1 + 1))) { + if (written > 0) { + sb.append(getStringCitProperty(CITATION_SEPARATOR)); + } + if ((minGroupingCount > 0) && (((i1 + 1) - combineFrom) >= minGroupingCount)) { + sb.append(combineFrom); + sb.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); + sb.append(i1); + written++; + } else { + // Either we should never group, or there aren't enough + // entries in this case to group. Output all: + for (int jj = combineFrom; jj <= i1; jj++) { + sb.append(jj); + if (jj < i1) { + sb.append(getStringCitProperty(CITATION_SEPARATOR)); + } + written++; + } + } + combineFrom = -1; + } + // If it doesn't end here, just keep iterating. + } + } + sb.append(bracketAfter); + return sb.toString(); + } + /* end_old */ + /** * Format a number-based citation marker for the given entries. * @@ -463,7 +532,7 @@ public OOText getNumCitationMarker2(List entries, minGroupingCount); } - /* moved to OOBibStyleGetCitationMarker + /* begin_old */ public String getCitationMarker(List entries, Map database, boolean inParenthesis, String[] uniquefiers, int[] unlimAuthors) { // Look for groups of uniquefied entries that should be combined in the output. @@ -527,9 +596,9 @@ public String getCitationMarker(List entries, Map entries, String[] uniquefiers, int from, int to) { String separator = getStringCitProperty(UNIQUEFIER_SEPARATOR); StringBuilder sb = new StringBuilder(uniquefiers[from]); @@ -540,9 +609,9 @@ private void group(List entries, String[] uniquefiers, int from, int t } uniquefiers[from] = sb.toString(); } - */ + /* end_old */ - /* moved to OOBibStyleGetCitationMarker + /* begin_old */ private String getAuthorYearParenthesisMarker(List entries, Map database, String[] uniquifiers, int[] unlimAuthors) { @@ -586,9 +655,9 @@ private String getAuthorYearParenthesisMarker(List entries, Map entries, Map database, String[] uniquefiers, int[] unlimAuthors) { @@ -638,9 +707,10 @@ private String getAuthorYearInTextMarker(List entries, Map Date: Thu, 27 May 2021 16:15:57 +0200 Subject: [PATCH 0916/1068] OOBibStyleTest.java only has additions now --- .../logic/openoffice/style/OOBibStyle.java | 6 + .../openoffice/style/OOBibStyleTest.java | 401 ++++++ .../openoffice/style/OOBibStyleTest2.java | 1101 ----------------- .../style/OOBibStyleTestHelper.java | 359 ++++++ 4 files changed, 766 insertions(+), 1101 deletions(-) delete mode 100644 src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest2.java create mode 100644 src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index 47fb6c29224..471d1747265 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -25,6 +25,11 @@ import org.jabref.logic.layout.LayoutFormatter; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.layout.LayoutHelper; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.Author; +import org.jabref.model.entry.AuthorList; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; @@ -39,6 +44,7 @@ import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.jabref.model.openoffice.style.PageInfo; import org.jabref.model.openoffice.util.OOListUtil; +import org.jabref.model.strings.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java index 786e678324c..3b9fb5095f5 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java @@ -11,7 +11,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.jabref.logic.layout.Layout; import org.jabref.logic.layout.LayoutFormatterPreferences; @@ -20,6 +24,14 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; +import org.jabref.model.openoffice.ootext.OOText; +import org.jabref.model.openoffice.style.Citation; +import org.jabref.model.openoffice.style.CitationLookupResult; +import org.jabref.model.openoffice.style.CitationMarkerEntry; +import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; +import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; +import org.jabref.model.openoffice.style.NonUniqueCitationMarker; +import org.jabref.model.openoffice.style.PageInfo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -80,13 +92,86 @@ void testNumerical() throws IOException { assertTrue(style.isSortByPosition()); } + /* + * begin helpers + */ + static String runGetNumCitationMarker2a(OOBibStyle style, + List num, int minGroupingCount, boolean inList ) { + return OOBibStyleTestHelper.runGetNumCitationMarker2a(style, num, minGroupingCount, inList); + } + + static CitationMarkerNumericEntry numEntry(String key, int num, String pageInfoOrNull) { + return OOBibStyleTestHelper.numEntry(key, num, pageInfoOrNull); + } + + static CitationMarkerNumericBibEntry numBibEntry(String key, Optional num) { + return OOBibStyleTestHelper.numBibEntry(key, num); + } + + static String runGetNumCitationMarker2b(OOBibStyle style, + int minGroupingCount, + CitationMarkerNumericEntry... s) { + List input = Stream.of(s).collect(Collectors.toList()); + OOText res = style.getNumCitationMarker2(input, minGroupingCount); + return res.asString(); + } + + static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, + BibDatabase database, + String uniqueLetterQ, + String pageInfoQ, + boolean isFirstAppearanceOfSource) { + return OOBibStyleTestHelper.makeCitationMarkerEntry(entry, + database, + uniqueLetterQ, + pageInfoQ, + isFirstAppearanceOfSource ); + } + + /* + * Similar to old API. pageInfo is new, and unlimAuthors is + * replaced with isFirstAppearanceOfSource + */ + String getCitationMarker2(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { + return OOBibStyleTestHelper.getCitationMarker2(style, + entries, + entryDBMap, + inParenthesis, + uniquefiers, + isFirstAppearanceOfSource, + pageInfo ); + } + + /* + * end helpers + */ + + @Test void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), -1, true)); + assertEquals("[1] ", runGetNumCitationMarker2a(style, Arrays.asList(1), -1, true)); + assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, false)); + assertEquals("[1]", runGetNumCitationMarker2a(style, Arrays.asList(1), -1, false)); + assertEquals("[1]", runGetNumCitationMarker2b(style, -1, numEntry("key", 1, null))); + assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), 0, true)); + assertEquals("[1] ", runGetNumCitationMarker2a(style, Arrays.asList(1), 0, true)); + + /* + * The following tests as for a numeric label for a + * bibliography entry containing more than one numbers. + * We do not need this, not reproduced. + */ assertEquals("[1-3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, true)); assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, true)); assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, true)); @@ -95,12 +180,24 @@ void testGetNumCitationMarker() throws IOException { String citation = style.getNumCitationMarker(Arrays.asList(1), -1, false); assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); + + CitationMarkerNumericEntry e2 = numEntry("key", 1, "pp. 55-56"); + assertEquals(true, e2.getPageInfo().isPresent()); + assertEquals("pp. 55-56", e2.getPageInfo().get().asString()); + citation = runGetNumCitationMarker2b(style, -1, e2); + assertEquals("[1; pp. 55-56]", citation); + + OOBibStyleTestHelper.testGetNumCitationMarkerExtra(style); } @Test void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + /* + * Testing bibliography labels with multiple numbers again. + * Not reproduced. + */ assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4] ", style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, true)); @@ -113,6 +210,55 @@ void testGetNumCitationMarkerUndefined() throws IOException { assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, true)); + + /* + * We have these instead: + */ + + // unresolved citations look like [??key] + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "]", + runGetNumCitationMarker2b(style, 1, + numEntry("key",0,null))); + + // pageInfo is shown for unresolved citations + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; p1]", + runGetNumCitationMarker2b(style, 1, + numEntry("key",0,"p1"))); + + // unresolved citations sorted to the front + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 2-4]", + runGetNumCitationMarker2b(style, 1, + numEntry("x4",4,""), + numEntry("x2",2,""), + numEntry("x3",3,""), + numEntry("key",0,""))); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 1-3]", + runGetNumCitationMarker2b(style, 1, + numEntry("x1",1,""), + numEntry("x2",2,""), + numEntry("y3",3,""), + numEntry("key",0,""))); + + // multiple unresolved citations are not collapsed + assertEquals("[" + + OOBibStyle.UNDEFINED_CITATION_MARKER + "x1" + "; " + + OOBibStyle.UNDEFINED_CITATION_MARKER + "x2" + "; " + + OOBibStyle.UNDEFINED_CITATION_MARKER + "x3" + "]", + runGetNumCitationMarker2b(style, 1, + numEntry("x1",0,""), + numEntry("x2",0,""), + numEntry("x3",0,""))); + + /* + * BIBLIOGRAPHY + */ + { + CitationMarkerNumericBibEntry x = numBibEntry("key", Optional.empty()); + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", + style.getNumCitationMarkerForBibliography(x).asString()); + } + } @Test @@ -120,14 +266,21 @@ void testGetCitProperty() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); assertEquals(", ", style.getStringCitProperty("AuthorSeparator")); + + // old assertEquals(3, style.getIntCitProperty("MaxAuthors")); assertTrue(style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)); + // new + assertEquals(3, style.getMaxAuthors()); + assertTrue(style.getMultiCiteChronological()); + assertEquals("Default", style.getCitationCharacterFormat()); assertEquals("Default [number] style file.", style.getName()); Set journals = style.getJournals(); assertTrue(journals.contains("Journal name 1")); } + @Test void testGetCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); @@ -138,17 +291,39 @@ void testGetCitationMarker() throws IOException { .withField(StandardField.PUBLISHER, "ACM") .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") .withField(StandardField.PAGES, "11--18"); + entry.setCitationKey("Bostrom2006"); // citation key is not optional now BibDatabase database = new BibDatabase(); database.insertEntry(entry); Map entryDBMap = new HashMap<>(); entryDBMap.put(entry, database); + // Check what unlimAuthors values correspond to isFirstAppearanceOfSource false/true + assertEquals(3, style.getMaxAuthors()); + assertEquals(-1, style.getMaxAuthorsFirst()); + assertEquals("[Boström et al., 2006]", style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, null)); + assertEquals("[Boström et al., 2006]", + getCitationMarker2(style, + Collections.singletonList(entry), entryDBMap, + true, null, null, null)); + assertEquals("Boström et al. [2006]", style.getCitationMarker(Collections.singletonList(entry), entryDBMap, false, null, new int[]{3})); + assertEquals("Boström et al. [2006]", + getCitationMarker2(style, + Collections.singletonList(entry), entryDBMap, + false, null, new Boolean[]{false}, null)); + assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, new int[]{5})); + assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", + getCitationMarker2(style, + Collections.singletonList(entry), entryDBMap, + true, + null, + new Boolean[]{true} /* corresponds to -1, not 5 */, + null)); } @Test @@ -225,6 +400,7 @@ void testInstitutionAuthorMarker() throws IOException { BibDatabase database = new BibDatabase(); BibEntry entry = new BibEntry(); + entry.setCitationKey("JabRef2016"); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "{JabRef Development Team}"); entry.setField(StandardField.TITLE, "JabRef Manual"); @@ -233,6 +409,10 @@ void testInstitutionAuthorMarker() throws IOException { entries.add(entry); entryDBMap.put(entry, database); assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + + assertEquals("[JabRef Development Team, 2016]", + getCitationMarker2(style, + entries, entryDBMap, true, null, null, null)); } @Test @@ -513,4 +693,225 @@ void testIsValidWithDefaultSectionAtTheStart() throws Exception { OOBibStyle style = new OOBibStyle("testWithDefaultAtFirstLIne.jstyle", layoutFormatterPreferences); assertTrue(style.isValid()); } + + @Test + void testGetCitationMarkerJoinFirst() throws IOException { + OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, + layoutFormatterPreferences); + + // Question: What should happen if some of the sources is + // marked as isFirstAppearanceOfSource? + // This test documents what is happening now. + + // Two entries with identical normalizedMarkers and many authors. + BibEntry entry1 = new BibEntry() + .withField(StandardField.AUTHOR, + "Gustav Bostr\\\"{o}m" + + " and Jaana W\\\"{a}yrynen" + + " and Marine Bod\\'{e}n" + + " and Konstantin Beznosov" + + " and Philippe Kruchten") + .withField(StandardField.YEAR, "2006") + .withField(StandardField.BOOKTITLE, "A book 1") + .withField(StandardField.PUBLISHER, "ACM") + .withField(StandardField.TITLE, "Title 1") + .withField(StandardField.PAGES, "11--18"); + entry1.setCitationKey("b1"); + + BibEntry entry2 = new BibEntry() + .withField(StandardField.AUTHOR, + "Gustav Bostr\\\"{o}m" + + " and Jaana W\\\"{a}yrynen" + + " and Marine Bod\\'{e}n" + + " and Konstantin Beznosov" + + " and Philippe Kruchten") + .withField(StandardField.YEAR, "2006") + .withField(StandardField.BOOKTITLE, "A book 2") + .withField(StandardField.PUBLISHER, "ACM") + .withField(StandardField.TITLE, "title2") + .withField(StandardField.PAGES, "11--18"); + entry2.setCitationKey("b2"); + + // Last Author differs. + BibEntry entry3 = new BibEntry() + .withField(StandardField.AUTHOR, + "Gustav Bostr\\\"{o}m" + + " and Jaana W\\\"{a}yrynen" + + " and Marine Bod\\'{e}n" + + " and Konstantin Beznosov" + + " and Philippe NotKruchten") + .withField(StandardField.YEAR, "2006") + .withField(StandardField.BOOKTITLE, "A book 3") + .withField(StandardField.PUBLISHER, "ACM") + .withField(StandardField.TITLE, "title3") + .withField(StandardField.PAGES, "11--18"); + entry3.setCitationKey("b3"); + + BibDatabase database = new BibDatabase(); + database.insertEntry(entry1); + database.insertEntry(entry2); + database.insertEntry(entry3); + + // Without pageInfo, two isFirstAppearanceOfSource may be joined. + // The third is NotKruchten, should not be joined. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + makeCitationMarkerEntry(entry1, database, "a", null, true); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + makeCitationMarkerEntry(entry2, database, "b", null, true); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + makeCitationMarkerEntry(entry3, database, "c", null, true); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" + +"; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); + + assertEquals("Boström, Wäyrynen, Bodén, Beznosov & Kruchten [2006a,b]" + + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten [2006c]", + style.createCitationMarker(citationMarkerEntries, + false, + NonUniqueCitationMarker.THROWS).asString()); + } + + // Without pageInfo, only the first is isFirstAppearanceOfSource. + // The second may be joined, based on expanded normalizedMarkers. + // The third is NotKruchten, should not be joined. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + makeCitationMarkerEntry(entry1, database, "a", null, true); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + makeCitationMarkerEntry(entry2, database, "b", null, false); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + makeCitationMarkerEntry(entry3, database, "c", null, false); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" + +"; Boström et al., 2006c]", + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); + + } + // Without pageInfo, only the second is isFirstAppearanceOfSource. + // The second is not joined, because it is a first appearance, thus + // requires more names to be shown. + // The third is NotKruchten, should not be joined. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + makeCitationMarkerEntry(entry1, database, "a", null, false); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + makeCitationMarkerEntry(entry2, database, "b", null, true); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + makeCitationMarkerEntry(entry3, database, "c", null, false); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström et al., 2006a" + + "; Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006b" + + "; Boström et al., 2006c]", + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); + } + + // Without pageInfo, neither is isFirstAppearanceOfSource. + // The second is joined. + // The third is NotKruchten, but is joined because NotKruchten is not among the names shown. + // Is this the correct behaviour? + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + makeCitationMarkerEntry(entry1, database, "a", null, false); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + makeCitationMarkerEntry(entry2, database, "b", null, false); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + makeCitationMarkerEntry(entry3, database, "c", null, false); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström et al., 2006a,b,c]", + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); + } + + // With pageInfo: different entries with identical non-null pageInfo: not joined. + // XY [2000a,b,c; p1] whould be confusing. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + makeCitationMarkerEntry(entry1, database, "a", "p1", false); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + makeCitationMarkerEntry(entry2, database, "b", "p1", false); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + makeCitationMarkerEntry(entry3, database, "c", "p1", false); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström et al., 2006a; p1" + + "; Boström et al., 2006b; p1" + + "; Boström et al., 2006c; p1]", + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); + } + + // With pageInfo: same entries with identical non-null pageInfo: collapsed. + // Note: "same" here looks at the visible parts and citation key only, + // but ignores the rest. Normally the citation key should distinguish. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + makeCitationMarkerEntry(entry1, database, "a", "p1", false); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + makeCitationMarkerEntry(entry1, database, "a", "p1", false); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + makeCitationMarkerEntry(entry1, database, "a", "p1", false); + citationMarkerEntries.add(cm3); + + assertEquals("[Boström et al., 2006a; p1]", + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); + } + // With pageInfo: same entries with different pageInfo: kept separate. + // Empty ("") and missing pageInfos considered equal, thus collapsed. + if (true) { + List citationMarkerEntries = new ArrayList<>(); + CitationMarkerEntry cm1 = + makeCitationMarkerEntry(entry1, database, "a", "p1", false); + citationMarkerEntries.add(cm1); + CitationMarkerEntry cm2 = + makeCitationMarkerEntry(entry1, database, "a", "p2", false); + citationMarkerEntries.add(cm2); + CitationMarkerEntry cm3 = + makeCitationMarkerEntry(entry1, database, "a", "", false); + citationMarkerEntries.add(cm3); + CitationMarkerEntry cm4 = + makeCitationMarkerEntry(entry1, database, "a", null, false); + citationMarkerEntries.add(cm4); + + assertEquals("[Boström et al., 2006a; p1" + + "; Boström et al., 2006a; p2" + + "; Boström et al., 2006a]", + style.createCitationMarker(citationMarkerEntries, + true, + NonUniqueCitationMarker.THROWS).asString()); + } + } } diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest2.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest2.java deleted file mode 100644 index 58952633af8..00000000000 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest2.java +++ /dev/null @@ -1,1101 +0,0 @@ -package org.jabref.logic.openoffice.style; - -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - - -import org.jabref.logic.layout.Layout; -import org.jabref.logic.layout.LayoutFormatterPreferences; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.StandardField; -import org.jabref.model.entry.types.StandardEntryType; -import org.jabref.model.entry.types.UnknownEntryType; -import org.jabref.model.openoffice.ootext.OOText; -import org.jabref.model.openoffice.style.Citation; -import org.jabref.model.openoffice.style.CitationLookupResult; -import org.jabref.model.openoffice.style.CitationMarkerEntry; -import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; -import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; -import org.jabref.model.openoffice.style.NonUniqueCitationMarker; -import org.jabref.model.openoffice.style.PageInfo; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Answers; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; - -class OOBibStyleTest { - private LayoutFormatterPreferences layoutFormatterPreferences; - - @BeforeEach - void setUp() { - layoutFormatterPreferences = mock(LayoutFormatterPreferences.class, Answers.RETURNS_DEEP_STUBS); - } - - @Test - void testAuthorYear() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, layoutFormatterPreferences); - assertTrue(style.isValid()); - assertTrue(style.isInternalStyle()); - assertFalse(style.isCitationKeyCiteMarkers()); - assertFalse(style.isBoldCitations()); - assertFalse(style.isFormatCitations()); - assertFalse(style.isItalicCitations()); - assertFalse(style.isNumberEntries()); - assertFalse(style.isSortByPosition()); - } - - @Test - void testAuthorYearAsFile() throws URISyntaxException, IOException { - File defFile = Path.of(OOBibStyleTest.class.getResource(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH).toURI()) - .toFile(); - OOBibStyle style = new OOBibStyle(defFile, layoutFormatterPreferences, StandardCharsets.UTF_8); - assertTrue(style.isValid()); - assertFalse(style.isInternalStyle()); - assertFalse(style.isCitationKeyCiteMarkers()); - assertFalse(style.isBoldCitations()); - assertFalse(style.isFormatCitations()); - assertFalse(style.isItalicCitations()); - assertFalse(style.isNumberEntries()); - assertFalse(style.isSortByPosition()); - } - - @Test - void testNumerical() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - assertTrue(style.isValid()); - assertFalse(style.isCitationKeyCiteMarkers()); - assertFalse(style.isBoldCitations()); - assertFalse(style.isFormatCitations()); - assertFalse(style.isItalicCitations()); - assertTrue(style.isNumberEntries()); - assertTrue(style.isSortByPosition()); - } - - /* - * Helpers for testing style.getNumCitationMarker2 - */ - - /* - * Minimal implementation for CitationMarkerNumericEntry - */ - static class CitationMarkerNumericEntryImpl implements CitationMarkerNumericEntry { - - /* - * The number encoding "this entry is unresolved" for the constructor. - */ - public final static int UNRESOLVED_ENTRY_NUMBER = 0; - - private String citationKey; - private Optional num; - private Optional pageInfo; - - public CitationMarkerNumericEntryImpl(String citationKey, int num, Optional pageInfo) { - this.citationKey = citationKey; - this.num = (num == UNRESOLVED_ENTRY_NUMBER - ? Optional.empty() - : Optional.of(num)); - this.pageInfo = PageInfo.normalizePageInfo(pageInfo); - } - - @Override - public String getCitationKey() { - return citationKey; - } - - @Override - public Optional getNumber() { - return num; - } - - @Override - public Optional getPageInfo() { - return pageInfo; - } - } - - public static class Tuple3 { - public final A a; - public final B b; - public final C c; - public Tuple3(A a, B b, C c) { - this.a = a; - this.b = b; - this.c = c; - } - } - - private static CitationMarkerNumericEntry - CitationMarkerNumericEntryFromTuple(Tuple3 x) { - Optional pageInfo = Optional.ofNullable(OOText.fromString(x.c)); - return new CitationMarkerNumericEntryImpl(x.a, x.b, pageInfo); - } - - static String mkNum(OOBibStyle style, - int minGroupingCount, - Tuple3... s) { - List input = (Stream.of(s) - .map(OOBibStyleTest::CitationMarkerNumericEntryFromTuple) - .collect(Collectors.toList())); - OOText res = style.getNumCitationMarker2(input, minGroupingCount); - return OOText.toString(res); - } - - static Tuple3 tup3(String a, Integer b, String c) { - return new Tuple3(a,b,c); - } - - /* - * For testing getNumCitationMarkerForBibliography - */ - static class CitationMarkerNumericBibEntryImpl implements CitationMarkerNumericBibEntry { - String key; - Optional number; - - public CitationMarkerNumericBibEntryImpl(String key, Optional number) { - this.key = key; - this.number = number; - } - - @Override - public String getCitationKey() { - return key; - } - - @Override - public Optional getNumber() { - return number; - } - } - - @Test - void testGetNumCitationMarker() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - - // Unfortunately these two are both "; " in - // jabref/src/main/resources/resource/openoffice/default_numerical.jstyle - // We might want to change one of them - // style.getPageInfoSeparator(); - // style.getCitationSeparator(); - - /* The default numerical style uses "[1]", no space after "]" for in-text, - * but "[1] " with space after "]" for the bibliography. - */ - assertEquals("[1]", mkNum(style, -1, tup3("xx", 1, null))); - - // Identical numeric entries are joined. - assertEquals("[1; 2]", mkNum(style, 3, - tup3("x1",1,null), - tup3("x2",2,null), - tup3("x1",2,null), - tup3("x2",1,null))); - - // ... unless minGroupingCount <= 0 - assertEquals("[1; 1; 2; 2]", mkNum(style, 0, - tup3("x1",1,null), - tup3("x2",2,null), - tup3("x1",2,null), - tup3("x2",1,null))); - - // ... or have different pageInfos - assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", mkNum(style, 1, - tup3("x1", 1, "p1a"), - tup3("x1", 1, "p1b"), - tup3("x2", 2, "p2"), - tup3("x2", 2, "p2"), - tup3("x3", 3, null), - tup3("x3", 3, null))); - - // Consecutive numbers can become a range ... - assertEquals("[1-3]", mkNum(style, 1, - tup3("x1", 1, null), - tup3("x2", 2, null), - tup3("x3", 3, null))); - - // ... unless minGroupingCount is too high - assertEquals("[1; 2; 3]", mkNum(style, 4, - tup3("x1", 1, null), - tup3("x2", 2, null), - tup3("x3", 3, null))); - - // ... or if minGroupingCount <= 0 - assertEquals("[1; 2; 3]", mkNum(style, 0, - tup3("x1", 1, null), - tup3("x2", 2, null), - tup3("x3", 3, null))); - - // ... a pageInfo needs to be emitted - assertEquals("[1; p1; 2-3]", mkNum(style, 1, - tup3("x1", 1, "p1"), - tup3("x2", 2, null), - tup3("x3", 3, null))); - - // null and "" pageInfos are taken as equal. - // Due to trimming, " " is the same as well. - assertEquals("[1]", mkNum(style, 1, - tup3("x1", 1, ""), - tup3("x1", 1, null), - tup3("x1", 1, " "))); - // style.getNumCitationMarker2(Arrays.asList(1, 1, 1), - // 1, /* minGroupingCount */ - // asPageInfos("",null," ")) - // .asString()); - - // pageInfos are trimmed - assertEquals("[1; p1]", mkNum(style, 1, - tup3("x1", 1, "p1"), - tup3("x1", 1, " p1"), - tup3("x1", 1, "p1 "))); - - // The citation numbers come out sorted - assertEquals("[3-5; 7; 10-12]", mkNum(style, 1, - tup3("x12", 12, null), - tup3("x7", 7, null), - tup3("x3", 3, null), - tup3("x4", 4, null), - tup3("x11", 11, null), - tup3("x10", 10, null), - tup3("x5", 5, null))); - - // pageInfos are sorted together with the numbers - // (but they inhibit ranges where they are, even if they are identical, - // but not empty-or-null) - assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", - mkNum(style, 1, - tup3("x12", 12, "px"), - tup3("x7", 7, "p7"), - tup3("x3", 3, "p3"), - tup3("x4", 4, "p4"), - tup3("x11", 11, "px"), - tup3("x10", 10, "px"), - tup3("x5", 5, "p5"))); - - // pageInfo sorting (for the same number) - assertEquals("[1; 1; a; 1; b]", - mkNum(style, 1, - tup3("x1", 1, ""), - tup3("x1", 1, "b"), - tup3("x1", 1, "a"))); - - // pageInfo sorting (for the same number) is not numeric. - assertEquals("[1; p100; 1; p20; 1; p9]", - mkNum(style, 1, - tup3("x1", 1, "p20"), - tup3("x1", 1, "p9"), - tup3("x1", 1, "p100"))); - - assertEquals("[1-3]", - mkNum(style, 1, - tup3("x1", 1, null), - tup3("x2", 2, null), - tup3("x3", 3, null))); - - assertEquals("[1; 2; 3]", - mkNum(style, 5, - tup3("x1", 1, null), - tup3("x2", 2, null), - tup3("x3", 3, null))); - - assertEquals("[1; 2; 3]", - mkNum(style, -1, - tup3("x1", 1, null), - tup3("x2", 2, null), - tup3("x3", 3, null))); - - assertEquals("[1; 3; 12]", - mkNum(style, 1, - tup3("x1", 1, null), - tup3("x12", 12, null), - tup3("x3", 3, null))); - - assertEquals("[3-5; 7; 10-12]", - mkNum(style, 1, - tup3("x12", 12, ""), - tup3("x7", 7, ""), - tup3("x3", 3, ""), - tup3("x4", 4, ""), - tup3("x11", 11, ""), - tup3("x10", 10, ""), - tup3("x5", 5, ""))); - - /* - * BIBLIOGRAPHY : I think - * style.getNumCitationMarkerForBibliography(int num); - * should be enough: we only need it for a single number, never more. - * Consequently minGroupingCount is not needed. - * Nor do we need pageInfo in the bibliography. - */ - { - CitationMarkerNumericBibEntry x = new CitationMarkerNumericBibEntryImpl("key", Optional.of(1)); - assertEquals("[1] ", - style.getNumCitationMarkerForBibliography(x).asString()); - } - - } - - @Test - void testGetNumCitationMarkerUndefined() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - - List> empty = null; - - // unresolved citations look like [??key] - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "]", - mkNum(style, 1, - tup3("key",0,null))); - - // pageInfo is shown for unresolved citations - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; p1]", - mkNum(style, 1, - tup3("key",0,"p1"))); - - // unresolved citations sorted to the front - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 2-4]", - mkNum(style, 1, - tup3("x4",4,""), - tup3("x2",2,""), - tup3("x3",3,""), - tup3("key",0,""))); - - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 1-3]", - mkNum(style, 1, - tup3("x1",1,""), - tup3("x2",2,""), - tup3("y3",3,""), - tup3("key",0,""))); - - // multiple unresolved citations are not collapsed - assertEquals("[" - + OOBibStyle.UNDEFINED_CITATION_MARKER + "x1" + "; " - + OOBibStyle.UNDEFINED_CITATION_MARKER + "x2" + "; " - + OOBibStyle.UNDEFINED_CITATION_MARKER + "x3" + "]", - mkNum(style, 1, - tup3("x1",0,""), - tup3("x2",0,""), - tup3("x3",0,""))); - - /* - * BIBLIOGRAPHY - */ - { - CitationMarkerNumericBibEntry x = - new CitationMarkerNumericBibEntryImpl("key", Optional.empty()); - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", - style.getNumCitationMarkerForBibliography(x).asString()); - } - - } - - @Test - void testGetCitProperty() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - assertEquals(", ", style.getStringCitProperty("AuthorSeparator")); - assertEquals(3, style.getMaxAuthors()); - assertTrue(style.getMultiCiteChronological()); - assertEquals("Default", style.getCitationCharacterFormat()); - assertEquals("Default [number] style file.", style.getName()); - Set journals = style.getJournals(); - assertTrue(journals.contains("Journal name 1")); - } - - private static CitationMarkerEntry makeCitationMarkerEntry(String citationKey, - BibEntry entry, - BibDatabase database, - String uniqueLetterQ, - String pageInfoQ, - boolean isFirstAppearanceOfSource) { - Objects.requireNonNull(citationKey); - Citation result = new Citation(citationKey); - result.setLookupResult(Optional.of(new CitationLookupResult(entry, database))); - result.setUniqueLetter(Optional.ofNullable(uniqueLetterQ)); - Optional pageInfo = Optional.ofNullable(OOText.fromString(pageInfoQ)); - result.setPageInfo(PageInfo.normalizePageInfo(pageInfo)); - result.setIsFirstAppearanceOfSource(isFirstAppearanceOfSource); - return result; - } - - @Test - void testGetCitationMarker() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - BibEntry entry = new BibEntry() - .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m and Jaana W\\\"{a}yrynen and Marine Bod\\'{e}n and Konstantin Beznosov and Philippe Kruchten") - .withField(StandardField.YEAR, "2006") - .withField(StandardField.BOOKTITLE, "SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems") - .withField(StandardField.PUBLISHER, "ACM") - .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") - .withField(StandardField.PAGES, "11--18"); - BibDatabase database = new BibDatabase(); - database.insertEntry(entry); - - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm = - makeCitationMarkerEntry("Bostrom2006", entry, database, null, null, false); - citationMarkerEntries.add(cm); - - assertEquals(3, style.getMaxAuthors()); - assertEquals(-1, style.getMaxAuthorsFirst()); - - /* - * For in-text citations most (maybe all) styles prescribe a single - * author's name before "et al." - */ - assertEquals("[Boström et al., 2006]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - - assertEquals("Boström et al. [2006]", - style.createCitationMarker(citationMarkerEntries, - false, - NonUniqueCitationMarker.THROWS).asString()); - - /* - * Currently there is no way override for getMaxAuthors(), except - * cm.isFirstAppearanceOfSource, which asks for getMaxAuthorsFirst() - */ - citationMarkerEntries.clear(); - cm = makeCitationMarkerEntry("Bostrom2006", entry, database, null, null, true); - citationMarkerEntries.add(cm); - - assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - - @Test - void testGetCitationMarkerJoinFirst() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - - // Question: What should happen if some of the sources is - // marked as isFirstAppearanceOfSource? - // This test documents what is happening now, - // but it is possible this is not what should. - - // Two entries with identical normalizedMarkers and many authors. - BibEntry entry1 = new BibEntry() - .withField(StandardField.AUTHOR, - "Gustav Bostr\\\"{o}m" - + " and Jaana W\\\"{a}yrynen" - + " and Marine Bod\\'{e}n" - + " and Konstantin Beznosov" - + " and Philippe Kruchten") - .withField(StandardField.YEAR, "2006") - .withField(StandardField.BOOKTITLE, "A book 1") - .withField(StandardField.PUBLISHER, "ACM") - .withField(StandardField.TITLE, "Title 1") - .withField(StandardField.PAGES, "11--18"); - - BibEntry entry2 = new BibEntry() - .withField(StandardField.AUTHOR, - "Gustav Bostr\\\"{o}m" - + " and Jaana W\\\"{a}yrynen" - + " and Marine Bod\\'{e}n" - + " and Konstantin Beznosov" - + " and Philippe Kruchten") - .withField(StandardField.YEAR, "2006") - .withField(StandardField.BOOKTITLE, "A book 2") - .withField(StandardField.PUBLISHER, "ACM") - .withField(StandardField.TITLE, "title2") - .withField(StandardField.PAGES, "11--18"); - - // Last Author differs. - BibEntry entry3 = new BibEntry() - .withField(StandardField.AUTHOR, - "Gustav Bostr\\\"{o}m" - + " and Jaana W\\\"{a}yrynen" - + " and Marine Bod\\'{e}n" - + " and Konstantin Beznosov" - + " and Philippe NotKruchten") - .withField(StandardField.YEAR, "2006") - .withField(StandardField.BOOKTITLE, "A book 3") - .withField(StandardField.PUBLISHER, "ACM") - .withField(StandardField.TITLE, "title3") - .withField(StandardField.PAGES, "11--18"); - - BibDatabase database = new BibDatabase(); - database.insertEntry(entry1); - database.insertEntry(entry2); - database.insertEntry(entry3); - - // Without pageInfo, two isFirstAppearanceOfSource may be joined. - // The third is NotKruchten, should not be joined. - if (true) { - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm1 = - makeCitationMarkerEntry("b1", entry1, database, "a", null, true); - citationMarkerEntries.add(cm1); - CitationMarkerEntry cm2 = - makeCitationMarkerEntry("b2", entry2, database, "b", null, true); - citationMarkerEntries.add(cm2); - CitationMarkerEntry cm3 = - makeCitationMarkerEntry("b3", entry3, database, "c", null, true); - citationMarkerEntries.add(cm3); - - assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" - +"; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - - assertEquals("Boström, Wäyrynen, Bodén, Beznosov & Kruchten [2006a,b]" - + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten [2006c]", - style.createCitationMarker(citationMarkerEntries, - false, - NonUniqueCitationMarker.THROWS).asString()); - } - - // Without pageInfo, only the first is isFirstAppearanceOfSource. - // The second may be joined, based on expanded normalizedMarkers. - // The third is NotKruchten, should not be joined. - if (true) { - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm1 = - makeCitationMarkerEntry("b1", entry1, database, "a", null, true); - citationMarkerEntries.add(cm1); - CitationMarkerEntry cm2 = - makeCitationMarkerEntry("b2", entry2, database, "b", null, false); - citationMarkerEntries.add(cm2); - CitationMarkerEntry cm3 = - makeCitationMarkerEntry("b3", entry3, database, "c", null, false); - citationMarkerEntries.add(cm3); - - assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" - +"; Boström et al., 2006c]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - - } - // Without pageInfo, only the second is isFirstAppearanceOfSource. - // The second is not joined, because it is a first appearance, thus - // requires more names to be shown. - // The third is NotKruchten, should not be joined. - if (true) { - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm1 = - makeCitationMarkerEntry("b1", entry1, database, "a", null, false); - citationMarkerEntries.add(cm1); - CitationMarkerEntry cm2 = - makeCitationMarkerEntry("b2", entry2, database, "b", null, true); - citationMarkerEntries.add(cm2); - CitationMarkerEntry cm3 = - makeCitationMarkerEntry("b3", entry3, database, "c", null, false); - citationMarkerEntries.add(cm3); - - assertEquals("[Boström et al., 2006a" - + "; Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006b" - + "; Boström et al., 2006c]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - - // Without pageInfo, only the neither is isFirstAppearanceOfSource. - // The second is joined. - // The third is NotKruchten, but is joined because NotKruchten is not among the names shown. - // Is this the correct behaviour? - if (true) { - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm1 = - makeCitationMarkerEntry("b1", entry1, database, "a", null, false); - citationMarkerEntries.add(cm1); - CitationMarkerEntry cm2 = - makeCitationMarkerEntry("b2", entry2, database, "b", null, false); - citationMarkerEntries.add(cm2); - CitationMarkerEntry cm3 = - makeCitationMarkerEntry("b3", entry3, database, "c", null, false); - citationMarkerEntries.add(cm3); - - assertEquals("[Boström et al., 2006a,b,c]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - - // With pageInfo: different entries with identical non-null pageInfo: not joined. - // XY [2000a,b,c; p1] whould be confusing. - if (true) { - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm1 = - makeCitationMarkerEntry("b1", entry1, database, "a", "p1", false); - citationMarkerEntries.add(cm1); - CitationMarkerEntry cm2 = - makeCitationMarkerEntry("b2", entry2, database, "b", "p1", false); - citationMarkerEntries.add(cm2); - CitationMarkerEntry cm3 = - makeCitationMarkerEntry("b3", entry3, database, "c", "p1", false); - citationMarkerEntries.add(cm3); - - assertEquals("[Boström et al., 2006a; p1" - + "; Boström et al., 2006b; p1" - + "; Boström et al., 2006c; p1]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - - // With pageInfo: same entries with identical non-null pageInfo: collapsed. - // Note: "same" here looks at the visible parts and citation key only, - // but ignores the rest. Normally the citation key should distinguish. - if (true) { - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm1 = - makeCitationMarkerEntry("b1", entry1, database, "a", "p1", false); - citationMarkerEntries.add(cm1); - CitationMarkerEntry cm2 = - makeCitationMarkerEntry("b1", entry1, database, "a", "p1", false); - citationMarkerEntries.add(cm2); - CitationMarkerEntry cm3 = - makeCitationMarkerEntry("b1", entry1, database, "a", "p1", false); - citationMarkerEntries.add(cm3); - - assertEquals("[Boström et al., 2006a; p1]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - // With pageInfo: same entries with different pageInfo: kept separate. - // Empty ("") and null pageInfos considered equal her, collapsed. - if (true) { - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm1 = - makeCitationMarkerEntry("b1", entry1, database, "a", "p1", false); - citationMarkerEntries.add(cm1); - CitationMarkerEntry cm2 = - makeCitationMarkerEntry("b1", entry1, database, "a", "p2", false); - citationMarkerEntries.add(cm2); - CitationMarkerEntry cm3 = - makeCitationMarkerEntry("b1", entry1, database, "a", "", false); - citationMarkerEntries.add(cm3); - CitationMarkerEntry cm4 = - makeCitationMarkerEntry("b1", entry1, database, "a", null, false); - citationMarkerEntries.add(cm4); - - assertEquals("[Boström et al., 2006a; p1" - + "; Boström et al., 2006a; p2" - + "; Boström et al., 2006a]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - } - - - @Test - void testLayout() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - - BibEntry entry = new BibEntry() - .withField(StandardField.AUTHOR, "Gustav Bostr\\\"{o}m and Jaana W\\\"{a}yrynen and Marine Bod\\'{e}n and Konstantin Beznosov and Philippe Kruchten") - .withField(StandardField.YEAR, "2006") - .withField(StandardField.BOOKTITLE, "SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems") - .withField(StandardField.PUBLISHER, "ACM") - .withField(StandardField.TITLE, "Extending XP practices to support security requirements engineering") - .withField(StandardField.PAGES, "11--18"); - BibDatabase database = new BibDatabase(); - database.insertEntry(entry); - - Layout l = style.getReferenceFormat(new UnknownEntryType("default")); - l.setPostFormatter(new OOPreFormatter()); - assertEquals( - "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006). Extending XP practices to support security requirements engineering, : 11-18.", - l.doLayout(entry, database)); - - l = style.getReferenceFormat(StandardEntryType.InCollection); - l.setPostFormatter(new OOPreFormatter()); - assertEquals( - "Boström, G.; Wäyrynen, J.; Bodén, M.; Beznosov, K. and Kruchten, P. (2006). Extending XP practices to support security requirements engineering. In: (Ed.), SESS '06: Proceedings of the 2006 international workshop on Software engineering for secure systems, ACM.", - l.doLayout(entry, database)); - } - - @Test - void testInstitutionAuthor() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - BibDatabase database = new BibDatabase(); - - Layout l = style.getReferenceFormat(StandardEntryType.Article); - l.setPostFormatter(new OOPreFormatter()); - - BibEntry entry = new BibEntry(); - entry.setType(StandardEntryType.Article); - entry.setField(StandardField.AUTHOR, "{JabRef Development Team}"); - entry.setField(StandardField.TITLE, "JabRef Manual"); - entry.setField(StandardField.YEAR, "2016"); - database.insertEntry(entry); - assertEquals("JabRef Development Team (2016). JabRef Manual, .", - l.doLayout(entry, database)); - } - - @Test - void testVonAuthor() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - BibDatabase database = new BibDatabase(); - - Layout l = style.getReferenceFormat(StandardEntryType.Article); - l.setPostFormatter(new OOPreFormatter()); - - BibEntry entry = new BibEntry(); - entry.setType(StandardEntryType.Article); - entry.setField(StandardField.AUTHOR, "Alpha von Beta"); - entry.setField(StandardField.TITLE, "JabRef Manual"); - entry.setField(StandardField.YEAR, "2016"); - database.insertEntry(entry); - assertEquals("von Beta, A. (2016). JabRef Manual, .", - l.doLayout(entry, database)); - } - - @Test - void testInstitutionAuthorMarker() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - - BibDatabase database = new BibDatabase(); - - BibEntry entry = new BibEntry(); - entry.setType(StandardEntryType.Article); - entry.setField(StandardField.AUTHOR, "{JabRef Development Team}"); - entry.setField(StandardField.TITLE, "JabRef Manual"); - entry.setField(StandardField.YEAR, "2016"); - database.insertEntry(entry); - - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm = - makeCitationMarkerEntry("JabRef2016", entry, database, null, null, false); - citationMarkerEntries.add(cm); - assertEquals("[JabRef Development Team, 2016]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - - @Test - void testVonAuthorMarker() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - - BibDatabase database = new BibDatabase(); - - BibEntry entry = new BibEntry(); - entry.setType(StandardEntryType.Article); - entry.setField(StandardField.AUTHOR, "Alpha von Beta"); - entry.setField(StandardField.TITLE, "JabRef Manual"); - entry.setField(StandardField.YEAR, "2016"); - database.insertEntry(entry); - - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm = - makeCitationMarkerEntry("vonBeta2016", entry, database, null, null, false); - citationMarkerEntries.add(cm); - - assertEquals("[von Beta, 2016]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - - @Test - void testNullAuthorMarker() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - - BibDatabase database = new BibDatabase(); - - BibEntry entry = new BibEntry(); - entry.setType(StandardEntryType.Article); - entry.setField(StandardField.YEAR, "2016"); - database.insertEntry(entry); - - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm = - makeCitationMarkerEntry("anon2016", entry, database, null, null, false); - citationMarkerEntries.add(cm); - - assertEquals("[, 2016]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - - @Test - void testNullYearMarker() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - - BibDatabase database = new BibDatabase(); - - BibEntry entry = new BibEntry(); - entry.setType(StandardEntryType.Article); - entry.setField(StandardField.AUTHOR, "Alpha von Beta"); - database.insertEntry(entry); - - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm = - makeCitationMarkerEntry("vonBetaNNNN", entry, database, null, null, false); - citationMarkerEntries.add(cm); - - assertEquals("[von Beta, ]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - - @Test - void testEmptyEntryMarker() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - - BibDatabase database = new BibDatabase(); - - BibEntry entry = new BibEntry(); - entry.setType(StandardEntryType.Article); - database.insertEntry(entry); - - List citationMarkerEntries = new ArrayList<>(); - CitationMarkerEntry cm = - makeCitationMarkerEntry("Empty", entry, database, null, null, false); - citationMarkerEntries.add(cm); - - assertEquals("[, ]", style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS) - .asString()); - } - - @Test - void testGetCitationMarkerUniquefiers() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - - BibDatabase database = new BibDatabase(); - - // Three different entries, the first two having the same - // normalized citation marks. - BibEntry entry1 = new BibEntry(); - entry1.setField(StandardField.AUTHOR, "Alpha Beta"); - entry1.setField(StandardField.TITLE, "Paper 1"); - entry1.setField(StandardField.YEAR, "2000"); - database.insertEntry(entry1); - - BibEntry entry3 = new BibEntry(); - entry3.setField(StandardField.AUTHOR, "Alpha Beta"); - entry3.setField(StandardField.TITLE, "Paper 2"); - entry3.setField(StandardField.YEAR, "2000"); - database.insertEntry(entry3); - - BibEntry entry2 = new BibEntry(); - entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); - entry2.setField(StandardField.YEAR, "2001"); - database.insertEntry(entry2); - - - // Without uniquefiers this is a problem createCitationMarker cannot - // solve, since it does not see the whole picture (citations outside its scope). - // It can throw a RuntimeException or forgive and provide a flawed presentation. - // - // This latter is used for providing a temporary citation mark - // for newly inserted citations. - CitationMarkerEntry cm1a = - makeCitationMarkerEntry("Beta2000a", entry1, database, null, null, false); - CitationMarkerEntry cm3a = - makeCitationMarkerEntry("Beta2000b", entry3, database, null, null, false); - CitationMarkerEntry cm2 = - makeCitationMarkerEntry("Epsilon2001", entry2, database, null, null, false); - - List citationMarkerEntriesA = new ArrayList<>(); - citationMarkerEntriesA.add(cm1a); - citationMarkerEntriesA.add(cm3a); - citationMarkerEntriesA.add(cm2); - - // Consecutive, different source without distinguishing uniquefiers - // can throw a RuntimeException. - boolean doesItThrow = false; - try { - style.createCitationMarker(citationMarkerEntriesA, - false, - NonUniqueCitationMarker.THROWS); - } catch (RuntimeException ex) { - doesItThrow = true; - } - assertEquals(true, doesItThrow); - - // Or can just emit a presentation with repeated marks. - assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", - style.createCitationMarker(citationMarkerEntriesA, - true, - NonUniqueCitationMarker.FORGIVEN).asString()); - - assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", - style.createCitationMarker(citationMarkerEntriesA, - false, - NonUniqueCitationMarker.FORGIVEN).asString()); - - - // With uniquefiers - CitationMarkerEntry cm1b = - makeCitationMarkerEntry("Beta2000a", entry1, database, "a", null, false); - CitationMarkerEntry cm3b = - makeCitationMarkerEntry("Beta2000b", entry3, database, "b", null, false); - - List citationMarkerEntriesB = new ArrayList<>(); - citationMarkerEntriesB.add(cm1b); - citationMarkerEntriesB.add(cm3b); - citationMarkerEntriesB.add(cm2); - - assertEquals("[Beta, 2000a,b; Epsilon, 2001]", - style.createCitationMarker(citationMarkerEntriesB, - true, - NonUniqueCitationMarker.THROWS).asString()); - - assertEquals("Beta [2000a,b]; Epsilon [2001]", - style.createCitationMarker(citationMarkerEntriesB, - false, - NonUniqueCitationMarker.THROWS).asString()); - } - - - @Test - void testGetCitationMarkerUniquefiersThreeSameAuthor() throws IOException { - OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - - BibDatabase database = new BibDatabase(); - - BibEntry entry1 = new BibEntry(); - entry1.setField(StandardField.AUTHOR, "Alpha Beta"); - entry1.setField(StandardField.TITLE, "Paper 1"); - entry1.setField(StandardField.YEAR, "2000"); - database.insertEntry(entry1); - - BibEntry entry2 = new BibEntry(); - entry2.setField(StandardField.AUTHOR, "Alpha Beta"); - entry2.setField(StandardField.TITLE, "Paper 2"); - entry2.setField(StandardField.YEAR, "2000"); - database.insertEntry(entry2); - - BibEntry entry3 = new BibEntry(); - entry3.setField(StandardField.AUTHOR, "Alpha Beta"); - entry3.setField(StandardField.TITLE, "Paper 3"); - entry3.setField(StandardField.YEAR, "2000"); - database.insertEntry(entry3); - - CitationMarkerEntry cm1 = - makeCitationMarkerEntry("v1", entry1, database, "a", null, false); - CitationMarkerEntry cm2 = - makeCitationMarkerEntry("v2", entry2, database, "b", null, false); - CitationMarkerEntry cm3 = - makeCitationMarkerEntry("v3", entry3, database, "c", null, false); - - List citationMarkerEntries = new ArrayList<>(); - citationMarkerEntries.add(cm1); - citationMarkerEntries.add(cm2); - citationMarkerEntries.add(cm3); - - assertEquals("[Beta, 2000a,b,c]", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - - assertEquals("Beta [2000a,b,c]", - style.createCitationMarker(citationMarkerEntries, - false, - NonUniqueCitationMarker.THROWS).asString()); - } - - @Test - // TODO: equals only work when initialized from file, not from reader - void testEquals() throws IOException { - OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - assertEquals(style1, style2); - } - - @Test - // TODO: equals only work when initialized from file, not from reader - void testNotEquals() throws IOException { - OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, - layoutFormatterPreferences); - assertNotEquals(style1, style2); - } - - @Test - void testCompareToEqual() throws IOException { - OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - assertEquals(0, style1.compareTo(style2)); - } - - @Test - void testCompareToNotEqual() throws IOException { - OOBibStyle style1 = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, - layoutFormatterPreferences); - OOBibStyle style2 = new OOBibStyle(StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH, - layoutFormatterPreferences); - assertTrue(style1.compareTo(style2) > 0); - assertFalse(style2.compareTo(style1) > 0); - } - - @Test - void testEmptyStringPropertyAndOxfordComma() throws Exception { - - OOBibStyle style = new OOBibStyle("test.jstyle", layoutFormatterPreferences); - - BibDatabase database = new BibDatabase(); - - BibEntry entry = new BibEntry(); - entry.setType(StandardEntryType.Article); - entry.setField(StandardField.AUTHOR, "Alpha von Beta and Gamma Epsilon and Ypsilon Tau"); - entry.setField(StandardField.TITLE, "JabRef Manual"); - entry.setField(StandardField.YEAR, "2016"); - database.insertEntry(entry); - - List citationMarkerEntries = new ArrayList<>(); - citationMarkerEntries.add( - makeCitationMarkerEntry("Beta2016", entry, database, null, null, false)); - - assertEquals("von Beta, Epsilon, & Tau, 2016", - style.createCitationMarker(citationMarkerEntries, - true, - NonUniqueCitationMarker.THROWS).asString()); - } - - @Test - void testIsValidWithDefaultSectionAtTheStart() throws Exception { - OOBibStyle style = new OOBibStyle("testWithDefaultAtFirstLIne.jstyle", layoutFormatterPreferences); - assertTrue(style.isValid()); - } - -} - diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java new file mode 100644 index 00000000000..7caaf96055c --- /dev/null +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java @@ -0,0 +1,359 @@ +package org.jabref.logic.openoffice.style; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.jabref.logic.layout.Layout; +import org.jabref.logic.layout.LayoutFormatterPreferences; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.StandardField; +import org.jabref.model.entry.types.StandardEntryType; +import org.jabref.model.entry.types.UnknownEntryType; +import org.jabref.model.openoffice.ootext.OOText; +import org.jabref.model.openoffice.style.Citation; +import org.jabref.model.openoffice.style.CitationLookupResult; +import org.jabref.model.openoffice.style.CitationMarkerEntry; +import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; +import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; +import org.jabref.model.openoffice.style.NonUniqueCitationMarker; +import org.jabref.model.openoffice.style.PageInfo; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +class OOBibStyleTestHelper { + /* + * begin Helpers for testing style.getNumCitationMarker2 + */ + + /* + * Minimal implementation for CitationMarkerNumericEntry + */ + static class CitationMarkerNumericEntryImpl implements CitationMarkerNumericEntry { + + /* + * The number encoding "this entry is unresolved" for the constructor. + */ + public final static int UNRESOLVED_ENTRY_NUMBER = 0; + + private String citationKey; + private Optional num; + private Optional pageInfo; + + public CitationMarkerNumericEntryImpl(String citationKey, int num, Optional pageInfo) { + this.citationKey = citationKey; + this.num = (num == UNRESOLVED_ENTRY_NUMBER + ? Optional.empty() + : Optional.of(num)); + this.pageInfo = PageInfo.normalizePageInfo(pageInfo); + } + + @Override + public String getCitationKey() { + return citationKey; + } + + @Override + public Optional getNumber() { + return num; + } + + @Override + public Optional getPageInfo() { + return pageInfo; + } + } + + static class CitationMarkerNumericBibEntryImpl implements CitationMarkerNumericBibEntry { + String key; + Optional number; + + public CitationMarkerNumericBibEntryImpl(String key, Optional number) { + this.key = key; + this.number = number; + } + + @Override + public String getCitationKey() { + return key; + } + + @Override + public Optional getNumber() { + return number; + } + } + + static CitationMarkerNumericBibEntry numBibEntry(String key, Optional number) { + return new CitationMarkerNumericBibEntryImpl(key, number); + } + + /** + * Reproduce old method + * + * @param inList true means label for the bibliography + */ + static String runGetNumCitationMarker2a(OOBibStyle style, + List num, int minGroupingCount, boolean inList ) { + if (inList) { + if (num.size() != 1) { + throw new RuntimeException("Numeric label for the bibliography with " + + String.valueOf(num.size()) + " numbers?"); + } + int n = num.get(0); + CitationMarkerNumericBibEntryImpl x = + new CitationMarkerNumericBibEntryImpl("key", + (n == 0) ? Optional.empty() : Optional.of(n)); + return style.getNumCitationMarkerForBibliography(x).asString(); + } else { + List input = + num.stream() + .map(n -> + new CitationMarkerNumericEntryImpl("key" + String.valueOf(n), + n, + Optional.empty())) + .collect(Collectors.toList()); + return style.getNumCitationMarker2(input, minGroupingCount).asString(); + } + } + + /* + * Unlike getNumCitationMarker, getNumCitationMarker2 can handle pageInfo. + */ + static CitationMarkerNumericEntry numEntry(String key, int num, String pageInfoOrNull) { + Optional pageInfo = Optional.ofNullable(OOText.fromString(pageInfoOrNull)); + return new CitationMarkerNumericEntryImpl(key, num, pageInfo); + } + + static String runGetNumCitationMarker2b(OOBibStyle style, + int minGroupingCount, + CitationMarkerNumericEntry... s) { + List input = Stream.of(s).collect(Collectors.toList()); + OOText res = style.getNumCitationMarker2(input, minGroupingCount); + return res.asString(); + } + + /* + * end Helpers for testing style.getNumCitationMarker2 + */ + + + /* + * begin helper + */ + static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, + BibDatabase database, + String uniqueLetterQ, + String pageInfoQ, + boolean isFirstAppearanceOfSource) { + if (!entry.getCitationKey().isPresent()) { + throw new RuntimeException("!entry.getCitationKey().isPresent()"); + } + String citationKey = entry.getCitationKey().get(); + Citation result = new Citation(citationKey); + result.setLookupResult(Optional.of(new CitationLookupResult(entry, database))); + result.setUniqueLetter(Optional.ofNullable(uniqueLetterQ)); + Optional pageInfo = Optional.ofNullable(OOText.fromString(pageInfoQ)); + result.setPageInfo(PageInfo.normalizePageInfo(pageInfo)); + result.setIsFirstAppearanceOfSource(isFirstAppearanceOfSource); + return result; + } + + /* + * Similar to old API. pageInfo is new, and unlimAuthors is + * replaced with isFirstAppearanceOfSource + */ + String getCitationMarker2(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { + if (uniquefiers == null) { + uniquefiers = new String[entries.size()]; + Arrays.fill(uniquefiers, null); + } + if (pageInfo == null) { + pageInfo = new String[entries.size()]; + Arrays.fill(pageInfo, null); + } + if (isFirstAppearanceOfSource == null) { + isFirstAppearanceOfSource = new Boolean[entries.size()]; + Arrays.fill(isFirstAppearanceOfSource, false); + } + List citationMarkerEntries = new ArrayList<>(); + for (int i = 0; i < entries.size(); i++) { + BibEntry entry = entries.get(i); + CitationMarkerEntry e = makeCitationMarkerEntry(entry, + entryDBMap.get(entry), + uniquefiers[i], + pageInfo[i], + isFirstAppearanceOfSource[i]); + citationMarkerEntries.add(e); + } + return style.createCitationMarker(citationMarkerEntries, + inParenthesis, + NonUniqueCitationMarker.THROWS).asString(); + } + + /* + * end helper + */ + + + static void testGetNumCitationMarkerExtra(OOBibStyle style) throws IOException { + // Identical numeric entries are joined. + assertEquals("[1; 2]", runGetNumCitationMarker2b(style, 3, + numEntry("x1",1,null), + numEntry("x2",2,null), + numEntry("x1",2,null), + numEntry("x2",1,null))); + + // ... unless minGroupingCount <= 0 + assertEquals("[1; 1; 2; 2]", runGetNumCitationMarker2b(style, 0, + numEntry("x1",1,null), + numEntry("x2",2,null), + numEntry("x1",2,null), + numEntry("x2",1,null))); + + // ... or have different pageInfos + assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", runGetNumCitationMarker2b(style, 1, + numEntry("x1", 1, "p1a"), + numEntry("x1", 1, "p1b"), + numEntry("x2", 2, "p2"), + numEntry("x2", 2, "p2"), + numEntry("x3", 3, null), + numEntry("x3", 3, null))); + + // Consecutive numbers can become a range ... + assertEquals("[1-3]", runGetNumCitationMarker2b(style, 1, + numEntry("x1", 1, null), + numEntry("x2", 2, null), + numEntry("x3", 3, null))); + + // ... unless minGroupingCount is too high + assertEquals("[1; 2; 3]", runGetNumCitationMarker2b(style, 4, + numEntry("x1", 1, null), + numEntry("x2", 2, null), + numEntry("x3", 3, null))); + + // ... or if minGroupingCount <= 0 + assertEquals("[1; 2; 3]", runGetNumCitationMarker2b(style, 0, + numEntry("x1", 1, null), + numEntry("x2", 2, null), + numEntry("x3", 3, null))); + + // ... a pageInfo needs to be emitted + assertEquals("[1; p1; 2-3]", runGetNumCitationMarker2b(style, 1, + numEntry("x1", 1, "p1"), + numEntry("x2", 2, null), + numEntry("x3", 3, null))); + + // null and "" pageInfos are taken as equal. + // Due to trimming, " " is the same as well. + assertEquals("[1]", runGetNumCitationMarker2b(style, 1, + numEntry("x1", 1, ""), + numEntry("x1", 1, null), + numEntry("x1", 1, " "))); + + // pageInfos are trimmed + assertEquals("[1; p1]", runGetNumCitationMarker2b(style, 1, + numEntry("x1", 1, "p1"), + numEntry("x1", 1, " p1"), + numEntry("x1", 1, "p1 "))); + + // The citation numbers come out sorted + assertEquals("[3-5; 7; 10-12]", runGetNumCitationMarker2b(style, 1, + numEntry("x12", 12, null), + numEntry("x7", 7, null), + numEntry("x3", 3, null), + numEntry("x4", 4, null), + numEntry("x11", 11, null), + numEntry("x10", 10, null), + numEntry("x5", 5, null))); + + // pageInfos are sorted together with the numbers + // (but they inhibit ranges where they are, even if they are identical, + // but not empty-or-null) + assertEquals("[3; p3; 4; p4; 5; p5; 7; p7; 10; px; 11; px; 12; px]", + runGetNumCitationMarker2b(style, 1, + numEntry("x12", 12, "px"), + numEntry("x7", 7, "p7"), + numEntry("x3", 3, "p3"), + numEntry("x4", 4, "p4"), + numEntry("x11", 11, "px"), + numEntry("x10", 10, "px"), + numEntry("x5", 5, "p5"))); + + // pageInfo sorting (for the same number) + assertEquals("[1; 1; a; 1; b]", + runGetNumCitationMarker2b(style, 1, + numEntry("x1", 1, ""), + numEntry("x1", 1, "b"), + numEntry("x1", 1, "a"))); + + // pageInfo sorting (for the same number) is not numeric. + assertEquals("[1; p100; 1; p20; 1; p9]", + runGetNumCitationMarker2b(style, 1, + numEntry("x1", 1, "p20"), + numEntry("x1", 1, "p9"), + numEntry("x1", 1, "p100"))); + + assertEquals("[1-3]", + runGetNumCitationMarker2b(style, 1, + numEntry("x1", 1, null), + numEntry("x2", 2, null), + numEntry("x3", 3, null))); + + assertEquals("[1; 2; 3]", + runGetNumCitationMarker2b(style, 5, + numEntry("x1", 1, null), + numEntry("x2", 2, null), + numEntry("x3", 3, null))); + + assertEquals("[1; 2; 3]", + runGetNumCitationMarker2b(style, -1, + numEntry("x1", 1, null), + numEntry("x2", 2, null), + numEntry("x3", 3, null))); + + assertEquals("[1; 3; 12]", + runGetNumCitationMarker2b(style, 1, + numEntry("x1", 1, null), + numEntry("x12", 12, null), + numEntry("x3", 3, null))); + + assertEquals("[3-5; 7; 10-12]", + runGetNumCitationMarker2b(style, 1, + numEntry("x12", 12, ""), + numEntry("x7", 7, ""), + numEntry("x3", 3, ""), + numEntry("x4", 4, ""), + numEntry("x11", 11, ""), + numEntry("x10", 10, ""), + numEntry("x5", 5, ""))); + } +} From 5a3e3e52aee59d3812be6d23ea88d7d9b64f11ad Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 28 May 2021 08:46:20 +0200 Subject: [PATCH 0917/1068] correction: getCitationMarker2 is static --- .../logic/openoffice/style/OOBibStyleTest.java | 14 +++++++------- .../openoffice/style/OOBibStyleTestHelper.java | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java index 3b9fb5095f5..bf0bdf945a4 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java @@ -132,13 +132,13 @@ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, * Similar to old API. pageInfo is new, and unlimAuthors is * replaced with isFirstAppearanceOfSource */ - String getCitationMarker2(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo) { + static String getCitationMarker2(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { return OOBibStyleTestHelper.getCitationMarker2(style, entries, entryDBMap, diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java index 7caaf96055c..c8302030fc6 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java @@ -185,13 +185,13 @@ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, * Similar to old API. pageInfo is new, and unlimAuthors is * replaced with isFirstAppearanceOfSource */ - String getCitationMarker2(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo) { + static String getCitationMarker2(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { if (uniquefiers == null) { uniquefiers = new String[entries.size()]; Arrays.fill(uniquefiers, null); From 2b8dea34646bdc734fe0efd1c095471df36bbaea Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 28 May 2021 08:47:52 +0200 Subject: [PATCH 0918/1068] ootext comments --- .../model/openoffice/ootext/OOFormat.java | 17 ++++++++--------- .../jabref/model/openoffice/ootext/OOText.java | 10 ++++++++++ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java index ca0d5b01832..472ca519161 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java @@ -16,9 +16,7 @@ public class OOFormat { * */ public static OOText setLocale(OOText s, String locale) { - return OOText.fromString(String.format("", locale) - + s.asString() - + ""); + return OOText.fromString(String.format("", locale) + s.asString() + ""); } /** @@ -52,20 +50,21 @@ public static OOText paragraph(OOText s, String paraStyle) { if (paraStyle == null || "".equals(paraStyle)) { return paragraph(s); } - return OOText.fromString(String.format("

", paraStyle) - + s.asString() - + "

"); + String startTag = String.format("

", paraStyle); + return OOText.fromString(startTag + s.asString() + "

"); } /** * Mark {@code s} as part of a paragraph. */ public static OOText paragraph(OOText s) { - return OOText.fromString("

" - + s.asString() - + "

"); + return OOText.fromString("

" + s.asString() + "

"); } + /** + * Format an OO cross-reference showing the target's page number + * as label to a reference mark. + */ public static OOText formatReferenceToPageNumberOfReferenceMark(String referencMarkName) { String s = String.format("", referencMarkName); diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java index 604f2c6c657..a568a7c6e8a 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java @@ -2,6 +2,13 @@ import java.util.Objects; +/** + * Text with HTML-like markup as understood by OOTextIntoOO.write + * + * Some of the tags can be added using OOFormat methods. Others come + * from the layout engine, either by interpreting LaTeX markup or from + * settings in the jstyle file. + */ public class OOText { private final String data; @@ -11,6 +18,7 @@ private OOText(String data) { this.data = data; } + /* null input is passed through */ public static OOText fromString(String s) { if (s == null) { return null; @@ -18,6 +26,7 @@ public static OOText fromString(String s) { return new OOText(s); } + /* null input is passed through */ public static String toString(OOText s) { if (s == null) { return null; @@ -29,6 +38,7 @@ public String asString() { return data; } + /* Object.equals */ @Override public boolean equals(Object o) { From 6a6e2584a7bf60c4c35ba730c9b0a84156e95863 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 28 May 2021 09:12:28 +0200 Subject: [PATCH 0919/1068] review rangesort --- .../rangesort/FunctionalTextViewCursor.java | 22 +++++++++---------- .../rangesort/RangeKeyedMapList.java | 6 +++++ .../openoffice/rangesort/RangeOverlap.java | 3 --- .../rangesort/RangeOverlapFinder.java | 5 ++++- .../rangesort/RangeOverlapKind.java | 3 ++- .../openoffice/rangesort/RangeSortVisual.java | 8 ++----- .../openoffice/rangesort/RangeSortable.java | 4 ---- 7 files changed, 24 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java b/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java index 039be4537ac..3f780274b0f 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java @@ -19,17 +19,17 @@ * instead. * * Here we manipulate the cursor via XSelectionSupplier.getSelection and - * XSelectionSupplierselect to move it to the text. + * XSelectionSupplier.select to move it to the text. * * Seems to work when the user selected a frame or image. * In these cases restoring the selection works, too. * * When the cursor is in a comment (referred to as "annotation" in OO - * API) then initialSelection is null, and select() does not help to + * API) then initialSelection is null, and select() fails to * get a functional viewCursor. * - * If get() reports error, we have to ask the user to move the cursor - * into the document text. + * If FunctionalTextViewCursor.get() reports error, we have to ask the + * user to move the cursor into the text part of the document. * * Usage: * @@ -60,13 +60,6 @@ public class FunctionalTextViewCursor { */ private XTextViewCursor viewCursor; - /** - * The constructor may change the selection (and cursor position) to provide - * a functional XTextViewCursor. - * - * On failure the constructor restores the selection. On success, the caller must call - * instance.restore() after finished using the cursor. - */ private FunctionalTextViewCursor(XTextRange initialPosition, XServiceInfo initialSelection, XTextViewCursor viewCursor) { @@ -80,6 +73,10 @@ private FunctionalTextViewCursor(XTextRange initialPosition, * * The cursor position may differ from the location * provided by the user. + * + * On failure the constructor restores the selection. On success, + * the caller may want to call instance.restore() after finished + * using the cursor. */ public static OOResult get(XTextDocument doc) { @@ -153,7 +150,8 @@ private static void restore(XTextDocument doc, } /* - * Restore initial state of selection (and thus viewCursor) + * Restore initial state of viewCursor (possibly by restoring + * selection) if possible. */ public void restore(XTextDocument doc) { FunctionalTextViewCursor.restore(doc, initialPosition, initialSelection); diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java index 1c77986c35a..9e6edd69738 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java @@ -6,6 +6,12 @@ import com.sun.star.text.XTextRange; +/* + * Partition by XTextRange.getText() and sort within the partitions a + * set of XTextRange values, while keeping their associated data + * recoverable. Allows identical XTextRange values, their data is + * collected in a list. + */ public class RangeKeyedMapList { private RangeKeyedMap> partitions; diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlap.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlap.java index 849f0e0405b..3edd059d7ff 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlap.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlap.java @@ -4,9 +4,6 @@ /** * Used in reporting range overlaps. - * - * You probably want {@code V} to include information - * identifying the ranges. */ public class RangeOverlap { public final RangeOverlapKind kind; diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java index 59fdf59592c..c5b74a0b42d 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java @@ -15,8 +15,11 @@ public class RangeOverlapFinder { * For overlapping and touching, only report consecutive ranges * and only with a single sample of otherwise identical ranges. * - * @param atMost Limit the number of records returneed to atMost. + * @param atMost Limit the number of records returned to atMost. * Zero or negative {@code atMost} means no limit. + * + * @param includeTouching Should the result contain ranges + * sharing only a boundary? */ public static List> findOverlappingRanges(RangeKeyedMapList input, int atMost, diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapKind.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapKind.java index 98bf6df2b40..2bb7f8f4af7 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapKind.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapKind.java @@ -1,7 +1,8 @@ package org.jabref.model.openoffice.rangesort; public enum RangeOverlapKind { - /** They share a boundary */ + + /** The ranges share a boundary */ TOUCH, /** They share some characters */ diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index 7ed3b54ab32..67b1fa0471d 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -22,12 +22,11 @@ * * Requires functional XTextViewCursor. * - * Problem: for multicolumn layout and view pages side-by-side mode of - * LO, the (top-down,left-to-right) order interpreted + * Problem: for multicolumn layout and when viewing pages side-by-side + * in LO, the (top-down,left-to-right) order interpreted * as-on-the-screen: an XTextRange at the top of the second * column or second page is sorted before one at the bottom * of the first column of the first page. - * */ public class RangeSortVisual { @@ -129,9 +128,6 @@ private static Point findPositionOfTextRange(XTextRange range, XTextViewCursor c * first, horizontal second, indexInPosition third. * * Used for sorting reference marks by their visual positions. - * - * - * */ private static class ComparableMark implements Comparable> { diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java index 6b2c1fa9e8f..39a16b4ecb2 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java @@ -4,10 +4,6 @@ /** * This is what {@code visualSort} needs in its input. - * - * But actually there is nothing visual in it. - * Maybe we could reuse it for other sorters. - * */ public interface RangeSortable { From 99574492b39986f9b8cde92dc57f103c2f2f0db7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 28 May 2021 10:42:33 +0200 Subject: [PATCH 0920/1068] insert (now commented out) "-Xlint:unchecked" --- build.gradle | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/build.gradle b/build.gradle index 24d8cf743f7..ec4eebcce1a 100644 --- a/build.gradle +++ b/build.gradle @@ -69,6 +69,13 @@ modularity.patchModule("test3", "sourcecode_2.12-0.1.4.jar") // See also https://github.com/java9-modularity/gradle-modules-plugin/issues/165 modularity.disableEffectiveArgumentsAdjustment() +tasks.withType(JavaCompile) { + options.compilerArgs += [ + // "-Xlint:deprecation", + // "-Xlint:unchecked" + ] +} + sourceSets { main { java { From 5f0dd885b7d24aec019cd8d9282926628ba846ed Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 28 May 2021 11:09:54 +0200 Subject: [PATCH 0921/1068] -Xlint:unchecked --- .../org/jabref/gui/openoffice/OOBibBase2.java | 3 +- .../logic/openoffice/frontend/OOFrontend.java | 38 +++++++++---------- .../style/OOFormatBibliography.java | 2 +- .../model/openoffice/ootext/OOTextIntoOO.java | 22 +++++------ .../openoffice/rangesort/RangeKeyedMap.java | 2 +- .../openoffice/style/CitationGroups.java | 2 +- .../model/openoffice/util/OOResult.java | 4 +- .../model/openoffice/util/OOVoidResult.java | 4 +- 8 files changed, 39 insertions(+), 38 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index 706f09c8e0d..b57e5b976bb 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -186,7 +186,8 @@ boolean testDialog(String title, List> results) { return testDialog(title, collectResults(title, results)); } - boolean testDialog(String title, OOVoidResult... results) { + @SafeVarargs + final boolean testDialog(String title, OOVoidResult... results) { List> rs = Arrays.asList(results); return testDialog(collectResults(title, rs)); } diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 507a7244899..49e9cafb985 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -124,12 +124,12 @@ public Optional healthReport(XTextDocument doc) NoDocumentException, WrappedTargetException { - List sortables = new ArrayList<>(); + List> sortables = new ArrayList<>(); for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { XTextRange range = (this .getMarkRange(doc, cg) .orElseThrow(RuntimeException::new)); - sortables.add(new RangeSortEntry(range, 0, cg)); + sortables.add(new RangeSortEntry<>(range, 0, cg)); } /* @@ -155,7 +155,7 @@ public Optional healthReport(XTextDocument doc) // Sort within partitions RangeKeyedMapList> rangeSorter = new RangeKeyedMapList<>(); - for (RangeSortEntry sortable : sortables) { + for (RangeSortEntry sortable : sortables) { rangeSorter.add(sortable.getRange(), sortable); } @@ -365,10 +365,10 @@ private List> citationRanges(XTextDocument for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { XTextRange range = this.getMarkRange(doc, cg).orElseThrow(RuntimeException::new); String description = cg.cgid.citationGroupIdAsString(); // cg.cgRangeStorage.nrGetRangeName(); - result.add(new RangeForOverlapCheck(range, - cg.cgid, - RangeForOverlapCheck.REFERENCE_MARK_KIND, - description)); + result.add(new RangeForOverlapCheck<>(range, + cg.cgid, + RangeForOverlapCheck.REFERENCE_MARK_KIND, + description)); } return result; } @@ -383,10 +383,10 @@ private List> bibliographyRanges(XTextDocu Optional range = UpdateBibliography.getBibliographyRange(doc); if (range.isPresent()) { String description = "bibliography"; - result.add(new RangeForOverlapCheck(range.get(), - new CitationGroupId("bibliography"), - RangeForOverlapCheck.BIBLIOGRAPHY_MARK_KIND, - description)); + result.add(new RangeForOverlapCheck<>(range.get(), + new CitationGroupId("bibliography"), + RangeForOverlapCheck.BIBLIOGRAPHY_MARK_KIND, + description)); } return result; } @@ -401,10 +401,10 @@ public List> viewCursorRanges(XTextDocumen Optional range = UnoCursor.getViewCursor(doc).map(e -> e); if (range.isPresent()) { String description = "cursor"; - result.add(new RangeForOverlapCheck(range.get(), - new CitationGroupId("cursor"), - RangeForOverlapCheck.CURSOR_MARK_KIND, - description)); + result.add(new RangeForOverlapCheck<>(range.get(), + new CitationGroupId("cursor"), + RangeForOverlapCheck.CURSOR_MARK_KIND, + description)); } return result; } @@ -447,10 +447,10 @@ private List> footnoteMarkRanges(XTextDocu boolean seenContains = seen.containsKey(footnoteMarkRange.get()); if (!seenContains) { seen.put(footnoteMarkRange.get(), true); - result.add(new RangeForOverlapCheck(footnoteMarkRange.get(), - citationRange.idWithinKind, - RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + citationRange.format())); + result.add(new RangeForOverlapCheck<>(footnoteMarkRange.get(), + citationRange.idWithinKind, + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + citationRange.format())); } } return result; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index 93988aa4770..c9ae527dcec 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -166,7 +166,7 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { String suffix = ")"; sb.append(prefix); - List citationGroups = new ArrayList(); + List citationGroups = new ArrayList<>(); for (CitationPath p : ck.getCitationPaths()) { CitationGroupId cgid = p.group; CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index e1983823870..f062bed7c40 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -670,33 +670,33 @@ private static boolean isPropertyDefault(XTextCursor cursor, String propertyName private static List> setCharWeight(float value) { List> settings = new ArrayList<>(); - settings.add(new OOPair("CharWeight", (Float) value)); + settings.add(new OOPair<>("CharWeight", (Float) value)); return settings; } private static List> setCharPosture(FontSlant value) { List> settings = new ArrayList<>(); - settings.add(new OOPair("CharPosture", (Object) value)); + settings.add(new OOPair<>("CharPosture", (Object) value)); return settings; } private static List> setCharCaseMap(short value) { List> settings = new ArrayList<>(); - settings.add(new OOPair("CharCaseMap", (Short) value)); + settings.add(new OOPair<>("CharCaseMap", (Short) value)); return settings; } // com.sun.star.awt.FontUnderline private static List> setCharUnderline(short value) { List> settings = new ArrayList<>(); - settings.add(new OOPair(CHAR_UNDERLINE, (Short) value)); + settings.add(new OOPair<>(CHAR_UNDERLINE, (Short) value)); return settings; } // com.sun.star.awt.FontStrikeout private static List> setCharStrikeout(short value) { List> settings = new ArrayList<>(); - settings.add(new OOPair(CHAR_STRIKEOUT, (Short) value)); + settings.add(new OOPair<>(CHAR_STRIKEOUT, (Short) value)); return settings; } @@ -704,7 +704,7 @@ private static List> setCharStrikeout(short value) { private static List> setCharStyleName(String value) { List> settings = new ArrayList<>(); if (value != null && value != "") { - settings.add(new OOPair(CHAR_STYLE_NAME, value)); + settings.add(new OOPair<>(CHAR_STYLE_NAME, value)); } else { LOGGER.warn("setCharStyleName: received null or empty value"); } @@ -714,7 +714,7 @@ private static List> setCharStyleName(String value) { // Locale private static List> setCharLocale(Locale value) { List> settings = new ArrayList<>(); - settings.add(new OOPair("CharLocale", (Object) value)); + settings.add(new OOPair<>("CharLocale", (Object) value)); return settings; } @@ -759,17 +759,17 @@ private static List> setCharEscapement(Optional va byte newHeight = (byte) Math.round(heightFloat * oldHeightFloat); short newValue = (short) Math.round(valueFloat * oldHeightFloat + oldValueFloat); if (value.isPresent()) { - settings.add(new OOPair(CHAR_ESCAPEMENT, (Short) newValue)); + settings.add(new OOPair<>(CHAR_ESCAPEMENT, (Short) newValue)); } if (height.isPresent()) { - settings.add(new OOPair(CHAR_ESCAPEMENT_HEIGHT, (Byte) newHeight)); + settings.add(new OOPair<>(CHAR_ESCAPEMENT_HEIGHT, (Byte) newHeight)); } } else { if (value.isPresent()) { - settings.add(new OOPair(CHAR_ESCAPEMENT, (Short) value.get())); + settings.add(new OOPair<>(CHAR_ESCAPEMENT, (Short) value.get())); } if (height.isPresent()) { - settings.add(new OOPair(CHAR_ESCAPEMENT_HEIGHT, (Byte) height.get())); + settings.add(new OOPair<>(CHAR_ESCAPEMENT_HEIGHT, (Byte) height.get())); } } return settings; diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java index 841b6f52355..094705f5fa8 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java @@ -85,6 +85,6 @@ public V put(XTextRange range, V value) { * @return A list of the partitions. */ public List> partitionValues() { - return new ArrayList(partitions.values()); + return new ArrayList<>(partitions.values()); } } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index c2767c3108a..f68aa4f115c 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -70,7 +70,7 @@ public void distributeToCitations(List where, continue; } Citation cit = cg.citationsInStorageOrder.get(p.storageIndexInGroup); - fun.accept(new OOPair(cit, value)); + fun.accept(new OOPair<>(cit, value)); } } diff --git a/src/main/java/org/jabref/model/openoffice/util/OOResult.java b/src/main/java/org/jabref/model/openoffice/util/OOResult.java index 1bc8cddcc13..2be478f6d8a 100644 --- a/src/main/java/org/jabref/model/openoffice/util/OOResult.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOResult.java @@ -31,14 +31,14 @@ private OOResult(Optional result, Optional error) { * @param result Null is not allowed. */ public static OOResult ok(R result) { - return new OOResult(Optional.of(result), Optional.empty()); + return new OOResult<>(Optional.of(result), Optional.empty()); } /** * @param error Null is not allowed. */ public static OOResult error(E error) { - return new OOResult(Optional.empty(), Optional.of(error)); + return new OOResult<>(Optional.empty(), Optional.of(error)); } /* diff --git a/src/main/java/org/jabref/model/openoffice/util/OOVoidResult.java b/src/main/java/org/jabref/model/openoffice/util/OOVoidResult.java index a0bb0ebebe2..5de68f8697c 100644 --- a/src/main/java/org/jabref/model/openoffice/util/OOVoidResult.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOVoidResult.java @@ -15,11 +15,11 @@ private OOVoidResult(Optional error) { } public static OOVoidResult ok() { - return new OOVoidResult(Optional.empty()); + return new OOVoidResult<>(Optional.empty()); } public static OOVoidResult error(E error) { - return new OOVoidResult(Optional.of(error)); + return new OOVoidResult<>(Optional.of(error)); } public boolean isError() { From 87444435f17cae19e3c66ccfb52852be89a1a0f1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 28 May 2021 11:17:40 +0200 Subject: [PATCH 0922/1068] comment type back from oobranch --- .../org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java index 78e8b8acb23..dd09ae4745a 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java @@ -147,7 +147,7 @@ public static void remove(XTextDocument doc, String property) * @param property Name of a custom document property in the * current document. * - * Keep silent if property dids not exist. + * Keep silent if property did not exist. */ public static void removeIfExists(XTextDocument doc, String property) throws From 4f4ba2120d0dbd0bd0ec76f91c702fc874294265 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 28 May 2021 13:52:58 +0200 Subject: [PATCH 0923/1068] do not call checkRangeOverlaps twice (too slow) --- src/main/java/org/jabref/gui/openoffice/OOBibBase2.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index b57e5b976bb..f8ee5777114 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -262,11 +262,6 @@ private static OOVoidResult checkRangeOverlaps(XTextDocument doc, OOFro private static OOVoidResult checkRangeOverlapsWithCursor(XTextDocument doc, OOFrontend fr) { final String title = "checkRangeOverlapsWithCursor"; - OOVoidResult precheck = checkRangeOverlaps(doc, fr); - if (precheck.isError()) { - return precheck; - } - List> userRanges; try { userRanges = fr.viewCursorRanges(doc); From 7769b362ea34a0d7a3a9dd3ea8ddd5763778bf8b Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 28 May 2021 23:11:05 +0200 Subject: [PATCH 0924/1068] format --- src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 30c43c1097d..03765f8ffd8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -49,8 +49,7 @@ class OOBibBaseConnect { /* * Constructor */ - public OOBibBaseConnect(Path loPath, - DialogService dialogService) + public OOBibBaseConnect(Path loPath, DialogService dialogService) throws BootstrapException, CreationException { From a91e5e5fe56e99993a10c8e7137037546cd151df Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 29 May 2021 12:52:03 +0200 Subject: [PATCH 0925/1068] lock screen refresh in EditInsert --- .../logic/openoffice/action/EditInsert.java | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index fdecec69c2c..277b92bec76 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -19,6 +19,7 @@ import org.jabref.model.openoffice.style.OODataModel; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoScreenRefresh; import org.jabref.model.openoffice.util.OOListUtil; import com.sun.star.beans.IllegalTypeException; @@ -110,15 +111,20 @@ public static void insertCitationGroup(XTextDocument doc, citeText = OOText.fromString("[?]"); } - UpdateCitationMarkers.createAndFillCitationGroup(fr, - doc, - citationKeys, - pageInfos, - citationType, - citeText, - cursor, - style, - true /* insertSpaceAfter */); + try { + UnoScreenRefresh.lockControllers(doc); + UpdateCitationMarkers.createAndFillCitationGroup(fr, + doc, + citationKeys, + pageInfos, + citationType, + citeText, + cursor, + style, + true /* insertSpaceAfter */); + } finally { + UnoScreenRefresh.unlockControllers(doc); + } } } From 9c32217da7541ca299c7ac87c208208db3c3b5ae Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 29 May 2021 22:29:23 +0200 Subject: [PATCH 0926/1068] Speed up cursor vs protected-range checking Only check cursor to protected-ranges, not among protected-ranges. --- .../org/jabref/gui/openoffice/OOBibBase2.java | 8 +- .../logic/openoffice/frontend/OOFrontend.java | 94 +++++++++++++++++-- .../openoffice/rangesort/RangeKeyedMap.java | 22 +---- .../jabref/model/openoffice/util/Tuple3.java | 13 +++ 4 files changed, 107 insertions(+), 30 deletions(-) create mode 100644 src/main/java/org/jabref/model/openoffice/util/Tuple3.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index f8ee5777114..c372185cf60 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -272,13 +272,11 @@ private static OOVoidResult checkRangeOverlapsWithCursor(XTextDocument } boolean requireSeparation = false; - int maxReportedOverlaps = 10; OOVoidResult res; try { - res = fr.checkRangeOverlaps(doc, - userRanges, - requireSeparation, - maxReportedOverlaps); + res = fr.checkRangeOverlapsWithCursor(doc, + userRanges, + requireSeparation); } catch (NoDocumentException ex) { return OOVoidResult.error(OOError.from(ex).setTitle(title)); } catch (WrappedTargetException ex) { diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 49e9cafb985..282bc1a64ef 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -29,10 +29,12 @@ import org.jabref.model.openoffice.style.OODataModel; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoCursor; import org.jabref.model.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.util.OOListUtil; import org.jabref.model.openoffice.util.OOVoidResult; +import org.jabref.model.openoffice.util.Tuple3; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -41,9 +43,11 @@ import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; +import com.sun.star.text.XTextRangeCompare; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -354,7 +358,7 @@ public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroup cg) * * result.size() == nRefMarks */ - private List> citationRanges(XTextDocument doc) + public List> citationRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { @@ -373,7 +377,7 @@ private List> citationRanges(XTextDocument return result; } - private List> bibliographyRanges(XTextDocument doc) + public List> bibliographyRanges(XTextDocument doc) throws NoDocumentException, WrappedTargetException { @@ -423,7 +427,9 @@ public List> viewCursorRanges(XTextDocumen * footnote marks does not depend on how do we mark or * structure those ranges. */ - private List> footnoteMarkRanges(XTextDocument doc) + public List> + footnoteMarkRanges(XTextDocument doc, + List> citationRanges) throws NoDocumentException, WrappedTargetException { @@ -434,7 +440,7 @@ private List> footnoteMarkRanges(XTextDocu List> result = new ArrayList<>(); - for (RangeForOverlapCheck citationRange : citationRanges(doc)) { + for (RangeForOverlapCheck citationRange : citationRanges) { Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(citationRange.range); @@ -456,6 +462,81 @@ private List> footnoteMarkRanges(XTextDocu return result; } + /** + * Check for any overlap between userRanges and protected ranges. + * + * Assume userRanges is small (usually 1 elements for checking the cursor) + * Returns on first problem found. + */ + public OOVoidResult + checkRangeOverlapsWithCursor(XTextDocument doc, + List> userRanges, + boolean requireSeparation) + throws + NoDocumentException, + WrappedTargetException { + + List> citationRanges = citationRanges(doc); + List> ranges = new ArrayList<>(); + + // ranges.addAll(userRanges); + ranges.addAll(bibliographyRanges(doc)); + ranges.addAll(citationRanges); + ranges.addAll(footnoteMarkRanges(doc, citationRanges)); + + if (userRanges.size() == 0) { + return OOVoidResult.ok(); + } + List>> userTuples = + new ArrayList<>(userRanges.size()); + for (RangeForOverlapCheck userRange : userRanges) { + XText text = userRange.range.getText(); + userTuples.add(new Tuple3<>(text, + UnoCast.unoQI(XTextRangeCompare.class, text), + userRange)); + } + + for (RangeForOverlapCheck range : ranges) { + XTextRange bRange = range.range; + XText bRangeText = bRange.getText(); + XTextRange bRangeStart = bRange.getStart(); + XTextRange bRangeEnd = bRange.getEnd(); + for (Tuple3> tup : userTuples){ + if (tup.a != bRangeText) { + continue; + } + XTextRangeCompare cmp = tup.b; + XTextRange aRange = tup.c.range; + int abEndToStart = -1 * cmp.compareRegionStarts(aRange.getEnd(), bRangeStart); + if (abEndToStart < 0 || (!requireSeparation && (abEndToStart==0))) { + continue; + } + int baEndToStart = -1 * cmp.compareRegionStarts(bRangeEnd, aRange.getStart()); + if (baEndToStart < 0 || (!requireSeparation && (baEndToStart==0))) { + continue; + } + + StringBuilder msg = new StringBuilder(); + boolean touching = (abEndToStart == 0 || baEndToStart == 0); + + if (touching) { + msg.append(Localization.lang("Found touching ranges")); + } else { + msg.append(Localization.lang("Found overlapping ranges")); + } + msg.append(": "); + msg.append(String.format("'%s'", tup.c.format())); + msg.append(", "); + msg.append(String.format("'%s'", range.format())); + msg.append("\n"); + + return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges", + msg.toString())); + } + } + return OOVoidResult.ok(); + } + /** * @param requireSeparation Report range pairs that only share a boundary. * @param reportAtMost Limit number of overlaps reported (0 for no limit) @@ -470,11 +551,12 @@ private List> footnoteMarkRanges(XTextDocu NoDocumentException, WrappedTargetException { + List> citationRanges = citationRanges(doc); List> ranges = new ArrayList<>(); ranges.addAll(userRanges); ranges.addAll(bibliographyRanges(doc)); - ranges.addAll(citationRanges(doc)); - ranges.addAll(footnoteMarkRanges(doc)); + ranges.addAll(citationRanges); + ranges.addAll(footnoteMarkRanges(doc, citationRanges)); RangeKeyedMapList> sorted = new RangeKeyedMapList<>(); for (RangeForOverlapCheck aRange : ranges) { diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java index 094705f5fa8..8850ddf1ef1 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java @@ -7,6 +7,8 @@ import java.util.Objects; import java.util.TreeMap; +import org.jabref.model.openoffice.uno.UnoTextRange; + import com.sun.star.text.XText; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextRangeCompare; @@ -54,28 +56,10 @@ public V get(XTextRange range) { return partition.get(range); } - /* - * Same as UnoTextRange.compareStartsThenEnds in logic. - */ - private static int comparator(XTextRange a, XTextRange b) { - if (a.getText() != b.getText()) { - throw new RuntimeException("comparator: got incomparable regions"); - } - - final XTextRangeCompare compare = - UnoRuntime.queryInterface(XTextRangeCompare.class, a.getText()); - - int cmpStart = (-1) * compare.compareRegionStarts(a, b); - if (cmpStart != 0) { - return cmpStart; - } - return (-1) * compare.compareRegionEnds(a, b); - } - public V put(XTextRange range, V value) { TreeMap partition = partitions.get(range.getText()); if (partition == null) { - partition = new TreeMap<>(RangeKeyedMap::comparator); + partition = new TreeMap<>(UnoTextRange::compareStartsThenEnds); partitions.put(range.getText(), partition); } return partition.put(range, value); diff --git a/src/main/java/org/jabref/model/openoffice/util/Tuple3.java b/src/main/java/org/jabref/model/openoffice/util/Tuple3.java new file mode 100644 index 00000000000..0ca241bcf0a --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/util/Tuple3.java @@ -0,0 +1,13 @@ +package org.jabref.model.openoffice.util; + +public class Tuple3 { + public final A a; + public final B b; + public final C c; + public Tuple3(A a, B b, C c) { + this.a = a; + this.b = b; + this.c = c; + } +} + From e8a4b643e8acb513855c5801aa04fcb38f830234 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 30 May 2021 00:04:53 +0200 Subject: [PATCH 0927/1068] add TimeLap.java --- .../openoffice/notforproduction/TimeLap.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java diff --git a/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java b/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java new file mode 100644 index 00000000000..d13ce9c7132 --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java @@ -0,0 +1,28 @@ +package org.jabref.model.openoffice.notforproduction; + +/* + * Measure execution time. + */ +public class TimeLap { + + /* + * Usage: + * long startTime = TimeLap.start(); + * // call to measure + * startTime = TimeLap.now("label1", startTime); + * // call to measure + * startTime = TimeLap.now("label2", startTime); + */ + // return time (nanoSeconds) for timing + public static long start() { + return System.nanoTime(); + } + + // return time (nanoSeconds) for next timing + public static long now(String label, long startTime) { + long endTime = System.nanoTime(); + long duration = (endTime - startTime); //divide by 1000000 to get milliseconds. + System.out.printf("%-40s: %.3f ms\n", label, duration /1000000.0); + return endTime; + } +} From 9c4a99f154a39c9b8d9b9bb1982154cab5221040 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 30 May 2021 00:05:41 +0200 Subject: [PATCH 0928/1068] visualSort throws on ControllersLocked --- .../org/jabref/model/openoffice/rangesort/RangeSortVisual.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index 67b1fa0471d..b2c8ab21063 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -53,6 +53,9 @@ public static List> visualSort(List> input LOGGER.warn("visualSort:" + " with ControllersLocked, viewCursor.gotoRange" + " is probably useless"); + throw new RuntimeException("visualSort:" + + " with ControllersLocked, viewCursor.gotoRange" + + " is probably useless"); } XTextViewCursor viewCursor = fcursor.getViewCursor(); From f4dd60e0f1cf3b7927c9dbe0f384d74ecbda842b Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 31 May 2021 10:21:19 +0200 Subject: [PATCH 0929/1068] rename Tuple3 -> OOTuple3 --- .../logic/openoffice/frontend/OOFrontend.java | 13 +++++++------ .../openoffice/util/{Tuple3.java => OOTuple3.java} | 4 ++-- 2 files changed, 9 insertions(+), 8 deletions(-) rename src/main/java/org/jabref/model/openoffice/util/{Tuple3.java => OOTuple3.java} (71%) diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 282bc1a64ef..72f1e7fe3a6 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -34,7 +34,7 @@ import org.jabref.model.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.util.OOListUtil; import org.jabref.model.openoffice.util.OOVoidResult; -import org.jabref.model.openoffice.util.Tuple3; +import org.jabref.model.openoffice.util.OOTuple3; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -487,13 +487,13 @@ public List> viewCursorRanges(XTextDocumen if (userRanges.size() == 0) { return OOVoidResult.ok(); } - List>> userTuples = + List>> userTuples = new ArrayList<>(userRanges.size()); for (RangeForOverlapCheck userRange : userRanges) { XText text = userRange.range.getText(); - userTuples.add(new Tuple3<>(text, - UnoCast.unoQI(XTextRangeCompare.class, text), - userRange)); + userTuples.add(new OOTuple3<>(text, + UnoCast.unoQI(XTextRangeCompare.class, text), + userRange)); } for (RangeForOverlapCheck range : ranges) { @@ -501,7 +501,8 @@ public List> viewCursorRanges(XTextDocumen XText bRangeText = bRange.getText(); XTextRange bRangeStart = bRange.getStart(); XTextRange bRangeEnd = bRange.getEnd(); - for (Tuple3> tup : userTuples){ + for (OOTuple3> tup : + userTuples){ if (tup.a != bRangeText) { continue; } diff --git a/src/main/java/org/jabref/model/openoffice/util/Tuple3.java b/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java similarity index 71% rename from src/main/java/org/jabref/model/openoffice/util/Tuple3.java rename to src/main/java/org/jabref/model/openoffice/util/OOTuple3.java index 0ca241bcf0a..ca324ebc4ad 100644 --- a/src/main/java/org/jabref/model/openoffice/util/Tuple3.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java @@ -1,10 +1,10 @@ package org.jabref.model.openoffice.util; -public class Tuple3 { +public class OOTuple3 { public final A a; public final B b; public final C c; - public Tuple3(A a, B b, C c) { + public OOTuple3(A a, B b, C c) { this.a = a; this.b = b; this.c = c; From fa0061b3dcb286aa3b37fc21139710d9c22dd3a7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 31 May 2021 16:47:37 +0200 Subject: [PATCH 0930/1068] RangeSort.java --- .../org/jabref/gui/openoffice/OOBibBase2.java | 2 +- .../logic/openoffice/frontend/OOFrontend.java | 125 +++++++----------- .../frontend/RangeForOverlapCheck.java | 10 +- .../openoffice/rangesort/RangeHolder.java | 7 + .../rangesort/RangeOverlapBetween.java | 92 +++++++++++++ .../rangesort/RangeOverlapFinder.java | 61 --------- .../rangesort/RangeOverlapWithin.java | 123 +++++++++++++++++ .../model/openoffice/rangesort/RangeSort.java | 86 ++++++++++++ .../openoffice/rangesort/RangeSortable.java | 2 +- .../model/openoffice/uno/UnoTextRange.java | 24 +++- 10 files changed, 381 insertions(+), 151 deletions(-) create mode 100644 src/main/java/org/jabref/model/openoffice/rangesort/RangeHolder.java create mode 100644 src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java delete mode 100644 src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java create mode 100644 src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java create mode 100644 src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index c372185cf60..846fa5e2c3a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -20,11 +20,11 @@ import org.jabref.logic.openoffice.action.ManageCitations; import org.jabref.logic.openoffice.action.Update; import org.jabref.logic.openoffice.frontend.OOFrontend; -import org.jabref.logic.openoffice.frontend.RangeForOverlapCheck; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.logic.openoffice.frontend.RangeForOverlapCheck; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationType; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 72f1e7fe3a6..7e6345de65f 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -15,10 +15,13 @@ import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; +import org.jabref.model.openoffice.rangesort.RangeHolder; import org.jabref.model.openoffice.rangesort.RangeKeyedMap; import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; import org.jabref.model.openoffice.rangesort.RangeOverlap; -import org.jabref.model.openoffice.rangesort.RangeOverlapFinder; +import org.jabref.model.openoffice.rangesort.RangeOverlapBetween; +import org.jabref.model.openoffice.rangesort.RangeOverlapKind; +import org.jabref.model.openoffice.rangesort.RangeOverlapWithin; import org.jabref.model.openoffice.rangesort.RangeSortEntry; import org.jabref.model.openoffice.rangesort.RangeSortVisual; import org.jabref.model.openoffice.rangesort.RangeSortable; @@ -157,8 +160,7 @@ public Optional healthReport(XTextDocument doc) */ // Sort within partitions - RangeKeyedMapList> rangeSorter = - new RangeKeyedMapList<>(); + RangeKeyedMapList> rangeSorter = new RangeKeyedMapList<>(); for (RangeSortEntry sortable : sortables) { rangeSorter.add(sortable.getRange(), sortable); } @@ -462,6 +464,31 @@ public List> viewCursorRanges(XTextDocumen return result; } + static String + rangeOverlapsToMessage(List>> overlaps) { + + if (overlaps.size() == 0) { + return "(*no overlaps*)"; + } + + StringBuilder msg = new StringBuilder(); + for (RangeOverlap> overlap : overlaps) { + String listOfRanges = (overlap.valuesForOverlappingRanges.stream() + .map(v -> String.format("'%s'", v.format())) + .collect(Collectors.joining(", "))); + msg.append( + switch (overlap.kind) { + case EQUAL_RANGE -> Localization.lang("Found identical ranges"); + case OVERLAP -> Localization.lang("Found overlapping ranges"); + case TOUCH -> Localization.lang("Found touching ranges"); + }); + msg.append(": "); + msg.append(listOfRanges); + msg.append("\n"); + } + return msg.toString(); + } + /** * Check for any overlap between userRanges and protected ranges. * @@ -484,58 +511,18 @@ public List> viewCursorRanges(XTextDocumen ranges.addAll(citationRanges); ranges.addAll(footnoteMarkRanges(doc, citationRanges)); - if (userRanges.size() == 0) { - return OOVoidResult.ok(); - } - List>> userTuples = - new ArrayList<>(userRanges.size()); - for (RangeForOverlapCheck userRange : userRanges) { - XText text = userRange.range.getText(); - userTuples.add(new OOTuple3<>(text, - UnoCast.unoQI(XTextRangeCompare.class, text), - userRange)); - } - - for (RangeForOverlapCheck range : ranges) { - XTextRange bRange = range.range; - XText bRangeText = bRange.getText(); - XTextRange bRangeStart = bRange.getStart(); - XTextRange bRangeEnd = bRange.getEnd(); - for (OOTuple3> tup : - userTuples){ - if (tup.a != bRangeText) { - continue; - } - XTextRangeCompare cmp = tup.b; - XTextRange aRange = tup.c.range; - int abEndToStart = -1 * cmp.compareRegionStarts(aRange.getEnd(), bRangeStart); - if (abEndToStart < 0 || (!requireSeparation && (abEndToStart==0))) { - continue; - } - int baEndToStart = -1 * cmp.compareRegionStarts(bRangeEnd, aRange.getStart()); - if (baEndToStart < 0 || (!requireSeparation && (baEndToStart==0))) { - continue; - } - - StringBuilder msg = new StringBuilder(); - boolean touching = (abEndToStart == 0 || baEndToStart == 0); + List>> overlaps = + RangeOverlapBetween.findFirst( + doc, + userRanges, + ranges, + requireSeparation); - if (touching) { - msg.append(Localization.lang("Found touching ranges")); - } else { - msg.append(Localization.lang("Found overlapping ranges")); - } - msg.append(": "); - msg.append(String.format("'%s'", tup.c.format())); - msg.append(", "); - msg.append(String.format("'%s'", range.format())); - msg.append("\n"); - - return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges", - msg.toString())); - } + if (overlaps.size() == 0) { + return OOVoidResult.ok(); } - return OOVoidResult.ok(); + return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges", + rangeOverlapsToMessage(overlaps))); } /** @@ -559,36 +546,14 @@ public List> viewCursorRanges(XTextDocumen ranges.addAll(citationRanges); ranges.addAll(footnoteMarkRanges(doc, citationRanges)); - RangeKeyedMapList> sorted = new RangeKeyedMapList<>(); - for (RangeForOverlapCheck aRange : ranges) { - sorted.add(aRange.range, aRange); - } - List>> overlaps = - RangeOverlapFinder.findOverlappingRanges(sorted, reportAtMost, requireSeparation); - - if (overlaps.size() > 0) { - StringBuilder msg = new StringBuilder(); - for (RangeOverlap> overlap : overlaps) { - String listOfRanges = (overlap.valuesForOverlappingRanges.stream() - .map(v -> String.format("'%s'", v.format())) - .collect(Collectors.joining(", "))); - - msg.append( - switch (overlap.kind) { - case EQUAL_RANGE -> Localization.lang("Found identical ranges"); - case OVERLAP -> Localization.lang("Found overlapping ranges"); - case TOUCH -> Localization.lang("Found touching ranges"); - }); - msg.append(": "); - msg.append(listOfRanges); - msg.append("\n"); - } - return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges", - msg.toString())); - } else { + RangeOverlapWithin.find(doc, ranges, requireSeparation, reportAtMost); + + if (overlaps.size() == 0) { return OOVoidResult.ok(); } + return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges", + rangeOverlapsToMessage(overlaps))); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java b/src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java index 02dd98636be..6cbf560ec62 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java @@ -1,5 +1,7 @@ package org.jabref.logic.openoffice.frontend; +import org.jabref.model.openoffice.rangesort.RangeHolder; + import com.sun.star.text.XTextRange; /** @@ -16,13 +18,15 @@ * tables or other identifier within its kind ({@code idWithinKind}) * */ -public class RangeForOverlapCheck { +public class RangeForOverlapCheck implements RangeHolder { + public final static int REFERENCE_MARK_KIND = 0; public final static int FOOTNOTE_MARK_KIND = 1; public final static int CURSOR_MARK_KIND = 2; public final static int BIBLIOGRAPHY_MARK_KIND = 3; public final XTextRange range; + public final int kind; public final T idWithinKind; private final String description; @@ -38,4 +42,8 @@ public String format() { return description; } + @Override + public XTextRange getRange() { + return range; + } } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeHolder.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeHolder.java new file mode 100644 index 00000000000..cae6f99e34e --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeHolder.java @@ -0,0 +1,7 @@ +package org.jabref.model.openoffice.rangesort; + +import com.sun.star.text.XTextRange; + +public interface RangeHolder { + XTextRange getRange(); +} diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java new file mode 100644 index 00000000000..952123e1d78 --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java @@ -0,0 +1,92 @@ +package org.jabref.model.openoffice.rangesort; + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeMap; + +import org.jabref.model.openoffice.uno.UnoCast; +import org.jabref.model.openoffice.uno.UnoTextRange; +import org.jabref.model.openoffice.util.OOTuple3; + +import com.sun.star.text.XText; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; +import com.sun.star.text.XTextRangeCompare; + +public class RangeOverlapBetween { + + private RangeOverlapBetween() {} + + /** + * Check for any overlap between two sets of XTextRange values. + * + * Assume fewHolders is small (usually 1 elements for checking the cursor) + * Returns on first problem found. + */ + public static + List> findFirst(XTextDocument doc, + List fewHolders, + List manyHolders, + boolean includeTouching) { + + List> result = new ArrayList<>(); + + if (fewHolders.size() == 0) { + return result; + } + + List> fewTuples = + new ArrayList<>(fewHolders.size()); + + for (V aHolder : fewHolders) { + XText aText = aHolder.getRange().getText(); + fewTuples.add(new OOTuple3<>(aText, + UnoCast.unoQI(XTextRangeCompare.class, aText), + aHolder)); + } + + for (V bHolder : manyHolders) { + XTextRange bRange = bHolder.getRange(); + XText bText = bRange.getText(); + XTextRange bRangeStart = bRange.getStart(); + XTextRange bRangeEnd = bRange.getEnd(); + + for (OOTuple3 tup : fewTuples) { + XText aText = tup.a; + XTextRangeCompare cmp = tup.b; + V aHolder = tup.c; + XTextRange aRange = aHolder.getRange(); + if (aText != bText) { + continue; + } + int abEndToStart = -1 * cmp.compareRegionStarts(aRange.getEnd(), bRangeStart); + if (abEndToStart < 0 || (!includeTouching && (abEndToStart==0))) { + continue; + } + int baEndToStart = -1 * cmp.compareRegionStarts(bRangeEnd, aRange.getStart()); + if (baEndToStart < 0 || (!includeTouching && (baEndToStart==0))) { + continue; + } + + boolean equal = UnoTextRange.compareStartsThenEnds(aRange, bRange) == 0; + boolean touching = (abEndToStart == 0 || baEndToStart == 0); + + // In case of two equal collapsed ranges there is an + // ambiguity : TOUCH or EQUAL_RANGE ? + // We return EQUAL_RANGE + RangeOverlapKind kind = + (equal ? RangeOverlapKind.EQUAL_RANGE + : (touching ? RangeOverlapKind.TOUCH + : RangeOverlapKind.OVERLAP)); + + List valuesForOverlappingRanges = new ArrayList<>(); + valuesForOverlappingRanges.add(aHolder); + valuesForOverlappingRanges.add(bHolder); + + result.add(new RangeOverlap(kind, valuesForOverlappingRanges)); + return result; + } + } + return result; + } +} diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java deleted file mode 100644 index c5b74a0b42d..00000000000 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapFinder.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.jabref.model.openoffice.rangesort; - -import java.util.ArrayList; -import java.util.List; -import java.util.TreeMap; - -import org.jabref.model.openoffice.uno.UnoTextRange; - -import com.sun.star.text.XTextRange; - -public class RangeOverlapFinder { - /** - * Report identical, overlapping or touching ranges. - * - * For overlapping and touching, only report consecutive ranges - * and only with a single sample of otherwise identical ranges. - * - * @param atMost Limit the number of records returned to atMost. - * Zero or negative {@code atMost} means no limit. - * - * @param includeTouching Should the result contain ranges - * sharing only a boundary? - */ - public static List> findOverlappingRanges(RangeKeyedMapList input, - int atMost, - boolean includeTouching) { - List> result = new ArrayList<>(); - for (TreeMap> partition : input.partitionValues()) { - List orderedRanges = new ArrayList<>(partition.keySet()); - for (int i = 0; i < orderedRanges.size(); i++) { - XTextRange aRange = orderedRanges.get(i); - List aValues = partition.get(aRange); - if (aValues.size() > 1) { - result.add(new RangeOverlap(RangeOverlapKind.EQUAL_RANGE, aValues)); - if (atMost > 0 && result.size() >= atMost) { - return result; - } - } - if ((i + 1) < orderedRanges.size()) { - XTextRange bRange = orderedRanges.get(i + 1); - int cmp = UnoTextRange.compareStarts(aRange.getEnd(), bRange.getStart()); - if (cmp > 0 || (includeTouching && (cmp == 0))) { - // found overlap or touch - List bValues = partition.get(bRange); - List valuesForOverlappingRanges = new ArrayList<>(); - valuesForOverlappingRanges.add(aValues.get(0)); - valuesForOverlappingRanges.add(bValues.get(0)); - result.add(new RangeOverlap((cmp == 0) - ? RangeOverlapKind.TOUCH - : RangeOverlapKind.OVERLAP, - valuesForOverlappingRanges)); - } - if (atMost > 0 && result.size() >= atMost) { - return result; - } - } - } - } - return result; - } -} diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java new file mode 100644 index 00000000000..62bb933b92b --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java @@ -0,0 +1,123 @@ +package org.jabref.model.openoffice.rangesort; + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeMap; + +import org.jabref.model.openoffice.uno.UnoCast; +import org.jabref.model.openoffice.uno.UnoTextRange; +import org.jabref.model.openoffice.util.OOTuple3; + +import com.sun.star.text.XText; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; +import com.sun.star.text.XTextRangeCompare; + +public class RangeOverlapWithin { + + private RangeOverlapWithin() {} + + /** + * Report identical, overlapping or touching ranges between + * elements of rangeHolders. + * + * For overlapping and touching, only report consecutive ranges + * and only with a single sample of otherwise identical ranges. + * + * @param atMost Limit the number of records returned to atMost. + * Zero {@code atMost} means no limit. + * + * @param includeTouching Should the result contain ranges + * sharing only a boundary? + */ + public static + List> find(XTextDocument doc, + List rangeHolders, + boolean includeTouching, + int reportAtMost) { + + RangeSort.RangePartitions partitions = RangeSort.partitionAndSortRanges(rangeHolders); + + List> overlaps = findOverlappingRanges(partitions, reportAtMost, includeTouching); + + return overlaps; + } + + /** + * Report identical, overlapping or touching ranges. + * + * For overlapping and touching, only report consecutive ranges + * and only with a single sample of otherwise identical ranges. + * + * @param atMost Limit the number of records returned to atMost. + * Zero {@code atMost} means no limit. + * + * @param includeTouching Should the result contain ranges + * sharing only a boundary? + */ + private static + List> findOverlappingRanges(RangeSort.RangePartitions input, + int atMost, + boolean includeTouching) { + assert atMost >= 0; + + List> result = new ArrayList<>(); + + for (List partition : input.partitions.values()) { + if (partition.size() == 0) { + continue; + } + XTextRangeCompare cmp = UnoCast.unoQI(XTextRangeCompare.class, + partition.get(0).getRange().getText()); + + for (int i = 0; i < (partition.size() - 1); i++) { + V aHolder = partition.get(i); + V bHolder = partition.get(i + 1); + XTextRange aRange = aHolder.getRange(); + XTextRange bRange = bHolder.getRange(); + + // check equal values + int cmpResult = UnoTextRange.compareStartsThenEndsUnsafe(cmp, aRange, bRange); + if (cmpResult == 0) { + List aValues = new ArrayList<>(); + aValues.add(aHolder); + // aValues.add(bHolder); + // collect those equal + while (i < (partition.size() - 1) && + UnoTextRange.compareStartsThenEndsUnsafe( + cmp, + aRange, + partition.get(i + 1).getRange()) == 0) { + bHolder = partition.get(i + 1); + aValues.add(bHolder); + i++; + } + result.add(new RangeOverlap(RangeOverlapKind.EQUAL_RANGE, aValues)); + if (atMost > 0 && result.size() >= atMost) { + return result; + } + continue; + } + + // Not equal, and (a <= b) since sorted. + // Check if a.end >= b.start + cmpResult = UnoTextRange.compareStartsUnsafe(cmp, aRange.getEnd(), bRange.getStart()); + if (cmpResult > 0 || (includeTouching && (cmpResult == 0))) { + // found overlap or touch + List valuesForOverlappingRanges = new ArrayList<>(); + valuesForOverlappingRanges.add(aHolder); + valuesForOverlappingRanges.add(bHolder); + result.add(new RangeOverlap((cmpResult == 0) + ? RangeOverlapKind.TOUCH + : RangeOverlapKind.OVERLAP, + valuesForOverlappingRanges)); + } + if (atMost > 0 && result.size() >= atMost) { + return result; + } + } + } + return result; + } + +} diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java new file mode 100644 index 00000000000..7a5d1c2fc62 --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -0,0 +1,86 @@ +package org.jabref.model.openoffice.rangesort; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jabref.model.openoffice.uno.UnoCast; +import org.jabref.model.openoffice.uno.UnoTextRange; + +import com.sun.star.text.XText; +import com.sun.star.text.XTextRangeCompare; + +public class RangeSort { + + /* + * Sort within a partition + */ + + public static class HolderComparatorWithinPartition implements Comparator { + + XTextRangeCompare cmp; + + HolderComparatorWithinPartition(XText text) { + cmp = UnoCast.unoQI(XTextRangeCompare.class, text); + } + + /* + * Assumes a and b belong to the same XText as cmp. + */ + @Override + public int compare(RangeHolder a, RangeHolder b) { + return UnoTextRange.compareStartsThenEndsUnsafe(cmp, a.getRange(), b.getRange()); + } + } + + public static + void sortWithinPartition(List rangeHolders) { + if (rangeHolders.isEmpty()) { + return; + } + XText text = rangeHolders.get(0).getRange().getText(); + rangeHolders.sort(new HolderComparatorWithinPartition(text)); + } + + /* + * Partitioning + */ + + public static class RangePartitions { + public final Map> partitions; + + public RangePartitions() { + this.partitions = new HashMap<>(); + } + + public void add(V holder) { + XText partitionKey = holder.getRange().getText(); + List partition = partitions.get(partitionKey); + if (partition == null) { + partition = new ArrayList<>(); + partitions.put(partitionKey, partition); + } + partition.add(holder); + } + } + + public static + RangePartitions partitionRanges(List holders) { + RangePartitions result = new RangePartitions<>(); + for (V holder : holders) { + result.add(holder); + } + return result; + } + + public static + RangePartitions partitionAndSortRanges(List holders) { + RangePartitions result = partitionRanges(holders); + for (List partition : result.partitions.values()) { + sortWithinPartition(partition); + } + return result; + } +} diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java index 39a16b4ecb2..66e17a5b35b 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java @@ -5,7 +5,7 @@ /** * This is what {@code visualSort} needs in its input. */ -public interface RangeSortable { +public interface RangeSortable extends RangeHolder { /** The XTextRange * diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java index 1559c55d490..b44ed6ce38b 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java @@ -40,12 +40,16 @@ public static boolean comparables(XTextRange a, XTextRange b) { * * 1 if (a > b); (-1) if (a < 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 RuntimeException("compareStarts: got incomparable regions"); } final XTextRangeCompare compare = UnoCast.unoQI(XTextRangeCompare.class, a.getText()); - return (-1) * compare.compareRegionStarts(a, b); + return compareStartsUnsafe(compare, a, b); } /** @@ -61,16 +65,22 @@ public static int compareEnds(XTextRange a, XTextRange b) { 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 RuntimeException("compareStartsThenEnds: got incomparable regions"); } final XTextRangeCompare compare = UnoCast.unoQI(XTextRangeCompare.class, a.getText()); - int res = (-1) * compare.compareRegionStarts(a, b); - if (res != 0) { - return res; - } - return (-1) * compare.compareRegionEnds(a, b); + return compareStartsThenEndsUnsafe(compare, a, b); } - } From 1d59771c325509a6c3869508394a9d4eb20b2148 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 31 May 2021 17:10:56 +0200 Subject: [PATCH 0931/1068] checkstyle --- src/main/java/org/jabref/gui/openoffice/OOBibBase2.java | 2 +- .../org/jabref/logic/openoffice/frontend/OOFrontend.java | 6 ------ .../model/openoffice/notforproduction/TimeLap.java | 4 ++-- .../jabref/model/openoffice/rangesort/RangeKeyedMap.java | 2 -- .../model/openoffice/rangesort/RangeOverlapBetween.java | 7 +++---- .../model/openoffice/rangesort/RangeOverlapWithin.java | 9 +++------ 6 files changed, 9 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index 846fa5e2c3a..c372185cf60 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -20,11 +20,11 @@ import org.jabref.logic.openoffice.action.ManageCitations; import org.jabref.logic.openoffice.action.Update; import org.jabref.logic.openoffice.frontend.OOFrontend; +import org.jabref.logic.openoffice.frontend.RangeForOverlapCheck; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.logic.openoffice.frontend.RangeForOverlapCheck; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationType; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 7e6345de65f..60af67ca5c2 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -15,12 +15,10 @@ import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; -import org.jabref.model.openoffice.rangesort.RangeHolder; import org.jabref.model.openoffice.rangesort.RangeKeyedMap; import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; import org.jabref.model.openoffice.rangesort.RangeOverlap; import org.jabref.model.openoffice.rangesort.RangeOverlapBetween; -import org.jabref.model.openoffice.rangesort.RangeOverlapKind; import org.jabref.model.openoffice.rangesort.RangeOverlapWithin; import org.jabref.model.openoffice.rangesort.RangeSortEntry; import org.jabref.model.openoffice.rangesort.RangeSortVisual; @@ -32,12 +30,10 @@ import org.jabref.model.openoffice.style.OODataModel; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; -import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoCursor; import org.jabref.model.openoffice.uno.UnoTextRange; import org.jabref.model.openoffice.util.OOListUtil; import org.jabref.model.openoffice.util.OOVoidResult; -import org.jabref.model.openoffice.util.OOTuple3; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -46,11 +42,9 @@ import com.sun.star.beans.UnknownPropertyException; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; -import com.sun.star.text.XText; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; -import com.sun.star.text.XTextRangeCompare; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java b/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java index d13ce9c7132..a5ef3d9706c 100644 --- a/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java +++ b/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java @@ -21,8 +21,8 @@ public static long start() { // return time (nanoSeconds) for next timing public static long now(String label, long startTime) { long endTime = System.nanoTime(); - long duration = (endTime - startTime); //divide by 1000000 to get milliseconds. - System.out.printf("%-40s: %.3f ms\n", label, duration /1000000.0); + long duration = (endTime - startTime); // divide by 1000000 to get milliseconds. + System.out.printf("%-40s: %.3f ms\n", label, duration / 1000000.0); return endTime; } } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java index 8850ddf1ef1..0d5df19069c 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java @@ -11,8 +11,6 @@ import com.sun.star.text.XText; import com.sun.star.text.XTextRange; -import com.sun.star.text.XTextRangeCompare; -import com.sun.star.uno.UnoRuntime; /** * Purpose: in order to check overlaps of XTextRange values, sort diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java index 952123e1d78..35d2d006fab 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java @@ -2,7 +2,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.TreeMap; import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoTextRange; @@ -15,7 +14,7 @@ public class RangeOverlapBetween { - private RangeOverlapBetween() {} + private RangeOverlapBetween() { } /** * Check for any overlap between two sets of XTextRange values. @@ -60,11 +59,11 @@ List> findFirst(XTextDocument doc, continue; } int abEndToStart = -1 * cmp.compareRegionStarts(aRange.getEnd(), bRangeStart); - if (abEndToStart < 0 || (!includeTouching && (abEndToStart==0))) { + if (abEndToStart < 0 || (!includeTouching && (abEndToStart == 0))) { continue; } int baEndToStart = -1 * cmp.compareRegionStarts(bRangeEnd, aRange.getStart()); - if (baEndToStart < 0 || (!includeTouching && (baEndToStart==0))) { + if (baEndToStart < 0 || (!includeTouching && (baEndToStart == 0))) { continue; } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java index 62bb933b92b..06fb370c8ac 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java @@ -2,20 +2,17 @@ import java.util.ArrayList; import java.util.List; -import java.util.TreeMap; import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoTextRange; -import org.jabref.model.openoffice.util.OOTuple3; -import com.sun.star.text.XText; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextRangeCompare; public class RangeOverlapWithin { - private RangeOverlapWithin() {} + private RangeOverlapWithin() { } /** * Report identical, overlapping or touching ranges between @@ -24,8 +21,8 @@ private RangeOverlapWithin() {} * For overlapping and touching, only report consecutive ranges * and only with a single sample of otherwise identical ranges. * - * @param atMost Limit the number of records returned to atMost. - * Zero {@code atMost} means no limit. + * @param reportAtMost Limit the number of records returned to atMost. + * Zero {@code reportAtMost} means no limit. * * @param includeTouching Should the result contain ranges * sharing only a boundary? From fbfbc70a4bcefc2fba1fb04edd93c66b91aee00d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 31 May 2021 18:56:08 +0200 Subject: [PATCH 0932/1068] use RangeSort.partitionAndSortRanges, drop RangeKeyedMapList --- .../org/jabref/gui/openoffice/OOBibBase2.java | 13 ++-- .../logic/openoffice/action/Update.java | 30 +++++--- .../logic/openoffice/frontend/OOFrontend.java | 65 +++++++++-------- .../openoffice/rangesort/RangeKeyedMap.java | 72 ------------------- .../rangesort/RangeKeyedMapList.java | 49 ------------- .../rangesort/RangeOverlapWithin.java | 12 ++-- .../model/openoffice/rangesort/RangeSet.java | 48 +++++++++++++ .../model/openoffice/rangesort/RangeSort.java | 8 ++- 8 files changed, 122 insertions(+), 175 deletions(-) delete mode 100644 src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java delete mode 100644 src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java create mode 100644 src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index c372185cf60..c955d7f1b10 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -25,6 +25,7 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.notforproduction.TimeLap; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationType; @@ -666,7 +667,7 @@ public void guiActionInsertEntry(List entries, pageInfo); if (syncOptions.isPresent()) { - Update.resync(doc, style, fcursor.get(), syncOptions.get()); + Update.resyncDocument(doc, style, fcursor.get(), syncOptions.get()); } } catch (NoDocumentException ex) { @@ -728,7 +729,7 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle if (madeModifications) { UnoCrossRef.refresh(doc); Update.SyncOptions syncOptions = new Update.SyncOptions(databases); - Update.resync(doc, style, fcursor.get(), syncOptions); + Update.resyncDocument(doc, style, fcursor.get(), syncOptions); } } catch (NoDocumentException ex) { @@ -791,7 +792,7 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s if (madeModifications) { UnoCrossRef.refresh(doc); Update.SyncOptions syncOptions = new Update.SyncOptions(databases); - Update.resync(doc, style, fcursor.get(), syncOptions); + Update.resyncDocument(doc, style, fcursor.get(), syncOptions); } } catch (NoDocumentException ex) { @@ -923,10 +924,13 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl return; } + long startTime = TimeLap.start(); OOFrontend fr = new OOFrontend(doc); + startTime = TimeLap.now("getFrontend", startTime); if (testDialog(title, checkRangeOverlaps(doc, fr))) { return; } + startTime = TimeLap.now("checkRangeOverlaps", startTime); List unresolvedKeys; try { @@ -937,7 +941,8 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl .setUpdateBibliography(true) .setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages); - unresolvedKeys = Update.sync(doc, fr, style, fcursor.get(), syncOptions); + unresolvedKeys = Update.synchronizeDocument(doc, fr, style, fcursor.get(), syncOptions); + startTime = TimeLap.now("Update.synchronizeDocument", startTime); } finally { UnoUndo.leaveUndoContext(doc); diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index 17ffff5a210..c411d6dcfa5 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -9,6 +9,7 @@ import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.model.database.BibDatabase; +import org.jabref.model.openoffice.notforproduction.TimeLap; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; @@ -47,8 +48,11 @@ private static List updateDocument(XTextDocument doc, final boolean useLockControllers = true; + long startTime = TimeLap.start(); fr.imposeGlobalOrder(doc, fcursor); + startTime = TimeLap.now(" imposeGlobalOrder", startTime); OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); + startTime = TimeLap.now(" produceCitationMarkers", startTime); try { if (useLockControllers) { @@ -56,6 +60,7 @@ private static List updateDocument(XTextDocument doc, } UpdateCitationMarkers.applyNewCitationMarkers(doc, fr, style); + startTime = TimeLap.now(" applyNewCitationMarkers", startTime); if (doUpdateBibliography) { UpdateBibliography.rebuildBibTextSection(doc, @@ -63,8 +68,11 @@ private static List updateDocument(XTextDocument doc, fr.citationGroups.getBibliography().get(), style, alwaysAddCitedOnPages); + startTime = TimeLap.now(" rebuildBibTextSection", startTime); } - return fr.citationGroups.getUnresolvedKeys(); + List result = fr.citationGroups.getUnresolvedKeys(); + startTime = TimeLap.now(" getUnresolvedKeys", startTime); + return result; } finally { if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { UnoScreenRefresh.unlockControllers(doc); @@ -95,11 +103,11 @@ public SyncOptions setAlwaysAddCitedOnPages(boolean value) { } } - public static List sync(XTextDocument doc, - OOFrontend fr, - OOBibStyle style, - FunctionalTextViewCursor fcursor, - SyncOptions syncOptions) + public static List synchronizeDocument(XTextDocument doc, + OOFrontend fr, + OOBibStyle style, + FunctionalTextViewCursor fcursor, + SyncOptions syncOptions) throws CreationException, JabRefException, @@ -122,10 +130,10 @@ public static List sync(XTextDocument doc, /* * Reread document before sync */ - public static List resync(XTextDocument doc, - OOBibStyle style, - FunctionalTextViewCursor fcursor, - SyncOptions syncOptions) + public static List resyncDocument(XTextDocument doc, + OOBibStyle style, + FunctionalTextViewCursor fcursor, + SyncOptions syncOptions) throws CreationException, JabRefException, @@ -138,7 +146,7 @@ public static List resync(XTextDocument doc, OOFrontend fr = new OOFrontend(doc); - return Update.sync(doc, fr, style, fcursor, syncOptions); + return Update.synchronizeDocument(doc, fr, style, fcursor, syncOptions); } } diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 60af67ca5c2..1aa63164d3f 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -6,20 +6,20 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.TreeMap; import java.util.stream.Collectors; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.backend.Backend52; import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.notforproduction.TimeLap; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; -import org.jabref.model.openoffice.rangesort.RangeKeyedMap; -import org.jabref.model.openoffice.rangesort.RangeKeyedMapList; import org.jabref.model.openoffice.rangesort.RangeOverlap; import org.jabref.model.openoffice.rangesort.RangeOverlapBetween; import org.jabref.model.openoffice.rangesort.RangeOverlapWithin; +import org.jabref.model.openoffice.rangesort.RangeSet; +import org.jabref.model.openoffice.rangesort.RangeSort; import org.jabref.model.openoffice.rangesort.RangeSortEntry; import org.jabref.model.openoffice.rangesort.RangeSortVisual; import org.jabref.model.openoffice.rangesort.RangeSortable; @@ -154,36 +154,28 @@ public Optional healthReport(XTextDocument doc) */ // Sort within partitions - RangeKeyedMapList> rangeSorter = new RangeKeyedMapList<>(); - for (RangeSortEntry sortable : sortables) { - rangeSorter.add(sortable.getRange(), sortable); - } + RangeSort.RangePartitions> partitions = + RangeSort.partitionAndSortRanges(sortables); // build final list List> result = new ArrayList<>(); - - for (TreeMap>> - partition : rangeSorter.partitionValues()) { - - List orderedRanges = new ArrayList<>(partition.keySet()); + for (List> partition : partitions.getPartitions()) { int indexInPartition = 0; - for (int i = 0; i < orderedRanges.size(); i++) { - XTextRange aRange = orderedRanges.get(i); - List> sortablesAtARange = partition.get(aRange); - for (RangeSortEntry sortable : sortablesAtARange) { - sortable.setIndexInPosition(indexInPartition++); - if (mapFootnotesToFootnoteMarks) { - Optional footnoteMarkRange = - UnoTextRange.getFootnoteMarkRange(sortable.getRange()); - // Adjust range if we are inside a footnote: - if (footnoteMarkRange.isPresent()) { - sortable.setRange(footnoteMarkRange.get()); - } + for (int i = 0; i < partition.size(); i++) { + RangeSortEntry sortable = partition.get(i); + XTextRange aRange = sortable.getRange(); + sortable.setIndexInPosition(indexInPartition++); + if (mapFootnotesToFootnoteMarks) { + Optional footnoteMarkRange = + UnoTextRange.getFootnoteMarkRange(sortable.getRange()); + // Adjust range if we are inside a footnote: + if (footnoteMarkRange.isPresent()) { + sortable.setRange(footnoteMarkRange.get()); } - result.add(sortable); } - } + result.add(sortable); + } } return result.stream().map(e -> e).collect(Collectors.toList()); } @@ -209,15 +201,26 @@ public Optional healthReport(XTextDocument doc) NoDocumentException, JabRefException { + long startTime = TimeLap.start(); + List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); + startTime = TimeLap.now(" createVisualSortInput", startTime); + List> sorted = RangeSortVisual.visualSort(sortables, doc, fcursor); - return (sorted.stream().map(e -> e.getContent()).collect(Collectors.toList())); + startTime = TimeLap.now(" visualSort", startTime); + + List result = + (sorted.stream().map(e -> e.getContent()).collect(Collectors.toList())); + + startTime = TimeLap.now(" map to CitationGroup", startTime); + + return result; } /** @@ -432,7 +435,7 @@ public List> viewCursorRanges(XTextDocumen // Avoid inserting the same mark twice. // Could use RangeSet if we had that. - RangeKeyedMap seen = new RangeKeyedMap<>(); + RangeSet seen = new RangeSet(); List> result = new ArrayList<>(); @@ -446,9 +449,9 @@ public List> viewCursorRanges(XTextDocumen continue; } - boolean seenContains = seen.containsKey(footnoteMarkRange.get()); + boolean seenContains = seen.contains(footnoteMarkRange.get()); if (!seenContains) { - seen.put(footnoteMarkRange.get(), true); + seen.add(footnoteMarkRange.get()); result.add(new RangeForOverlapCheck<>(footnoteMarkRange.get(), citationRange.idWithinKind, RangeForOverlapCheck.FOOTNOTE_MARK_KIND, @@ -541,7 +544,7 @@ public List> viewCursorRanges(XTextDocumen ranges.addAll(footnoteMarkRanges(doc, citationRanges)); List>> overlaps = - RangeOverlapWithin.find(doc, ranges, requireSeparation, reportAtMost); + RangeOverlapWithin.findOverlappingRanges(doc, ranges, requireSeparation, reportAtMost); if (overlaps.size() == 0) { return OOVoidResult.ok(); diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java deleted file mode 100644 index 0d5df19069c..00000000000 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMap.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.jabref.model.openoffice.rangesort; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.TreeMap; - -import org.jabref.model.openoffice.uno.UnoTextRange; - -import com.sun.star.text.XText; -import com.sun.star.text.XTextRange; - -/** - * Purpose: in order to check overlaps of XTextRange values, sort - * them, and allow recovering some corresponding information - * (of type V) - * - * Since XTextRange values are only comparable if they share the same - * range.getText(), we group them by these. - * - * Within such groups (partitions) we may define comparison, here - * based on (range.getStart(),range.getEnd()), where equality means identical - * ranges. - * - * For finding overlapping ranges this class proved insufficient, - * beacause it does not allow multiple values to be associated with a - * single XTextRange. The class RangeKeyedMapList solves this. - * - */ -public class RangeKeyedMap { - - private final Map> partitions; - - public RangeKeyedMap() { - this.partitions = new HashMap<>(); - } - - public boolean containsKey(XTextRange range) { - Objects.requireNonNull(range); - XText partitionKey = range.getText(); - if (!partitions.containsKey(partitionKey)) { - return false; - } - return partitions.get(partitionKey).containsKey(range); - } - - public V get(XTextRange range) { - TreeMap partition = partitions.get(range.getText()); - if (partition == null) { - return null; - } - return partition.get(range); - } - - public V put(XTextRange range, V value) { - TreeMap partition = partitions.get(range.getText()); - if (partition == null) { - partition = new TreeMap<>(UnoTextRange::compareStartsThenEnds); - partitions.put(range.getText(), partition); - } - return partition.put(range, value); - } - - /** - * @return A list of the partitions. - */ - public List> partitionValues() { - return new ArrayList<>(partitions.values()); - } -} diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java deleted file mode 100644 index 9e6edd69738..00000000000 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeKeyedMapList.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.jabref.model.openoffice.rangesort; - -import java.util.ArrayList; -import java.util.List; -import java.util.TreeMap; - -import com.sun.star.text.XTextRange; - -/* - * Partition by XTextRange.getText() and sort within the partitions a - * set of XTextRange values, while keeping their associated data - * recoverable. Allows identical XTextRange values, their data is - * collected in a list. - */ -public class RangeKeyedMapList { - - private RangeKeyedMap> partitions; - - public RangeKeyedMapList() { - this.partitions = new RangeKeyedMap<>(); - } - - public boolean containsKey(XTextRange range) { - return partitions.containsKey(range); - } - - public List get(XTextRange range) { - return partitions.get(range); - } - - public void add(XTextRange range, V value) { - List values = partitions.get(range); - if (values == null) { - values = new ArrayList<>(); - values.add(value); - partitions.put(range, values); - } else { - values.add(value); - } - } - - /** - * @return A list of the partitions. - */ - public List>> partitionValues() { - return this.partitions.partitionValues(); - } - -} diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java index 06fb370c8ac..62ee6d82ca0 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java @@ -28,10 +28,10 @@ private RangeOverlapWithin() { } * sharing only a boundary? */ public static - List> find(XTextDocument doc, - List rangeHolders, - boolean includeTouching, - int reportAtMost) { + List> findOverlappingRanges(XTextDocument doc, + List rangeHolders, + boolean includeTouching, + int reportAtMost) { RangeSort.RangePartitions partitions = RangeSort.partitionAndSortRanges(rangeHolders); @@ -52,7 +52,7 @@ List> find(XTextDocument doc, * @param includeTouching Should the result contain ranges * sharing only a boundary? */ - private static + public static List> findOverlappingRanges(RangeSort.RangePartitions input, int atMost, boolean includeTouching) { @@ -60,7 +60,7 @@ List> findOverlappingRanges(RangeSort.RangePartitions input, List> result = new ArrayList<>(); - for (List partition : input.partitions.values()) { + for (List partition : input.getPartitions()) { if (partition.size() == 0) { continue; } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java new file mode 100644 index 00000000000..f7fbe37ba25 --- /dev/null +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java @@ -0,0 +1,48 @@ +package org.jabref.model.openoffice.rangesort; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.TreeSet; + +import org.jabref.model.openoffice.uno.UnoTextRange; + +import com.sun.star.text.XText; +import com.sun.star.text.XTextRange; + +public class RangeSet { + + private final Map> partitions; + + public RangeSet() { + this.partitions = new HashMap<>(); + } + + public boolean contains(XTextRange range) { + Objects.requireNonNull(range); + XText partitionKey = range.getText(); + if (!this.partitions.containsKey(partitionKey)) { + return false; + } + return partitions.get(partitionKey).contains(range); + } + + /* return false if already contained */ + public boolean add(XTextRange range) { + TreeSet partition = partitions.get(range.getText()); + if (partition == null) { + partition = new TreeSet<>(UnoTextRange::compareStartsThenEnds); + partitions.put(range.getText(), partition); + } + return partition.add(range); + } + + /** + * @return A list of the partitions. + */ + public List> partitionValues() { + return new ArrayList<>(partitions.values()); + } +} diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java index 7a5d1c2fc62..2f5daa0e1aa 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -49,7 +49,7 @@ void sortWithinPartition(List rangeHolders) { */ public static class RangePartitions { - public final Map> partitions; + private final Map> partitions; public RangePartitions() { this.partitions = new HashMap<>(); @@ -64,6 +64,10 @@ public void add(V holder) { } partition.add(holder); } + + public List> getPartitions() { + return new ArrayList<>(partitions.values()); + } } public static @@ -78,7 +82,7 @@ RangePartitions partitionRanges(List holders) { public static RangePartitions partitionAndSortRanges(List holders) { RangePartitions result = partitionRanges(holders); - for (List partition : result.partitions.values()) { + for (List partition : result.getPartitions()) { sortWithinPartition(partition); } return result; From e2b2fb9c80d3166f20be7db53fad5102d3f96230 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 31 May 2021 21:37:37 +0200 Subject: [PATCH 0933/1068] timelap format --- .../org/jabref/model/openoffice/notforproduction/TimeLap.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java b/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java index a5ef3d9706c..8c927fe9e0a 100644 --- a/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java +++ b/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java @@ -22,7 +22,7 @@ public static long start() { public static long now(String label, long startTime) { long endTime = System.nanoTime(); long duration = (endTime - startTime); // divide by 1000000 to get milliseconds. - System.out.printf("%-40s: %.3f ms\n", label, duration / 1000000.0); + System.out.printf("%-40s: %10.3f ms\n", label, duration / 1000000.0); return endTime; } } From c4c4025293789ba28ea4d658a487c4070f35bcbd Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 31 May 2021 21:40:49 +0200 Subject: [PATCH 0934/1068] use Collections.sort --- .../model/openoffice/rangesort/RangeSortVisual.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index b2c8ab21063..2131c3cecb9 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -1,10 +1,9 @@ package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Objects; -import java.util.Set; -import java.util.TreeSet; import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.uno.UnoScreenRefresh; @@ -62,12 +61,10 @@ public static List> visualSort(List> input // find coordinates List positions = new ArrayList<>(inputSize); - for (RangeSortable v : inputs) { positions.add(findPositionOfTextRange(v.getRange(), viewCursor)); } - fcursor.restore(doc); if (positions.size() != inputSize) { @@ -75,12 +72,14 @@ public static List> visualSort(List> input } // order by position - Set>> set = new TreeSet<>(); + ArrayList>> set = new ArrayList<>(inputSize); for (int i = 0; i < inputSize; i++) { + RangeSortable input = inputs.get(i); set.add(new ComparableMark<>(positions.get(i), - inputs.get(i).getIndexInPosition(), - inputs.get(i))); + input.getIndexInPosition(), + input)); } + Collections.sort(set); if (set.size() != inputSize) { throw new RuntimeException("visualSort: set.size() != inputSize"); From c8926f828e03dd220adddd153f6c72dda3127fd1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 31 May 2021 22:19:23 +0200 Subject: [PATCH 0935/1068] handle padded integers in OOBibStyle parser --- .../java/org/jabref/logic/openoffice/style/OOBibStyle.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index 471d1747265..44416ea0a29 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -418,8 +418,8 @@ private void handlePropertiesLine(String line, Map map) { value = value.trim().substring(1, value.trim().length() - 1); } Object toSet = value; - if (NUM_PATTERN.matcher(value).matches()) { - toSet = Integer.parseInt(value); + if (NUM_PATTERN.matcher(value.trim()).matches()) { + toSet = Integer.parseInt(value.trim()); } else if ("true".equalsIgnoreCase(value.trim())) { toSet = Boolean.TRUE; } else if ("false".equalsIgnoreCase(value.trim())) { From becb2f26179999121c2212b82da80011ba8bd060 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 31 May 2021 23:55:17 +0200 Subject: [PATCH 0936/1068] EditMerge was eating character after last merged --- .../org/jabref/logic/openoffice/action/EditMerge.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index ae9f13ddc0c..823610c51cf 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -239,17 +239,21 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR (currentRange.getText().createTextCursorByRange(state.cursorBetween.getEnd())); while (couldExpand && (UnoTextRange.compareEnds(state.cursorBetween, rangeStart) < 0)) { - couldExpand = state.cursorBetween.goRight((short) 1, true); - state.currentGroupCursor.goRight((short) 1, true); // // Check that we only walk through inline whitespace. // - thisCharCursor.goRight((short) 1, true); + couldExpand = thisCharCursor.goRight((short) 1, true); String thisChar = thisCharCursor.getString(); thisCharCursor.collapseToEnd(); if (thisChar.isEmpty() || thisChar.equals("\n") || !thisChar.trim().isEmpty()) { couldExpand = false; + if (!thisChar.isEmpty()) { + thisCharCursor.goLeft((short) 1, false); + } + break; } + state.cursorBetween.goRight((short) 1, true); + state.currentGroupCursor.goRight((short) 1, true); // These two should move in sync: if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { From 9d248bef32cc9ba71a7246c0564ab352b105741a Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 31 May 2021 23:55:50 +0200 Subject: [PATCH 0937/1068] try to speed up applyNewCitationMarkers --- .../backend/NamedRangeReferenceMark.java | 136 +++++++++--------- 1 file changed, 71 insertions(+), 65 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index ae4a3e1caaa..38ac716d9ac 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -76,7 +76,7 @@ private static XTextCursor safeInsertSpacesBetweenReferenceMarks(XTextRange posi cursor.goLeft((short) n, false); // left(n) cursor.goLeft((short) 1, true); cursor.setString(""); // left-delete - cursor.goRight((short) n, true); + cursor.goRight((short) n, true); // select the newly inserted spaces return cursor; } @@ -276,7 +276,7 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) throw new RuntimeException(msg); } // too short, recreate - if (debugThisFun) { + if (true || debugThisFun) { System.out.println("nrGetFillCursor: too short, recreate"); } full.setString(""); @@ -307,12 +307,6 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) if (fullText.length() < 2) { throw new RuntimeException("nrGetFillCursor: fullText.length() < 2 (after loop)'%n"); } - // we have at least two characters inside - XTextCursor alpha = full.getText().createTextCursorByRange(full); - alpha.collapseToStart(); - XTextCursor omega = full.getText().createTextCursorByRange(full); - omega.collapseToEnd(); - XTextCursor beta = full.getText().createTextCursorByRange(full); beta.collapseToStart(); beta.goRight((short) 1, false); @@ -320,56 +314,73 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) if (debugThisFun) { System.out.printf("nrGetFillCursor: beta(1) covers '%s'%n", beta.getString()); } - // beta now covers everything except first and last character - // Replace its content with brackets - String paddingx = "x"; - String paddingy = "y"; - String paddingz = "z"; - beta.setString(paddingx + left + paddingy + right + paddingz); - if (debugThisFun) { - System.out.printf("nrGetFillCursor: beta(2) covers '%s'%n", beta.getString()); - } - // move beta to before the right bracket - beta.collapseToEnd(); - beta.goLeft((short) (rightLength + 1), false); - // remove middle padding - beta.goLeft((short) 1, true); - if (debugThisFun) { - System.out.printf("nrGetFillCursor: beta(3) covers '%s'%n", beta.getString()); - } - // only drop paddingy later: beta.setString(""); + if (fullText.startsWith(left) && fullText.endsWith(right)) { + beta.setString(""); + } else { + if (debugThisFun) { + String msg = String.format("nrGetFillCursor: recreating brackets for '%s'", fullText); + // LOGGER.warn(msg); + System.out.println(msg); + } - // drop the initial character and paddingx - alpha.collapseToStart(); - alpha.goRight((short) (1 + 1), true); - if (debugThisFun) { - System.out.printf("nrGetFillCursor: alpha(4) covers '%s'%n", alpha.getString()); - } - alpha.setString(""); - // drop the last character and paddingz - omega.collapseToEnd(); - omega.goLeft((short) (1 + 1), true); - if (debugThisFun) { - System.out.printf("nrGetFillCursor: omega(5) covers '%s'%n", omega.getString()); - } - omega.setString(""); + // we have at least two characters inside + XTextCursor alpha = full.getText().createTextCursorByRange(full); + alpha.collapseToStart(); - // drop paddingy now - if (debugThisFun) { - System.out.printf("nrGetFillCursor: beta(6) covers '%s'%n", beta.getString()); - } - beta.setString(""); - // should be OK now. - if (debugThisFun) { - alpha.goRight(leftLength, true); - System.out.printf("nrGetFillCursor: alpha(7) covers '%s', should be '%s'%n", - alpha.getString(), left); - omega.goLeft(rightLength, true); - System.out.printf("nrGetFillCursor: omega(8) covers '%s', should be '%s'%n", - omega.getString(), right); + XTextCursor omega = full.getText().createTextCursorByRange(full); + omega.collapseToEnd(); + + // beta now covers everything except first and last character + // Replace its content with brackets + String paddingx = "x"; + String paddingy = "y"; + String paddingz = "z"; + beta.setString(paddingx + left + paddingy + right + paddingz); + if (debugThisFun) { + System.out.printf("nrGetFillCursor: beta(2) covers '%s'%n", beta.getString()); + } + // move beta to before the right bracket + beta.collapseToEnd(); + beta.goLeft((short) (rightLength + 1), false); + // remove middle padding + beta.goLeft((short) 1, true); + if (debugThisFun) { + System.out.printf("nrGetFillCursor: beta(3) covers '%s'%n", beta.getString()); + } + // only drop paddingy later: beta.setString(""); + + // drop the initial character and paddingx + alpha.collapseToStart(); + alpha.goRight((short) (1 + 1), true); + if (debugThisFun) { + System.out.printf("nrGetFillCursor: alpha(4) covers '%s'%n", alpha.getString()); + } + alpha.setString(""); + // drop the last character and paddingz + omega.collapseToEnd(); + omega.goLeft((short) (1 + 1), true); + if (debugThisFun) { + System.out.printf("nrGetFillCursor: omega(5) covers '%s'%n", omega.getString()); + } + omega.setString(""); + + // drop paddingy now + if (debugThisFun) { + System.out.printf("nrGetFillCursor: beta(6) covers '%s'%n", beta.getString()); + } + beta.setString(""); + // should be OK now. + if (debugThisFun) { + alpha.goRight(leftLength, true); + System.out.printf("nrGetFillCursor: alpha(7) covers '%s', should be '%s'%n", + alpha.getString(), left); + omega.goLeft(rightLength, true); + System.out.printf("nrGetFillCursor: omega(8) covers '%s', should be '%s'%n", + omega.getString(), right); + } } - NamedRangeReferenceMark.checkFillCursor(beta); + // NamedRangeReferenceMark.checkFillCursor(beta); return beta; } @@ -427,7 +438,8 @@ public void nrCleanFillCursor(XTextDocument doc) // alwaysRemoveBrackets : full compatibility with JabRef 5.2: // brackets are temporary, only exist between nrGetFillCursor // and nrCleanFillCursor. - final boolean alwaysRemoveBrackets = true; + final boolean alwaysRemoveBrackets = false; + // removeBracketsFromEmpty is intended to force removal if we // are working on an "Empty citation" (INVISIBLE_CIT). final boolean removeBracketsFromEmpty = false; @@ -443,16 +455,6 @@ public void nrCleanFillCursor(XTextDocument doc) final String fullText = full.getString(); final int fullTextLength = fullText.length(); - XTextCursor alpha = full.getText().createTextCursorByRange(full); - alpha.collapseToStart(); - - XTextCursor beta = full.getText().createTextCursorByRange(full); - beta.collapseToStart(); - beta.goRight(leftLength, false); - - XTextCursor omega = full.getText().createTextCursorByRange(full); - omega.collapseToEnd(); - if (!fullText.startsWith(left)) { String msg = String.format("nrCleanFillCursor:" + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", @@ -482,11 +484,15 @@ public void nrCleanFillCursor(XTextDocument doc) || alwaysRemoveBrackets); if (removeRight) { + XTextCursor omega = full.getText().createTextCursorByRange(full); + omega.collapseToEnd(); omega.goLeft(rightLength, true); omega.setString(""); } if (removeLeft) { + XTextCursor alpha = full.getText().createTextCursorByRange(full); + alpha.collapseToStart(); alpha.goRight(leftLength, true); alpha.setString(""); } From 2d047132a0b1ef8b2d61769e73d2a4b67bda493c Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 1 Jun 2021 09:14:18 +0200 Subject: [PATCH 0938/1068] remove TimeLap calls --- src/main/java/org/jabref/gui/openoffice/OOBibBase2.java | 5 ----- .../java/org/jabref/logic/openoffice/action/Update.java | 7 ------- .../org/jabref/logic/openoffice/frontend/OOFrontend.java | 9 --------- 3 files changed, 21 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index c955d7f1b10..ca8324cda2a 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -25,7 +25,6 @@ import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.model.openoffice.notforproduction.TimeLap; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationType; @@ -924,13 +923,10 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl return; } - long startTime = TimeLap.start(); OOFrontend fr = new OOFrontend(doc); - startTime = TimeLap.now("getFrontend", startTime); if (testDialog(title, checkRangeOverlaps(doc, fr))) { return; } - startTime = TimeLap.now("checkRangeOverlaps", startTime); List unresolvedKeys; try { @@ -942,7 +938,6 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl .setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages); unresolvedKeys = Update.synchronizeDocument(doc, fr, style, fcursor.get(), syncOptions); - startTime = TimeLap.now("Update.synchronizeDocument", startTime); } finally { UnoUndo.leaveUndoContext(doc); diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index c411d6dcfa5..151e4b6575b 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -9,7 +9,6 @@ import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.OOProcess; import org.jabref.model.database.BibDatabase; -import org.jabref.model.openoffice.notforproduction.TimeLap; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; @@ -48,11 +47,8 @@ private static List updateDocument(XTextDocument doc, final boolean useLockControllers = true; - long startTime = TimeLap.start(); fr.imposeGlobalOrder(doc, fcursor); - startTime = TimeLap.now(" imposeGlobalOrder", startTime); OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); - startTime = TimeLap.now(" produceCitationMarkers", startTime); try { if (useLockControllers) { @@ -60,7 +56,6 @@ private static List updateDocument(XTextDocument doc, } UpdateCitationMarkers.applyNewCitationMarkers(doc, fr, style); - startTime = TimeLap.now(" applyNewCitationMarkers", startTime); if (doUpdateBibliography) { UpdateBibliography.rebuildBibTextSection(doc, @@ -68,10 +63,8 @@ private static List updateDocument(XTextDocument doc, fr.citationGroups.getBibliography().get(), style, alwaysAddCitedOnPages); - startTime = TimeLap.now(" rebuildBibTextSection", startTime); } List result = fr.citationGroups.getUnresolvedKeys(); - startTime = TimeLap.now(" getUnresolvedKeys", startTime); return result; } finally { if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 1aa63164d3f..fd0523a4bf8 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -12,7 +12,6 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.backend.Backend52; import org.jabref.model.openoffice.CitationEntry; -import org.jabref.model.openoffice.notforproduction.TimeLap; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; import org.jabref.model.openoffice.rangesort.RangeOverlap; @@ -201,25 +200,17 @@ public Optional healthReport(XTextDocument doc) NoDocumentException, JabRefException { - long startTime = TimeLap.start(); - List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); - startTime = TimeLap.now(" createVisualSortInput", startTime); - List> sorted = RangeSortVisual.visualSort(sortables, doc, fcursor); - startTime = TimeLap.now(" visualSort", startTime); - List result = (sorted.stream().map(e -> e.getContent()).collect(Collectors.toList())); - startTime = TimeLap.now(" map to CitationGroup", startTime); - return result; } From 05dd8e8770081014c923b1c2b7949e02e75074e0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 1 Jun 2021 12:21:45 +0200 Subject: [PATCH 0939/1068] delNamesArray size correction --- .../java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index f062bed7c40..b9d67efcb5b 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -604,11 +604,11 @@ void apply(XTextCursor cursor) { } // namesArray must be alphabetically sorted. String[] namesArray = names.toArray(new String[names.size()]); - String[] delNamesArray = delNames.toArray(new String[names.size()]); + String[] delNamesArray = delNames.toArray(new String[delNames.size()]); mpss.setPropertiesToDefault(delNamesArray); mps.setPropertyValues(namesArray, values.toArray()); } catch (UnknownPropertyException ex) { - LOGGER.warn("UnknownPropertyException in MyPropertyStack.apply"); + LOGGER.warn("UnknownPropertyException in MyPropertyStack.apply", ex); } catch (PropertyVetoException ex) { LOGGER.warn("PropertyVetoException in MyPropertyStack.apply"); } catch (IllegalArgumentException ex) { From 57d4369f2f41c8eb75e5095b459183cf8381d9d9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 3 Jun 2021 13:29:21 +0200 Subject: [PATCH 0940/1068] cleanup OOBibStyle --- .../logic/openoffice/style/OOBibStyle.java | 379 +----------------- .../openoffice/style/OOBibStyleTest.java | 115 +++--- .../style/OOBibStyleTestHelper.java | 51 ++- 3 files changed, 122 insertions(+), 423 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index 44416ea0a29..0d81bdbd024 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -25,11 +25,6 @@ import org.jabref.logic.layout.LayoutFormatter; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.layout.LayoutHelper; -import org.jabref.model.database.BibDatabase; -import org.jabref.model.entry.Author; -import org.jabref.model.entry.AuthorList; -import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; @@ -44,7 +39,6 @@ import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.jabref.model.openoffice.style.PageInfo; import org.jabref.model.openoffice.util.OOListUtil; -import org.jabref.model.strings.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -447,324 +441,6 @@ public Layout getReferenceFormat(EntryType type) { } } - /* begin_old */ - /** - * Format a number-based citation marker for the given number. - * - * @param number The citation numbers. - * @return The text for the citation. - */ - public String getNumCitationMarker(List number, int minGroupingCount, boolean inList) { - String bracketBefore = getStringCitProperty(BRACKET_BEFORE); - if (inList && (citProperties.containsKey(BRACKET_BEFORE_IN_LIST))) { - bracketBefore = getStringCitProperty(BRACKET_BEFORE_IN_LIST); - } - String bracketAfter = getStringCitProperty(BRACKET_AFTER); - if (inList && (citProperties.containsKey(BRACKET_AFTER_IN_LIST))) { - bracketAfter = getStringCitProperty(BRACKET_AFTER_IN_LIST); - } - // Sort the numbers: - List lNum = new ArrayList<>(number); - Collections.sort(lNum); - StringBuilder sb = new StringBuilder(bracketBefore); - int combineFrom = -1; - int written = 0; - for (int i = 0; i < lNum.size(); i++) { - int i1 = lNum.get(i); - if (combineFrom < 0) { - // Check if next entry is the next in the ref list: - if ((i < (lNum.size() - 1)) && (lNum.get(i + 1) == (i1 + 1)) && (i1 > 0)) { - combineFrom = i1; - } else { - // Add single entry: - if (i > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); - } - sb.append(lNum.get(i) > 0 ? String.valueOf(lNum.get(i)) : OOBibStyle.UNDEFINED_CITATION_MARKER); - written++; - } - } else { - // We are building a list of combined entries. - // Check if it ends here: - if ((i == (lNum.size() - 1)) || (lNum.get(i + 1) != (i1 + 1))) { - if (written > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); - } - if ((minGroupingCount > 0) && (((i1 + 1) - combineFrom) >= minGroupingCount)) { - sb.append(combineFrom); - sb.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); - sb.append(i1); - written++; - } else { - // Either we should never group, or there aren't enough - // entries in this case to group. Output all: - for (int jj = combineFrom; jj <= i1; jj++) { - sb.append(jj); - if (jj < i1) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); - } - written++; - } - } - combineFrom = -1; - } - // If it doesn't end here, just keep iterating. - } - } - sb.append(bracketAfter); - return sb.toString(); - } - /* end_old */ - - /** - * Format a number-based citation marker for the given entries. - * - * @return The text for the citation. - */ - public OOText getNumCitationMarker2(List entries) { - final int minGroupingCount = this.getMinimumGroupingCount(); - return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, - entries, - minGroupingCount); - } - - /** - * For some tests we need to override minGroupingCount. - */ - public OOText getNumCitationMarker2(List entries, - int minGroupingCount) { - return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, - entries, - minGroupingCount); - } - - /* begin_old */ - public String getCitationMarker(List entries, Map database, boolean inParenthesis, - String[] uniquefiers, int[] unlimAuthors) { - // Look for groups of uniquefied entries that should be combined in the output. - // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). - int piv = -1; - String tmpMarker = null; - if (uniquefiers != null) { - for (int i = 0; i < uniquefiers.length; i++) { - - if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { - // This entry has no uniquefier. - // Check if we just passed a group of more than one entry with uniquefier: - if ((piv > -1) && (i > (piv + 1))) { - // Do the grouping: - group(entries, uniquefiers, piv, i - 1); - } - - piv = -1; - } else { - BibEntry currentEntry = entries.get(i); - if (piv == -1) { - piv = i; - tmpMarker = getAuthorYearParenthesisMarker(Collections.singletonList(currentEntry), database, - null, unlimAuthors); - } else { - // See if this entry can go into a group with the previous one: - String thisMarker = getAuthorYearParenthesisMarker(Collections.singletonList(currentEntry), - database, null, unlimAuthors); - - String authorField = getStringCitProperty(AUTHOR_FIELD); - int maxAuthors = getIntCitProperty(MAX_AUTHORS); - String author = getCitationMarkerField(currentEntry, database.get(currentEntry), - authorField); - AuthorList al = AuthorList.parse(author); - int prevALim = unlimAuthors[i - 1]; // i always at least 1 here - if (!thisMarker.equals(tmpMarker) - || ((al.getNumberOfAuthors() > maxAuthors) && (unlimAuthors[i] != prevALim))) { - // No match. Update piv to exclude the previous entry. But first check if the - // previous entry was part of a group: - if ((piv > -1) && (i > (piv + 1))) { - // Do the grouping: - group(entries, uniquefiers, piv, i - 1); - } - tmpMarker = thisMarker; - piv = i; - } - } - } - - } - // Finished with the loop. See if the last entries form a group: - if (piv >= 0) { - // Do the grouping: - group(entries, uniquefiers, piv, uniquefiers.length - 1); - } - } - - if (inParenthesis) { - return getAuthorYearParenthesisMarker(entries, database, uniquefiers, unlimAuthors); - } else { - return getAuthorYearInTextMarker(entries, database, uniquefiers, unlimAuthors); - } - } - /* end_old */ - - /* begin_old */ - private void group(List entries, String[] uniquefiers, int from, int to) { - String separator = getStringCitProperty(UNIQUEFIER_SEPARATOR); - StringBuilder sb = new StringBuilder(uniquefiers[from]); - for (int i = from + 1; i <= to; i++) { - sb.append(separator); - sb.append(uniquefiers[i]); - entries.set(i, null); - } - uniquefiers[from] = sb.toString(); - } - /* end_old */ - - /* begin_old */ - private String getAuthorYearParenthesisMarker(List entries, Map database, - String[] uniquifiers, int[] unlimAuthors) { - - String authorField = getStringCitProperty(AUTHOR_FIELD); // The bibtex field providing author names, e.g. "author" or "editor". - int maxA = getIntCitProperty(MAX_AUTHORS); // The maximum number of authors to write out in full without using etal. Set to - // -1 to always write out all authors. - String yearSep = getStringCitProperty(YEAR_SEPARATOR); // The String to separate authors from year, e.g. "; ". - String startBrace = getStringCitProperty(BRACKET_BEFORE); // The opening parenthesis. - String endBrace = getStringCitProperty(BRACKET_AFTER); // The closing parenthesis. - String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); // The String to separate citations from each other. - String yearField = getStringCitProperty(YEAR_FIELD); // The bibtex field providing the year, e.g. "year". - String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR); // The String to add between the two last author names, e.g. " & ". - StringBuilder sb = new StringBuilder(startBrace); - for (int j = 0; j < entries.size(); j++) { - BibEntry currentEntry = entries.get(j); - - // Check if this entry has been nulled due to grouping with the previous entry(ies): - if (currentEntry == null) { - continue; - } - - if (j > 0) { - sb.append(citationSeparator); - } - - BibDatabase currentDatabase = database.get(currentEntry); - int unlimA = unlimAuthors == null ? -1 : unlimAuthors[j]; - int maxAuthors = unlimA > 0 ? unlimA : maxA; - - String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); - String authorString = createAuthorList(author, maxAuthors, andString, yearSep); - sb.append(authorString); - String year = getCitationMarkerField(currentEntry, currentDatabase, yearField); - if (year != null) { - sb.append(year); - } - if ((uniquifiers != null) && (uniquifiers[j] != null)) { - sb.append(uniquifiers[j]); - } - } - sb.append(endBrace); - return sb.toString(); - } - /* end_old */ - - /* begin_old */ - private String getAuthorYearInTextMarker(List entries, Map database, - String[] uniquefiers, - int[] unlimAuthors) { - String authorField = getStringCitProperty(AUTHOR_FIELD); // The bibtex field providing author names, e.g. "author" or "editor". - int maxA = getIntCitProperty(MAX_AUTHORS); // The maximum number of authors to write out in full without using etal. Set to - // -1 to always write out all authors. - String yearSep = getStringCitProperty(IN_TEXT_YEAR_SEPARATOR); // The String to separate authors from year, e.g. "; ". - String startBrace = getStringCitProperty(BRACKET_BEFORE); // The opening parenthesis. - String endBrace = getStringCitProperty(BRACKET_AFTER); // The closing parenthesis. - String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); // The String to separate citations from each other. - String yearField = getStringCitProperty(YEAR_FIELD); // The bibtex field providing the year, e.g. "year". - String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR_IN_TEXT); // The String to add between the two last author names, e.g. " & ". - - if (andString == null) { - // Use the default one if no explicit separator for text is defined - andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR); - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < entries.size(); i++) { - BibEntry currentEntry = entries.get(i); - - // Check if this entry has been nulled due to grouping with the previous entry(ies): - if (currentEntry == null) { - continue; - } - - BibDatabase currentDatabase = database.get(currentEntry); - int unlimA = unlimAuthors == null ? -1 : unlimAuthors[i]; - int maxAuthors = unlimA > 0 ? unlimA : maxA; - - if (i > 0) { - sb.append(citationSeparator); - } - String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); - String authorString = createAuthorList(author, maxAuthors, andString, yearSep); - sb.append(authorString); - sb.append(startBrace); - String year = getCitationMarkerField(currentEntry, currentDatabase, yearField); - if (year != null) { - sb.append(year); - } - if ((uniquefiers != null) && (uniquefiers[i] != null)) { - sb.append(uniquefiers[i]); - } - sb.append(endBrace); - } - return sb.toString(); - - } - /* end_old */ - - /* begin_old */ - /* moved to OOBibStyleGetCitationMarker */ - private String getCitationMarkerField(BibEntry entry, BibDatabase database, String fields) { - Objects.requireNonNull(entry, "Entry cannot be null"); - Objects.requireNonNull(database, "database cannot be null"); - - Set authorFields = FieldFactory.parseOrFields(getStringCitProperty(AUTHOR_FIELD)); - for (Field field : FieldFactory.parseOrFields(fields)) { - Optional content = entry.getResolvedFieldOrAlias(field, database); - - if ((content.isPresent()) && !content.get().trim().isEmpty()) { - if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content.get())) { - return "{" + fieldFormatter.format(content.get()) + "}"; - } - return fieldFormatter.format(content.get()); - } - } - // No luck? Return an empty string: - return ""; - } - /* end_old */ - - /* begin_old */ - /* moved to OOBibStyleGetCitationMarker */ - private String getAuthorLastName(AuthorList al, int number) { - StringBuilder sb = new StringBuilder(); - - if (al.getNumberOfAuthors() > number) { - Author a = al.getAuthor(number); - a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> sb.append(von).append(' ')); - sb.append(a.getLast().orElse("")); - } - - return sb.toString(); - } - /* end_old */ - - /* begin_old */ - /* removed */ - public String insertPageInfo(String citation, String pageInfo) { - String bracketAfter = getStringCitProperty(BRACKET_AFTER); - if (citation.endsWith(bracketAfter)) { - String first = citation.substring(0, citation.length() - bracketAfter.length()); - return first + getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo + bracketAfter; - } else { - return citation + getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo; - } - } - /* end_old */ - /** * Convenience method for checking the property for whether we use number citations or * author-year citations. @@ -890,39 +566,6 @@ public int hashCode() { return Objects.hash(path, name, citProperties, properties); } - /* begin_old */ - /* moved to OOBibStyleGetCitationMarker as formatAuthorList */ - private String createAuthorList(String author, int maxAuthors, String andString, - String yearSep) { - Objects.requireNonNull(author); - String etAlString = getStringCitProperty(ET_AL_STRING); // The String to represent authors that are not mentioned, e.g. " et al." - String authorSep = getStringCitProperty(AUTHOR_SEPARATOR); // The String to add between author names except the last two, e.g. ", ". - String oxfordComma = getStringCitProperty(OXFORD_COMMA); // The String to put after the second to last author in case of three or more authors - StringBuilder sb = new StringBuilder(); - AuthorList al = AuthorList.parse(author); - if (!al.isEmpty()) { - sb.append(getAuthorLastName(al, 0)); - } - if ((al.getNumberOfAuthors() > 1) && ((al.getNumberOfAuthors() <= maxAuthors) || (maxAuthors < 0))) { - int j = 1; - while (j < (al.getNumberOfAuthors() - 1)) { - sb.append(authorSep); - sb.append(getAuthorLastName(al, j)); - j++; - } - if (al.getNumberOfAuthors() > 2) { - sb.append(oxfordComma); - } - sb.append(andString); - sb.append(getAuthorLastName(al, al.getNumberOfAuthors() - 1)); - } else if (al.getNumberOfAuthors() > maxAuthors) { - sb.append(etAlString); - } - sb.append(yearSep); - return sb.toString(); - } - /* end_old */ - enum BibStyleMode { NONE, LAYOUT, @@ -1024,6 +667,28 @@ protected void setDefaultBibLayout(Layout l) { defaultBibLayout = l; } + /** + * Format a number-based citation marker for the given entries. + * + * @return The text for the citation. + */ + public OOText getNumCitationMarker2(List entries) { + final int minGroupingCount = this.getMinimumGroupingCount(); + return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, + entries, + minGroupingCount); + } + + /** + * For some tests we need to override minGroupingCount. + */ + public OOText getNumCitationMarker2(List entries, + int minGroupingCount) { + return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, + entries, + minGroupingCount); + } + /** * Format a number-based bibliography label for the given number. */ diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java index bf0bdf945a4..8d5da6e4d00 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java @@ -148,6 +148,22 @@ static String getCitationMarker2(OOBibStyle style, pageInfo ); } + static String getCitationMarker2b(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { + return OOBibStyleTestHelper.getCitationMarker2b(style, + entries, + entryDBMap, + inParenthesis, + uniquefiers, + isFirstAppearanceOfSource, + pageInfo ); + } + /* * end helpers */ @@ -157,35 +173,16 @@ static String getCitationMarker2(OOBibStyle style, void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), -1, true)); assertEquals("[1] ", runGetNumCitationMarker2a(style, Arrays.asList(1), -1, true)); - assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, false)); assertEquals("[1]", runGetNumCitationMarker2a(style, Arrays.asList(1), -1, false)); assertEquals("[1]", runGetNumCitationMarker2b(style, -1, numEntry("key", 1, null))); - assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), 0, true)); assertEquals("[1] ", runGetNumCitationMarker2a(style, Arrays.asList(1), 0, true)); - /* - * The following tests as for a numeric label for a - * bibliography entry containing more than one numbers. - * We do not need this, not reproduced. - */ - assertEquals("[1-3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, true)); - assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, true)); - assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, true)); - assertEquals("[1; 3; 12] ", style.getNumCitationMarker(Arrays.asList(1, 12, 3), 1, true)); - assertEquals("[3-5; 7; 10-12] ", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, true)); - - String citation = style.getNumCitationMarker(Arrays.asList(1), -1, false); - assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); - CitationMarkerNumericEntry e2 = numEntry("key", 1, "pp. 55-56"); assertEquals(true, e2.getPageInfo().isPresent()); assertEquals("pp. 55-56", e2.getPageInfo().get().asString()); - citation = runGetNumCitationMarker2b(style, -1, e2); - assertEquals("[1; pp. 55-56]", citation); OOBibStyleTestHelper.testGetNumCitationMarkerExtra(style); } @@ -194,26 +191,6 @@ void testGetNumCitationMarker() throws IOException { void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - /* - * Testing bibliography labels with multiple numbers again. - * Not reproduced. - */ - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4] ", - style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, true)); - - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarker(Arrays.asList(0), 1, true)); - - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3] ", - style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, true)); - - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " - + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, true)); - - /* - * We have these instead: - */ // unresolved citations look like [??key] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "]", @@ -301,28 +278,22 @@ void testGetCitationMarker() throws IOException { assertEquals(3, style.getMaxAuthors()); assertEquals(-1, style.getMaxAuthorsFirst()); - assertEquals("[Boström et al., 2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, null)); assertEquals("[Boström et al., 2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, true, null, null, null)); - assertEquals("Boström et al. [2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, false, null, new int[]{3})); assertEquals("Boström et al. [2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, false, null, new Boolean[]{false}, null)); - assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, new int[]{5})); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, true, null, - new Boolean[]{true} /* corresponds to -1, not 5 */, + new Boolean[]{true}, null)); } @@ -408,7 +379,6 @@ void testInstitutionAuthorMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); assertEquals("[JabRef Development Team, 2016]", getCitationMarker2(style, @@ -429,10 +399,11 @@ void testVonAuthorMarker() throws IOException { entry.setField(StandardField.AUTHOR, "Alpha von Beta"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); + entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[von Beta, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + assertEquals("[von Beta, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test @@ -447,10 +418,11 @@ void testNullAuthorMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.YEAR, "2016"); + entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + assertEquals("[, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test @@ -465,10 +437,11 @@ void testNullYearMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Alpha von Beta"); + entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[von Beta, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + assertEquals("[von Beta, ]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test @@ -482,10 +455,11 @@ void testEmptyEntryMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); + entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + assertEquals("[, ]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test @@ -501,17 +475,20 @@ void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); + entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); + entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); + entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); for (BibEntry entry : database.getEntries()) { @@ -519,9 +496,12 @@ void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { } assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", - style.getCitationMarker(entries, entryDBMap, true, null, null)); + getCitationMarker2b(style, entries, entryDBMap, true, null, null, null)); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", - style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); + getCitationMarker2(style, entries, entryDBMap, true, + new String[]{"a", "b", ""}, + new Boolean[]{false, false, false}, + null)); } @Test @@ -537,27 +517,33 @@ void testGetCitationMarkerInTextUniquefiers() throws IOException { entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); + entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); + entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); entries.add(entry2); + entry2.setCitationKey("a2"); database.insertEntry(entry2); for (BibEntry entry : database.getEntries()) { entryDBMap.put(entry, database); } assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", - style.getCitationMarker(entries, entryDBMap, false, null, null)); + getCitationMarker2b(style, entries, entryDBMap, false, null, null, null)); assertEquals("Beta [2000a,b]; Epsilon [2001]", - style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); + getCitationMarker2(style, entries, entryDBMap, false, + new String[]{"a", "b", ""}, + new Boolean[]{false, false, false}, + null)); } @Test @@ -573,18 +559,21 @@ void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExc entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); + entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); + entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); + entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); for (BibEntry entry : database.getEntries()) { @@ -592,7 +581,10 @@ void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExc } assertEquals("[Beta, 2000a,b,c]", - style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); + getCitationMarker2(style, entries, entryDBMap, true, + new String[]{"a", "b", "c"}, + new Boolean[]{false, false, false}, + null)); } @Test @@ -608,18 +600,21 @@ void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); + entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); + entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); + entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); for (BibEntry entry : database.getEntries()) { @@ -627,7 +622,10 @@ void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException } assertEquals("Beta [2000a,b,c]", - style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); + getCitationMarker2(style, entries, entryDBMap, false, + new String[]{"a", "b", "c"}, + new Boolean[]{false, false, false}, + null)); } @Test @@ -681,11 +679,12 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { entry.setField(StandardField.AUTHOR, "Alpha von Beta and Gamma Epsilon and Ypsilon Tau"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); + entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); assertEquals("von Beta, Epsilon, & Tau, 2016", - style.getCitationMarker(entries, entryDBMap, true, null, null)); + getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java index c8302030fc6..2bc6e7bb976 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java @@ -185,13 +185,14 @@ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, * Similar to old API. pageInfo is new, and unlimAuthors is * replaced with isFirstAppearanceOfSource */ - static String getCitationMarker2(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo) { + static String getCitationMarker2ab(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo, + NonUniqueCitationMarker nonunique) { if (uniquefiers == null) { uniquefiers = new String[entries.size()]; Arrays.fill(uniquefiers, null); @@ -216,7 +217,41 @@ static String getCitationMarker2(OOBibStyle style, } return style.createCitationMarker(citationMarkerEntries, inParenthesis, - NonUniqueCitationMarker.THROWS).asString(); + nonunique).asString(); + } + + static String getCitationMarker2(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { + return getCitationMarker2ab(style, + entries, + entryDBMap, + inParenthesis, + uniquefiers, + isFirstAppearanceOfSource, + pageInfo, + NonUniqueCitationMarker.THROWS); + } + + static String getCitationMarker2b(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { + return getCitationMarker2ab(style, + entries, + entryDBMap, + inParenthesis, + uniquefiers, + isFirstAppearanceOfSource, + pageInfo, + NonUniqueCitationMarker.FORGIVEN); } /* From 122d5133fa6c7b44245c5ba5600d398775718664 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 4 Jun 2021 09:17:26 +0200 Subject: [PATCH 0941/1068] adjust OOBibStyleTest.java --- .../openoffice/style/OOBibStyleTest.java | 166 +++++++++--------- .../style/OOBibStyleTestHelper.java | 92 ++-------- 2 files changed, 96 insertions(+), 162 deletions(-) diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java index 8d5da6e4d00..03a0b535e34 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java @@ -11,7 +11,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -25,13 +24,10 @@ import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; import org.jabref.model.openoffice.ootext.OOText; -import org.jabref.model.openoffice.style.Citation; -import org.jabref.model.openoffice.style.CitationLookupResult; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; -import org.jabref.model.openoffice.style.PageInfo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -96,7 +92,7 @@ void testNumerical() throws IOException { * begin helpers */ static String runGetNumCitationMarker2a(OOBibStyle style, - List num, int minGroupingCount, boolean inList ) { + List num, int minGroupingCount, boolean inList) { return OOBibStyleTestHelper.runGetNumCitationMarker2a(style, num, minGroupingCount, inList); } @@ -125,7 +121,7 @@ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, database, uniqueLetterQ, pageInfoQ, - isFirstAppearanceOfSource ); + isFirstAppearanceOfSource); } /* @@ -145,44 +141,46 @@ static String getCitationMarker2(OOBibStyle style, inParenthesis, uniquefiers, isFirstAppearanceOfSource, - pageInfo ); - } - - static String getCitationMarker2b(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo) { - return OOBibStyleTestHelper.getCitationMarker2b(style, - entries, - entryDBMap, - inParenthesis, - uniquefiers, - isFirstAppearanceOfSource, - pageInfo ); + pageInfo); } /* * end helpers */ - @Test void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), -1, true)); assertEquals("[1] ", runGetNumCitationMarker2a(style, Arrays.asList(1), -1, true)); + assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, false)); assertEquals("[1]", runGetNumCitationMarker2a(style, Arrays.asList(1), -1, false)); assertEquals("[1]", runGetNumCitationMarker2b(style, -1, numEntry("key", 1, null))); + assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), 0, true)); assertEquals("[1] ", runGetNumCitationMarker2a(style, Arrays.asList(1), 0, true)); + /* + * The following tests as for a numeric label for a + * bibliography entry containing more than one numbers. + * We do not need this, not reproduced. + */ + assertEquals("[1-3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, true)); + assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, true)); + assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, true)); + assertEquals("[1; 3; 12] ", style.getNumCitationMarker(Arrays.asList(1, 12, 3), 1, true)); + assertEquals("[3-5; 7; 10-12] ", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, true)); + + String citation = style.getNumCitationMarker(Arrays.asList(1), -1, false); + assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); + CitationMarkerNumericEntry e2 = numEntry("key", 1, "pp. 55-56"); assertEquals(true, e2.getPageInfo().isPresent()); assertEquals("pp. 55-56", e2.getPageInfo().get().asString()); + citation = runGetNumCitationMarker2b(style, -1, e2); + assertEquals("[1; pp. 55-56]", citation); OOBibStyleTestHelper.testGetNumCitationMarkerExtra(style); } @@ -191,31 +189,51 @@ void testGetNumCitationMarker() throws IOException { void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + /* + * Testing bibliography labels with multiple numbers again. + * Not reproduced. + */ + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4] ", + style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, true)); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", + style.getNumCitationMarker(Arrays.asList(0), 1, true)); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3] ", + style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, true)); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", + style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, true)); + + /* + * We have these instead: + */ // unresolved citations look like [??key] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "]", runGetNumCitationMarker2b(style, 1, - numEntry("key",0,null))); + numEntry("key", 0, null))); // pageInfo is shown for unresolved citations assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; p1]", runGetNumCitationMarker2b(style, 1, - numEntry("key",0,"p1"))); + numEntry("key", 0, "p1"))); // unresolved citations sorted to the front assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 2-4]", runGetNumCitationMarker2b(style, 1, - numEntry("x4",4,""), - numEntry("x2",2,""), - numEntry("x3",3,""), - numEntry("key",0,""))); + numEntry("x4", 4, ""), + numEntry("x2", 2, ""), + numEntry("x3", 3, ""), + numEntry("key", 0, ""))); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 1-3]", runGetNumCitationMarker2b(style, 1, - numEntry("x1",1,""), - numEntry("x2",2,""), - numEntry("y3",3,""), - numEntry("key",0,""))); + numEntry("x1", 1, ""), + numEntry("x2", 2, ""), + numEntry("y3", 3, ""), + numEntry("key", 0, ""))); // multiple unresolved citations are not collapsed assertEquals("[" @@ -223,19 +241,16 @@ void testGetNumCitationMarkerUndefined() throws IOException { + OOBibStyle.UNDEFINED_CITATION_MARKER + "x2" + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "x3" + "]", runGetNumCitationMarker2b(style, 1, - numEntry("x1",0,""), - numEntry("x2",0,""), - numEntry("x3",0,""))); + numEntry("x1", 0, ""), + numEntry("x2", 0, ""), + numEntry("x3", 0, ""))); /* * BIBLIOGRAPHY */ - { - CitationMarkerNumericBibEntry x = numBibEntry("key", Optional.empty()); - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", - style.getNumCitationMarkerForBibliography(x).asString()); - } - + CitationMarkerNumericBibEntry x = numBibEntry("key", Optional.empty()); + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", + style.getNumCitationMarkerForBibliography(x).asString()); } @Test @@ -257,7 +272,6 @@ void testGetCitProperty() throws IOException { assertTrue(journals.contains("Journal name 1")); } - @Test void testGetCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); @@ -278,22 +292,28 @@ void testGetCitationMarker() throws IOException { assertEquals(3, style.getMaxAuthors()); assertEquals(-1, style.getMaxAuthorsFirst()); + assertEquals("[Boström et al., 2006]", + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, null)); assertEquals("[Boström et al., 2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, true, null, null, null)); + assertEquals("Boström et al. [2006]", + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, false, null, new int[]{3})); assertEquals("Boström et al. [2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, false, null, new Boolean[]{false}, null)); + assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, new int[]{5})); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, true, null, - new Boolean[]{true}, + new Boolean[]{true} /* corresponds to -1, not 5 */, null)); } @@ -379,6 +399,7 @@ void testInstitutionAuthorMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); + assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); assertEquals("[JabRef Development Team, 2016]", getCitationMarker2(style, @@ -399,11 +420,10 @@ void testVonAuthorMarker() throws IOException { entry.setField(StandardField.AUTHOR, "Alpha von Beta"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); - entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[von Beta, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); + assertEquals("[von Beta, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); } @Test @@ -418,11 +438,10 @@ void testNullAuthorMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.YEAR, "2016"); - entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); + assertEquals("[, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); } @Test @@ -437,11 +456,10 @@ void testNullYearMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Alpha von Beta"); - entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[von Beta, ]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); + assertEquals("[von Beta, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); } @Test @@ -455,11 +473,10 @@ void testEmptyEntryMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); - entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[, ]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); + assertEquals("[, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); } @Test @@ -475,20 +492,17 @@ void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); - entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); - entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); - entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); for (BibEntry entry : database.getEntries()) { @@ -496,12 +510,9 @@ void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { } assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", - getCitationMarker2b(style, entries, entryDBMap, true, null, null, null)); + style.getCitationMarker(entries, entryDBMap, true, null, null)); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", - getCitationMarker2(style, entries, entryDBMap, true, - new String[]{"a", "b", ""}, - new Boolean[]{false, false, false}, - null)); + style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); } @Test @@ -517,33 +528,27 @@ void testGetCitationMarkerInTextUniquefiers() throws IOException { entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); - entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); - entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); entries.add(entry2); - entry2.setCitationKey("a2"); database.insertEntry(entry2); for (BibEntry entry : database.getEntries()) { entryDBMap.put(entry, database); } assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", - getCitationMarker2b(style, entries, entryDBMap, false, null, null, null)); + style.getCitationMarker(entries, entryDBMap, false, null, null)); assertEquals("Beta [2000a,b]; Epsilon [2001]", - getCitationMarker2(style, entries, entryDBMap, false, - new String[]{"a", "b", ""}, - new Boolean[]{false, false, false}, - null)); + style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); } @Test @@ -559,21 +564,18 @@ void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExc entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); - entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); - entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); - entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); for (BibEntry entry : database.getEntries()) { @@ -581,10 +583,7 @@ void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExc } assertEquals("[Beta, 2000a,b,c]", - getCitationMarker2(style, entries, entryDBMap, true, - new String[]{"a", "b", "c"}, - new Boolean[]{false, false, false}, - null)); + style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); } @Test @@ -600,21 +599,18 @@ void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); - entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); - entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); - entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); for (BibEntry entry : database.getEntries()) { @@ -622,10 +618,7 @@ void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException } assertEquals("Beta [2000a,b,c]", - getCitationMarker2(style, entries, entryDBMap, false, - new String[]{"a", "b", "c"}, - new Boolean[]{false, false, false}, - null)); + style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); } @Test @@ -679,12 +672,11 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { entry.setField(StandardField.AUTHOR, "Alpha von Beta and Gamma Epsilon and Ypsilon Tau"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); - entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); assertEquals("von Beta, Epsilon, & Tau, 2016", - getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); + style.getCitationMarker(entries, entryDBMap, true, null, null)); } @Test @@ -766,7 +758,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" - +"; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", + + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).asString()); @@ -794,7 +786,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" - +"; Boström et al., 2006c]", + + "; Boström et al., 2006c]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).asString()); diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java index 2bc6e7bb976..9fbe9579ccb 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java @@ -1,29 +1,16 @@ package org.jabref.logic.openoffice.style; -import java.io.File; import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.jabref.logic.layout.Layout; -import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.StandardField; -import org.jabref.model.entry.types.StandardEntryType; -import org.jabref.model.entry.types.UnknownEntryType; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationLookupResult; @@ -33,15 +20,7 @@ import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.jabref.model.openoffice.style.PageInfo; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Answers; - import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; class OOBibStyleTestHelper { /* @@ -116,7 +95,7 @@ static CitationMarkerNumericBibEntry numBibEntry(String key, Optional n * @param inList true means label for the bibliography */ static String runGetNumCitationMarker2a(OOBibStyle style, - List num, int minGroupingCount, boolean inList ) { + List num, int minGroupingCount, boolean inList) { if (inList) { if (num.size() != 1) { throw new RuntimeException("Numeric label for the bibliography with " @@ -159,7 +138,6 @@ static String runGetNumCitationMarker2b(OOBibStyle style, * end Helpers for testing style.getNumCitationMarker2 */ - /* * begin helper */ @@ -185,14 +163,13 @@ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, * Similar to old API. pageInfo is new, and unlimAuthors is * replaced with isFirstAppearanceOfSource */ - static String getCitationMarker2ab(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo, - NonUniqueCitationMarker nonunique) { + static String getCitationMarker2(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { if (uniquefiers == null) { uniquefiers = new String[entries.size()]; Arrays.fill(uniquefiers, null); @@ -217,62 +194,27 @@ static String getCitationMarker2ab(OOBibStyle style, } return style.createCitationMarker(citationMarkerEntries, inParenthesis, - nonunique).asString(); - } - - static String getCitationMarker2(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo) { - return getCitationMarker2ab(style, - entries, - entryDBMap, - inParenthesis, - uniquefiers, - isFirstAppearanceOfSource, - pageInfo, - NonUniqueCitationMarker.THROWS); - } - - static String getCitationMarker2b(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo) { - return getCitationMarker2ab(style, - entries, - entryDBMap, - inParenthesis, - uniquefiers, - isFirstAppearanceOfSource, - pageInfo, - NonUniqueCitationMarker.FORGIVEN); + NonUniqueCitationMarker.THROWS).asString(); } /* * end helper */ - static void testGetNumCitationMarkerExtra(OOBibStyle style) throws IOException { // Identical numeric entries are joined. assertEquals("[1; 2]", runGetNumCitationMarker2b(style, 3, - numEntry("x1",1,null), - numEntry("x2",2,null), - numEntry("x1",2,null), - numEntry("x2",1,null))); + numEntry("x1", 1, null), + numEntry("x2", 2, null), + numEntry("x1", 2, null), + numEntry("x2", 1, null))); // ... unless minGroupingCount <= 0 assertEquals("[1; 1; 2; 2]", runGetNumCitationMarker2b(style, 0, - numEntry("x1",1,null), - numEntry("x2",2,null), - numEntry("x1",2,null), - numEntry("x2",1,null))); + numEntry("x1", 1, null), + numEntry("x2", 2, null), + numEntry("x1", 2, null), + numEntry("x2", 1, null))); // ... or have different pageInfos assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", runGetNumCitationMarker2b(style, 1, From f31f11abdb736733e49e261306092ba0324b8383 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 09:47:46 +0200 Subject: [PATCH 0942/1068] Revert "adjust OOBibStyleTest.java" This reverts commit 122d5133fa6c7b44245c5ba5600d398775718664. --- .../openoffice/style/OOBibStyleTest.java | 166 +++++++++--------- .../style/OOBibStyleTestHelper.java | 92 ++++++++-- 2 files changed, 162 insertions(+), 96 deletions(-) diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java index 03a0b535e34..8d5da6e4d00 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java @@ -11,6 +11,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -24,10 +25,13 @@ import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; import org.jabref.model.openoffice.ootext.OOText; +import org.jabref.model.openoffice.style.Citation; +import org.jabref.model.openoffice.style.CitationLookupResult; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; +import org.jabref.model.openoffice.style.PageInfo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -92,7 +96,7 @@ void testNumerical() throws IOException { * begin helpers */ static String runGetNumCitationMarker2a(OOBibStyle style, - List num, int minGroupingCount, boolean inList) { + List num, int minGroupingCount, boolean inList ) { return OOBibStyleTestHelper.runGetNumCitationMarker2a(style, num, minGroupingCount, inList); } @@ -121,7 +125,7 @@ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, database, uniqueLetterQ, pageInfoQ, - isFirstAppearanceOfSource); + isFirstAppearanceOfSource ); } /* @@ -141,46 +145,44 @@ static String getCitationMarker2(OOBibStyle style, inParenthesis, uniquefiers, isFirstAppearanceOfSource, - pageInfo); + pageInfo ); + } + + static String getCitationMarker2b(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { + return OOBibStyleTestHelper.getCitationMarker2b(style, + entries, + entryDBMap, + inParenthesis, + uniquefiers, + isFirstAppearanceOfSource, + pageInfo ); } /* * end helpers */ + @Test void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), -1, true)); assertEquals("[1] ", runGetNumCitationMarker2a(style, Arrays.asList(1), -1, true)); - assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, false)); assertEquals("[1]", runGetNumCitationMarker2a(style, Arrays.asList(1), -1, false)); assertEquals("[1]", runGetNumCitationMarker2b(style, -1, numEntry("key", 1, null))); - assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), 0, true)); assertEquals("[1] ", runGetNumCitationMarker2a(style, Arrays.asList(1), 0, true)); - /* - * The following tests as for a numeric label for a - * bibliography entry containing more than one numbers. - * We do not need this, not reproduced. - */ - assertEquals("[1-3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, true)); - assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, true)); - assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, true)); - assertEquals("[1; 3; 12] ", style.getNumCitationMarker(Arrays.asList(1, 12, 3), 1, true)); - assertEquals("[3-5; 7; 10-12] ", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, true)); - - String citation = style.getNumCitationMarker(Arrays.asList(1), -1, false); - assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); - CitationMarkerNumericEntry e2 = numEntry("key", 1, "pp. 55-56"); assertEquals(true, e2.getPageInfo().isPresent()); assertEquals("pp. 55-56", e2.getPageInfo().get().asString()); - citation = runGetNumCitationMarker2b(style, -1, e2); - assertEquals("[1; pp. 55-56]", citation); OOBibStyleTestHelper.testGetNumCitationMarkerExtra(style); } @@ -189,51 +191,31 @@ void testGetNumCitationMarker() throws IOException { void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); - /* - * Testing bibliography labels with multiple numbers again. - * Not reproduced. - */ - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4] ", - style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, true)); - - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarker(Arrays.asList(0), 1, true)); - - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3] ", - style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, true)); - - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " - + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", - style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, true)); - - /* - * We have these instead: - */ // unresolved citations look like [??key] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "]", runGetNumCitationMarker2b(style, 1, - numEntry("key", 0, null))); + numEntry("key",0,null))); // pageInfo is shown for unresolved citations assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; p1]", runGetNumCitationMarker2b(style, 1, - numEntry("key", 0, "p1"))); + numEntry("key",0,"p1"))); // unresolved citations sorted to the front assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 2-4]", runGetNumCitationMarker2b(style, 1, - numEntry("x4", 4, ""), - numEntry("x2", 2, ""), - numEntry("x3", 3, ""), - numEntry("key", 0, ""))); + numEntry("x4",4,""), + numEntry("x2",2,""), + numEntry("x3",3,""), + numEntry("key",0,""))); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 1-3]", runGetNumCitationMarker2b(style, 1, - numEntry("x1", 1, ""), - numEntry("x2", 2, ""), - numEntry("y3", 3, ""), - numEntry("key", 0, ""))); + numEntry("x1",1,""), + numEntry("x2",2,""), + numEntry("y3",3,""), + numEntry("key",0,""))); // multiple unresolved citations are not collapsed assertEquals("[" @@ -241,16 +223,19 @@ void testGetNumCitationMarkerUndefined() throws IOException { + OOBibStyle.UNDEFINED_CITATION_MARKER + "x2" + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "x3" + "]", runGetNumCitationMarker2b(style, 1, - numEntry("x1", 0, ""), - numEntry("x2", 0, ""), - numEntry("x3", 0, ""))); + numEntry("x1",0,""), + numEntry("x2",0,""), + numEntry("x3",0,""))); /* * BIBLIOGRAPHY */ - CitationMarkerNumericBibEntry x = numBibEntry("key", Optional.empty()); - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", - style.getNumCitationMarkerForBibliography(x).asString()); + { + CitationMarkerNumericBibEntry x = numBibEntry("key", Optional.empty()); + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", + style.getNumCitationMarkerForBibliography(x).asString()); + } + } @Test @@ -272,6 +257,7 @@ void testGetCitProperty() throws IOException { assertTrue(journals.contains("Journal name 1")); } + @Test void testGetCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); @@ -292,28 +278,22 @@ void testGetCitationMarker() throws IOException { assertEquals(3, style.getMaxAuthors()); assertEquals(-1, style.getMaxAuthorsFirst()); - assertEquals("[Boström et al., 2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, null)); assertEquals("[Boström et al., 2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, true, null, null, null)); - assertEquals("Boström et al. [2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, false, null, new int[]{3})); assertEquals("Boström et al. [2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, false, null, new Boolean[]{false}, null)); - assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", - style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, new int[]{5})); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, true, null, - new Boolean[]{true} /* corresponds to -1, not 5 */, + new Boolean[]{true}, null)); } @@ -399,7 +379,6 @@ void testInstitutionAuthorMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); assertEquals("[JabRef Development Team, 2016]", getCitationMarker2(style, @@ -420,10 +399,11 @@ void testVonAuthorMarker() throws IOException { entry.setField(StandardField.AUTHOR, "Alpha von Beta"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); + entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[von Beta, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + assertEquals("[von Beta, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test @@ -438,10 +418,11 @@ void testNullAuthorMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.YEAR, "2016"); + entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + assertEquals("[, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test @@ -456,10 +437,11 @@ void testNullYearMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Alpha von Beta"); + entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[von Beta, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + assertEquals("[von Beta, ]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test @@ -473,10 +455,11 @@ void testEmptyEntryMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); + entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); + assertEquals("[, ]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test @@ -492,17 +475,20 @@ void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); + entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); + entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); + entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); for (BibEntry entry : database.getEntries()) { @@ -510,9 +496,12 @@ void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { } assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", - style.getCitationMarker(entries, entryDBMap, true, null, null)); + getCitationMarker2b(style, entries, entryDBMap, true, null, null, null)); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", - style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); + getCitationMarker2(style, entries, entryDBMap, true, + new String[]{"a", "b", ""}, + new Boolean[]{false, false, false}, + null)); } @Test @@ -528,27 +517,33 @@ void testGetCitationMarkerInTextUniquefiers() throws IOException { entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); + entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); + entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); entries.add(entry2); + entry2.setCitationKey("a2"); database.insertEntry(entry2); for (BibEntry entry : database.getEntries()) { entryDBMap.put(entry, database); } assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", - style.getCitationMarker(entries, entryDBMap, false, null, null)); + getCitationMarker2b(style, entries, entryDBMap, false, null, null, null)); assertEquals("Beta [2000a,b]; Epsilon [2001]", - style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); + getCitationMarker2(style, entries, entryDBMap, false, + new String[]{"a", "b", ""}, + new Boolean[]{false, false, false}, + null)); } @Test @@ -564,18 +559,21 @@ void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExc entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); + entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); + entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); + entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); for (BibEntry entry : database.getEntries()) { @@ -583,7 +581,10 @@ void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExc } assertEquals("[Beta, 2000a,b,c]", - style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); + getCitationMarker2(style, entries, entryDBMap, true, + new String[]{"a", "b", "c"}, + new Boolean[]{false, false, false}, + null)); } @Test @@ -599,18 +600,21 @@ void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); + entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); + entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); + entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); for (BibEntry entry : database.getEntries()) { @@ -618,7 +622,10 @@ void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException } assertEquals("Beta [2000a,b,c]", - style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); + getCitationMarker2(style, entries, entryDBMap, false, + new String[]{"a", "b", "c"}, + new Boolean[]{false, false, false}, + null)); } @Test @@ -672,11 +679,12 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { entry.setField(StandardField.AUTHOR, "Alpha von Beta and Gamma Epsilon and Ypsilon Tau"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); + entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); assertEquals("von Beta, Epsilon, & Tau, 2016", - style.getCitationMarker(entries, entryDBMap, true, null, null)); + getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); } @Test @@ -758,7 +766,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" - + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", + +"; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).asString()); @@ -786,7 +794,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" - + "; Boström et al., 2006c]", + +"; Boström et al., 2006c]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).asString()); diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java index 9fbe9579ccb..2bc6e7bb976 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java @@ -1,16 +1,29 @@ package org.jabref.logic.openoffice.style; +import java.io.File; import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.jabref.logic.layout.Layout; +import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.StandardField; +import org.jabref.model.entry.types.StandardEntryType; +import org.jabref.model.entry.types.UnknownEntryType; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationLookupResult; @@ -20,7 +33,15 @@ import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.jabref.model.openoffice.style.PageInfo; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; + import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; class OOBibStyleTestHelper { /* @@ -95,7 +116,7 @@ static CitationMarkerNumericBibEntry numBibEntry(String key, Optional n * @param inList true means label for the bibliography */ static String runGetNumCitationMarker2a(OOBibStyle style, - List num, int minGroupingCount, boolean inList) { + List num, int minGroupingCount, boolean inList ) { if (inList) { if (num.size() != 1) { throw new RuntimeException("Numeric label for the bibliography with " @@ -138,6 +159,7 @@ static String runGetNumCitationMarker2b(OOBibStyle style, * end Helpers for testing style.getNumCitationMarker2 */ + /* * begin helper */ @@ -163,13 +185,14 @@ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, * Similar to old API. pageInfo is new, and unlimAuthors is * replaced with isFirstAppearanceOfSource */ - static String getCitationMarker2(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo) { + static String getCitationMarker2ab(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo, + NonUniqueCitationMarker nonunique) { if (uniquefiers == null) { uniquefiers = new String[entries.size()]; Arrays.fill(uniquefiers, null); @@ -194,27 +217,62 @@ static String getCitationMarker2(OOBibStyle style, } return style.createCitationMarker(citationMarkerEntries, inParenthesis, - NonUniqueCitationMarker.THROWS).asString(); + nonunique).asString(); + } + + static String getCitationMarker2(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { + return getCitationMarker2ab(style, + entries, + entryDBMap, + inParenthesis, + uniquefiers, + isFirstAppearanceOfSource, + pageInfo, + NonUniqueCitationMarker.THROWS); + } + + static String getCitationMarker2b(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { + return getCitationMarker2ab(style, + entries, + entryDBMap, + inParenthesis, + uniquefiers, + isFirstAppearanceOfSource, + pageInfo, + NonUniqueCitationMarker.FORGIVEN); } /* * end helper */ + static void testGetNumCitationMarkerExtra(OOBibStyle style) throws IOException { // Identical numeric entries are joined. assertEquals("[1; 2]", runGetNumCitationMarker2b(style, 3, - numEntry("x1", 1, null), - numEntry("x2", 2, null), - numEntry("x1", 2, null), - numEntry("x2", 1, null))); + numEntry("x1",1,null), + numEntry("x2",2,null), + numEntry("x1",2,null), + numEntry("x2",1,null))); // ... unless minGroupingCount <= 0 assertEquals("[1; 1; 2; 2]", runGetNumCitationMarker2b(style, 0, - numEntry("x1", 1, null), - numEntry("x2", 2, null), - numEntry("x1", 2, null), - numEntry("x2", 1, null))); + numEntry("x1",1,null), + numEntry("x2",2,null), + numEntry("x1",2,null), + numEntry("x2",1,null))); // ... or have different pageInfos assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", runGetNumCitationMarker2b(style, 1, From 7ff80d08fe2d873d3bf7c77f687adab9615b1e34 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 09:48:30 +0200 Subject: [PATCH 0943/1068] Revert "cleanup OOBibStyle" This reverts commit 57d4369f2f41c8eb75e5095b459183cf8381d9d9. --- .../logic/openoffice/style/OOBibStyle.java | 379 +++++++++++++++++- .../openoffice/style/OOBibStyleTest.java | 115 +++--- .../style/OOBibStyleTestHelper.java | 51 +-- 3 files changed, 423 insertions(+), 122 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index 0d81bdbd024..44416ea0a29 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -25,6 +25,11 @@ import org.jabref.logic.layout.LayoutFormatter; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.layout.LayoutHelper; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.Author; +import org.jabref.model.entry.AuthorList; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; @@ -39,6 +44,7 @@ import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.jabref.model.openoffice.style.PageInfo; import org.jabref.model.openoffice.util.OOListUtil; +import org.jabref.model.strings.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -441,6 +447,324 @@ public Layout getReferenceFormat(EntryType type) { } } + /* begin_old */ + /** + * Format a number-based citation marker for the given number. + * + * @param number The citation numbers. + * @return The text for the citation. + */ + public String getNumCitationMarker(List number, int minGroupingCount, boolean inList) { + String bracketBefore = getStringCitProperty(BRACKET_BEFORE); + if (inList && (citProperties.containsKey(BRACKET_BEFORE_IN_LIST))) { + bracketBefore = getStringCitProperty(BRACKET_BEFORE_IN_LIST); + } + String bracketAfter = getStringCitProperty(BRACKET_AFTER); + if (inList && (citProperties.containsKey(BRACKET_AFTER_IN_LIST))) { + bracketAfter = getStringCitProperty(BRACKET_AFTER_IN_LIST); + } + // Sort the numbers: + List lNum = new ArrayList<>(number); + Collections.sort(lNum); + StringBuilder sb = new StringBuilder(bracketBefore); + int combineFrom = -1; + int written = 0; + for (int i = 0; i < lNum.size(); i++) { + int i1 = lNum.get(i); + if (combineFrom < 0) { + // Check if next entry is the next in the ref list: + if ((i < (lNum.size() - 1)) && (lNum.get(i + 1) == (i1 + 1)) && (i1 > 0)) { + combineFrom = i1; + } else { + // Add single entry: + if (i > 0) { + sb.append(getStringCitProperty(CITATION_SEPARATOR)); + } + sb.append(lNum.get(i) > 0 ? String.valueOf(lNum.get(i)) : OOBibStyle.UNDEFINED_CITATION_MARKER); + written++; + } + } else { + // We are building a list of combined entries. + // Check if it ends here: + if ((i == (lNum.size() - 1)) || (lNum.get(i + 1) != (i1 + 1))) { + if (written > 0) { + sb.append(getStringCitProperty(CITATION_SEPARATOR)); + } + if ((minGroupingCount > 0) && (((i1 + 1) - combineFrom) >= minGroupingCount)) { + sb.append(combineFrom); + sb.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); + sb.append(i1); + written++; + } else { + // Either we should never group, or there aren't enough + // entries in this case to group. Output all: + for (int jj = combineFrom; jj <= i1; jj++) { + sb.append(jj); + if (jj < i1) { + sb.append(getStringCitProperty(CITATION_SEPARATOR)); + } + written++; + } + } + combineFrom = -1; + } + // If it doesn't end here, just keep iterating. + } + } + sb.append(bracketAfter); + return sb.toString(); + } + /* end_old */ + + /** + * Format a number-based citation marker for the given entries. + * + * @return The text for the citation. + */ + public OOText getNumCitationMarker2(List entries) { + final int minGroupingCount = this.getMinimumGroupingCount(); + return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, + entries, + minGroupingCount); + } + + /** + * For some tests we need to override minGroupingCount. + */ + public OOText getNumCitationMarker2(List entries, + int minGroupingCount) { + return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, + entries, + minGroupingCount); + } + + /* begin_old */ + public String getCitationMarker(List entries, Map database, boolean inParenthesis, + String[] uniquefiers, int[] unlimAuthors) { + // Look for groups of uniquefied entries that should be combined in the output. + // E.g. (Olsen, 2005a, b) should be output instead of (Olsen, 2005a; Olsen, 2005b). + int piv = -1; + String tmpMarker = null; + if (uniquefiers != null) { + for (int i = 0; i < uniquefiers.length; i++) { + + if ((uniquefiers[i] == null) || uniquefiers[i].isEmpty()) { + // This entry has no uniquefier. + // Check if we just passed a group of more than one entry with uniquefier: + if ((piv > -1) && (i > (piv + 1))) { + // Do the grouping: + group(entries, uniquefiers, piv, i - 1); + } + + piv = -1; + } else { + BibEntry currentEntry = entries.get(i); + if (piv == -1) { + piv = i; + tmpMarker = getAuthorYearParenthesisMarker(Collections.singletonList(currentEntry), database, + null, unlimAuthors); + } else { + // See if this entry can go into a group with the previous one: + String thisMarker = getAuthorYearParenthesisMarker(Collections.singletonList(currentEntry), + database, null, unlimAuthors); + + String authorField = getStringCitProperty(AUTHOR_FIELD); + int maxAuthors = getIntCitProperty(MAX_AUTHORS); + String author = getCitationMarkerField(currentEntry, database.get(currentEntry), + authorField); + AuthorList al = AuthorList.parse(author); + int prevALim = unlimAuthors[i - 1]; // i always at least 1 here + if (!thisMarker.equals(tmpMarker) + || ((al.getNumberOfAuthors() > maxAuthors) && (unlimAuthors[i] != prevALim))) { + // No match. Update piv to exclude the previous entry. But first check if the + // previous entry was part of a group: + if ((piv > -1) && (i > (piv + 1))) { + // Do the grouping: + group(entries, uniquefiers, piv, i - 1); + } + tmpMarker = thisMarker; + piv = i; + } + } + } + + } + // Finished with the loop. See if the last entries form a group: + if (piv >= 0) { + // Do the grouping: + group(entries, uniquefiers, piv, uniquefiers.length - 1); + } + } + + if (inParenthesis) { + return getAuthorYearParenthesisMarker(entries, database, uniquefiers, unlimAuthors); + } else { + return getAuthorYearInTextMarker(entries, database, uniquefiers, unlimAuthors); + } + } + /* end_old */ + + /* begin_old */ + private void group(List entries, String[] uniquefiers, int from, int to) { + String separator = getStringCitProperty(UNIQUEFIER_SEPARATOR); + StringBuilder sb = new StringBuilder(uniquefiers[from]); + for (int i = from + 1; i <= to; i++) { + sb.append(separator); + sb.append(uniquefiers[i]); + entries.set(i, null); + } + uniquefiers[from] = sb.toString(); + } + /* end_old */ + + /* begin_old */ + private String getAuthorYearParenthesisMarker(List entries, Map database, + String[] uniquifiers, int[] unlimAuthors) { + + String authorField = getStringCitProperty(AUTHOR_FIELD); // The bibtex field providing author names, e.g. "author" or "editor". + int maxA = getIntCitProperty(MAX_AUTHORS); // The maximum number of authors to write out in full without using etal. Set to + // -1 to always write out all authors. + String yearSep = getStringCitProperty(YEAR_SEPARATOR); // The String to separate authors from year, e.g. "; ". + String startBrace = getStringCitProperty(BRACKET_BEFORE); // The opening parenthesis. + String endBrace = getStringCitProperty(BRACKET_AFTER); // The closing parenthesis. + String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); // The String to separate citations from each other. + String yearField = getStringCitProperty(YEAR_FIELD); // The bibtex field providing the year, e.g. "year". + String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR); // The String to add between the two last author names, e.g. " & ". + StringBuilder sb = new StringBuilder(startBrace); + for (int j = 0; j < entries.size(); j++) { + BibEntry currentEntry = entries.get(j); + + // Check if this entry has been nulled due to grouping with the previous entry(ies): + if (currentEntry == null) { + continue; + } + + if (j > 0) { + sb.append(citationSeparator); + } + + BibDatabase currentDatabase = database.get(currentEntry); + int unlimA = unlimAuthors == null ? -1 : unlimAuthors[j]; + int maxAuthors = unlimA > 0 ? unlimA : maxA; + + String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); + String authorString = createAuthorList(author, maxAuthors, andString, yearSep); + sb.append(authorString); + String year = getCitationMarkerField(currentEntry, currentDatabase, yearField); + if (year != null) { + sb.append(year); + } + if ((uniquifiers != null) && (uniquifiers[j] != null)) { + sb.append(uniquifiers[j]); + } + } + sb.append(endBrace); + return sb.toString(); + } + /* end_old */ + + /* begin_old */ + private String getAuthorYearInTextMarker(List entries, Map database, + String[] uniquefiers, + int[] unlimAuthors) { + String authorField = getStringCitProperty(AUTHOR_FIELD); // The bibtex field providing author names, e.g. "author" or "editor". + int maxA = getIntCitProperty(MAX_AUTHORS); // The maximum number of authors to write out in full without using etal. Set to + // -1 to always write out all authors. + String yearSep = getStringCitProperty(IN_TEXT_YEAR_SEPARATOR); // The String to separate authors from year, e.g. "; ". + String startBrace = getStringCitProperty(BRACKET_BEFORE); // The opening parenthesis. + String endBrace = getStringCitProperty(BRACKET_AFTER); // The closing parenthesis. + String citationSeparator = getStringCitProperty(CITATION_SEPARATOR); // The String to separate citations from each other. + String yearField = getStringCitProperty(YEAR_FIELD); // The bibtex field providing the year, e.g. "year". + String andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR_IN_TEXT); // The String to add between the two last author names, e.g. " & ". + + if (andString == null) { + // Use the default one if no explicit separator for text is defined + andString = getStringCitProperty(AUTHOR_LAST_SEPARATOR); + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < entries.size(); i++) { + BibEntry currentEntry = entries.get(i); + + // Check if this entry has been nulled due to grouping with the previous entry(ies): + if (currentEntry == null) { + continue; + } + + BibDatabase currentDatabase = database.get(currentEntry); + int unlimA = unlimAuthors == null ? -1 : unlimAuthors[i]; + int maxAuthors = unlimA > 0 ? unlimA : maxA; + + if (i > 0) { + sb.append(citationSeparator); + } + String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); + String authorString = createAuthorList(author, maxAuthors, andString, yearSep); + sb.append(authorString); + sb.append(startBrace); + String year = getCitationMarkerField(currentEntry, currentDatabase, yearField); + if (year != null) { + sb.append(year); + } + if ((uniquefiers != null) && (uniquefiers[i] != null)) { + sb.append(uniquefiers[i]); + } + sb.append(endBrace); + } + return sb.toString(); + + } + /* end_old */ + + /* begin_old */ + /* moved to OOBibStyleGetCitationMarker */ + private String getCitationMarkerField(BibEntry entry, BibDatabase database, String fields) { + Objects.requireNonNull(entry, "Entry cannot be null"); + Objects.requireNonNull(database, "database cannot be null"); + + Set authorFields = FieldFactory.parseOrFields(getStringCitProperty(AUTHOR_FIELD)); + for (Field field : FieldFactory.parseOrFields(fields)) { + Optional content = entry.getResolvedFieldOrAlias(field, database); + + if ((content.isPresent()) && !content.get().trim().isEmpty()) { + if (authorFields.contains(field) && StringUtil.isInCurlyBrackets(content.get())) { + return "{" + fieldFormatter.format(content.get()) + "}"; + } + return fieldFormatter.format(content.get()); + } + } + // No luck? Return an empty string: + return ""; + } + /* end_old */ + + /* begin_old */ + /* moved to OOBibStyleGetCitationMarker */ + private String getAuthorLastName(AuthorList al, int number) { + StringBuilder sb = new StringBuilder(); + + if (al.getNumberOfAuthors() > number) { + Author a = al.getAuthor(number); + a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> sb.append(von).append(' ')); + sb.append(a.getLast().orElse("")); + } + + return sb.toString(); + } + /* end_old */ + + /* begin_old */ + /* removed */ + public String insertPageInfo(String citation, String pageInfo) { + String bracketAfter = getStringCitProperty(BRACKET_AFTER); + if (citation.endsWith(bracketAfter)) { + String first = citation.substring(0, citation.length() - bracketAfter.length()); + return first + getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo + bracketAfter; + } else { + return citation + getStringCitProperty(PAGE_INFO_SEPARATOR) + pageInfo; + } + } + /* end_old */ + /** * Convenience method for checking the property for whether we use number citations or * author-year citations. @@ -566,6 +890,39 @@ public int hashCode() { return Objects.hash(path, name, citProperties, properties); } + /* begin_old */ + /* moved to OOBibStyleGetCitationMarker as formatAuthorList */ + private String createAuthorList(String author, int maxAuthors, String andString, + String yearSep) { + Objects.requireNonNull(author); + String etAlString = getStringCitProperty(ET_AL_STRING); // The String to represent authors that are not mentioned, e.g. " et al." + String authorSep = getStringCitProperty(AUTHOR_SEPARATOR); // The String to add between author names except the last two, e.g. ", ". + String oxfordComma = getStringCitProperty(OXFORD_COMMA); // The String to put after the second to last author in case of three or more authors + StringBuilder sb = new StringBuilder(); + AuthorList al = AuthorList.parse(author); + if (!al.isEmpty()) { + sb.append(getAuthorLastName(al, 0)); + } + if ((al.getNumberOfAuthors() > 1) && ((al.getNumberOfAuthors() <= maxAuthors) || (maxAuthors < 0))) { + int j = 1; + while (j < (al.getNumberOfAuthors() - 1)) { + sb.append(authorSep); + sb.append(getAuthorLastName(al, j)); + j++; + } + if (al.getNumberOfAuthors() > 2) { + sb.append(oxfordComma); + } + sb.append(andString); + sb.append(getAuthorLastName(al, al.getNumberOfAuthors() - 1)); + } else if (al.getNumberOfAuthors() > maxAuthors) { + sb.append(etAlString); + } + sb.append(yearSep); + return sb.toString(); + } + /* end_old */ + enum BibStyleMode { NONE, LAYOUT, @@ -667,28 +1024,6 @@ protected void setDefaultBibLayout(Layout l) { defaultBibLayout = l; } - /** - * Format a number-based citation marker for the given entries. - * - * @return The text for the citation. - */ - public OOText getNumCitationMarker2(List entries) { - final int minGroupingCount = this.getMinimumGroupingCount(); - return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, - entries, - minGroupingCount); - } - - /** - * For some tests we need to override minGroupingCount. - */ - public OOText getNumCitationMarker2(List entries, - int minGroupingCount) { - return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, - entries, - minGroupingCount); - } - /** * Format a number-based bibliography label for the given number. */ diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java index 8d5da6e4d00..bf0bdf945a4 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java @@ -148,22 +148,6 @@ static String getCitationMarker2(OOBibStyle style, pageInfo ); } - static String getCitationMarker2b(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo) { - return OOBibStyleTestHelper.getCitationMarker2b(style, - entries, - entryDBMap, - inParenthesis, - uniquefiers, - isFirstAppearanceOfSource, - pageInfo ); - } - /* * end helpers */ @@ -173,16 +157,35 @@ static String getCitationMarker2b(OOBibStyle style, void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), -1, true)); assertEquals("[1] ", runGetNumCitationMarker2a(style, Arrays.asList(1), -1, true)); + assertEquals("[1]", style.getNumCitationMarker(Arrays.asList(1), -1, false)); assertEquals("[1]", runGetNumCitationMarker2a(style, Arrays.asList(1), -1, false)); assertEquals("[1]", runGetNumCitationMarker2b(style, -1, numEntry("key", 1, null))); + assertEquals("[1] ", style.getNumCitationMarker(Arrays.asList(1), 0, true)); assertEquals("[1] ", runGetNumCitationMarker2a(style, Arrays.asList(1), 0, true)); + /* + * The following tests as for a numeric label for a + * bibliography entry containing more than one numbers. + * We do not need this, not reproduced. + */ + assertEquals("[1-3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 1, true)); + assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), 5, true)); + assertEquals("[1; 2; 3] ", style.getNumCitationMarker(Arrays.asList(1, 2, 3), -1, true)); + assertEquals("[1; 3; 12] ", style.getNumCitationMarker(Arrays.asList(1, 12, 3), 1, true)); + assertEquals("[3-5; 7; 10-12] ", style.getNumCitationMarker(Arrays.asList(12, 7, 3, 4, 11, 10, 5), 1, true)); + + String citation = style.getNumCitationMarker(Arrays.asList(1), -1, false); + assertEquals("[1; pp. 55-56]", style.insertPageInfo(citation, "pp. 55-56")); + CitationMarkerNumericEntry e2 = numEntry("key", 1, "pp. 55-56"); assertEquals(true, e2.getPageInfo().isPresent()); assertEquals("pp. 55-56", e2.getPageInfo().get().asString()); + citation = runGetNumCitationMarker2b(style, -1, e2); + assertEquals("[1; pp. 55-56]", citation); OOBibStyleTestHelper.testGetNumCitationMarkerExtra(style); } @@ -191,6 +194,26 @@ void testGetNumCitationMarker() throws IOException { void testGetNumCitationMarkerUndefined() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); + /* + * Testing bibliography labels with multiple numbers again. + * Not reproduced. + */ + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 2-4] ", + style.getNumCitationMarker(Arrays.asList(4, 2, 3, 0), 1, true)); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", + style.getNumCitationMarker(Arrays.asList(0), 1, true)); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; 1-3] ", + style.getNumCitationMarker(Arrays.asList(1, 2, 3, 0), 1, true)); + + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "; " + + OOBibStyle.UNDEFINED_CITATION_MARKER + "] ", + style.getNumCitationMarker(Arrays.asList(0, 0, 0), 1, true)); + + /* + * We have these instead: + */ // unresolved citations look like [??key] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "]", @@ -278,22 +301,28 @@ void testGetCitationMarker() throws IOException { assertEquals(3, style.getMaxAuthors()); assertEquals(-1, style.getMaxAuthorsFirst()); + assertEquals("[Boström et al., 2006]", + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, null)); assertEquals("[Boström et al., 2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, true, null, null, null)); + assertEquals("Boström et al. [2006]", + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, false, null, new int[]{3})); assertEquals("Boström et al. [2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, false, null, new Boolean[]{false}, null)); + assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", + style.getCitationMarker(Collections.singletonList(entry), entryDBMap, true, null, new int[]{5})); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006]", getCitationMarker2(style, Collections.singletonList(entry), entryDBMap, true, null, - new Boolean[]{true}, + new Boolean[]{true} /* corresponds to -1, not 5 */, null)); } @@ -379,6 +408,7 @@ void testInstitutionAuthorMarker() throws IOException { database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); + assertEquals("[JabRef Development Team, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); assertEquals("[JabRef Development Team, 2016]", getCitationMarker2(style, @@ -399,11 +429,10 @@ void testVonAuthorMarker() throws IOException { entry.setField(StandardField.AUTHOR, "Alpha von Beta"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); - entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[von Beta, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); + assertEquals("[von Beta, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); } @Test @@ -418,11 +447,10 @@ void testNullAuthorMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.YEAR, "2016"); - entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[, 2016]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); + assertEquals("[, 2016]", style.getCitationMarker(entries, entryDBMap, true, null, null)); } @Test @@ -437,11 +465,10 @@ void testNullYearMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); entry.setField(StandardField.AUTHOR, "Alpha von Beta"); - entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[von Beta, ]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); + assertEquals("[von Beta, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); } @Test @@ -455,11 +482,10 @@ void testEmptyEntryMarker() throws IOException { BibEntry entry = new BibEntry(); entry.setType(StandardEntryType.Article); - entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); - assertEquals("[, ]", getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); + assertEquals("[, ]", style.getCitationMarker(entries, entryDBMap, true, null, null)); } @Test @@ -475,20 +501,17 @@ void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); - entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); - entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); - entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); for (BibEntry entry : database.getEntries()) { @@ -496,12 +519,9 @@ void testGetCitationMarkerInParenthesisUniquefiers() throws IOException { } assertEquals("[Beta, 2000; Beta, 2000; Epsilon, 2001]", - getCitationMarker2b(style, entries, entryDBMap, true, null, null, null)); + style.getCitationMarker(entries, entryDBMap, true, null, null)); assertEquals("[Beta, 2000a,b; Epsilon, 2001]", - getCitationMarker2(style, entries, entryDBMap, true, - new String[]{"a", "b", ""}, - new Boolean[]{false, false, false}, - null)); + style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); } @Test @@ -517,33 +537,27 @@ void testGetCitationMarkerInTextUniquefiers() throws IOException { entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); - entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 2"); entry3.setField(StandardField.YEAR, "2000"); - entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Gamma Epsilon"); entry2.setField(StandardField.YEAR, "2001"); entries.add(entry2); - entry2.setCitationKey("a2"); database.insertEntry(entry2); for (BibEntry entry : database.getEntries()) { entryDBMap.put(entry, database); } assertEquals("Beta [2000]; Beta [2000]; Epsilon [2001]", - getCitationMarker2b(style, entries, entryDBMap, false, null, null, null)); + style.getCitationMarker(entries, entryDBMap, false, null, null)); assertEquals("Beta [2000a,b]; Epsilon [2001]", - getCitationMarker2(style, entries, entryDBMap, false, - new String[]{"a", "b", ""}, - new Boolean[]{false, false, false}, - null)); + style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", ""}, new int[]{1, 1, 1})); } @Test @@ -559,21 +573,18 @@ void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExc entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); - entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); - entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); - entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); for (BibEntry entry : database.getEntries()) { @@ -581,10 +592,7 @@ void testGetCitationMarkerInParenthesisUniquefiersThreeSameAuthor() throws IOExc } assertEquals("[Beta, 2000a,b,c]", - getCitationMarker2(style, entries, entryDBMap, true, - new String[]{"a", "b", "c"}, - new Boolean[]{false, false, false}, - null)); + style.getCitationMarker(entries, entryDBMap, true, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); } @Test @@ -600,21 +608,18 @@ void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException entry1.setField(StandardField.AUTHOR, "Alpha Beta"); entry1.setField(StandardField.TITLE, "Paper 1"); entry1.setField(StandardField.YEAR, "2000"); - entry1.setCitationKey("a1"); entries.add(entry1); database.insertEntry(entry1); BibEntry entry2 = new BibEntry(); entry2.setField(StandardField.AUTHOR, "Alpha Beta"); entry2.setField(StandardField.TITLE, "Paper 2"); entry2.setField(StandardField.YEAR, "2000"); - entry2.setCitationKey("a2"); entries.add(entry2); database.insertEntry(entry2); BibEntry entry3 = new BibEntry(); entry3.setField(StandardField.AUTHOR, "Alpha Beta"); entry3.setField(StandardField.TITLE, "Paper 3"); entry3.setField(StandardField.YEAR, "2000"); - entry3.setCitationKey("a3"); entries.add(entry3); database.insertEntry(entry3); for (BibEntry entry : database.getEntries()) { @@ -622,10 +627,7 @@ void testGetCitationMarkerInTextUniquefiersThreeSameAuthor() throws IOException } assertEquals("Beta [2000a,b,c]", - getCitationMarker2(style, entries, entryDBMap, false, - new String[]{"a", "b", "c"}, - new Boolean[]{false, false, false}, - null)); + style.getCitationMarker(entries, entryDBMap, false, new String[]{"a", "b", "c"}, new int[]{1, 1, 1})); } @Test @@ -679,12 +681,11 @@ void testEmptyStringPropertyAndOxfordComma() throws Exception { entry.setField(StandardField.AUTHOR, "Alpha von Beta and Gamma Epsilon and Ypsilon Tau"); entry.setField(StandardField.TITLE, "JabRef Manual"); entry.setField(StandardField.YEAR, "2016"); - entry.setCitationKey("a1"); database.insertEntry(entry); entries.add(entry); entryDBMap.put(entry, database); assertEquals("von Beta, Epsilon, & Tau, 2016", - getCitationMarker2(style, entries, entryDBMap, true, null, null, null)); + style.getCitationMarker(entries, entryDBMap, true, null, null)); } @Test diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java index 2bc6e7bb976..c8302030fc6 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java @@ -185,14 +185,13 @@ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, * Similar to old API. pageInfo is new, and unlimAuthors is * replaced with isFirstAppearanceOfSource */ - static String getCitationMarker2ab(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo, - NonUniqueCitationMarker nonunique) { + static String getCitationMarker2(OOBibStyle style, + List entries, + Map entryDBMap, + boolean inParenthesis, + String[] uniquefiers, + Boolean[] isFirstAppearanceOfSource, + String[] pageInfo) { if (uniquefiers == null) { uniquefiers = new String[entries.size()]; Arrays.fill(uniquefiers, null); @@ -217,41 +216,7 @@ static String getCitationMarker2ab(OOBibStyle style, } return style.createCitationMarker(citationMarkerEntries, inParenthesis, - nonunique).asString(); - } - - static String getCitationMarker2(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo) { - return getCitationMarker2ab(style, - entries, - entryDBMap, - inParenthesis, - uniquefiers, - isFirstAppearanceOfSource, - pageInfo, - NonUniqueCitationMarker.THROWS); - } - - static String getCitationMarker2b(OOBibStyle style, - List entries, - Map entryDBMap, - boolean inParenthesis, - String[] uniquefiers, - Boolean[] isFirstAppearanceOfSource, - String[] pageInfo) { - return getCitationMarker2ab(style, - entries, - entryDBMap, - inParenthesis, - uniquefiers, - isFirstAppearanceOfSource, - pageInfo, - NonUniqueCitationMarker.FORGIVEN); + NonUniqueCitationMarker.THROWS).asString(); } /* From 63338b1caf1605ff665bcb81fe4b21692d922e71 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 18:46:15 +0200 Subject: [PATCH 0944/1068] add Makefile --- Makefile | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 00000000000..4d97fe576ab --- /dev/null +++ b/Makefile @@ -0,0 +1,52 @@ +# -*- makefile -*- + +all: build + +# https://devdocs.jabref.org/getting-into-the-code/guidelines-for-setting-up-a-local-workspace +# +# Generate additional source code: ./gradlew assemble +# +assemble: + ./gradlew assemble + +build: + make checkstyle + make tmp-clean + ./gradlew build + make tmp-clean + +build-notest: + make checkstyle + make tmp-clean + ./gradlew build -x test + make tmp-clean + +clean: + ./gradlew clean + make tmp-clean + +check: + make checkstyle + make tmp-clean + ./gradlew check + +test: + make checkstyle + make tmp-clean + ./gradlew test + +run: + make checkstyle + ./gradlew run + +tmp-clean: + rm -rf /tmp/journal[0-9][0-9][0-9][0-9][0-9][0-9]* \ + /tmp/junit[0-9][0-9][0-9][0-9][0-9][0-9]* \ + /tmp/gradle-worker-* \ + /tmp/LICENSE*.md \ + /tmp/INPROC-2016*.pdf \ + /tmp/[0-9][0-9][0-9][0-9][0-9][0-9][0-9]*.tmp + +checkstyle: + ./gradlew checkstyleMain 2>&1 | sed -e 's|[[]ant[:]checkstyle] [[]ERROR] ||g' + ./gradlew checkstyletest 2>&1 | sed -e 's|[[]ant[:]checkstyle] [[]ERROR] ||g' From b727d12acb71cb873b5f4aa54fa337fc8f960b65 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 22:07:57 +0200 Subject: [PATCH 0945/1068] JabRef 5.3 already exists, rename 'future version' to JabRef60 --- .../logic/openoffice/backend/Backend52.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index de2cfaec518..0fe444aae24 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -237,7 +237,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, } } break; - case JabRef53: + case JabRef60: cit.setPageInfo(pageInfo); break; } @@ -303,7 +303,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, } return OODataModel.fakePageInfos(cgPageInfo, nCitations); - case JabRef53: + case JabRef60: return (joinableGroup.stream() .flatMap(cg -> (cg.citationsInStorageOrder.stream() .map(Citation::getPageInfo))) @@ -403,7 +403,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups switch (dataModel) { case JabRef52: // One context per CitationGroup: Backend52 (DataModel.JabRef52) - // For DataModel.JabRef53 (Backend53) we need one context per Citation + // For DataModel.JabRef60 (Backend60) we need one context per Citation int n = cgs.numberOfCitationGroups(); List citations = new ArrayList<>(n); for (CitationGroup cg : cgs.getCitationGroupsUnordered()) { @@ -420,9 +420,9 @@ public List getCitationEntries(XTextDocument doc, CitationGroups citations.add(entry); } return citations; - case JabRef53: - //xx - throw new RuntimeException("getCitationEntries for JabRef53 is not implemented yet"); + case JabRef60: + // xx + throw new RuntimeException("getCitationEntries for JabRef60 is not implemented yet"); default: throw new RuntimeException("getCitationEntries: unhandled dataModel "); } @@ -453,9 +453,9 @@ public void applyCitationEntries(XTextDocument doc, List citation } } break; - case JabRef53: - //xx - throw new RuntimeException("applyCitationEntries for JabRef53 is not implemented yet"); + case JabRef60: + // xx + throw new RuntimeException("applyCitationEntries for JabRef60 is not implemented yet"); default: throw new RuntimeException("applyCitationEntries: unhandled dataModel "); } From 5bc534ba5adb85b6bb7b4733cdf7192f2d806b67 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 22:08:51 +0200 Subject: [PATCH 0946/1068] cleanup for checkstyle on tests --- .../openoffice/style/OOBibStyleTest.java | 51 ++++++++----------- .../style/OOBibStyleTestHelper.java | 41 ++++----------- 2 files changed, 30 insertions(+), 62 deletions(-) diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java index bf0bdf945a4..03a0b535e34 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java @@ -11,7 +11,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -25,13 +24,10 @@ import org.jabref.model.entry.types.StandardEntryType; import org.jabref.model.entry.types.UnknownEntryType; import org.jabref.model.openoffice.ootext.OOText; -import org.jabref.model.openoffice.style.Citation; -import org.jabref.model.openoffice.style.CitationLookupResult; import org.jabref.model.openoffice.style.CitationMarkerEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; -import org.jabref.model.openoffice.style.PageInfo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -96,7 +92,7 @@ void testNumerical() throws IOException { * begin helpers */ static String runGetNumCitationMarker2a(OOBibStyle style, - List num, int minGroupingCount, boolean inList ) { + List num, int minGroupingCount, boolean inList) { return OOBibStyleTestHelper.runGetNumCitationMarker2a(style, num, minGroupingCount, inList); } @@ -125,7 +121,7 @@ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, database, uniqueLetterQ, pageInfoQ, - isFirstAppearanceOfSource ); + isFirstAppearanceOfSource); } /* @@ -145,14 +141,13 @@ static String getCitationMarker2(OOBibStyle style, inParenthesis, uniquefiers, isFirstAppearanceOfSource, - pageInfo ); + pageInfo); } /* * end helpers */ - @Test void testGetNumCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, @@ -218,27 +213,27 @@ void testGetNumCitationMarkerUndefined() throws IOException { // unresolved citations look like [??key] assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "]", runGetNumCitationMarker2b(style, 1, - numEntry("key",0,null))); + numEntry("key", 0, null))); // pageInfo is shown for unresolved citations assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; p1]", runGetNumCitationMarker2b(style, 1, - numEntry("key",0,"p1"))); + numEntry("key", 0, "p1"))); // unresolved citations sorted to the front assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 2-4]", runGetNumCitationMarker2b(style, 1, - numEntry("x4",4,""), - numEntry("x2",2,""), - numEntry("x3",3,""), - numEntry("key",0,""))); + numEntry("x4", 4, ""), + numEntry("x2", 2, ""), + numEntry("x3", 3, ""), + numEntry("key", 0, ""))); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "; 1-3]", runGetNumCitationMarker2b(style, 1, - numEntry("x1",1,""), - numEntry("x2",2,""), - numEntry("y3",3,""), - numEntry("key",0,""))); + numEntry("x1", 1, ""), + numEntry("x2", 2, ""), + numEntry("y3", 3, ""), + numEntry("key", 0, ""))); // multiple unresolved citations are not collapsed assertEquals("[" @@ -246,19 +241,16 @@ void testGetNumCitationMarkerUndefined() throws IOException { + OOBibStyle.UNDEFINED_CITATION_MARKER + "x2" + "; " + OOBibStyle.UNDEFINED_CITATION_MARKER + "x3" + "]", runGetNumCitationMarker2b(style, 1, - numEntry("x1",0,""), - numEntry("x2",0,""), - numEntry("x3",0,""))); + numEntry("x1", 0, ""), + numEntry("x2", 0, ""), + numEntry("x3", 0, ""))); /* * BIBLIOGRAPHY */ - { - CitationMarkerNumericBibEntry x = numBibEntry("key", Optional.empty()); - assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", - style.getNumCitationMarkerForBibliography(x).asString()); - } - + CitationMarkerNumericBibEntry x = numBibEntry("key", Optional.empty()); + assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", + style.getNumCitationMarkerForBibliography(x).asString()); } @Test @@ -280,7 +272,6 @@ void testGetCitProperty() throws IOException { assertTrue(journals.contains("Journal name 1")); } - @Test void testGetCitationMarker() throws IOException { OOBibStyle style = new OOBibStyle(StyleLoader.DEFAULT_NUMERICAL_STYLE_PATH, layoutFormatterPreferences); @@ -767,7 +758,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" - +"; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", + + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).asString()); @@ -795,7 +786,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { citationMarkerEntries.add(cm3); assertEquals("[Boström, Wäyrynen, Bodén, Beznosov & Kruchten, 2006a,b" - +"; Boström et al., 2006c]", + + "; Boström et al., 2006c]", style.createCitationMarker(citationMarkerEntries, true, NonUniqueCitationMarker.THROWS).asString()); diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java index c8302030fc6..9fbe9579ccb 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java @@ -1,29 +1,16 @@ package org.jabref.logic.openoffice.style; -import java.io.File; import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.jabref.logic.layout.Layout; -import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; -import org.jabref.model.entry.field.StandardField; -import org.jabref.model.entry.types.StandardEntryType; -import org.jabref.model.entry.types.UnknownEntryType; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.style.Citation; import org.jabref.model.openoffice.style.CitationLookupResult; @@ -33,15 +20,7 @@ import org.jabref.model.openoffice.style.NonUniqueCitationMarker; import org.jabref.model.openoffice.style.PageInfo; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Answers; - import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; class OOBibStyleTestHelper { /* @@ -116,7 +95,7 @@ static CitationMarkerNumericBibEntry numBibEntry(String key, Optional n * @param inList true means label for the bibliography */ static String runGetNumCitationMarker2a(OOBibStyle style, - List num, int minGroupingCount, boolean inList ) { + List num, int minGroupingCount, boolean inList) { if (inList) { if (num.size() != 1) { throw new RuntimeException("Numeric label for the bibliography with " @@ -159,7 +138,6 @@ static String runGetNumCitationMarker2b(OOBibStyle style, * end Helpers for testing style.getNumCitationMarker2 */ - /* * begin helper */ @@ -223,21 +201,20 @@ static String getCitationMarker2(OOBibStyle style, * end helper */ - static void testGetNumCitationMarkerExtra(OOBibStyle style) throws IOException { // Identical numeric entries are joined. assertEquals("[1; 2]", runGetNumCitationMarker2b(style, 3, - numEntry("x1",1,null), - numEntry("x2",2,null), - numEntry("x1",2,null), - numEntry("x2",1,null))); + numEntry("x1", 1, null), + numEntry("x2", 2, null), + numEntry("x1", 2, null), + numEntry("x2", 1, null))); // ... unless minGroupingCount <= 0 assertEquals("[1; 1; 2; 2]", runGetNumCitationMarker2b(style, 0, - numEntry("x1",1,null), - numEntry("x2",2,null), - numEntry("x1",2,null), - numEntry("x2",1,null))); + numEntry("x1", 1, null), + numEntry("x2", 2, null), + numEntry("x1", 2, null), + numEntry("x2", 1, null))); // ... or have different pageInfos assertEquals("[1; p1a; 1; p1b; 2; p2; 3]", runGetNumCitationMarker2b(style, 1, From be723d675d99a20675eec403e14e0f85600515a0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 22:10:08 +0200 Subject: [PATCH 0947/1068] describe OOTuple3 --- .../org/jabref/model/openoffice/util/OOTuple3.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java b/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java index ca324ebc4ad..3a4143f4489 100644 --- a/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java @@ -1,9 +1,21 @@ package org.jabref.model.openoffice.util; +/** + * This class allows three objects to be packed together, and later + * accessed as fields `a`, `b` and `c`. + * + * Can be used to avoid creating a new class for just this purpose. + * + * Can be useful if you do not have `Trifunction` at hand but need to + * pass three objects at a time. + * + */ public class OOTuple3 { + 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; From 1dc82bb13794fa11a8eb95c0c0a69e6182a67d4a Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 22:10:23 +0200 Subject: [PATCH 0948/1068] apply requested changes to OOResult --- .../jabref/model/openoffice/util/OOResult.java | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/util/OOResult.java b/src/main/java/org/jabref/model/openoffice/util/OOResult.java index 2be478f6d8a..1572ac4e016 100644 --- a/src/main/java/org/jabref/model/openoffice/util/OOResult.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOResult.java @@ -1,42 +1,36 @@ package org.jabref.model.openoffice.util; +import java.util.NoSuchElementException; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; /* - * error cannot be null - * result cannot be null + * 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 { + private final Optional result; private final Optional error; /** * Exactly one of the arguments should be Optional.empty() - * - * @param result - * @param error */ private OOResult(Optional result, Optional error) { this.result = result; this.error = error; } - /** - * @param result Null is not allowed. - */ public static OOResult ok(R result) { return new OOResult<>(Optional.of(result), Optional.empty()); } - /** - * @param error Null is not allowed. - */ public static OOResult error(E error) { return new OOResult<>(Optional.empty(), Optional.of(error)); } @@ -67,7 +61,7 @@ public boolean isOK() { public R get() { if (isError()) { - throw new RuntimeException("Cannot get from error"); + throw new NoSuchElementException("Cannot get from error"); } return result.get(); } From 8766098417ab30e30339a981fb40ff482adfe119 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 22:11:05 +0200 Subject: [PATCH 0949/1068] rename JabRef53 -> JabRef60 continued --- .../java/org/jabref/model/openoffice/style/OODataModel.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/style/OODataModel.java b/src/main/java/org/jabref/model/openoffice/style/OODataModel.java index 50c3a9e4842..860038ee299 100644 --- a/src/main/java/org/jabref/model/openoffice/style/OODataModel.java +++ b/src/main/java/org/jabref/model/openoffice/style/OODataModel.java @@ -15,13 +15,13 @@ public enum OODataModel { JabRef52, /** - * JabRef53: pageInfo belongs to Citation. + * JabRef60: pageInfo belongs to Citation. */ - JabRef53; + JabRef60; /** * @param pageInfo Nullable. - * @return JabRef53 style pageInfo list with pageInfo in the last slot. + * @return JabRef60 style pageInfo list with pageInfo in the last slot. */ public static List> fakePageInfos(String pageInfo, int nCitations) { List> pageInfos = new ArrayList<>(nCitations); From 4a41c117622d73eff50f3e69605d61f0e6fa3b00 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 22:11:55 +0200 Subject: [PATCH 0950/1068] use LOGGER.debug instead of debugThisFun --- .../model/openoffice/ootext/OOTextIntoOO.java | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index b9d67efcb5b..015a03383fd 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -155,17 +155,13 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) NoSuchElementException, CreationException { - final boolean debugThisFun = false; - Objects.requireNonNull(doc); Objects.requireNonNull(ootext); Objects.requireNonNull(position); String lText = OOText.toString(ootext); - if (debugThisFun) { - System.out.println(lText); - } + LOGGER.debug(lText); XText text = position.getText(); XTextCursor cursor = text.createTextCursorByRange(position); @@ -242,15 +238,11 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) //

if (value != null && !value.equals("")) { if (setParagraphStyle(cursor, value)) { - if (debugThisFun) { - // Presumably tested already: - LOGGER.warn(String.format("oo:ParaStyleName=\"%s\" failed", value)); - } + // Presumably tested already: + LOGGER.debug(String.format("oo:ParaStyleName=\"%s\" failed", value)); } } else { - if (debugThisFun) { - LOGGER.warn(String.format("oo:ParaStyleName inherited")); - } + LOGGER.debug(String.format("oo:ParaStyleName inherited")); } break; default: From cc8e60691b2cb31222834db6f5cfed71af7805a5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 22:12:36 +0200 Subject: [PATCH 0951/1068] rename s to ootext --- .../model/openoffice/ootext/OOFormat.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java index 472ca519161..2dc18fc71fd 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java @@ -3,7 +3,7 @@ public class OOFormat { /** - * Mark {@code s} as using a character locale known to OO. + * Mark {@code ootext} as using a character locale known to OO. * * @param locale language[-country[-territory]] * @@ -15,50 +15,50 @@ public class OOFormat { * vendor and browser-specific", so probably best to avoid them if possible. * */ - public static OOText setLocale(OOText s, String locale) { - return OOText.fromString(String.format("", locale) + s.asString() + ""); + public static OOText setLocale(OOText ootext, String locale) { + return OOText.fromString(String.format("", locale) + ootext.asString() + ""); } /** - * Mark {@code s} as using the character locale "zxx", which means + * Mark {@code ootext} as using the character locale "zxx", which means * "no language", "no linguistic content". * * Used around citation marks, probably to turn off spellchecking. * */ - public static OOText setLocaleNone(OOText s) { - return OOFormat.setLocale(s, "zxx"); + public static OOText setLocaleNone(OOText ootext) { + return OOFormat.setLocale(ootext, "zxx"); } /** - * Mark {@code s} using a character style {@code charStyle} + * Mark {@code ootext} using a character style {@code charStyle} * * @param charStyle Name of a character style known to OO. May be * empty for "Standard", which in turn means do not override any properties. * */ - public static OOText setCharStyle(OOText s, String charStyle) { + public static OOText setCharStyle(OOText ootext, String charStyle) { return OOText.fromString(String.format("", charStyle) - + s.asString() + + ootext.asString() + ""); } /** - * Mark {@code s} as part of a paragraph with style {@code paraStyle} + * Mark {@code ootext} as part of a paragraph with style {@code paraStyle} */ - public static OOText paragraph(OOText s, String paraStyle) { + public static OOText paragraph(OOText ootext, String paraStyle) { if (paraStyle == null || "".equals(paraStyle)) { - return paragraph(s); + return paragraph(ootext); } String startTag = String.format("

", paraStyle); - return OOText.fromString(startTag + s.asString() + "

"); + return OOText.fromString(startTag + ootext.asString() + "

"); } /** - * Mark {@code s} as part of a paragraph. + * Mark {@code ootext} as part of a paragraph. */ - public static OOText paragraph(OOText s) { - return OOText.fromString("

" + s.asString() + "

"); + public static OOText paragraph(OOText ootext) { + return OOText.fromString("

" + ootext.asString() + "

"); } /** @@ -66,8 +66,8 @@ public static OOText paragraph(OOText s) { * as label to a reference mark. */ public static OOText formatReferenceToPageNumberOfReferenceMark(String referencMarkName) { - String s = String.format("", - referencMarkName); - return OOText.fromString(s); + String string = String.format("", + referencMarkName); + return OOText.fromString(string); } } From bcda69725ebfde8a3e6f6e806f4ecd6fdafcb7e2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 22:13:07 +0200 Subject: [PATCH 0952/1068] use LOGGER.debug. debugThisFun still needed --- .../backend/NamedRangeReferenceMark.java | 61 +++++++------------ 1 file changed, 23 insertions(+), 38 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index 38ac716d9ac..7accb95f989 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -230,11 +230,11 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) String name = this.nrGetRangeName(); - final boolean debugThisFun = false; final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); + final boolean debugThisFun = false; XTextCursor full = null; String fullText = null; @@ -257,15 +257,11 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) fullText = full.getString(); - if (debugThisFun) { - System.out.printf("nrGetFillCursor: fulltext = '%s'%n", fullText); - } + LOGGER.debug("nrGetFillCursor: fulltext = '{}'", fullText); if (fullText.length() >= 2) { - if (debugThisFun) { - System.out.printf("nrGetFillCursor: (attempt: %d) fulltext.length() >= 2," - + " break loop%n", i); - } + LOGGER.debug("nrGetFillCursor: (attempt: {}) fulltext.length() >= 2," + + " break loop%n", i); break; } else { // (fullText.length() < 2) @@ -276,9 +272,8 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) throw new RuntimeException(msg); } // too short, recreate - if (true || debugThisFun) { - System.out.println("nrGetFillCursor: too short, recreate"); - } + LOGGER.warn("nrGetFillCursor: too short, recreate"); + full.setString(""); try { UnoReferenceMark.remove(doc, name); @@ -311,17 +306,12 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) beta.collapseToStart(); beta.goRight((short) 1, false); beta.goRight((short) (fullText.length() - 2), true); - if (debugThisFun) { - System.out.printf("nrGetFillCursor: beta(1) covers '%s'%n", beta.getString()); - } + LOGGER.debug("nrGetFillCursor: beta(1) covers '{}'", beta.getString()); + if (fullText.startsWith(left) && fullText.endsWith(right)) { beta.setString(""); } else { - if (debugThisFun) { - String msg = String.format("nrGetFillCursor: recreating brackets for '%s'", fullText); - // LOGGER.warn(msg); - System.out.println(msg); - } + LOGGER.debug("nrGetFillCursor: recreating brackets for '{}'", fullText); // we have at least two characters inside XTextCursor alpha = full.getText().createTextCursorByRange(full); @@ -336,47 +326,42 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) String paddingy = "y"; String paddingz = "z"; beta.setString(paddingx + left + paddingy + right + paddingz); - if (debugThisFun) { - System.out.printf("nrGetFillCursor: beta(2) covers '%s'%n", beta.getString()); - } + LOGGER.debug("nrGetFillCursor: beta(2) covers '{}'", beta.getString()); + // move beta to before the right bracket beta.collapseToEnd(); beta.goLeft((short) (rightLength + 1), false); // remove middle padding beta.goLeft((short) 1, true); - if (debugThisFun) { - System.out.printf("nrGetFillCursor: beta(3) covers '%s'%n", beta.getString()); - } + LOGGER.debug("nrGetFillCursor: beta(3) covers '{}'", beta.getString()); + // only drop paddingy later: beta.setString(""); // drop the initial character and paddingx alpha.collapseToStart(); alpha.goRight((short) (1 + 1), true); - if (debugThisFun) { - System.out.printf("nrGetFillCursor: alpha(4) covers '%s'%n", alpha.getString()); - } + LOGGER.debug("nrGetFillCursor: alpha(4) covers '{}'", alpha.getString()); + alpha.setString(""); // drop the last character and paddingz omega.collapseToEnd(); omega.goLeft((short) (1 + 1), true); - if (debugThisFun) { - System.out.printf("nrGetFillCursor: omega(5) covers '%s'%n", omega.getString()); - } + LOGGER.debug("nrGetFillCursor: omega(5) covers '{}'", omega.getString()); + omega.setString(""); // drop paddingy now - if (debugThisFun) { - System.out.printf("nrGetFillCursor: beta(6) covers '%s'%n", beta.getString()); - } + LOGGER.debug("nrGetFillCursor: beta(6) covers '{}'", beta.getString()); + beta.setString(""); // should be OK now. if (debugThisFun) { alpha.goRight(leftLength, true); - System.out.printf("nrGetFillCursor: alpha(7) covers '%s', should be '%s'%n", - alpha.getString(), left); + LOGGER.debug("nrGetFillCursor: alpha(7) covers '{}', should be '{}'", + alpha.getString(), left); omega.goLeft(rightLength, true); - System.out.printf("nrGetFillCursor: omega(8) covers '%s', should be '%s'%n", - omega.getString(), right); + LOGGER.debug("nrGetFillCursor: omega(8) covers '%s', should be '%s'%n", + omega.getString(), right); } } From 9a116f09bed2c922079900882b029715aed14d3e Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 6 Jun 2021 22:14:18 +0200 Subject: [PATCH 0953/1068] links to openoffice/README.md --- docs/README.md | 4 ++++ docs/SUMMARY.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index f9e2379ec54..21cab01baaa 100644 --- a/docs/README.md +++ b/docs/README.md @@ -51,3 +51,7 @@ For new ADRs, please use [template.md](https://github.com/JabRef/jabref/tree/3b3 Also filed as IntelliJ issue [IDEA-240250](https://youtrack.jetbrains.com/issue/IDEA-240250). +## About OpenOffice/LibreOffice + +[here](openoffice/README.md) + diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index f66102da3a8..491ecca47f7 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -19,4 +19,4 @@ * [Readings on Coding](readings-on-coding/README.md) * [Readings on JavaFX](readings-on-coding/javafx.md) * [Useful development tooling](readings-on-coding/tools.md) - +* [The OpenOffice/LibreOffice panel](openoffice/README.md) From 326d2261f014b4c74cb60c3690f5ca4e44cd468a Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 7 Jun 2021 20:38:51 +0200 Subject: [PATCH 0954/1068] prefer map(Class::method) --- .../java/org/jabref/model/openoffice/uno/UnoBookmark.java | 2 +- src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java | 2 +- .../org/jabref/model/openoffice/uno/UnoReferenceMark.java | 2 +- src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java | 2 +- .../java/org/jabref/model/openoffice/uno/UnoTextDocument.java | 4 ++-- .../java/org/jabref/model/openoffice/uno/UnoTextSection.java | 3 ++- src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java | 2 +- .../jabref/model/openoffice/uno/UnoUserDefinedProperty.java | 3 ++- 8 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java b/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java index b97618a3231..c509f6ad2eb 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java @@ -45,7 +45,7 @@ public static Optional getAnchor(XTextDocument doc, String name) XNameAccess nameAccess = getNameAccess(doc); return (UnoNameAccess.getTextContentByName(nameAccess, name) - .map(e -> e.getAnchor())); + .map(XTextContent::getAnchor)); } /** diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java index b7115feb8e1..193db1e3a68 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java @@ -19,7 +19,7 @@ private UnoCursor() { } public static Optional getViewCursor(XTextDocument doc) { return (UnoTextDocument.getCurrentController(doc) .flatMap(e -> UnoCast.optUnoQI(XTextViewCursorSupplier.class, e)) - .map(e -> e.getViewCursor())); + .map(XTextViewCursorSupplier::getViewCursor)); } /** diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java b/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java index 8185c1ffbe3..52d092f8b07 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java @@ -97,7 +97,7 @@ public static Optional getAnchor(XTextDocument doc, String name) NoDocumentException, WrappedTargetException { return (UnoReferenceMark.getAsTextContent(doc, name) - .map(e -> e.getAnchor())); + .map(XTextContent::getAnchor)); } /** diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java index 86222872597..2281bcfbd59 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java @@ -62,7 +62,7 @@ public static Optional getInternalNameOfStyle(XTextDocument doc, String throws WrappedTargetException { return (getStyleFromFamily(doc, familyName, name) - .map(e -> e.getName())); + .map(XStyle::getName)); } public static Optional getInternalNameOfParagraphStyle(XTextDocument doc, String name) diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java index 188a092465a..ae3bfdcb62d 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java @@ -59,7 +59,7 @@ public static Optional getCurrentController(XTextDocument doc) { */ public static Optional getFrameTitle(XTextDocument doc) { - Optional frame = getCurrentController(doc).map(e -> e.getFrame()); + Optional frame = getCurrentController(doc).map(XController::getFrame); if (frame.isEmpty()) { return Optional.empty(); } @@ -86,7 +86,7 @@ public static Optional getFrameTitle(XTextDocument doc) { static Optional getDocumentProperties(XTextDocument doc) { return (Optional.ofNullable(doc) .map(e -> UnoCast.unoQI(XDocumentPropertiesSupplier.class, e)) - .map(e -> e.getDocumentProperties())); + .map(XDocumentPropertiesSupplier::getDocumentProperties)); } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java index 107e7a0e018..b0ab372297e 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java @@ -8,6 +8,7 @@ import com.sun.star.lang.DisposedException; import com.sun.star.lang.IllegalArgumentException; 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; @@ -61,7 +62,7 @@ public static Optional getAnchor(XTextDocument doc, String name) XNameAccess nameAccess = getNameAccess(doc); return (UnoNameAccess.getTextContentByName(nameAccess, name) - .map(e -> e.getAnchor())); + .map(XTextContent::getAnchor)); } /** diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java index 7f41515dd1c..fda9b44b4f2 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java @@ -17,7 +17,7 @@ private UnoUndo() { } public static Optional getXUndoManager(XTextDocument doc) { // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html return (UnoCast.optUnoQI(XUndoManagerSupplier.class, doc) - .map(e -> e.getUndoManager())); + .map(XUndoManagerSupplier::getUndoManager)); } /** diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java index dd09ae4745a..47a2287f880 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java @@ -13,6 +13,7 @@ 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.IllegalArgumentException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; @@ -33,7 +34,7 @@ public class UnoUserDefinedProperty { private UnoUserDefinedProperty() { } public static Optional getPropertyContainer(XTextDocument doc) { - return UnoTextDocument.getDocumentProperties(doc).map(e -> e.getUserDefinedProperties()); + return UnoTextDocument.getDocumentProperties(doc).map(XDocumentProperties::getUserDefinedProperties); } public static List getListOfNames(XTextDocument doc) { From ce64bdf21197e412d55d74448939bc1d32262583 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 7 Jun 2021 21:15:57 +0200 Subject: [PATCH 0955/1068] renamed OOText.toString -> OOText.asString --- .../logic/openoffice/action/EditInsert.java | 2 +- .../logic/openoffice/backend/Backend52.java | 8 ++++---- .../logic/openoffice/frontend/OOFrontend.java | 2 +- .../style/OOBibStyleGetCitationMarker.java | 6 +++--- .../style/OOBibStyleGetNumCitationMarker.java | 2 +- .../style/OOProcessAuthorYearMarkers.java | 2 +- .../model/openoffice/ootext/OOText.java | 20 +++++++++---------- .../model/openoffice/ootext/OOTextIntoOO.java | 2 +- .../model/openoffice/style/PageInfo.java | 4 ++-- 9 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index 277b92bec76..42eaf2194f9 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -107,7 +107,7 @@ public static void insertCitationGroup(XTextDocument doc, citationType.inParenthesis(), NonUniqueCitationMarker.FORGIVEN)); - if ("".equals(OOText.toString(citeText))) { + if ("".equals(OOText.asString(citeText))) { citeText = OOText.fromString("[?]"); } diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 0fe444aae24..70f0c8d7ee6 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -256,7 +256,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, Optional pageInfo = PageInfo.normalizePageInfo(pageInfos.get(last)); if (pageInfo.isPresent()) { - String pageInfoString = OOText.toString(pageInfo.get()); + String pageInfoString = OOText.asString(pageInfo.get()); UnoUserDefinedProperty.createStringProperty(doc, refMarkName, pageInfoString); } else { // do not inherit from trash @@ -291,12 +291,12 @@ public CitationGroup createCitationGroup(XTextDocument doc, // Try to do something of the cgPageInfos. String cgPageInfo = (cgPageInfos.stream() .filter(pi -> pi.isPresent()) - .map(pi -> OOText.toString(pi.get())) + .map(pi -> OOText.asString(pi.get())) .distinct() .collect(Collectors.joining("; "))); int nCitations = (joinableGroup.stream() - .map(cg -> cg.numberOfCitations()) + .map(CitationGroup::numberOfCitations) .mapToInt(Integer::intValue).sum()); if ("".equals(cgPageInfo)) { cgPageInfo = null; @@ -414,7 +414,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups String context = GetContext.getCursorStringWithContext(cursor, 30, 30, true); Optional pageInfo = (cg.numberOfCitations() > 0 ? (getPageInfoFromData(cg) - .map(e -> OOText.toString(e))) + .map(e -> OOText.asString(e))) : Optional.empty()); CitationEntry entry = new CitationEntry(name, context, pageInfo); citations.add(entry); diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index fd0523a4bf8..22b9f13034e 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -209,7 +209,7 @@ public Optional healthReport(XTextDocument doc) fcursor); List result = - (sorted.stream().map(e -> e.getContent()).collect(Collectors.toList())); + (sorted.stream().map(RangeSortable::getContent).collect(Collectors.toList())); return result; } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java index ee2bba27e7e..5ed3209d547 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java @@ -439,7 +439,7 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, PageInfo.normalizePageInfo(ce.getPageInfo()); if (pageInfo.isPresent()) { pageInfoPart.append(pageInfoSeparator); - pageInfoPart.append(OOText.toString(pageInfo.get())); + pageInfoPart.append(OOText.asString(pageInfo.get())); } } @@ -650,8 +650,8 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, final CitationMarkerEntry ce1 = citationMarkerEntries.get(i - 1); final CitationMarkerEntry ce2 = citationMarkerEntries.get(i); - final String nm1 = OOText.toString(normalizedMarkers.get(i - 1)); - final String nm2 = OOText.toString(normalizedMarkers.get(i)); + final String nm1 = OOText.asString(normalizedMarkers.get(i - 1)); + final String nm2 = OOText.asString(normalizedMarkers.get(i)); final boolean isUnresolved1 = ce1.getLookupResult().isEmpty(); final boolean isUnresolved2 = ce2.getLookupResult().isEmpty(); diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java index 376c4478421..cdff6110f45 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java @@ -105,7 +105,7 @@ private static void emitBlock(List block, Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { sb.append(style.getPageInfoSeparator()); - sb.append(OOText.toString(pageInfo.get())); + sb.append(OOText.asString(pageInfo.get())); } return; } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index a55d59107a8..04c03b9c321 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -56,7 +56,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup // Map> normCitMarkerToClachingKeys = new HashMap<>(); for (CitedKey citedKey : sortedCitedKeys.values()) { - String normCitMarker = OOText.toString(citedKey.getNormalizedCitationMarker().get()); + String normCitMarker = OOText.asString(citedKey.getNormalizedCitationMarker().get()); String citationKey = citedKey.citationKey; if (!normCitMarkerToClachingKeys.containsKey(normCitMarker)) { diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java index a568a7c6e8a..3e1eafaff20 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java @@ -19,19 +19,19 @@ private OOText(String data) { } /* null input is passed through */ - public static OOText fromString(String s) { - if (s == null) { + public static OOText fromString(String string) { + if (string == null) { return null; } - return new OOText(s); + return new OOText(string); } /* null input is passed through */ - public static String toString(OOText s) { - if (s == null) { + public static String asString(OOText ootext) { + if (ootext == null) { return null; } - return s.data; + return ootext.data; } public String asString() { @@ -40,17 +40,17 @@ public String asString() { /* Object.equals */ @Override - public boolean equals(Object o) { + public boolean equals(Object object) { - if (o == this) { + if (object == this) { return true; } - if (!(o instanceof OOText)) { + if (!(object instanceof OOText)) { return false; } - OOText c = (OOText) o; + OOText c = (OOText) object; return data.equals(c.data); } diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index 015a03383fd..f8f2bbcadac 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -159,7 +159,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) Objects.requireNonNull(ootext); Objects.requireNonNull(position); - String lText = OOText.toString(ootext); + String lText = OOText.asString(ootext); LOGGER.debug(lText); diff --git a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java index 6807ecf0753..9aa4a1cef9b 100644 --- a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java +++ b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java @@ -14,10 +14,10 @@ private PageInfo() { * pageInfo normalization */ public static Optional normalizePageInfo(Optional o) { - if (o == null || o.isEmpty() || "".equals(OOText.toString(o.get()))) { + if (o == null || o.isEmpty() || "".equals(OOText.asString(o.get()))) { return Optional.empty(); } - String s = OOText.toString(o.get()); + String s = OOText.asString(o.get()); if (s.trim().equals("")) { return Optional.empty(); } From af846a31edd61c21480728f5971ce45ea4d42510 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 7 Jun 2021 21:36:53 +0200 Subject: [PATCH 0956/1068] docs/openoffice/ --- docs/openoffice/.gitignore | 2 + docs/openoffice/README.md | 5 + docs/openoffice/order-of-appearance.md | 28 +++ docs/openoffice/overview.md | 257 +++++++++++++++++++++++++ 4 files changed, 292 insertions(+) create mode 100644 docs/openoffice/.gitignore create mode 100644 docs/openoffice/README.md create mode 100644 docs/openoffice/order-of-appearance.md create mode 100644 docs/openoffice/overview.md diff --git a/docs/openoffice/.gitignore b/docs/openoffice/.gitignore new file mode 100644 index 00000000000..5c96c8016d7 --- /dev/null +++ b/docs/openoffice/.gitignore @@ -0,0 +1,2 @@ +# +*.html diff --git a/docs/openoffice/README.md b/docs/openoffice/README.md new file mode 100644 index 00000000000..97ccc6f07c8 --- /dev/null +++ b/docs/openoffice/README.md @@ -0,0 +1,5 @@ + +# OpenOffice/LibreOffice integration + +- [Overview](overview.md) + diff --git a/docs/openoffice/order-of-appearance.md b/docs/openoffice/order-of-appearance.md new file mode 100644 index 00000000000..27d9d6e7da3 --- /dev/null +++ b/docs/openoffice/order-of-appearance.md @@ -0,0 +1,28 @@ + +## Order of appearance of citation groups + +This seems trivial at first. Take the textual order of citation markers, and + +In the presence of figures, tables, footnotes/endnotes, tables with +footnotes possibly either far from the location they are referred to +in the text, or wrapped around with text it becomes obvious what is +the correct order. + +For example: + +- In a two-column layout, a text frame or figure mostly, but not fully + in the second column: shall we consider it part of the second column? + + +Technically LibreOffice allows several types of +[XTextContent](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextContent.html) +to be inserted. + +- Some of these allow text inside with further insertions. +- Many, but not all of them supports getting a "technical" insertion point or text range +through [getAnchor](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextContent.html#ae82a8b42f6b2578549b68b4483a877d3). In Libreoffice positioning both anchors and for example a frame seems hard, moving the frame +tends to also move the anchor. +- Consequence: producing an order of appearance for the citation + groups requires to handle many cases, may still turn out + insufficient and may require the user to + diff --git a/docs/openoffice/overview.md b/docs/openoffice/overview.md new file mode 100644 index 00000000000..20bd9b67dc0 --- /dev/null +++ b/docs/openoffice/overview.md @@ -0,0 +1,257 @@ + +## Overview + +This is a partial overview of the OpenOffice/LibreOffice panel and the +code behind. + +I am going to refer to OpenOffice Writer and LibreOffice Writer as +LibreOffice or LO: their UNO APIs are still mostly identical, but I +only tested with LibreOffice and differences do exist. + +- What is stored in a document, how. +- Generating citation markers and bibliography (excluding the + bibliography entries, which is delegated to the layout module) +- How to access: `JabRef/[menu:View]/[OpenOffice/LibreOffice]` to show the panel. +- The user documentation is at +[https://docs.jabref.org/cite/openofficeintegration](https://docs.jabref.org/cite/openofficeintegration) + +### Purpose + + 1. Allow the user to insert **citations** in a LibreOffice writer + document. + - Automatically format these according to some prescribed style as **citation markers**. + - Generate a **bibliography**, also formatted according to the style. + - The bibliography consists of a title (e.g. "References") and a sorted list + of formatted bibliography entries, possibly prefixed with a marker (e.g. "[1]") + + 2. Citations (actually citation groups, see below) have three types + depending on how the citation marker is intended to appear in the + text: + - **Parenthesized**: "(Smith, 2000)" + - **In-text**: "Smith (2000)" + - **Invisible**: these have a location in the document, but no + visible citation mark generated. + - This lets the user to use any form for the citation + by taking control (and responsibility) back from the style. + - In the bibliography these behave as the other two citation types. + + - These citation types correspond to `\citep{Smith2000}`, + `\citet{Smith2000}` in + [natbib](http://tug.ctan.org/macros/latex/contrib/natbib/natnotes.pdf) + and `\nocite{Smith2000}` + + 3. The citations can be augmented with a string detailing which part + of a document is cited, for example "page 11" or "chapter 2". + + Sample citation markers (with LaTeX pseudocode): + + - `\citep[page 11]{Smith2000}` "(Smith, 2000; page 11)" + - `\citet[page 11]{Smith2000}` "Smith (2000; page 11)" + - `\nocite[page 11]{Smith2000}` "" + + - This string is referred to as **`pageInfo`** in the code. + - In the GUI the labels "Cite special", "Extra information + (e.g. page number)" are used. + + 4. Citations can be grouped. + - A group of parenthesized citations share the parentheses around, + like this: "(Smith, 2000; Jones 2001)". + + - Examples with pseudocode: + - `\citep{Smith2000,Jones2001}` "(Smith, 2000; Jones 2001)" + - `\citet{Smith2000,Jones2001}` "Smith (2000); Jones (2001)" + - `\nocite{Smith2000,Jones2001}` "" + + - From the user's point of view, citation groups can be created by + 1. Selecting multiple entries in a bibliography database, then + - `[click:Cite]` or + - `[click:Cite in-text]` or + - `[click:Cite special]` or + - `[click:Insert empty citation]` in the panel. + + This method allows any of the citation types to be used. + + 2. `[click:Merge]` finds all sets of consecutive citations in the text and + replaces each with a group. + - The new code only merges consecutive parenthesized citations. + - This is inconsistent with the solution used in `[click:Cite]` + - My impression is that + - groups of in-text or invisible citations are probably not useful + - mixed groups are even less. However, with a numbered style + there is no visual difference between parenthesized and in-text + citations, the user may be left wondering why did merge not work. + - One way out could be to merge as a "parenthesized" + group. But then users switching between styles get a + surprise, we have unexpectedly overridden their choice. + - I would prefer a visible log-like warning that does not require + a click to close and lets me see multiple warnings. + Could the main window have such an area at the bottom? + - Starting with JabRef 5.3 there is also `[click:Separate]` + that breaks all groups to single citations. + - This allows moving individual citations around (between citation groups). + - (Copy does not work.) + - (Moving a citation within a group has no effect on the final output + due to sorting of citations within groups. See [Sorting within a citation group](#localOrder)) + + In order to manage single citations and groups uniformly, we + consider each citation in the document to belong to a citation + group, even if it means a group containing a single citation. + + 5. The details of how to format the bibliography and the citation markers are described + in a text file. + + - These normally use `.jstyle` extension, and I will refer to them + as jstyle files. + - See the [User documentation](https://docs.jabref.org/cite/openofficeintegration#the-style-file) + for details. + - I will refer to keywords in jstyle files as `jstyle:keyword` below. + +## Citation styles + +Four major types citation of styles can be described by a jstyle. + +- (1) `jstyle:BibTeXKeyCitations` + + - The citation markers show the citationKey. + - It is not fully implemented + - does not produce markers before the bibliography entries + - does not show pageInfo + - It is not advertised in the [User documentation](https://docs.jabref.org/cite/openofficeintegration#the-style-file). + - Its intended purpose may be + + - (likely) a proper style, with "[Smith2000]" style citation markers + - (possibly) a style for "draft mode" that + - can avoid lookup of citation markers in the database when only the + citation markers are updated + - can produce unique citation markers trivially (only needs local information) + - makes the citation keys visible to the user + - can work without knowing the order of appearance of citation groups + - In case we expect to handle larger documents, a "draft mode" + minimizing work during "click:Cite" may be useful. + +- There are two types of numbered (`jstyle:IsNumberEntries`) citation styles: + + - (2) Citations numbered in order of first appearance (`jstyle:IsSortByPosition`) + - (3) Citations numbered according to their order in the sorted bibliography + +- (4) Author-year styles + +### Sorting + +#### Sorting te bibliography + +The bibliography is sorted in (author, year, title) order + +- except for `jstyle:IsSortByPosition`, that uses the order of first + appearance of the cited sources. + +#### Sorting within a citation group + +The order of citations within a citation group is controlled by +`jstyle:MultiCiteChronological`. + + - true asks for (year, author, title) ordering, + - false for (author, year, title). + - (There is no option for "in the order provided by the user"). + +In the code I referred to this order as `localOrder`. + +This ordering is used directly in author-year citation styles. + + - The (author, year, title) order promotes discovering citations + sharing authors and year and emitting them in a shorter form. For + example as "(Smith 2000a,b)". + +For numbered styles, the citations within a group are sorted again +during generation of the citation marker, now by the numbers +themselves. This promotes discovering duplicates and ranges of +consecutive numbers, allowing for example "[1-7; 11]" to be emitted +instead of an exhaustive list of the citation numbers. + + - Note: the numbering itself is based the first sort (localOrder), + this second sorting does not override that. + - The result of the second sorting is not stored. + +#### Order of the citation groups + +The location of each citation group in the document is provided by the +user. In a text with no insets, footnotes, figures etc. this directly +provides the order. In the presence of these, it becomes more +complicated, see [Order of appearance of +citation groups](order-of-appearance.md). In the code I referred to +this order as `globalOrder`. + +#### Order of the citations + +- `globalOrder` and `localOrder` together fix the order of appearance of +citations (for author-year styles literally, for numbered styles less so). +- This also provides the order of first appearance of the cited sources. + + First appearance order of sources is used + - in `jstyle:IsSortByPosition` numbered styles + - in author-year styles: first appearance of "Smith200a" + should precede that of "Smith200b". + To achieve this, the sources get the letters + according the order of their first appearance. + - This seems to contradict the statement "The bibliography is + sorted in (author, year, title) order" above. +
It does not. As of JabRef 5.3 both are true. +
Consequence: in the references + Smith2000b may precede Smith2000a. + ([reported](https://github.com/JabRef/jabref/issues/7805)) + - Some author-year citation styles prescribe a higher threshold on + the number of authors for switching to "FirstAuthor et al." form + (`jstyle:MaxAuthors`) at the first citation of a source + (`jstyle:MaxAuthorsFirst`) + + + +### What is stored in a document (JabRef5.2) + +- Each group of citations has a reference mark. Its purposes: + + 1. The text range of the reference mark tells where to write or update the text of the citation. + 2. The name of the reference mark + - Lets us select only those reference marks that belong to us + - Encodes the citation type + - Contains the list of citation keys that belong to this group + - It may contain an extra number, to make the name unique in the document + - Format: `"JR_cite{number}_{type}_{citationKeys}"`, where + - `{number}` is either empty or an unsigned integer (it can be zero) to make the name unique + - `{type}` is 1, 2, or 3 for parenthesized, in-text and invisible + - `{citationKeys}` contains the comma-separated list of citation keys + - Examples: + - `JR_cite_1_Smith2000` (empty number part, parenthesized, single citation) + - `JR_cite0_2_Smith2000,Jones2001` (number part is 0, two citations) + - `JR_cite1_3_Smith2000,Jones2001` (number part is 1) + +- Each group of citations may have an associated pageInfo. + + - In LibreOffice, these can be found at + `[LibreOffice]/[menu:File]/[Properties]/[Custom Properties]` + - The property names are identical to the name of the reference mark + corresponding to the citation group. + - JabRef 5.2 never cleans up these, they are left around. New citations may + "pick up" these unexpectedly. + +- The bibliography, if not found, is created at the end of the document. + - The location and extent of the bibliography is marked by the Section (in LibreOffice sense) + named `"JR_bib"`. + - JabRef 5.2 also creates a bookmark named `"JR_bib_end"`, but does + not use it. During bibliography update it attempts to create it again without + removing the old bookmark. The result is a new bookmark, with a number appended to its name + (by LibreOffice, to ensure unique names of bookmarks). + +### How does it work? + +- An important limitation we have to deal with is that we (I mean the +jabref program) are only loosely coupled to the document. Between two +GUI actions we do not receive any information from LibreOffice. We do +not distinguish between the user changing a single character in the +document or rewriting everything. Getting all the information we need +from the document, including consistency checking has to fit in a +limited time frame. + + + + From cebd8ab246a9dfcf4af510427711c1daedc79313 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 7 Jun 2021 22:06:02 +0200 Subject: [PATCH 0957/1068] prefer filter(Class::method) --- src/main/java/org/jabref/gui/openoffice/OOBibBase2.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index ca8324cda2a..b3d368b79dc 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -164,7 +164,7 @@ void showDialog(String title, OOError ex) { OOVoidResult collectResults(String title, List> results) { String msg = (results.stream() - .filter(e -> e.isError()) + .filter(OOVoidResult::isError) .map(e -> e.getError().getLocalizedMessage()) .collect(Collectors.joining("\n\n"))); if (msg.isEmpty()) { From 26f21263e876381834831d19b4d3d0a2520245e0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 7 Jun 2021 22:06:48 +0200 Subject: [PATCH 0958/1068] add .PHONY targets --- Makefile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Makefile b/Makefile index 4d97fe576ab..d18e1e84b19 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,7 @@ # -*- makefile -*- +.PHONY: all assemble build build-notest clean check test run tmp-clean checkstyle + all: build # https://devdocs.jabref.org/getting-into-the-code/guidelines-for-setting-up-a-local-workspace From 555845525aec4613e78eeb0fdec558b357a574c2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 7 Jun 2021 22:07:29 +0200 Subject: [PATCH 0959/1068] overview.md --- docs/openoffice/overview.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/openoffice/overview.md b/docs/openoffice/overview.md index 20bd9b67dc0..6f180650653 100644 --- a/docs/openoffice/overview.md +++ b/docs/openoffice/overview.md @@ -244,13 +244,13 @@ citations (for author-year styles literally, for numbered styles less so). ### How does it work? -- An important limitation we have to deal with is that we (I mean the -jabref program) are only loosely coupled to the document. Between two -GUI actions we do not receive any information from LibreOffice. We do -not distinguish between the user changing a single character in the -document or rewriting everything. Getting all the information we need -from the document, including consistency checking has to fit in a -limited time frame. +- An important limitation is that we (I mean the jabref program) are +only loosely coupled to the document. Between two GUI actions we do +not receive any information from LibreOffice. We do not distinguish +between the user changing a single character in the document or +rewriting everything. Getting all the information we need from the +document, including consistency checking has to fit in a limited time +frame. From 1c9df5500fb0e877cad8bd8423c0c8d69bbb0fb4 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 8 Jun 2021 09:16:24 +0200 Subject: [PATCH 0960/1068] add .dir-locals.el --- .dir-locals.el | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .dir-locals.el diff --git a/.dir-locals.el b/.dir-locals.el new file mode 100644 index 00000000000..82f64f5cbcf --- /dev/null +++ b/.dir-locals.el @@ -0,0 +1,7 @@ +((nil . ((fill-column . 100) + )) + (c-mode . ((fill-column . 50))) + (java-mode . ((fill-column . 100) + ;; (add-hook 'java-mode-hook (lambda () (set-fill-column 120))) + )) + ) From 1aad247a7cbcc9f0344ac706c010390eb929a0af Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 8 Jun 2021 09:24:53 +0200 Subject: [PATCH 0961/1068] use less linebreaks --- .../logic/openoffice/action/EditInsert.java | 17 ++-- .../logic/openoffice/action/EditMerge.java | 56 +++++-------- .../logic/openoffice/action/EditSeparate.java | 23 ++---- .../logic/openoffice/action/ExportCited.java | 2 +- .../logic/openoffice/action/Update.java | 6 +- .../logic/openoffice/backend/Backend52.java | 29 +++---- .../logic/openoffice/backend/Codec52.java | 28 +++---- .../logic/openoffice/backend/GetContext.java | 8 +- .../NamedRangeManagerReferenceMark.java | 6 +- .../backend/NamedRangeReferenceMark.java | 82 +++++++------------ .../model/openoffice/backend/NamedRange.java | 8 +- .../model/openoffice/ootext/OOFormat.java | 22 +++-- .../model/openoffice/ootext/OOText.java | 5 +- .../model/openoffice/ootext/OOTextIntoOO.java | 29 +++---- .../rangesort/FunctionalTextViewCursor.java | 52 ++++-------- .../rangesort/RangeOverlapBetween.java | 15 ++-- .../rangesort/RangeOverlapWithin.java | 17 ++-- .../model/openoffice/rangesort/RangeSort.java | 9 +- .../openoffice/rangesort/RangeSortVisual.java | 46 +++++------ .../openoffice/rangesort/RangeSortable.java | 6 +- .../model/openoffice/style/CitationGroup.java | 9 +- .../openoffice/style/CitationGroupId.java | 3 +- .../openoffice/style/CitationGroups.java | 45 ++++------ .../style/CitationLookupResult.java | 3 +- .../openoffice/style/CitationMarkerEntry.java | 10 +-- .../style/CitationMarkerNormEntry.java | 7 +- .../model/openoffice/style/CitationPath.java | 4 +- .../model/openoffice/style/CitedKey.java | 5 +- .../openoffice/style/CompareCitation.java | 4 +- .../openoffice/style/CompareCitedKey.java | 4 +- .../style/NonUniqueCitationMarker.java | 6 +- .../model/openoffice/style/OODataModel.java | 8 +- .../model/openoffice/uno/UnoBookmark.java | 21 ++--- .../jabref/model/openoffice/uno/UnoCast.java | 3 +- .../model/openoffice/uno/UnoCrossRef.java | 16 ++-- .../model/openoffice/uno/UnoNameAccess.java | 3 +- .../jabref/model/openoffice/uno/UnoNamed.java | 30 +++---- .../openoffice/uno/UnoReferenceMark.java | 30 +++---- .../model/openoffice/uno/UnoTextSection.java | 21 ++--- .../jabref/model/openoffice/uno/UnoUndo.java | 5 +- .../uno/UnoUserDefinedProperty.java | 25 +++--- .../model/openoffice/util/OOResult.java | 5 +- .../model/openoffice/util/OOTuple3.java | 7 +- 43 files changed, 285 insertions(+), 455 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index 42eaf2194f9..6e3d7d2a8c8 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -43,28 +43,21 @@ public class EditInsert { * * In the document we store citations by their citation key. * - * If the citation key is missing, the best we can do is to notify - * the user. Or the programmer, that we cannot accept such input. + * If the citation key is missing, the best we can do is to notify the user. Or the programmer, + * that we cannot accept such input. * */ private static String insertEntryGetCitationKey(BibEntry entry) { Optional key = entry.getCitationKey(); if (key.isEmpty()) { - throw new RuntimeException("insertEntryGetCitationKey:" - + " cannot cite entries without citation key"); + throw new RuntimeException("insertEntryGetCitationKey: cannot cite entries without citation key"); } return key.get(); } - /* + /** * @param cursor Where to insert. - * - * @param sync If not empty, update citation markers and, - * depending on the embedded options, the - * bibliography. - * - * @param fcursor If sync.isPresent(), it must provide a - * FunctionalTextViewCursor. Otherwise not used. + * @param pageInfo A single pageInfo for a list of entries. This is what we get from the GUI. */ public static void insertCitationGroup(XTextDocument doc, OOFrontend fr, diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index 823610c51cf..bd639c64351 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -107,14 +107,10 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBi } private static class JoinableGroupData { - /* - * A list of consecutive citation groups only separated by spaces. - */ + /** A list of consecutive citation groups only separated by spaces. */ List group; - /* - * A cursor covering the XTextRange of each entry in group - * (and the spaces between them) - */ + + /** A cursor covering the XTextRange of each entry in group (and the spaces between them) */ XTextCursor groupCursor; JoinableGroupData(List group, XTextCursor groupCursor) { @@ -128,21 +124,21 @@ private static class ScanState { // Citation groups in the current group List currentGroup; - // A cursor that covers the Citation groups in currentGroup, - // including the space between them. - // Null if currentGroup.isEmpty() + // A cursor that covers the Citation groups in currentGroup, including the space between + // them. + // null if currentGroup.isEmpty() XTextCursor currentGroupCursor; // A cursor starting at the end of the last CitationGroup in - // currentGroup. Null if currentGroup.isEmpty() + // currentGroup. null if currentGroup.isEmpty() XTextCursor cursorBetween; // The last element of currentGroup. - // Null if currentGroup.isEmpty() + // null if currentGroup.isEmpty() CitationGroup prev; // The XTextRange for prev. - // Null if currentGroup.isEmpty() + // null if currentGroup.isEmpty() XTextRange prevRange; ScanState() { @@ -164,9 +160,8 @@ void reset() { * @param cg The CitationGroup to test * @param currentRange The XTextRange corresponding to cg. * - * @return false if cannot add, true if can. If returned true, - * then state.cursorBetween and state.currentGroupCursor are - * expanded to end at the start of currentRange. + * @return false if cannot add, true if can. If returned true, then state.cursorBetween and + * state.currentGroupCursor are expanded to end at the start of currentRange. */ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextRange currentRange) { @@ -186,8 +181,7 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR if (state.prev != null) { - // Even if we combine AUTHORYEAR_INTEXT citations, we - // would not mix them with AUTHORYEAR_PAR + // Even if we combine AUTHORYEAR_INTEXT citations, we would not mix them with AUTHORYEAR_PAR if (cg.citationType != state.prev.citationType) { return false; } @@ -196,8 +190,7 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR return false; } - // Sanity check: the current range should start later than - // the previous. + // Sanity check: the current range should start later than the previous. int textOrder = UnoTextRange.compareStarts(state.prevRange, currentRange); if (textOrder != (-1)) { String msg = @@ -208,8 +201,7 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR currentRange.getString(), ((textOrder == 0) ? "they start at the same position" - : ("the start of the latter precedes" - + " the start of the first"))); + : "the start of the latter precedes the start of the first")); LOGGER.warn(msg); return false; } @@ -224,14 +216,13 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { - String msg = ("MergeCitationGroups:" - + " cursorBetween.end != currentGroupCursor.end"); + String msg = ("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end"); throw new RuntimeException(msg); } /* - * Try to expand state.currentGroupCursor and state.cursorBetween by going right - * to reach rangeStart. + * Try to expand state.currentGroupCursor and state.cursorBetween by going right to reach + * rangeStart. */ XTextRange rangeStart = currentRange.getStart(); boolean couldExpand = true; @@ -257,12 +248,10 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR // These two should move in sync: if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { - String msg = ("MergeCitationGroups:" - + " cursorBetween.end != currentGroupCursor.end" - + " (during expand)"); + String msg = ("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end (during expand)"); throw new RuntimeException(msg); } - } // while + } if (!couldExpand) { return false; @@ -321,9 +310,7 @@ private static List scan(XTextDocument doc, OOFrontend fr) WrappedTargetException { List result = new ArrayList<>(); - List cgs = - fr.getCitationGroupsSortedWithinPartitions(doc, - false /* mapFootnotesToFootnoteMarks */); + List cgs = fr.getCitationGroupsSortedWithinPartitions(doc, false /* mapFootnotesToFootnoteMarks */); if (cgs.isEmpty()) { return result; } @@ -341,8 +328,7 @@ private static List scan(XTextDocument doc, OOFrontend fr) boolean addToGroup = checkAddToGroup(state, cg, currentRange); /* - * Even if we do not add it to an existing group, - * we might use it to start a new group. + * Even if we do not add it to an existing group, we might use it to start a new group. * * Can it start a new group? */ diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index 31c23ed52d0..76774ef90fe 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -49,10 +49,6 @@ public static boolean separateCitations(XTextDocument doc, boolean madeModifications = false; - // To reduce surprises in JabRef52 mode, impose localOrder to - // decide the visually last Citation in the group. Unless the - // style changed since refresh this is the last on the screen - // as well. fr.citationGroups.lookupCitations(databases); fr.citationGroups.imposeLocalOrder(OOProcess.comparatorForMulticite(style)); @@ -82,16 +78,15 @@ public static boolean separateCitations(XTextDocument doc, boolean insertSpaceAfter = (i != last); Citation cit = cits.get(i); - UpdateCitationMarkers.createAndFillCitationGroup( - fr, - doc, - List.of(cit.citationKey), - List.of(cit.getPageInfo()), - cg.citationType, - OOText.fromString(cit.citationKey), - textCursor, - style, - insertSpaceAfter); + UpdateCitationMarkers.createAndFillCitationGroup(fr, + doc, + List.of(cit.citationKey), + List.of(cit.getPageInfo()), + cg.citationType, + OOText.fromString(cit.citationKey), + textCursor, + style, + insertSpaceAfter); textCursor.collapseToEnd(); } diff --git a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java index 8d344688c68..ef7985d666a 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java @@ -41,7 +41,7 @@ public static class GenerateDatabaseResult { * If a key is not found, it is added to result.unresolvedKeys * * Cross references (in StandardField.CROSSREF) are followed (not recursively): - * if the referenced entry is found, it is included in the result. + * If the referenced entry is found, it is included in the result. * If it is not found, it is silently ignored. */ public static GenerateDatabaseResult generateDatabase(XTextDocument doc, List databases) diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index 151e4b6575b..675afb2a79f 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -20,13 +20,13 @@ import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; -/* +/** * Update document: citation marks and bibliography */ public class Update { - /* - * @return unresolvedKeys + /** + * @return the list of unresolved citation keys */ private static List updateDocument(XTextDocument doc, OOFrontend fr, diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 70f0c8d7ee6..a3112389d80 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -67,8 +67,8 @@ public List getJabRefReferenceMarkNames(XTextDocument doc) } /** - * Names of custom properties belonging to us, but without a - * corresponding reference mark. These can be deleted. + * Names of custom properties belonging to us, but without a corresponding reference mark. + * These can be deleted. * * @param citationGroupNames These are the names that are used. * @@ -178,16 +178,14 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str } /** - * Create a reference mark with the given name, at the - * end of position. + * Create a reference mark with the given name, at the end of position. * - * On return {@code position} is collapsed, and is after the - * inserted space, or at the end of the reference mark. + * On return {@code position} is collapsed, and is after the inserted space, or at the end of + * the reference mark. * * @param position Collapsed to its end. - * @param insertSpaceAfter We insert a space after the mark, that - * carries on format of characters from - * the original position. + * @param insertSpaceAfter We insert a space after the mark, that carries on format of + * characters from the original position. */ public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, @@ -274,11 +272,10 @@ public CitationGroup createCitationGroup(XTextDocument doc, } /** - * @return A list with a nullable pageInfo entry for each citation in - * joinableGroups. + * @return A list with a nullable pageInfo entry for each citation in joinableGroups. * - * TODO: JabRef52 combinePageInfos is not reversible. Should warn - * user to check the result. Or ask what to do. + * TODO: JabRef52 combinePageInfos is not reversible. Should warn user to check the result. Or + * ask what to do. */ public static List> combinePageInfosCommon(OODataModel dataModel, List joinableGroup) { @@ -346,9 +343,7 @@ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) } /** - * * @return Optional.empty if the reference mark is missing. - * */ public Optional getMarkRange(CitationGroup cg, XTextDocument doc) throws @@ -360,8 +355,8 @@ public Optional getMarkRange(CitationGroup cg, XTextDocument doc) } /** - * Cursor for the reference marks as is, not prepared for filling, - * but does not need cleanFillCursorForCitationGroup either. + * Cursor for the reference marks as is: not prepared for filling, but does not need + * cleanFillCursorForCitationGroup either. */ public Optional getRawCursorForCitationGroup(CitationGroup cg, XTextDocument doc) throws diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index 352df27cdeb..8a8b6aa6ff2 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -16,7 +16,6 @@ * How and what is encoded in a mark names. * * - pageInfo does not appear here. It is not encoded in the mark name. - * - Does not depend on the type of marks (reference mark of bookmark) used. */ class Codec52 { private static final String BIB_CITATION = "JR_cite"; @@ -27,7 +26,6 @@ class Codec52 { /** * This is what we get back from parsing a refMarkName. - * */ public static class ParsedMarkName { /** "", "0", "1" ... */ @@ -46,9 +44,8 @@ public static class ParsedMarkName { } } - /* - * Integer representation was written into the document in - * JabRef52, keep it for compatibility. + /** + * Integer representation was written into the document in JabRef52, keep it for compatibility. */ public static CitationType CitationTypeFromInt(int i) { switch (i) { @@ -77,16 +74,13 @@ public static int CitationTypeToInt(CitationType i) { } /** - * Produce a reference mark name for JabRef for the given citation - * key and citationType that does not yet appear among the reference - * marks of the document. + * Produce a reference mark name for JabRef for the given citation key and citationType that + * does not yet appear among the reference marks of the document. * * @param bibtexKey The citation key. - * @param citationType Encodes the effect of withText and - * inParenthesis options. + * @param citationType Encodes the effect of withText and inParenthesis options. * - * The first occurrence of bibtexKey gets no serial number, the - * second gets 0, the third 1 ... + * The first occurrence of bibtexKey gets no serial number, the second gets 0, the third 1 ... * * Or the first unused in this series, after removals. */ @@ -97,10 +91,10 @@ public static String getUniqueMarkName(Set usedNames, NoDocumentException { int i = 0; - int j = CitationTypeToInt(citationType); - String name = BIB_CITATION + '_' + j + '_' + bibtexKey; + int citTypeCode = CitationTypeToInt(citationType); + String name = BIB_CITATION + '_' + citTypeCode + '_' + bibtexKey; while (usedNames.contains(name)) { - name = BIB_CITATION + i + '_' + j + '_' + bibtexKey; + name = BIB_CITATION + i + '_' + citTypeCode + '_' + bibtexKey; i++; } return name; @@ -121,8 +115,8 @@ public static Optional parseMarkName(String refMarkName) { List keys = Arrays.asList(citeMatcher.group(3).split(",")); String i = citeMatcher.group(1); - int j = Integer.parseInt(citeMatcher.group(2)); - CitationType citationType = CitationTypeFromInt(j); + int citTypeCode = Integer.parseInt(citeMatcher.group(2)); + CitationType citationType = CitationTypeFromInt(citTypeCode); return (Optional.of(new Codec52.ParsedMarkName(i, citationType, keys))); } diff --git a/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java b/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java index 468d630e756..4cde12ad236 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java @@ -27,8 +27,8 @@ private GetContext() { * @param cursor * @param charBefore Number of characters requested. * @param charAfter Number of characters requested. - * @param htmlMarkup If true, the text belonging to the - * reference mark is surrounded by bold html tag. + * @param htmlMarkup If true, the text belonging to the reference mark is surrounded by bold + * html tag. * */ public static String getCursorStringWithContext(XTextCursor cursor, @@ -46,8 +46,8 @@ public static String getCursorStringWithContext(XTextCursor cursor, for (int i = 0; i < charBefore; i++) { try { cursor.goLeft((short) 1, true); - // If we are close to charBefore and see a space, - // then cut here. Might avoid cutting a word in half. + // If we are close to charBefore and see a space, then cut here. Might avoid cutting + // a word in half. if ((i >= (charBefore - flex)) && Character.isWhitespace(cursor.getString().charAt(0))) { break; diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java index 157dd87cf0c..d82ad08378e 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java @@ -23,11 +23,7 @@ public NamedRange nrmCreate(XTextDocument doc, boolean withoutBrackets) throws CreationException { - return NamedRangeReferenceMark.create(doc, - refMarkName, - position, - insertSpaceAfter, - withoutBrackets); + return NamedRangeReferenceMark.create(doc, refMarkName, position, insertSpaceAfter, withoutBrackets); } @Override diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index 7accb95f989..ad3a29cdb7a 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -47,11 +47,11 @@ String getId() { } /** - * Insert {@code n} spaces in a way that reference - * marks just before or just after the cursor are not affected. + * Insert {@code n} spaces in a way that reference marks just before or just after the cursor + * are not affected. * - * This is based on the observation, that starting two - * new paragraphs separates us from a reference mark on either side. + * This is based on the observation, that starting two new paragraphs separates us from + * reference marks on either side. * * The pattern used is: * {@code safeInsertSpaces(n): para, para, left, space(n), right-delete, left(n), left-delete} @@ -61,8 +61,6 @@ String getId() { * * @return a new cursor, covering the just-inserted spaces. * - * This could be generalized to insert arbitrary text safely - * between two reference marks. But we do not need that now. */ private static XTextCursor safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { // Start with an empty cursor at position.getStart(); @@ -129,19 +127,14 @@ static NamedRangeReferenceMark create(XTextDocument doc, throws CreationException { - createReprInDocument(doc, - refMarkName, - position, - insertSpaceAfter, - withoutBrackets); + createReprInDocument(doc, refMarkName, position, insertSpaceAfter, withoutBrackets); return new NamedRangeReferenceMark(refMarkName); } /** * @return Optional.empty if there is no corresponding range. */ - static Optional getFromDocument(XTextDocument doc, - String refMarkName) + static Optional getFromDocument(XTextDocument doc, String refMarkName) throws NoDocumentException, WrappedTargetException { @@ -185,11 +178,11 @@ public Optional nrGetMarkRange(XTextDocument doc) } /** - * Cursor for the reference marks as is, not prepared for filling, - * but does not need nrCleanFillCursor either. + * Cursor for the reference marks as is, not prepared for filling, but does not need + * nrCleanFillCursor either. * * @return Optional.empty() if reference mark is missing from the document, - * otherwise an XTextCursor for getMarkRange + * otherwise an XTextCursor for getMarkRange * * See: getRawCursorForCitationGroup */ @@ -242,10 +235,7 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) Optional markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name); if (markAsTextContent.isEmpty()) { - String msg = String.format("nrGetFillCursor:" - + " markAsTextContent(%s).isEmpty (attempt %d)", - name, - i); + String msg = String.format("nrGetFillCursor: markAsTextContent(%s).isEmpty (attempt %d)", name, i); throw new RuntimeException(msg); } @@ -260,15 +250,12 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) LOGGER.debug("nrGetFillCursor: fulltext = '{}'", fullText); if (fullText.length() >= 2) { - LOGGER.debug("nrGetFillCursor: (attempt: {}) fulltext.length() >= 2," - + " break loop%n", i); + LOGGER.debug("nrGetFillCursor: (attempt: {}) fulltext.length() >= 2, break loop%n", i); break; } else { // (fullText.length() < 2) if (i == 2) { - String msg = String.format("nrGetFillCursor:" - + " (fullText.length() < 2) (attempt %d)", - i); + String msg = String.format("nrGetFillCursor: (fullText.length() < 2) (attempt %d)", i); throw new RuntimeException(msg); } // too short, recreate @@ -278,16 +265,13 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) try { UnoReferenceMark.remove(doc, name); } catch (NoSuchElementException ex) { - String msg = String.format("nrGetFillCursor got NoSuchElementException" - + " for '%s'", - name); + String msg = String.format("nrGetFillCursor got NoSuchElementException for '%s'", name); LOGGER.warn(msg); } - createReprInDocument(doc, - name, - full, - false, /* insertSpaceAfter */ - false /* withoutBrackets */); + + final boolean insertSpaceAfter = false; + final boolean withoutBrackets = false; + createReprInDocument(doc, name, full, insertSpaceAfter, withoutBrackets); } } @@ -357,11 +341,9 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) // should be OK now. if (debugThisFun) { alpha.goRight(leftLength, true); - LOGGER.debug("nrGetFillCursor: alpha(7) covers '{}', should be '{}'", - alpha.getString(), left); + LOGGER.debug("nrGetFillCursor: alpha(7) covers '{}', should be '{}'", alpha.getString(), left); omega.goLeft(rightLength, true); - LOGGER.debug("nrGetFillCursor: omega(8) covers '%s', should be '%s'%n", - omega.getString(), right); + LOGGER.debug("nrGetFillCursor: omega(8) covers '%s', should be '%s'%n", omega.getString(), right); } } @@ -388,8 +370,7 @@ public static void checkFillCursor(XTextCursor cursor) { alpha.goLeft(leftLength, true); if (!left.equals(alpha.getString())) { String msg = String.format("checkFillCursor:" - + " ('%s') is not prefixed with" - + " REFERENCE_MARK_LEFT_BRACKET, has '%s'", + + " ('%s') is not prefixed with REFERENCE_MARK_LEFT_BRACKET, has '%s'", cursor.getString(), alpha.getString()); throw new RuntimeException(msg); } @@ -399,8 +380,7 @@ public static void checkFillCursor(XTextCursor cursor) { omega.goRight(rightLength, true); if (!right.equals(omega.getString())) { String msg = String.format("checkFillCursor:" - + " ('%s') is not followed by" - + " REFERENCE_MARK_RIGHT_BRACKET, has '%s'", + + " ('%s') is not followed by REFERENCE_MARK_RIGHT_BRACKET, has '%s'", cursor.getString(), omega.getString()); throw new RuntimeException(msg); } @@ -408,8 +388,8 @@ public static void checkFillCursor(XTextCursor cursor) { } /** - * Remove brackets, but if the result would become empty, leave - * them; if the result would be a single characer, leave the left bracket. + * Remove brackets, but if the result would become empty, leave them; if the result would be a + * single characer, leave the left bracket. * * See: cleanFillCursorForCitationGroup */ @@ -420,13 +400,11 @@ public void nrCleanFillCursor(XTextDocument doc) WrappedTargetException, CreationException { - // alwaysRemoveBrackets : full compatibility with JabRef 5.2: - // brackets are temporary, only exist between nrGetFillCursor - // and nrCleanFillCursor. + // alwaysRemoveBrackets : full compatibility with JabRef 5.2: brackets are temporary, only + // exist between nrGetFillCursor and nrCleanFillCursor. final boolean alwaysRemoveBrackets = false; - // removeBracketsFromEmpty is intended to force removal if we - // are working on an "Empty citation" (INVISIBLE_CIT). + // removeBracketsFromEmpty is intended to force removal if we are working on an "Empty citation" (INVISIBLE_CIT). final boolean removeBracketsFromEmpty = false; final String left = REFERENCE_MARK_LEFT_BRACKET; @@ -441,16 +419,12 @@ public void nrCleanFillCursor(XTextDocument doc) final int fullTextLength = fullText.length(); if (!fullText.startsWith(left)) { - String msg = String.format("nrCleanFillCursor:" - + " (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", - name); + String msg = String.format("nrCleanFillCursor: (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", name); throw new RuntimeException(msg); } if (!fullText.endsWith(right)) { - String msg = String.format("nrCleanFillCursor:" - + " (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", - name); + String msg = String.format("nrCleanFillCursor: (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", name); throw new RuntimeException(msg); } diff --git a/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java b/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java index e5c54773b07..d8e1832b6ef 100644 --- a/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java +++ b/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java @@ -24,8 +24,8 @@ public Optional nrGetMarkRange(XTextDocument doc) WrappedTargetException; /** - * Cursor for the reference marks as is, not prepared for filling, - * but does not need nrCleanFillCursor either. + * Cursor for the reference marks as is, not prepared for filling, but does not need + * nrCleanFillCursor either. */ public Optional nrGetRawCursor(XTextDocument doc) throws @@ -44,8 +44,8 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) CreationException; /** - * Remove brackets, but if the result would become empty, leave - * them; if the result would be a single characer, leave the left bracket. + * Remove brackets, but if the result would become empty, leave them; if the result would be a + * single characer, leave the left bracket. * */ public void nrCleanFillCursor(XTextDocument doc) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java index 2dc18fc71fd..c452abe3080 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java @@ -11,8 +11,8 @@ public class OOFormat { * * The country part is optional. * - * The territory part is not only optional, the allowed "codes are - * vendor and browser-specific", so probably best to avoid them if possible. + * The territory part is not only optional, the allowed "codes are vendor and browser-specific", + * so probably best to avoid them if possible. * */ public static OOText setLocale(OOText ootext, String locale) { @@ -20,8 +20,8 @@ public static OOText setLocale(OOText ootext, String locale) { } /** - * Mark {@code ootext} as using the character locale "zxx", which means - * "no language", "no linguistic content". + * Mark {@code ootext} as using the character locale "zxx", which means "no language", "no + * linguistic content". * * Used around citation marks, probably to turn off spellchecking. * @@ -33,14 +33,14 @@ public static OOText setLocaleNone(OOText ootext) { /** * Mark {@code ootext} using a character style {@code charStyle} * - * @param charStyle Name of a character style known to OO. May be - * empty for "Standard", which in turn means do not override any properties. + * @param charStyle Name of a character style known to OO. May be empty for "Standard", which in + * turn means do not override any properties. * */ public static OOText setCharStyle(OOText ootext, String charStyle) { return OOText.fromString(String.format("", charStyle) - + ootext.asString() - + ""); + + ootext.asString() + + ""); } /** @@ -62,12 +62,10 @@ public static OOText paragraph(OOText ootext) { } /** - * Format an OO cross-reference showing the target's page number - * as label to a reference mark. + * Format an OO cross-reference showing the target's page number as label to a reference mark. */ public static OOText formatReferenceToPageNumberOfReferenceMark(String referencMarkName) { - String string = String.format("", - referencMarkName); + String string = String.format("", referencMarkName); return OOText.fromString(string); } } diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java index 3e1eafaff20..f7d093cf30f 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java @@ -5,9 +5,8 @@ /** * Text with HTML-like markup as understood by OOTextIntoOO.write * - * Some of the tags can be added using OOFormat methods. Others come - * from the layout engine, either by interpreting LaTeX markup or from - * settings in the jstyle file. + * Some of the tags can be added using OOFormat methods. Others come from the layout engine, either + * by interpreting LaTeX markup or from settings in the jstyle file. */ public class OOText { diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index f8f2bbcadac..05e51bfd42f 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -471,10 +471,9 @@ static class MyPropertyStack { final String[] goodNames; /** - * Maintain a stack of layers, each containing a description - * of the desired state of properties. Each description is an - * ArrayList of property values, Optional.empty() encoding - * "not directly set". + * Maintain a stack of layers, each containing a description of the desired state of + * properties. Each description is an ArrayList of property values, Optional.empty() + * encoding "not directly set". */ final Stack>> layers; @@ -507,8 +506,7 @@ static class MyPropertyStack { goodNames[ entry.getValue() ] = entry.getKey(); } - // XMultiPropertySet.setPropertyValues() - // requires alphabetically sorted property names. + // XMultiPropertySet.setPropertyValues() requires alphabetically sorted property names. // We adjust here: Arrays.sort(goodNames); for (int i = 0; i < goodSize; i++) { @@ -539,9 +537,8 @@ static class MyPropertyStack { } /** - * Given a list of property name, property value pairs, - * construct and push a new layer describing the intended - * state after these have been applied. + * Given a list of property name, property value pairs, construct and push a new layer + * describing the intended state after these have been applied. * * Opening tags usually call this. */ @@ -574,6 +571,7 @@ void popLayer() { /** * Apply the current desired formatting state to a cursor. + * * The idea is to minimize the number of calls to OpenOffice. */ void apply(XTextCursor cursor) { @@ -640,9 +638,9 @@ private static List> parseAttributes(String s) { } /* - * We rely on property values being either DIRECT_VALUE or - * DEFAULT_VALUE (not AMBIGUOUS_VALUE). If the cursor covers a homogeneous region, - * or is collapsed, then this is true. + * We rely on property values being either DIRECT_VALUE or DEFAULT_VALUE (not + * AMBIGUOUS_VALUE). If the cursor covers a homogeneous region, or is collapsed, then this is + * true. */ private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) throws @@ -650,8 +648,7 @@ private static boolean isPropertyDefault(XTextCursor cursor, String propertyName XPropertyState xPropertyState = UnoCast.unoQI(XPropertyState.class, cursor); PropertyState state = xPropertyState.getPropertyState(propertyName); if (state == PropertyState.AMBIGUOUS_VALUE) { - throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE" - + " (expected properties for a homogeneous cursor)"); + throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE (expected properties for a homogeneous cursor)"); } return state == PropertyState.DEFAULT_VALUE; } @@ -727,8 +724,8 @@ private static List> setCharLocale(String value) { /* * SuperScript and SubScript. * - * @param relative If true, calculate the new values relative to - * the current values. This allows subscript-in-superscript. + * @param relative If true, calculate the new values relative to the current values. This allows + * subscript-in-superscript. */ private static List> setCharEscapement(Optional value, Optional height, diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java b/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java index 3f780274b0f..e08a7f4a2ad 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java @@ -13,23 +13,21 @@ import com.sun.star.text.XTextViewCursor; /* - * A problem with XTextViewCursor: if it is not in text, then we get a - * crippled version that does not support viewCursor.getStart() or - * viewCursor.gotoRange(range,false), and will throw an exception - * instead. + * A problem with XTextViewCursor: if it is not in text, then we get a crippled version that does + * not support viewCursor.getStart() or viewCursor.gotoRange(range,false), and will throw an + * exception instead. * - * Here we manipulate the cursor via XSelectionSupplier.getSelection and - * XSelectionSupplier.select to move it to the text. + * Here we manipulate the cursor via XSelectionSupplier.getSelection and XSelectionSupplier.select + * to move it to the text. * * Seems to work when the user selected a frame or image. * In these cases restoring the selection works, too. * - * When the cursor is in a comment (referred to as "annotation" in OO - * API) then initialSelection is null, and select() fails to - * get a functional viewCursor. + * When the cursor is in a comment (referred to as "annotation" in OO API) then initialSelection is + * null, and select() fails to get a functional viewCursor. * - * If FunctionalTextViewCursor.get() reports error, we have to ask the - * user to move the cursor into the text part of the document. + * If FunctionalTextViewCursor.get() reports error, we have to ask the user to move the cursor into + * the text part of the document. * * Usage: * @@ -45,19 +43,13 @@ */ public class FunctionalTextViewCursor { - /* - * The initial position of the cursor or null. - */ + /* The initial position of the cursor or null. */ private XTextRange initialPosition; - /* - * The initial selection in the document or null. - */ + /* The initial selection in the document or null. */ private XServiceInfo initialSelection; - /* - * The view cursor, potentially moved from its original location. - */ + /* The view cursor, potentially moved from its original location. */ private XTextViewCursor viewCursor; private FunctionalTextViewCursor(XTextRange initialPosition, @@ -71,12 +63,10 @@ private FunctionalTextViewCursor(XTextRange initialPosition, /* * Get a functional XTextViewCursor or an error message. * - * The cursor position may differ from the location - * provided by the user. + * The cursor position may differ from the location provided by the user. * - * On failure the constructor restores the selection. On success, - * the caller may want to call instance.restore() after finished - * using the cursor. + * On failure the constructor restores the selection. On success, the caller may want to call + * instance.restore() after finished using the cursor. */ public static OOResult get(XTextDocument doc) { @@ -89,9 +79,7 @@ public static OOResult get(XTextDocument doc) try { initialPosition = UnoCursor.createTextCursorByRange(viewCursor); viewCursor.getStart(); - return OOResult.ok(new FunctionalTextViewCursor(initialPosition, - initialSelection, - viewCursor)); + return OOResult.ok(new FunctionalTextViewCursor(initialPosition, initialSelection, viewCursor)); } catch (com.sun.star.uno.RuntimeException ex) { // bad cursor viewCursor = null; @@ -100,8 +88,7 @@ public static OOResult get(XTextDocument doc) } if (initialSelection == null) { - String errorMessage = ("Selection is not available:" - + " cannot provide a functional view cursor"); + String errorMessage = ("Selection is not available: cannot provide a functional view cursor"); return OOResult.error(errorMessage); } else if (!Arrays.stream(initialSelection.getSupportedServiceNames()) .anyMatch("com.sun.star.text.TextRanges"::equals)) { @@ -149,10 +136,7 @@ private static void restore(XTextDocument doc, } } - /* - * Restore initial state of viewCursor (possibly by restoring - * selection) if possible. - */ + /* Restore initial state of viewCursor (possibly by restoring selection) if possible. */ public void restore(XTextDocument doc) { FunctionalTextViewCursor.restore(doc, initialPosition, initialSelection); } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java index 35d2d006fab..152483c585c 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java @@ -19,7 +19,8 @@ private RangeOverlapBetween() { } /** * Check for any overlap between two sets of XTextRange values. * - * Assume fewHolders is small (usually 1 elements for checking the cursor) + * Assume fewHolders is small (usually a single element, for checking the cursor) + * * Returns on first problem found. */ public static @@ -70,13 +71,13 @@ List> findFirst(XTextDocument doc, boolean equal = UnoTextRange.compareStartsThenEnds(aRange, bRange) == 0; boolean touching = (abEndToStart == 0 || baEndToStart == 0); - // In case of two equal collapsed ranges there is an - // ambiguity : TOUCH or EQUAL_RANGE ? + // In case of two equal collapsed ranges there is an ambiguity : TOUCH or + // EQUAL_RANGE ? + // // We return EQUAL_RANGE - RangeOverlapKind kind = - (equal ? RangeOverlapKind.EQUAL_RANGE - : (touching ? RangeOverlapKind.TOUCH - : RangeOverlapKind.OVERLAP)); + RangeOverlapKind kind = (equal ? RangeOverlapKind.EQUAL_RANGE + : (touching ? RangeOverlapKind.TOUCH + : RangeOverlapKind.OVERLAP)); List valuesForOverlappingRanges = new ArrayList<>(); valuesForOverlappingRanges.add(aHolder); diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java index 62ee6d82ca0..b5015fca69d 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java @@ -15,17 +15,15 @@ public class RangeOverlapWithin { private RangeOverlapWithin() { } /** - * Report identical, overlapping or touching ranges between - * elements of rangeHolders. + * Report identical, overlapping or touching ranges between elements of rangeHolders. * - * For overlapping and touching, only report consecutive ranges - * and only with a single sample of otherwise identical ranges. + * For overlapping and touching, only report consecutive ranges and only with a single sample of + * otherwise identical ranges. * * @param reportAtMost Limit the number of records returned to atMost. * Zero {@code reportAtMost} means no limit. * - * @param includeTouching Should the result contain ranges - * sharing only a boundary? + * @param includeTouching Should the result contain ranges sharing only a boundary? */ public static List> findOverlappingRanges(XTextDocument doc, @@ -43,14 +41,13 @@ List> findOverlappingRanges(XTextDocument doc, /** * Report identical, overlapping or touching ranges. * - * For overlapping and touching, only report consecutive ranges - * and only with a single sample of otherwise identical ranges. + * For overlapping and touching, only report consecutive ranges and only with a single sample of + * otherwise identical ranges. * * @param atMost Limit the number of records returned to atMost. * Zero {@code atMost} means no limit. * - * @param includeTouching Should the result contain ranges - * sharing only a boundary? + * @param includeTouching Should the result contain ranges sharing only a boundary? */ public static List> findOverlappingRanges(RangeSort.RangePartitions input, diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java index 2f5daa0e1aa..98573e780f0 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -35,8 +35,7 @@ public int compare(RangeHolder a, RangeHolder b) { } } - public static - void sortWithinPartition(List rangeHolders) { + public static void sortWithinPartition(List rangeHolders) { if (rangeHolders.isEmpty()) { return; } @@ -70,8 +69,7 @@ public List> getPartitions() { } } - public static - RangePartitions partitionRanges(List holders) { + public static RangePartitions partitionRanges(List holders) { RangePartitions result = new RangePartitions<>(); for (V holder : holders) { result.add(holder); @@ -79,8 +77,7 @@ RangePartitions partitionRanges(List holders) { return result; } - public static - RangePartitions partitionAndSortRanges(List holders) { + public static RangePartitions partitionAndSortRanges(List holders) { RangePartitions result = partitionRanges(holders); for (List partition : result.getPartitions()) { sortWithinPartition(partition); diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index 2131c3cecb9..cadbada7dc1 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -21,11 +21,10 @@ * * Requires functional XTextViewCursor. * - * Problem: for multicolumn layout and when viewing pages side-by-side - * in LO, the (top-down,left-to-right) order interpreted - * as-on-the-screen: an XTextRange at the top of the second - * column or second page is sorted before one at the bottom - * of the first column of the first page. + * Problem: for multicolumn layout and when viewing pages side-by-side in LO, the + * (top-down,left-to-right) order interpreted as-on-the-screen: an XTextRange at the top of + * the second column or second page is sorted before an XTextRange at the bottom of the + * first column of the first page. */ public class RangeSortVisual { @@ -36,8 +35,7 @@ public class RangeSortVisual { * * Requires a functional {@code XTextViewCursor}. * - * @return The input, sorted by the elements XTextRange and - * getIndexInPosition. + * @return The input, sorted by the elements XTextRange and getIndexInPosition. */ public static List> visualSort(List> inputs, XTextDocument doc, @@ -49,12 +47,9 @@ public static List> visualSort(List> input final int inputSize = inputs.size(); if (UnoScreenRefresh.hasControllersLocked(doc)) { - LOGGER.warn("visualSort:" - + " with ControllersLocked, viewCursor.gotoRange" - + " is probably useless"); - throw new RuntimeException("visualSort:" - + " with ControllersLocked, viewCursor.gotoRange" - + " is probably useless"); + final String msg = "visualSort: with ControllersLocked, viewCursor.gotoRange is probably useless"; + LOGGER.warn(msg); + throw new RuntimeException(msg); } XTextViewCursor viewCursor = fcursor.getViewCursor(); @@ -62,8 +57,7 @@ public static List> visualSort(List> input // find coordinates List positions = new ArrayList<>(inputSize); for (RangeSortable v : inputs) { - positions.add(findPositionOfTextRange(v.getRange(), - viewCursor)); + positions.add(findPositionOfTextRange(v.getRange(), viewCursor)); } fcursor.restore(doc); @@ -99,19 +93,17 @@ public static List> visualSort(List> input } /** - * Given a location, return its position: coordinates relative to - * the top left position of the first page of the document. + * Given a location, return its position: coordinates relative to the top left position of the + * first page of the document. * - * Note: for text layouts with two or more columns, this gives the - * wrong order: top-down/left-to-right does not match - * reading order. + * Note: for text layouts with two or more columns, this gives the wrong order: + * top-down/left-to-right does not match reading order. * - * Note: The "relative to the top left position of the first page" - * is meant "as it appears on the screen". + * Note: The "relative to the top left position of the first page" is meant "as it appears on + * the screen". * - * In particular: when viewing pages side-by-side, the top - * half of the right page is higher than the lower half of - * the left page. Again, top-down/left-to-right does not + * In particular: when viewing pages side-by-side, the top half of the right page is + * higher than the lower half of the left page. Again, top-down/left-to-right does not * match reading order. * * @param range Location. @@ -126,8 +118,8 @@ private static Point findPositionOfTextRange(XTextRange range, XTextViewCursor c /** * A reference mark name paired with its visual position. * - * Comparison is based on (Y,X,indexInPosition): vertical compared - * first, horizontal second, indexInPosition third. + * Comparison is based on (Y,X,indexInPosition): vertical compared first, horizontal second, + * indexInPosition third. * * Used for sorting reference marks by their visual positions. */ diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java index 66e17a5b35b..c3eab225889 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java @@ -9,14 +9,12 @@ public interface RangeSortable extends RangeHolder { /** The XTextRange * - * For citation marks in footnotes this may be the range of the - * footnote mark. + * For citation marks in footnotes this may be the range of the footnote mark. */ public XTextRange getRange(); /** - * For citation marks in footnotes this may provide order within - * the footnote. + * For citation marks in footnotes this may provide order within the footnote. */ public int getIndexInPosition(); diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java index 075c55cc2ef..2986a6f4501 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java @@ -36,15 +36,14 @@ public class CitationGroup { * A name of a reference mark to link to by formatCitedOnPages. * May be initially empty, if backend does not use reference marks. * - * produceCitationMarkers might want fill it to support - * cross-references to citation groups from the bibliography. + * produceCitationMarkers might want fill it to support cross-references to citation groups from + * the bibliography. */ private Optional referenceMarkNameForLinking; /* - * Indices into citations: citations[localOrder[i]] provides ith - * citation according to the currently imposed local order for - * presentation. + * Indices into citations: citations[localOrder[i]] provides ith citation according to the + * currently imposed local order for presentation. * * Initialized to (0..(nCitations-1)) in the constructor. */ diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java index bac1e3c1387..6ba6b760cb6 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java @@ -10,8 +10,7 @@ public CitationGroupId(String id) { } /** - * CitationEntry needs some string identifying the group - * that it can pass back later. + * CitationEntry needs some string identifying the group that it can pass back later. */ public String citationGroupIdAsString() { return id; diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index f68aa4f115c..398964c9de1 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -20,8 +20,7 @@ /** * CitationGroups : the set of citation groups in the document. * - * This is the main input (as well as output) for creating citation - * markers and bibliography. + * This is the main input (as well as output) for creating citation markers and bibliography. * */ public class CitationGroups { @@ -56,8 +55,7 @@ public int numberOfCitationGroups() { } /** - * For each citation in {@code where} - * call {@code fun.accept(new Pair(citation, value));} + * For each citation in {@code where} call {@code fun.accept(new Pair(citation, value));} */ public void distributeToCitations(List where, Consumer> fun, @@ -84,21 +82,19 @@ public void lookupCitations(List databases) { if (true) { // collect-lookup-distribute // - // CitationDatabaseLookupResult for the same citation key - // is the same object. Until we insert a new citation from the GUI. + // 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); } else { // 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. + // 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 cg : getCitationGroupsUnordered()) { for (Citation cit : cg.citationsInStorageOrder) { @@ -123,16 +119,15 @@ public List getCitationGroupsInGlobalOrder() { } /** - * Impose an order of citation groups by providing the order - * of their citation group idendifiers. + * Impose an order of citation groups by providing the order of their citation group + * idendifiers. * * Also set indexInGlobalOrder for each citation group. */ public void setGlobalOrder(List globalOrder) { Objects.requireNonNull(globalOrder); if (globalOrder.size() != numberOfCitationGroups()) { - throw new RuntimeException("setGlobalOrder:" - + " globalOrder.size() != numberOfCitationGroups()"); + throw new RuntimeException("setGlobalOrder: globalOrder.size() != numberOfCitationGroups()"); } this.globalOrder = Optional.of(globalOrder); @@ -158,8 +153,8 @@ public void imposeLocalOrder(Comparator entryComparator) { } /** - * Collect citations into a list of cited sources using neither - * CitationGroup.globalOrder or Citation.localOrder + * Collect citations into a list of cited sources using neither CitationGroup.globalOrder or + * Citation.localOrder */ public CitedKeys getCitedKeysUnordered() { LinkedHashMap res = new LinkedHashMap<>(); @@ -224,8 +219,7 @@ public List getUnresolvedKeys() { public void createNumberedBibliographySortedInOrderOfAppearance() { if (!bibliography.isEmpty()) { - throw new RuntimeException("createNumberedBibliographySortedInOrderOfAppearance:" - + " already have a bibliography"); + throw new RuntimeException("createNumberedBibliographySortedInOrderOfAppearance: already have a bibliography"); } CitedKeys citedKeys = getCitedKeysSortedInOrderOfAppearance(); citedKeys.numberCitedKeysInCurrentOrder(); @@ -238,8 +232,7 @@ public void createNumberedBibliographySortedInOrderOfAppearance() { */ public void createPlainBibliographySortedByComparator(Comparator entryComparator) { if (!bibliography.isEmpty()) { - throw new RuntimeException("createPlainBibliographySortedByComparator:" - + " already have a bibliography"); + throw new RuntimeException("createPlainBibliographySortedByComparator: already have a bibliography"); } CitedKeys citedKeys = getCitedKeysUnordered(); citedKeys.sortByComparator(entryComparator); @@ -251,8 +244,7 @@ public void createPlainBibliographySortedByComparator(Comparator entry */ public void createNumberedBibliographySortedByComparator(Comparator entryComparator) { if (!bibliography.isEmpty()) { - throw new RuntimeException("createNumberedBibliographySortedByComparator:" - + " already have a bibliography"); + throw new RuntimeException("createNumberedBibliographySortedByComparator: already have a bibliography"); } CitedKeys citedKeys = getCitedKeysUnordered(); citedKeys.sortByComparator(entryComparator); @@ -276,8 +268,7 @@ public Optional getCitationGroup(CitationGroupId cgid) { public CitationGroup getCitationGroupOrThrow(CitationGroupId cgid) { CitationGroup cg = citationGroupsUnordered.get(cgid); if (cg == null) { - throw new RuntimeException("getCitationGroupOrThrow:" - + " the requested CitationGroup is not available"); + throw new RuntimeException("getCitationGroupOrThrow: the requested CitationGroup is not available"); } return cg; } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java b/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java index 866a0de34c3..b17ec100ee2 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java @@ -23,8 +23,7 @@ public CitationLookupResult(BibEntry entry, BibDatabase database) { * Consequently, {@code this.database.equals(that.database)} below * is equivalent to {@code this.database == that.database}. * - * Since within each GUI call we use a fixed list of - * databases, it is OK. + * Since within each GUI call we use a fixed list of databases, it is OK. */ @Override public boolean equals(Object o) { diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java index 4ab2c626b68..5fcb9bcc1a8 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java @@ -5,8 +5,7 @@ import org.jabref.model.openoffice.ootext.OOText; /** - * This is what we need for createCitationMarker to produce author-year - * citation markers. + * This is what we need for createCitationMarker to produce author-year citation markers. */ public interface CitationMarkerEntry extends CitationMarkerNormEntry { @@ -17,14 +16,13 @@ public interface CitationMarkerEntry extends CitationMarkerNormEntry { /** * pageInfo for this citation, provided by the user. - * May be empty, for none. + * May be empty, for none. */ Optional 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. + * @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(); } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNormEntry.java b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNormEntry.java index e9df5ec961f..a2581b38b60 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNormEntry.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNormEntry.java @@ -3,16 +3,13 @@ import java.util.Optional; /** - * This is what we need to produce normalized author-year citation - * markers. + * 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. * - * Used if getBibEntry() and/or getDatabase() returns - * empty, which indicates failure to lookup in the databases. - * + * Used if getLookupResult() returns empty, which indicates failure to lookup in the databases. */ String getCitationKey(); diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationPath.java b/src/main/java/org/jabref/model/openoffice/style/CitationPath.java index 05aeb6547f6..0920ea20feb 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationPath.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationPath.java @@ -1,8 +1,8 @@ package org.jabref.model.openoffice.style; /** - * Identifies a citation with the citation group containing it and - * its storage index within. + * Identifies a citation with the identifier of the citation group containing it and its storage + * index within. */ public class CitationPath { diff --git a/src/main/java/org/jabref/model/openoffice/style/CitedKey.java b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java index 08b2ffb1bb8..bc032fb46ac 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java @@ -11,9 +11,8 @@ /** * Cited keys are collected from the citations in citation groups. * - * 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. + * 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, diff --git a/src/main/java/org/jabref/model/openoffice/style/CompareCitation.java b/src/main/java/org/jabref/model/openoffice/style/CompareCitation.java index 916f8ec610c..966715b11a8 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CompareCitation.java +++ b/src/main/java/org/jabref/model/openoffice/style/CompareCitation.java @@ -5,8 +5,8 @@ import org.jabref.model.entry.BibEntry; /* - * Given a Comparator provide a Comparator - * that can handle unresolved citation keys and takes pageInfo into account. + * Given a Comparator provide a Comparator that can handle unresolved + * citation keys and takes pageInfo into account. */ public class CompareCitation implements Comparator { diff --git a/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java b/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java index 439d0556c2d..a5484560316 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java @@ -6,8 +6,8 @@ import org.jabref.model.entry.BibEntry; /* - * Given a Comparator provide a Comparator - * that also handles unresolved citation keys. + * Given a Comparator provide a Comparator that also handles + * unresolved citation keys. */ public class CompareCitedKey implements Comparator { diff --git a/src/main/java/org/jabref/model/openoffice/style/NonUniqueCitationMarker.java b/src/main/java/org/jabref/model/openoffice/style/NonUniqueCitationMarker.java index e7d988ee216..34300734d2f 100644 --- a/src/main/java/org/jabref/model/openoffice/style/NonUniqueCitationMarker.java +++ b/src/main/java/org/jabref/model/openoffice/style/NonUniqueCitationMarker.java @@ -1,15 +1,15 @@ package org.jabref.model.openoffice.style; /** - * What should createCitationMarker do if it discovers that - * uniqueLetters provided are not sufficient for unique presentation? + * 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 a RuntimeException */ + /** Throw an exception */ THROWS } diff --git a/src/main/java/org/jabref/model/openoffice/style/OODataModel.java b/src/main/java/org/jabref/model/openoffice/style/OODataModel.java index 860038ee299..20b2365ebf2 100644 --- a/src/main/java/org/jabref/model/openoffice/style/OODataModel.java +++ b/src/main/java/org/jabref/model/openoffice/style/OODataModel.java @@ -9,14 +9,10 @@ /** What is the data stored? */ public enum OODataModel { - /** - * JabRef52: pageInfo belongs to CitationGroup, not Citation. - */ + /** JabRef52: pageInfo belongs to CitationGroup, not Citation. */ JabRef52, - /** - * JabRef60: pageInfo belongs to Citation. - */ + /** JabRef60: pageInfo belongs to Citation. */ JabRef60; /** diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java b/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java index c509f6ad2eb..7e501351060 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java @@ -44,36 +44,29 @@ public static Optional getAnchor(XTextDocument doc, String name) NoDocumentException { XNameAccess nameAccess = getNameAccess(doc); - return (UnoNameAccess.getTextContentByName(nameAccess, name) - .map(XTextContent::getAnchor)); + 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. + * 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. * * 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 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. + * 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 IllegalArgumentException, CreationException { - return UnoNamed.insertNamedTextContent(doc, - "com.sun.star.text.Bookmark", - name, - range, - absorb); + return UnoNamed.insertNamedTextContent(doc, "com.sun.star.text.Bookmark", name, range, absorb); } /** diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoCast.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCast.java index df5be51db36..9640470beb2 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoCast.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCast.java @@ -11,8 +11,7 @@ private UnoCast() { } /** * unoQI : short for UnoRuntime.queryInterface * - * @return A reference to the requested UNO interface type if available, - * otherwise null + * @return A reference to the requested UNO interface type if available, otherwise null */ public static T unoQI(Class zInterface, Object object) { return UnoRuntime.queryInterface(zInterface, object); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java index 0e8b84e8d22..799e93bb650 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java @@ -26,11 +26,10 @@ public static void refresh(XTextDocument doc) { } /** - * Insert a clickable cross-reference to a reference mark, - * with a label containing the target's page number. + * Insert a clickable cross-reference to a reference mark, with a label containing the target's + * page number. * - * May need a documentConnection.refresh() after, to update - * the text shown. + * May need a documentConnection.refresh() after, to update the text shown. */ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, String referenceMarkName, @@ -48,8 +47,7 @@ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, XPropertySet xFieldProps; try { String name = "com.sun.star.text.textfield.GetReference"; - xFieldProps = (XPropertySet) UnoCast.unoQI(XPropertySet.class, - msf.createInstance(name)); + xFieldProps = (XPropertySet) UnoCast.unoQI(XPropertySet.class, msf.createInstance(name)); } catch (Exception e) { throw new CreationException(e.getMessage()); } @@ -59,12 +57,10 @@ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, // specify that the source is a reference mark (could also be a footnote, // bookmark or sequence field) - xFieldProps.setPropertyValue("ReferenceFieldSource", - new Short(ReferenceFieldSource.REFERENCE_MARK)); + xFieldProps.setPropertyValue("ReferenceFieldSource", new Short(ReferenceFieldSource.REFERENCE_MARK)); // We want the reference displayed as page number - xFieldProps.setPropertyValue("ReferenceFieldPart", - new Short(ReferenceFieldPart.PAGE)); + xFieldProps.setPropertyValue("ReferenceFieldPart", new Short(ReferenceFieldPart.PAGE)); // Get the XTextContent interface of the GetReference text field XTextContent xRefContent = (XTextContent) UnoCast.unoQI(XTextContent.class, xFieldProps); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java b/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java index 3d172d11f14..6df243a604e 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java @@ -12,8 +12,7 @@ public class UnoNameAccess { private UnoNameAccess() { } /** - * @return null if name not found, or if the result does not - * support the XTextContent interface. + * @return null if name not found, or if the result does not support the XTextContent interface. */ public static Optional getTextContentByName(XNameAccess nameAccess, String name) throws diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java b/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java index d99b6702153..0d4b5ed92ce 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java @@ -11,30 +11,24 @@ public class UnoNamed { private UnoNamed() { } /** - * Insert a new instance of a service at the provided cursor - * position. + * 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". + * "com.sun.star.text.ReferenceMark", + * "com.sun.star.text.Bookmark" or + * "com.sun.star.text.TextSection". * - * Passed to this.asXMultiServiceFactory().createInstance(service) - * The result is expected to support the - * XNamed and XTextContent interfaces. + * 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 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 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. + * @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. * diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java b/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java index 52d092f8b07..1009665384d 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java @@ -22,8 +22,7 @@ private UnoReferenceMark() { } /** * @throws NoDocumentException If cannot get reference marks * - * Note: also used by `isDocumentConnectionMissing` to test if - * we have a working connection. + * Note: also used by `isDocumentConnectionMissing` to test if we have a working connection. * */ public static XNameAccess getNameAccess(XTextDocument doc) @@ -101,22 +100,19 @@ public static Optional getAnchor(XTextDocument doc, String name) } /** - * Insert a new reference mark at the provided cursor - * position. + * Insert a new reference mark at the provided cursor position. * - * If {@code absorb} is true, the text in the cursor range will become - * the text with gray background. + * If {@code absorb} is true, the text in the cursor range will become the text with gray + * background. * - * 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. + * 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. + * @param range Cursor marking the location or range for the reference mark. */ public static XNamed create(XTextDocument doc, String name, @@ -124,10 +120,6 @@ public static XNamed create(XTextDocument doc, boolean absorb) throws CreationException { - return UnoNamed.insertNamedTextContent(doc, - "com.sun.star.text.ReferenceMark", - name, - range, - absorb); + return UnoNamed.insertNamedTextContent(doc, "com.sun.star.text.ReferenceMark", name, range, absorb); } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java index b0ab372297e..daaad560a11 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java @@ -41,9 +41,7 @@ public static Optional getByName(XTextDocument doc, String name) NoDocumentException { XNameAccess nameAccess = getNameAccess(doc); try { - return Optional.ofNullable((XTextSection) - ((Any) nameAccess.getByName(name)) - .getObject()); + return Optional.ofNullable((XTextSection) ((Any) nameAccess.getByName(name)).getObject()); } catch (NoSuchElementException ex) { return Optional.empty(); } @@ -61,31 +59,24 @@ public static Optional getAnchor(XTextDocument doc, String name) NoDocumentException { XNameAccess nameAccess = getNameAccess(doc); - return (UnoNameAccess.getTextContentByName(nameAccess, name) - .map(XTextContent::getAnchor)); + return (UnoNameAccess.getTextContentByName(nameAccess, name).map(XTextContent::getAnchor)); } /** - * Create a text section with the provided name and insert it at - * the provided cursor. + * 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. * - * 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. + * 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 IllegalArgumentException, CreationException { - return UnoNamed.insertNamedTextContent(doc, - "com.sun.star.text.TextSection", - name, - range, - absorb); + return UnoNamed.insertNamedTextContent(doc, "com.sun.star.text.TextSection", name, range, absorb); } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java index fda9b44b4f2..0aebadb1b7e 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java @@ -21,9 +21,8 @@ public static Optional getXUndoManager(XTextDocument doc) { } /** - * Each call to enterUndoContext must be paired by a call to - * leaveUndoContext, otherwise, the document's undo stack is - * left in an inconsistent state. + * 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) { Optional um = getXUndoManager(doc); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java index 47a2287f880..1c0a3494e7a 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java @@ -7,6 +7,7 @@ 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; @@ -44,13 +45,12 @@ public static List getListOfNames(XTextDocument doc) { } /** - * @param property Name of a custom document property in the - * current document. + * @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. + * These properties are used to store extra data about individual citation. + * In particular, the `pageInfo` part. * */ public static Optional getStringValue(XTextDocument doc, String property) @@ -70,8 +70,8 @@ public static Optional getStringValue(XTextDocument doc, String property } /** - * @param property Name of a custom document property in the - * current document. Created if does not exist yet. + * @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. */ @@ -109,14 +109,11 @@ public static void createStringProperty(XTextDocument doc, String property, Stri } } - container.get().addProperty(property, - com.sun.star.beans.PropertyAttribute.REMOVEABLE, - new Any(Type.STRING, value)); + container.get().addProperty(property, PropertyAttribute.REMOVEABLE, new Any(Type.STRING, value)); } /** - * @param property Name of a custom document property in the - * current document. + * @param property Name of a custom document property in the current document. * * Logs warning if does not exist. */ @@ -138,15 +135,13 @@ public static void remove(XTextDocument doc, String property) try { container.get().removeProperty(property); } catch (UnknownPropertyException ex) { - LOGGER.warn(String.format("UnoUserDefinedProperty.remove(%s)" - + " This property was not there to remove", + 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. + * @param property Name of a custom document property in the current document. * * Keep silent if property did not exist. */ diff --git a/src/main/java/org/jabref/model/openoffice/util/OOResult.java b/src/main/java/org/jabref/model/openoffice/util/OOResult.java index 1572ac4e016..61a37e45894 100644 --- a/src/main/java/org/jabref/model/openoffice/util/OOResult.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOResult.java @@ -6,9 +6,8 @@ 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. + * 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. * diff --git a/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java b/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java index 3a4143f4489..8742e06764f 100644 --- a/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java @@ -1,13 +1,12 @@ package org.jabref.model.openoffice.util; /** - * This class allows three objects to be packed together, and later - * accessed as fields `a`, `b` and `c`. + * This class allows three objects to be packed together, and later accessed as fields `a`, `b` and + * `c`. * * Can be used to avoid creating a new class for just this purpose. * - * Can be useful if you do not have `Trifunction` at hand but need to - * pass three objects at a time. + * Can be useful if you do not have `Trifunction` at hand but need to pass three objects at a time. * */ public class OOTuple3 { From cde024dd9dc893007e78385f086a5183037f7fd0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 8 Jun 2021 13:30:50 +0200 Subject: [PATCH 0962/1068] com.sun.star.uno.Exception --- src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java index 799e93bb650..02aba5afc1b 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java @@ -48,7 +48,7 @@ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, try { String name = "com.sun.star.text.textfield.GetReference"; xFieldProps = (XPropertySet) UnoCast.unoQI(XPropertySet.class, msf.createInstance(name)); - } catch (Exception e) { + } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } From 8999f6e1d8ff4c0ebce2bbe734f7463343dfc992 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 8 Jun 2021 14:08:33 +0200 Subject: [PATCH 0963/1068] drop group comments --- .../org/jabref/model/openoffice/util/OOResult.java | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/util/OOResult.java b/src/main/java/org/jabref/model/openoffice/util/OOResult.java index 61a37e45894..c90bc68ad13 100644 --- a/src/main/java/org/jabref/model/openoffice/util/OOResult.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOResult.java @@ -34,10 +34,6 @@ public static OOResult error(E error) { return new OOResult<>(Optional.empty(), Optional.of(error)); } - /* - * Test state - */ - public boolean isPresent() { return result.isPresent(); } @@ -54,10 +50,6 @@ public boolean isOK() { return !isError(); } - /* - * getters - */ - public R get() { if (isError()) { throw new NoSuchElementException("Cannot get from error"); @@ -69,10 +61,6 @@ public E getError() { return error.get(); } - /* - * Conditionals - */ - public OOResult ifPresent(Consumer fun) { if (isPresent()) { fun.accept(get()); From 463ffdfe8e88e28677d5df29730f4bd64b595323 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 8 Jun 2021 14:40:03 +0200 Subject: [PATCH 0964/1068] renamed asString -> toString --- .../logic/openoffice/action/EditInsert.java | 2 +- .../logic/openoffice/backend/Backend52.java | 8 +++---- .../frontend/UpdateCitationMarkers.java | 2 +- .../style/OOBibStyleGetCitationMarker.java | 6 ++--- .../style/OOBibStyleGetNumCitationMarker.java | 2 +- .../style/OOFormatBibliography.java | 12 +++++----- .../style/OOProcessAuthorYearMarkers.java | 2 +- .../model/openoffice/ootext/OOFormat.java | 8 +++---- .../model/openoffice/ootext/OOText.java | 5 +++-- .../model/openoffice/ootext/OOTextIntoOO.java | 2 +- .../model/openoffice/style/PageInfo.java | 6 ++--- .../openoffice/style/OOBibStyleTest.java | 22 +++++++++---------- .../style/OOBibStyleTestHelper.java | 8 +++---- 13 files changed, 43 insertions(+), 42 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index 6e3d7d2a8c8..7b81c2465c2 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -100,7 +100,7 @@ public static void insertCitationGroup(XTextDocument doc, citationType.inParenthesis(), NonUniqueCitationMarker.FORGIVEN)); - if ("".equals(OOText.asString(citeText))) { + if ("".equals(OOText.toString(citeText))) { citeText = OOText.fromString("[?]"); } diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index a3112389d80..a6f98583b47 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -254,7 +254,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, Optional pageInfo = PageInfo.normalizePageInfo(pageInfos.get(last)); if (pageInfo.isPresent()) { - String pageInfoString = OOText.asString(pageInfo.get()); + String pageInfoString = OOText.toString(pageInfo.get()); UnoUserDefinedProperty.createStringProperty(doc, refMarkName, pageInfoString); } else { // do not inherit from trash @@ -288,7 +288,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, // Try to do something of the cgPageInfos. String cgPageInfo = (cgPageInfos.stream() .filter(pi -> pi.isPresent()) - .map(pi -> OOText.asString(pi.get())) + .map(pi -> OOText.toString(pi.get())) .distinct() .collect(Collectors.joining("; "))); @@ -409,7 +409,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups String context = GetContext.getCursorStringWithContext(cursor, 30, 30, true); Optional pageInfo = (cg.numberOfCitations() > 0 ? (getPageInfoFromData(cg) - .map(e -> OOText.asString(e))) + .map(e -> OOText.toString(e))) : Optional.empty()); CitationEntry entry = new CitationEntry(name, context, pageInfo); citations.add(entry); @@ -444,7 +444,7 @@ public void applyCitationEntries(XTextDocument doc, List citation pageInfo = PageInfo.normalizePageInfo(pageInfo); if (pageInfo.isPresent()) { String name = entry.getRefMarkName(); - UnoUserDefinedProperty.createStringProperty(doc, name, pageInfo.get().asString()); + UnoUserDefinedProperty.createStringProperty(doc, name, pageInfo.get().toString()); } } break; diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index 7d864ab1063..3f2be8254ec 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -102,7 +102,7 @@ public static void fillCitationMarkInCursor(XTextDocument doc, OOText citationText2 = style.decorateCitationMarker(citationText); // inject a ZERO_WIDTH_SPACE to hold the initial character format final String ZERO_WIDTH_SPACE = "\u200b"; - citationText2 = OOText.fromString(ZERO_WIDTH_SPACE + citationText2.asString()); + citationText2 = OOText.fromString(ZERO_WIDTH_SPACE + citationText2.toString()); OOTextIntoOO.write(doc, cursor, citationText2); } else { cursor.setString(""); diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java index 5ed3209d547..ee2bba27e7e 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java @@ -439,7 +439,7 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, PageInfo.normalizePageInfo(ce.getPageInfo()); if (pageInfo.isPresent()) { pageInfoPart.append(pageInfoSeparator); - pageInfoPart.append(OOText.asString(pageInfo.get())); + pageInfoPart.append(OOText.toString(pageInfo.get())); } } @@ -650,8 +650,8 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, final CitationMarkerEntry ce1 = citationMarkerEntries.get(i - 1); final CitationMarkerEntry ce2 = citationMarkerEntries.get(i); - final String nm1 = OOText.asString(normalizedMarkers.get(i - 1)); - final String nm2 = OOText.asString(normalizedMarkers.get(i)); + final String nm1 = OOText.toString(normalizedMarkers.get(i - 1)); + final String nm2 = OOText.toString(normalizedMarkers.get(i)); final boolean isUnresolved1 = ce1.getLookupResult().isEmpty(); final boolean isUnresolved2 = ce2.getLookupResult().isEmpty(); diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java index cdff6110f45..376c4478421 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java @@ -105,7 +105,7 @@ private static void emitBlock(List block, Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { sb.append(style.getPageInfoSeparator()); - sb.append(OOText.asString(pageInfo.get())); + sb.append(OOText.toString(pageInfo.get())); } return; } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index c9ae527dcec..58bbb5fdeeb 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -36,7 +36,7 @@ public static OOText formatBibliography(CitationGroups cgs, OOText title = style.getFormattedBibliographyTitle(); OOText body = formatBibliographyBody(cgs, bibliography, style, alwaysAddCitedOnPages); - return OOText.fromString(title.asString() + body.asString()); + return OOText.fromString(title.toString() + body.toString()); } /** @@ -51,7 +51,7 @@ public static OOText formatBibliographyBody(CitationGroups cgs, for (CitedKey ck : bibliography.values()) { OOText entryText = formatBibliographyEntry(cgs, ck, style, alwaysAddCitedOnPages); - stringBuilder.append(entryText.asString()); + stringBuilder.append(entryText.toString()); } return OOText.fromString(stringBuilder.toString()); @@ -68,18 +68,18 @@ public static OOText formatBibliographyEntry(CitationGroups cgs, // insert marker "[1]" if (style.isNumberEntries()) { - sb.append(style.getNumCitationMarkerForBibliography(ck).asString()); + sb.append(style.getNumCitationMarkerForBibliography(ck).toString()); } else { // !style.isNumberEntries() : emit no prefix // Note: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); } // Add entry body - sb.append(formatBibliographyEntryBody(ck, style).asString()); + sb.append(formatBibliographyEntryBody(ck, style).toString()); // Add "Cited on pages" if (ck.getLookupResult().isEmpty() || alwaysAddCitedOnPages) { - sb.append(formatCitedOnPages(cgs, ck).asString()); + sb.append(formatCitedOnPages(cgs, ck).toString()); } // Add paragraph @@ -187,7 +187,7 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { } String markName = cg.getReferenceMarkNameForLinking().orElseThrow(RuntimeException::new); OOText xref = OOFormat.formatReferenceToPageNumberOfReferenceMark(markName); - sb.append(xref.asString()); + sb.append(xref.toString()); i++; } sb.append(suffix); diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index 04c03b9c321..a55d59107a8 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -56,7 +56,7 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup // Map> normCitMarkerToClachingKeys = new HashMap<>(); for (CitedKey citedKey : sortedCitedKeys.values()) { - String normCitMarker = OOText.asString(citedKey.getNormalizedCitationMarker().get()); + String normCitMarker = OOText.toString(citedKey.getNormalizedCitationMarker().get()); String citationKey = citedKey.citationKey; if (!normCitMarkerToClachingKeys.containsKey(normCitMarker)) { diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java index c452abe3080..2c48a36f9b9 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java @@ -16,7 +16,7 @@ public class OOFormat { * */ public static OOText setLocale(OOText ootext, String locale) { - return OOText.fromString(String.format("", locale) + ootext.asString() + ""); + return OOText.fromString(String.format("", locale) + ootext.toString() + ""); } /** @@ -39,7 +39,7 @@ public static OOText setLocaleNone(OOText ootext) { */ public static OOText setCharStyle(OOText ootext, String charStyle) { return OOText.fromString(String.format("", charStyle) - + ootext.asString() + + ootext.toString() + ""); } @@ -51,14 +51,14 @@ public static OOText paragraph(OOText ootext, String paraStyle) { return paragraph(ootext); } String startTag = String.format("

", paraStyle); - return OOText.fromString(startTag + ootext.asString() + "

"); + return OOText.fromString(startTag + ootext.toString() + "

"); } /** * Mark {@code ootext} as part of a paragraph. */ public static OOText paragraph(OOText ootext) { - return OOText.fromString("

" + ootext.asString() + "

"); + return OOText.fromString("

" + ootext.toString() + "

"); } /** diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java index f7d093cf30f..ad0b9fb448d 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java @@ -26,14 +26,15 @@ public static OOText fromString(String string) { } /* null input is passed through */ - public static String asString(OOText ootext) { + public static String toString(OOText ootext) { if (ootext == null) { return null; } return ootext.data; } - public String asString() { + @Override + public String toString() { return data; } diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index 05e51bfd42f..c02183bdecd 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -159,7 +159,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) Objects.requireNonNull(ootext); Objects.requireNonNull(position); - String lText = OOText.asString(ootext); + String lText = OOText.toString(ootext); LOGGER.debug(lText); diff --git a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java index 9aa4a1cef9b..ace7eedae02 100644 --- a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java +++ b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java @@ -14,10 +14,10 @@ private PageInfo() { * pageInfo normalization */ public static Optional normalizePageInfo(Optional o) { - if (o == null || o.isEmpty() || "".equals(OOText.asString(o.get()))) { + if (o == null || o.isEmpty() || "".equals(OOText.toString(o.get()))) { return Optional.empty(); } - String s = OOText.asString(o.get()); + String s = OOText.toString(o.get()); if (s.trim().equals("")) { return Optional.empty(); } @@ -42,6 +42,6 @@ public static int comparePageInfo(Optional a, Optional b) { if (bb.isEmpty()) { return +1; } - return aa.get().asString().compareTo(bb.get().asString()); + return aa.get().toString().compareTo(bb.get().toString()); } } diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java index 03a0b535e34..82d7888afd8 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTest.java @@ -109,7 +109,7 @@ static String runGetNumCitationMarker2b(OOBibStyle style, CitationMarkerNumericEntry... s) { List input = Stream.of(s).collect(Collectors.toList()); OOText res = style.getNumCitationMarker2(input, minGroupingCount); - return res.asString(); + return res.toString(); } static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, @@ -178,7 +178,7 @@ void testGetNumCitationMarker() throws IOException { CitationMarkerNumericEntry e2 = numEntry("key", 1, "pp. 55-56"); assertEquals(true, e2.getPageInfo().isPresent()); - assertEquals("pp. 55-56", e2.getPageInfo().get().asString()); + assertEquals("pp. 55-56", e2.getPageInfo().get().toString()); citation = runGetNumCitationMarker2b(style, -1, e2); assertEquals("[1; pp. 55-56]", citation); @@ -250,7 +250,7 @@ void testGetNumCitationMarkerUndefined() throws IOException { */ CitationMarkerNumericBibEntry x = numBibEntry("key", Optional.empty()); assertEquals("[" + OOBibStyle.UNDEFINED_CITATION_MARKER + "key" + "] ", - style.getNumCitationMarkerForBibliography(x).asString()); + style.getNumCitationMarkerForBibliography(x).toString()); } @Test @@ -761,13 +761,13 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten, 2006c]", style.createCitationMarker(citationMarkerEntries, true, - NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).toString()); assertEquals("Boström, Wäyrynen, Bodén, Beznosov & Kruchten [2006a,b]" + "; Boström, Wäyrynen, Bodén, Beznosov & NotKruchten [2006c]", style.createCitationMarker(citationMarkerEntries, false, - NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).toString()); } // Without pageInfo, only the first is isFirstAppearanceOfSource. @@ -789,7 +789,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström et al., 2006c]", style.createCitationMarker(citationMarkerEntries, true, - NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).toString()); } // Without pageInfo, only the second is isFirstAppearanceOfSource. @@ -813,7 +813,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström et al., 2006c]", style.createCitationMarker(citationMarkerEntries, true, - NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).toString()); } // Without pageInfo, neither is isFirstAppearanceOfSource. @@ -835,7 +835,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a,b,c]", style.createCitationMarker(citationMarkerEntries, true, - NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).toString()); } // With pageInfo: different entries with identical non-null pageInfo: not joined. @@ -857,7 +857,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström et al., 2006c; p1]", style.createCitationMarker(citationMarkerEntries, true, - NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).toString()); } // With pageInfo: same entries with identical non-null pageInfo: collapsed. @@ -878,7 +878,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { assertEquals("[Boström et al., 2006a; p1]", style.createCitationMarker(citationMarkerEntries, true, - NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).toString()); } // With pageInfo: same entries with different pageInfo: kept separate. // Empty ("") and missing pageInfos considered equal, thus collapsed. @@ -902,7 +902,7 @@ void testGetCitationMarkerJoinFirst() throws IOException { + "; Boström et al., 2006a]", style.createCitationMarker(citationMarkerEntries, true, - NonUniqueCitationMarker.THROWS).asString()); + NonUniqueCitationMarker.THROWS).toString()); } } } diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java index 9fbe9579ccb..2d480d496fa 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java @@ -105,7 +105,7 @@ static String runGetNumCitationMarker2a(OOBibStyle style, CitationMarkerNumericBibEntryImpl x = new CitationMarkerNumericBibEntryImpl("key", (n == 0) ? Optional.empty() : Optional.of(n)); - return style.getNumCitationMarkerForBibliography(x).asString(); + return style.getNumCitationMarkerForBibliography(x).toString(); } else { List input = num.stream() @@ -114,7 +114,7 @@ static String runGetNumCitationMarker2a(OOBibStyle style, n, Optional.empty())) .collect(Collectors.toList()); - return style.getNumCitationMarker2(input, minGroupingCount).asString(); + return style.getNumCitationMarker2(input, minGroupingCount).toString(); } } @@ -131,7 +131,7 @@ static String runGetNumCitationMarker2b(OOBibStyle style, CitationMarkerNumericEntry... s) { List input = Stream.of(s).collect(Collectors.toList()); OOText res = style.getNumCitationMarker2(input, minGroupingCount); - return res.asString(); + return res.toString(); } /* @@ -194,7 +194,7 @@ static String getCitationMarker2(OOBibStyle style, } return style.createCitationMarker(citationMarkerEntries, inParenthesis, - NonUniqueCitationMarker.THROWS).asString(); + NonUniqueCitationMarker.THROWS).toString(); } /* From 14f406a14d1e27c9da9346b58aede70c2b961653 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 8 Jun 2021 15:42:02 +0200 Subject: [PATCH 0965/1068] merge with H --- .../openoffice/BibEntryNotFoundException.java | 16 + .../openoffice/ConnectionLostException.java | 11 + .../org/jabref/gui/openoffice/OOBibBase.java | 1424 +++++++++++++++++ .../org/jabref/logic/openoffice/OOUtil.java | 285 ++++ .../openoffice/UndefinedBibtexEntry.java | 22 + .../UndefinedParagraphFormatException.java | 18 + 6 files changed, 1776 insertions(+) create mode 100644 src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java create mode 100644 src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java create mode 100644 src/main/java/org/jabref/gui/openoffice/OOBibBase.java create mode 100644 src/main/java/org/jabref/logic/openoffice/OOUtil.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UndefinedBibtexEntry.java create mode 100644 src/main/java/org/jabref/logic/openoffice/UndefinedParagraphFormatException.java diff --git a/src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java b/src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java new file mode 100644 index 00000000000..b3db5f8f9e7 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/BibEntryNotFoundException.java @@ -0,0 +1,16 @@ +package org.jabref.gui.openoffice; + +class BibEntryNotFoundException extends Exception { + + private final String citationKey; + + public BibEntryNotFoundException(String citationKey, String message) { + super(message); + + this.citationKey = citationKey; + } + + public String getCitationKey() { + return citationKey; + } +} diff --git a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java b/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java new file mode 100644 index 00000000000..36fc16e5e3f --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java @@ -0,0 +1,11 @@ +package org.jabref.gui.openoffice; + +/** + * This exception is used to indicate that connection to OpenOffice has been lost. + */ +class ConnectionLostException extends RuntimeException { + + public ConnectionLostException(String s) { + super(s); + } +} diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java new file mode 100644 index 00000000000..540c5f9216b --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -0,0 +1,1424 @@ +package org.jabref.gui.openoffice; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import org.jabref.architecture.AllowedToUseAwt; +import org.jabref.gui.DialogService; +import org.jabref.logic.bibtex.comparator.FieldComparator; +import org.jabref.logic.bibtex.comparator.FieldComparatorStack; +import org.jabref.logic.l10n.Localization; +import org.jabref.logic.layout.Layout; +import org.jabref.logic.openoffice.OOUtil; +import org.jabref.logic.openoffice.UndefinedBibtexEntry; +import org.jabref.logic.openoffice.UndefinedParagraphFormatException; +import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.logic.openoffice.style.OOPreFormatter; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.StandardField; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; + +import com.sun.star.awt.Point; +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +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.comp.helper.BootstrapException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XEnumeration; +import com.sun.star.container.XEnumerationAccess; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNamed; +import com.sun.star.document.XDocumentPropertiesSupplier; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XController; +import com.sun.star.frame.XDesktop; +import com.sun.star.frame.XModel; +import com.sun.star.lang.DisposedException; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.Locale; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.text.XBookmarksSupplier; +import com.sun.star.text.XDocumentIndexesSupplier; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XReferenceMarksSupplier; +import com.sun.star.text.XText; +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.XTextRangeCompare; +import com.sun.star.text.XTextSection; +import com.sun.star.text.XTextSectionsSupplier; +import com.sun.star.text.XTextViewCursor; +import com.sun.star.text.XTextViewCursorSupplier; +import com.sun.star.uno.Any; +import com.sun.star.uno.Type; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class for manipulating the Bibliography of the currently start document in OpenOffice. + */ +@AllowedToUseAwt("Requires AWT for italics and bold") +class OOBibBase { + + private static final OOPreFormatter POSTFORMATTER = new OOPreFormatter(); + + private static final String BIB_SECTION_NAME = "JR_bib"; + private static final String BIB_SECTION_END_NAME = "JR_bib_end"; + private static final String BIB_CITATION = "JR_cite"; + private static final Pattern CITE_PATTERN = Pattern.compile(OOBibBase.BIB_CITATION + "\\d*_(\\d*)_(.*)"); + + private static final String CHAR_STYLE_NAME = "CharStyleName"; + + private static final int AUTHORYEAR_PAR = 1; + private static final int AUTHORYEAR_INTEXT = 2; + private static final int INVISIBLE_CIT = 3; + + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); + private XMultiServiceFactory mxDocFactory; + private XTextDocument mxDoc; + private XText text; + private final XDesktop xDesktop; + private XTextViewCursorSupplier xViewCursorSupplier; + private XComponent xCurrentComponent; + private XPropertySet propertySet; + + private XPropertyContainer userProperties; + private final boolean atEnd; + private final Comparator entryComparator; + private final Comparator yearAuthorTitleComparator; + private final FieldComparator authComp = new FieldComparator(StandardField.AUTHOR); + private final FieldComparator yearComp = new FieldComparator(StandardField.YEAR); + + private final FieldComparator titleComp = new FieldComparator(StandardField.TITLE); + private final List> authorYearTitleList = new ArrayList<>(3); + + private final List> yearAuthorTitleList = new ArrayList<>(3); + private final Map uniquefiers = new HashMap<>(); + private List sortedReferenceMarks; + + private final DialogService dialogService; + + public OOBibBase(Path loPath, boolean atEnd, DialogService dialogService) throws IllegalAccessException, InvocationTargetException, BootstrapException, CreationException, IOException, ClassNotFoundException { + + this.dialogService = dialogService; + + authorYearTitleList.add(authComp); + authorYearTitleList.add(yearComp); + authorYearTitleList.add(titleComp); + + yearAuthorTitleList.add(yearComp); + yearAuthorTitleList.add(authComp); + yearAuthorTitleList.add(titleComp); + + entryComparator = new FieldComparatorStack<>(authorYearTitleList); + yearAuthorTitleComparator = new FieldComparatorStack<>(yearAuthorTitleList); + + this.atEnd = atEnd; + + xDesktop = simpleBootstrap(loPath); + } + + public boolean isConnectedToDocument() { + return xCurrentComponent != null; + } + + public XTextDocument selectComponent(List list) { + List viewModel = list.stream().map(DocumentTitleViewModel::new).collect(Collectors.toList()); + // this whole method is part of a background task when auto-detecting instances, so we need to show dialog in FX thread + Optional selectedDocument = dialogService.showChoiceDialogAndWait(Localization.lang("Select document"), Localization.lang("Found documents:"), Localization.lang("Use selected document"), viewModel); + return selectedDocument.map(DocumentTitleViewModel::getXtextDocument).orElse(null); + } + + public Optional getCurrentDocumentTitle() { + return getDocumentTitle(mxDoc); + } + + private Optional getDocumentTitle(XTextDocument doc) { + if (doc == null) { + return Optional.empty(); + } else { + try { + return Optional.of(String.valueOf(OOUtil.getProperty(doc.getCurrentController().getFrame(), "Title"))); + } catch (UnknownPropertyException | WrappedTargetException e) { + LOGGER.warn("Could not get document title", e); + return Optional.empty(); + } + } + } + + public void selectDocument() throws NoDocumentException, NoSuchElementException, WrappedTargetException { + List textDocumentList = getTextDocuments(); + XTextDocument selected; + if (textDocumentList.isEmpty()) { + // No text documents found. + throw new NoDocumentException("No Writer documents found"); + } else if (textDocumentList.size() == 1) { + // Get the only one + selected = textDocumentList.get(0); + } else { + // Bring up a dialog + selected = selectComponent(textDocumentList); + } + + if (selected == null) { + return; + } + xCurrentComponent = UnoRuntime.queryInterface(XComponent.class, selected); + mxDoc = selected; + + UnoRuntime.queryInterface(XDocumentIndexesSupplier.class, xCurrentComponent); + + XModel xModel = UnoRuntime.queryInterface(XModel.class, xCurrentComponent); + XController xController = xModel.getCurrentController(); + xViewCursorSupplier = UnoRuntime.queryInterface(XTextViewCursorSupplier.class, xController); + + // get a reference to the body text of the document + text = mxDoc.getText(); + + // Access the text document's multi service factory: + mxDocFactory = UnoRuntime.queryInterface(XMultiServiceFactory.class, mxDoc); + + XDocumentPropertiesSupplier supp = UnoRuntime.queryInterface(XDocumentPropertiesSupplier.class, mxDoc); + userProperties = supp.getDocumentProperties().getUserDefinedProperties(); + propertySet = UnoRuntime.queryInterface(XPropertySet.class, userProperties); + } + + private List getTextDocuments() throws NoSuchElementException, WrappedTargetException { + List result = new ArrayList<>(); + XEnumerationAccess enumAccess = xDesktop.getComponents(); + XEnumeration componentEnumeration = enumAccess.createEnumeration(); + + // TODO: http://api.openoffice.org/docs/DevelopersGuide/OfficeDev/OfficeDev.xhtml#1_1_3_2_1_2_Frame_Hierarchies + + while (componentEnumeration.hasMoreElements()) { + Object nextElement = componentEnumeration.nextElement(); + XComponent component = UnoRuntime.queryInterface(XComponent.class, nextElement); + XTextDocument document = UnoRuntime.queryInterface(XTextDocument.class, component); + if (document != null) { + result.add(document); + } + } + return result; + } + + private XDesktop simpleBootstrap(Path loPath) + throws CreationException, BootstrapException { + + // Get the office component context: + XComponentContext xContext = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); + // Get the office service manager: + XMultiComponentFactory xServiceManager = xContext.getServiceManager(); + // Create the desktop, which is the root frame of the + // hierarchy of frames that contain viewable components: + Object desktop; + try { + desktop = xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + XDesktop resultDesktop = UnoRuntime.queryInterface(XDesktop.class, desktop); + + UnoRuntime.queryInterface(XComponentLoader.class, desktop); + + return resultDesktop; + } + + public Optional getCustomProperty(String property) throws UnknownPropertyException, WrappedTargetException { + if (propertySet.getPropertySetInfo().hasPropertyByName(property)) { + return Optional.ofNullable(propertySet.getPropertyValue(property).toString()); + } + return Optional.empty(); + } + + public void updateSortedReferenceMarks() throws WrappedTargetException, NoSuchElementException { + sortedReferenceMarks = getSortedReferenceMarks(getReferenceMarks()); + } + + public void setCustomProperty(String property, String value) throws UnknownPropertyException, + NotRemoveableException, PropertyExistException, IllegalTypeException, IllegalArgumentException { + if (propertySet.getPropertySetInfo().hasPropertyByName(property)) { + userProperties.removeProperty(property); + } + if (value != null) { + userProperties.addProperty(property, com.sun.star.beans.PropertyAttribute.REMOVEABLE, + new Any(Type.STRING, value)); + } + } + + /** + * This method inserts a cite marker in the text for the given BibEntry, and may refresh the bibliography. + * + * @param entries The entries to cite. + * @param database The database the entry belongs to. + * @param style The bibliography style we are using. + * @param inParenthesis Indicates whether it is an in-text citation or a citation in parenthesis. This is not relevant if numbered citations are used. + * @param withText Indicates whether this should be a normal citation (true) or an empty (invisible) citation (false). + * @param sync Indicates whether the reference list should be refreshed. + * @throws IllegalTypeException + * @throws PropertyExistException + * @throws NotRemoveableException + * @throws UnknownPropertyException + * @throws UndefinedCharacterFormatException + * @throws NoSuchElementException + * @throws WrappedTargetException + * @throws IOException + * @throws PropertyVetoException + * @throws CreationException + * @throws BibEntryNotFoundException + * @throws UndefinedParagraphFormatException + */ + public void insertEntry(List entries, BibDatabase database, + List allBases, OOBibStyle style, + boolean inParenthesis, boolean withText, String pageInfo, boolean sync) + throws IllegalArgumentException, + UnknownPropertyException, NotRemoveableException, PropertyExistException, IllegalTypeException, + UndefinedCharacterFormatException, WrappedTargetException, NoSuchElementException, PropertyVetoException, + IOException, CreationException, BibEntryNotFoundException, UndefinedParagraphFormatException { + + try { + + XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor(); + + if (entries.size() > 1) { + if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { + entries.sort(yearAuthorTitleComparator); + } else { + entries.sort(entryComparator); + } + } + + String keyString = String.join(",", + entries.stream().map(entry -> entry.getCitationKey().orElse("")).collect(Collectors.toList())); + // Insert bookmark: + String bName = getUniqueReferenceMarkName(keyString, + withText ? inParenthesis ? OOBibBase.AUTHORYEAR_PAR : OOBibBase.AUTHORYEAR_INTEXT : OOBibBase.INVISIBLE_CIT); + + // If we should store metadata for page info, do that now: + if (pageInfo != null) { + LOGGER.info("Storing page info: " + pageInfo); + setCustomProperty(bName, pageInfo); + } + + xViewCursor.getText().insertString(xViewCursor, " ", false); + if (style.isFormatCitations()) { + XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, xViewCursor); + String charStyle = style.getCitationCharacterFormat(); + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | + WrappedTargetException ex) { + // Setting the character format failed, so we throw an exception that + // will result in an error message for the user. Before that, + // delete the space we inserted: + xViewCursor.goLeft((short) 1, true); + xViewCursor.setString(""); + throw new UndefinedCharacterFormatException(charStyle); + } + } + xViewCursor.goLeft((short) 1, false); + Map databaseMap = new HashMap<>(); + for (BibEntry entry : entries) { + databaseMap.put(entry, database); + } + String citeText = style.isNumberEntries() ? "-" : style.getCitationMarker(entries, databaseMap, + inParenthesis, null, null); + insertReferenceMark(bName, citeText, xViewCursor, withText, style); + + xViewCursor.collapseToEnd(); + xViewCursor.goRight((short) 1, false); + + XTextRange position = xViewCursor.getEnd(); + + if (sync) { + // To account for numbering and for uniqiefiers, we must refresh the cite markers: + updateSortedReferenceMarks(); + refreshCiteMarkers(allBases, style); + + // Insert it at the current position: + rebuildBibTextSection(allBases, style); + } + + // Go back to the relevant position: + xViewCursor.gotoRange(position, false); + } catch (DisposedException ex) { + // We need to catch this one here because the OpenOfficePanel class is + // loaded before connection, and therefore cannot directly reference + // or catch a DisposedException (which is in a OO JAR file). + throw new ConnectionLostException(ex.getMessage()); + } + } + + public List getJabRefReferenceMarks(XNameAccess nameAccess) { + String[] names = nameAccess.getElementNames(); + // Remove all reference marks that don't look like JabRef citations: + List result = new ArrayList<>(); + if (names != null) { + for (String name : names) { + if (CITE_PATTERN.matcher(name).find()) { + result.add(name); + } + } + } + return result; + } + + /** + * Refresh all cite markers in the document. + * + * @param databases The databases to get entries from. + * @param style The bibliography style to use. + * @return A list of those referenced citation keys that could not be resolved. + * @throws UndefinedCharacterFormatException + * @throws NoSuchElementException + * @throws IllegalArgumentException + * @throws WrappedTargetException + * @throws BibEntryNotFoundException + * @throws CreationException + * @throws IOException + * @throws PropertyVetoException + * @throws UnknownPropertyException + */ + public List refreshCiteMarkers(List databases, OOBibStyle style) + throws WrappedTargetException, IllegalArgumentException, NoSuchElementException, + UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, IOException, + CreationException, BibEntryNotFoundException { + try { + return refreshCiteMarkersInternal(databases, style); + } catch (DisposedException ex) { + // We need to catch this one here because the OpenOfficePanel class is + // loaded before connection, and therefore cannot directly reference + // or catch a DisposedException (which is in a OO JAR file). + throw new ConnectionLostException(ex.getMessage()); + } + } + + private List refreshCiteMarkersInternal(List databases, OOBibStyle style) + throws WrappedTargetException, IllegalArgumentException, NoSuchElementException, + UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, + CreationException, BibEntryNotFoundException { + + List cited = findCitedKeys(); + Map linkSourceBase = new HashMap<>(); + Map entries = findCitedEntries(databases, cited, linkSourceBase); + + XNameAccess xReferenceMarks = getReferenceMarks(); + + List names; + if (style.isSortByPosition()) { + // We need to sort the reference marks according to their order of appearance: + names = sortedReferenceMarks; + } else if (style.isNumberEntries()) { + // We need to sort the reference marks according to the sorting of the bibliographic + // entries: + SortedMap newMap = new TreeMap<>(entryComparator); + for (Map.Entry bibtexEntryBibtexDatabaseEntry : entries.entrySet()) { + newMap.put(bibtexEntryBibtexDatabaseEntry.getKey(), bibtexEntryBibtexDatabaseEntry.getValue()); + } + entries = newMap; + // Rebuild the list of cited keys according to the sort order: + cited.clear(); + for (BibEntry entry : entries.keySet()) { + cited.add(entry.getCitationKey().orElse(null)); + } + names = Arrays.asList(xReferenceMarks.getElementNames()); + } else { + names = sortedReferenceMarks; + } + + // Remove all reference marks that don't look like JabRef citations: + List tmp = new ArrayList<>(); + for (String name : names) { + if (CITE_PATTERN.matcher(name).find()) { + tmp.add(name); + } + } + names = tmp; + + Map numbers = new HashMap<>(); + int lastNum = 0; + // First compute citation markers for all citations: + String[] citMarkers = new String[names.size()]; + String[][] normCitMarkers = new String[names.size()][]; + String[][] bibtexKeys = new String[names.size()][]; + + int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + + int[] types = new int[names.size()]; + for (int i = 0; i < names.size(); i++) { + Matcher citeMatcher = CITE_PATTERN.matcher(names.get(i)); + if (citeMatcher.find()) { + String typeStr = citeMatcher.group(1); + int type = Integer.parseInt(typeStr); + types[i] = type; // Remember the type in case we need to uniquefy. + String[] keys = citeMatcher.group(2).split(","); + bibtexKeys[i] = keys; + BibEntry[] cEntries = new BibEntry[keys.length]; + for (int j = 0; j < cEntries.length; j++) { + BibDatabase database = linkSourceBase.get(keys[j]); + Optional tmpEntry = Optional.empty(); + if (database != null) { + tmpEntry = database.getEntryByCitationKey(keys[j]); + } + if (tmpEntry.isPresent()) { + cEntries[j] = tmpEntry.get(); + } else { + LOGGER.info("Citation key not found: '" + keys[j] + '\''); + LOGGER.info("Problem with reference mark: '" + names.get(i) + '\''); + throw new BibEntryNotFoundException(names.get(i), Localization + .lang("Could not resolve BibTeX entry for citation marker '%0'.", names.get(i))); + } + } + + String[] normCitMarker = new String[keys.length]; + String citationMarker; + if (style.isCitationKeyCiteMarkers()) { + StringBuilder sb = new StringBuilder(); + normCitMarkers[i] = new String[keys.length]; + for (int j = 0; j < keys.length; j++) { + normCitMarkers[i][j] = cEntries[j].getCitationKey().orElse(null); + sb.append(cEntries[j].getCitationKey().orElse("")); + if (j < (keys.length - 1)) { + sb.append(','); + } + } + citationMarker = sb.toString(); + } else if (style.isNumberEntries()) { + if (style.isSortByPosition()) { + // We have sorted the citation markers according to their order of appearance, + // so we simply count up for each marker referring to a new entry: + List num = new ArrayList<>(keys.length); + for (int j = 0; j < keys.length; j++) { + if (cEntries[j] instanceof UndefinedBibtexEntry) { + num.add(j, -1); + } else { + num.add(j, lastNum + 1); + if (numbers.containsKey(keys[j])) { + num.set(j, numbers.get(keys[j])); + } else { + numbers.put(keys[j], num.get(j)); + lastNum = num.get(j); + } + } + } + citationMarker = style.getNumCitationMarker(num, minGroupingCount, false); + for (int j = 0; j < keys.length; j++) { + normCitMarker[j] = style.getNumCitationMarker(Collections.singletonList(num.get(j)), + minGroupingCount, false); + } + } else { + // We need to find the number of the cited entry in the bibliography, + // and use that number for the cite marker: + List num = findCitedEntryIndex(names.get(i), cited); + + if (num.isEmpty()) { + throw new BibEntryNotFoundException(names.get(i), Localization + .lang("Could not resolve BibTeX entry for citation marker '%0'.", names.get(i))); + } else { + citationMarker = style.getNumCitationMarker(num, minGroupingCount, false); + } + + for (int j = 0; j < keys.length; j++) { + List list = new ArrayList<>(1); + list.add(num.get(j)); + normCitMarker[j] = style.getNumCitationMarker(list, minGroupingCount, false); + } + } + } else { + + if (cEntries.length > 1) { + if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) { + Arrays.sort(cEntries, yearAuthorTitleComparator); + } else { + Arrays.sort(cEntries, entryComparator); + } + // Update key list to match the new sorting: + for (int j = 0; j < cEntries.length; j++) { + bibtexKeys[i][j] = cEntries[j].getCitationKey().orElse(null); + } + } + + citationMarker = style.getCitationMarker(Arrays.asList(cEntries), entries, + type == OOBibBase.AUTHORYEAR_PAR, null, null); + // We need "normalized" (in parenthesis) markers for uniqueness checking purposes: + for (int j = 0; j < cEntries.length; j++) { + normCitMarker[j] = style.getCitationMarker(Collections.singletonList(cEntries[j]), entries, + true, null, new int[] {-1}); + } + } + citMarkers[i] = citationMarker; + normCitMarkers[i] = normCitMarker; + } + } + + uniquefiers.clear(); + if (!style.isCitationKeyCiteMarkers() && !style.isNumberEntries()) { + // See if there are duplicate citations marks referring to different entries. If so, we need to + // use uniquefiers: + Map> refKeys = new HashMap<>(); + Map> refNums = new HashMap<>(); + for (int i = 0; i < citMarkers.length; i++) { + String[] markers = normCitMarkers[i]; // compare normalized markers, since the actual markers can be different + for (int j = 0; j < markers.length; j++) { + String marker = markers[j]; + String currentKey = bibtexKeys[i][j]; + if (refKeys.containsKey(marker)) { + // Ok, we have seen this exact marker before. + if (!refKeys.get(marker).contains(currentKey)) { + // ... but not for this entry. + refKeys.get(marker).add(currentKey); + refNums.get(marker).add(i); + } + } else { + List l = new ArrayList<>(1); + l.add(currentKey); + refKeys.put(marker, l); + List l2 = new ArrayList<>(1); + l2.add(i); + refNums.put(marker, l2); + } + } + } + // Go through the collected lists and see where we need to uniquefy: + for (Map.Entry> stringListEntry : refKeys.entrySet()) { + List keys = stringListEntry.getValue(); + if (keys.size() > 1) { + // This marker appears for more than one unique entry: + int uniq = 'a'; + for (String key : keys) { + // Update the map of uniquefiers for the benefit of both the following generation of new + // citation markers, and for the method that builds the bibliography: + uniquefiers.put(key, String.valueOf((char) uniq)); + uniq++; + } + } + } + + // Finally, go through all citation markers, and update those referring to entries in our current list: + int maxAuthorsFirst = style.getIntCitProperty(OOBibStyle.MAX_AUTHORS_FIRST); + Set seenBefore = new HashSet<>(); + for (int j = 0; j < bibtexKeys.length; j++) { + boolean needsChange = false; + int[] firstLimAuthors = new int[bibtexKeys[j].length]; + String[] uniquif = new String[bibtexKeys[j].length]; + BibEntry[] cEntries = new BibEntry[bibtexKeys[j].length]; + for (int k = 0; k < bibtexKeys[j].length; k++) { + String currentKey = bibtexKeys[j][k]; + firstLimAuthors[k] = -1; + if (maxAuthorsFirst > 0) { + if (!seenBefore.contains(currentKey)) { + firstLimAuthors[k] = maxAuthorsFirst; + } + seenBefore.add(currentKey); + } + String uniq = uniquefiers.get(currentKey); + Optional tmpEntry = Optional.empty(); + if (uniq == null) { + if (firstLimAuthors[k] > 0) { + needsChange = true; + BibDatabase database = linkSourceBase.get(currentKey); + if (database != null) { + tmpEntry = database.getEntryByCitationKey(currentKey); + } + } else { + BibDatabase database = linkSourceBase.get(currentKey); + if (database != null) { + tmpEntry = database.getEntryByCitationKey(currentKey); + } + } + uniquif[k] = ""; + } else { + needsChange = true; + BibDatabase database = linkSourceBase.get(currentKey); + if (database != null) { + tmpEntry = database.getEntryByCitationKey(currentKey); + } + uniquif[k] = uniq; + } + if (tmpEntry.isPresent()) { + cEntries[k] = tmpEntry.get(); + } + } + if (needsChange) { + citMarkers[j] = style.getCitationMarker(Arrays.asList(cEntries), entries, + types[j] == OOBibBase.AUTHORYEAR_PAR, uniquif, firstLimAuthors); + } + } + } + + // Refresh all reference marks with the citation markers we computed: + boolean hadBibSection = getBookmarkRange(OOBibBase.BIB_SECTION_NAME) != null; + // Check if we are supposed to set a character format for citations: + boolean mustTestCharFormat = style.isFormatCitations(); + for (int i = 0; i < names.size(); i++) { + Object referenceMark = xReferenceMarks.getByName(names.get(i)); + XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark); + + XTextCursor cursor = bookmark.getAnchor().getText().createTextCursorByRange(bookmark.getAnchor()); + + if (mustTestCharFormat) { + // If we are supposed to set character format for citations, must run a test before we + // delete old citation markers. Otherwise, if the specified character format doesn't + // exist, we end up deleting the markers before the process crashes due to a the missing + // format, with catastrophic consequences for the user. + mustTestCharFormat = false; // need to do this only once + XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, cursor); + String charStyle = style.getCitationCharacterFormat(); + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | + WrappedTargetException ex) { + throw new UndefinedCharacterFormatException(charStyle); + } + } + + text.removeTextContent(bookmark); + + insertReferenceMark(names.get(i), citMarkers[i], cursor, types[i] != OOBibBase.INVISIBLE_CIT, style); + if (hadBibSection && (getBookmarkRange(OOBibBase.BIB_SECTION_NAME) == null)) { + // We have overwritten the marker for the start of the reference list. + // We need to add it again. + cursor.collapseToEnd(); + OOUtil.insertParagraphBreak(text, cursor); + insertBookMark(OOBibBase.BIB_SECTION_NAME, cursor); + } + } + + List unresolvedKeys = new ArrayList<>(); + for (BibEntry entry : entries.keySet()) { + if (entry instanceof UndefinedBibtexEntry) { + String key = ((UndefinedBibtexEntry) entry).getKey(); + if (!unresolvedKeys.contains(key)) { + unresolvedKeys.add(key); + } + } + } + return unresolvedKeys; + } + + private List getSortedReferenceMarks(final XNameAccess nameAccess) + throws WrappedTargetException, NoSuchElementException { + XTextViewCursorSupplier cursorSupplier = UnoRuntime.queryInterface(XTextViewCursorSupplier.class, + mxDoc.getCurrentController()); + + XTextViewCursor viewCursor = cursorSupplier.getViewCursor(); + XTextRange initialPos = viewCursor.getStart(); + List names = Arrays.asList(nameAccess.getElementNames()); + List positions = new ArrayList<>(names.size()); + for (String name : names) { + XTextContent textContent = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(name)); + XTextRange range = textContent.getAnchor(); + // Check if we are inside a footnote: + if (UnoRuntime.queryInterface(XFootnote.class, range.getText()) != null) { + // Find the linking footnote marker: + XFootnote footer = UnoRuntime.queryInterface(XFootnote.class, range.getText()); + // The footnote's anchor gives the correct position in the text: + range = footer.getAnchor(); + } + + positions.add(findPosition(viewCursor, range)); + } + Set set = new TreeSet<>(); + for (int i = 0; i < positions.size(); i++) { + set.add(new ComparableMark(names.get(i), positions.get(i))); + } + + List result = new ArrayList<>(set.size()); + for (ComparableMark mark : set) { + result.add(mark.getName()); + } + viewCursor.gotoRange(initialPos, false); + + return result; + } + + public XNameAccess getReferenceMarks() { + XReferenceMarksSupplier supplier = UnoRuntime.queryInterface(XReferenceMarksSupplier.class, xCurrentComponent); + return supplier.getReferenceMarks(); + } + + private String getUniqueReferenceMarkName(String bibtexKey, int type) { + XNameAccess xNamedRefMarks = getReferenceMarks(); + int i = 0; + String name = OOBibBase.BIB_CITATION + '_' + type + '_' + bibtexKey; + while (xNamedRefMarks.hasByName(name)) { + name = OOBibBase.BIB_CITATION + i + '_' + type + '_' + bibtexKey; + i++; + } + return name; + } + + public void rebuildBibTextSection(List databases, OOBibStyle style) + throws NoSuchElementException, WrappedTargetException, IllegalArgumentException, + CreationException, PropertyVetoException, UnknownPropertyException, UndefinedParagraphFormatException { + List cited = findCitedKeys(); + Map linkSourceBase = new HashMap<>(); + Map entries = findCitedEntries(databases, cited, linkSourceBase); // Although entries are redefined without use, this also updates linkSourceBase + + List names = sortedReferenceMarks; + + if (style.isSortByPosition()) { + // We need to sort the entries according to their order of appearance: + entries = getSortedEntriesFromSortedRefMarks(names, linkSourceBase); + } else { + SortedMap newMap = new TreeMap<>(entryComparator); + for (Map.Entry bibtexEntryBibtexDatabaseEntry : findCitedEntries(databases, cited, + linkSourceBase).entrySet()) { + newMap.put(bibtexEntryBibtexDatabaseEntry.getKey(), bibtexEntryBibtexDatabaseEntry.getValue()); + } + entries = newMap; + } + clearBibTextSectionContent2(); + populateBibTextSection(entries, style); + } + + private List findCitedKeys() throws NoSuchElementException, WrappedTargetException { + XNameAccess xNamedMarks = getReferenceMarks(); + String[] names = xNamedMarks.getElementNames(); + List keys = new ArrayList<>(); + for (String name1 : names) { + Object bookmark = xNamedMarks.getByName(name1); + UnoRuntime.queryInterface(XTextContent.class, bookmark); + + List newKeys = parseRefMarkName(name1); + for (String key : newKeys) { + if (!keys.contains(key)) { + keys.add(key); + } + } + } + + return keys; + } + + private Map findCitedEntries(List databases, List keys, + Map linkSourceBase) { + Map entries = new LinkedHashMap<>(); + for (String key : keys) { + boolean found = false; + for (BibDatabase database : databases) { + Optional entry = database.getEntryByCitationKey(key); + if (entry.isPresent()) { + entries.put(entry.get(), database); + linkSourceBase.put(key, database); + found = true; + break; + } + } + + if (!found) { + entries.put(new UndefinedBibtexEntry(key), null); + } + } + return entries; + } + + private Point findPosition(XTextViewCursor cursor, XTextRange range) { + cursor.gotoRange(range, false); + return cursor.getPosition(); + } + + /** + * Extract the list of citation keys from a reference mark name. + * + * @param name The reference mark name. + * @return The list of citation keys encoded in the name. + */ + public List parseRefMarkName(String name) { + List keys = new ArrayList<>(); + Matcher citeMatcher = CITE_PATTERN.matcher(name); + if (citeMatcher.find()) { + String[] keystring = citeMatcher.group(2).split(","); + for (String aKeystring : keystring) { + if (!keys.contains(aKeystring)) { + keys.add(aKeystring); + } + } + } + return keys; + } + + /** + * Resolve the citation key from a citation reference marker name, and look up the index of the key in a list of keys. + * + * @param citRefName The name of the ReferenceMark representing the citation. + * @param keys A List of citation keys representing the entries in the bibliography. + * @return the indices of the cited keys, -1 if a key is not found. Returns null if the ref name could not be resolved as a citation. + */ + private List findCitedEntryIndex(String citRefName, List keys) { + Matcher citeMatcher = CITE_PATTERN.matcher(citRefName); + if (citeMatcher.find()) { + List keyStrings = Arrays.asList(citeMatcher.group(2).split(",")); + List result = new ArrayList<>(keyStrings.size()); + for (String key : keyStrings) { + int ind = keys.indexOf(key); + result.add(ind == -1 ? -1 : 1 + ind); + } + return result; + } else { + return Collections.emptyList(); + } + } + + private Map getSortedEntriesFromSortedRefMarks(List names, + Map linkSourceBase) { + + Map newList = new LinkedHashMap<>(); + for (String name : names) { + Matcher citeMatcher = CITE_PATTERN.matcher(name); + if (citeMatcher.find()) { + String[] keys = citeMatcher.group(2).split(","); + for (String key : keys) { + BibDatabase database = linkSourceBase.get(key); + Optional origEntry = Optional.empty(); + if (database != null) { + origEntry = database.getEntryByCitationKey(key); + } + if (origEntry.isPresent()) { + if (!newList.containsKey(origEntry.get())) { + newList.put(origEntry.get(), database); + } + } else { + LOGGER.info("Citation key not found: '" + key + "'"); + LOGGER.info("Problem with reference mark: '" + name + "'"); + newList.put(new UndefinedBibtexEntry(key), null); + } + } + } + } + + return newList; + } + + public String getCitationContext(XNameAccess nameAccess, String refMarkName, int charBefore, int charAfter, + boolean htmlMarkup) + throws NoSuchElementException, WrappedTargetException { + Object referenceMark = nameAccess.getByName(refMarkName); + XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark); + + XTextCursor cursor = bookmark.getAnchor().getText().createTextCursorByRange(bookmark.getAnchor()); + String citPart = cursor.getString(); + int flex = 8; + for (int i = 0; i < charBefore; i++) { + try { + cursor.goLeft((short) 1, true); + if ((i >= (charBefore - flex)) && Character.isWhitespace(cursor.getString().charAt(0))) { + break; + } + } catch (IndexOutOfBoundsException ex) { + LOGGER.warn("Problem going left", ex); + } + } + int length = cursor.getString().length(); + int added = length - citPart.length(); + cursor.collapseToStart(); + for (int i = 0; i < (charAfter + length); i++) { + try { + cursor.goRight((short) 1, true); + if (i >= ((charAfter + length) - flex)) { + String strNow = cursor.getString(); + if (Character.isWhitespace(strNow.charAt(strNow.length() - 1))) { + break; + } + } + } catch (IndexOutOfBoundsException ex) { + LOGGER.warn("Problem going right", ex); + } + } + + String result = cursor.getString(); + if (htmlMarkup) { + result = result.substring(0, added) + "" + citPart + "" + result.substring(length); + } + return result.trim(); + } + + private void insertFullReferenceAtCursor(XTextCursor cursor, Map entries, OOBibStyle style, + String parFormat) + throws UndefinedParagraphFormatException, IllegalArgumentException, + UnknownPropertyException, PropertyVetoException, WrappedTargetException { + Map correctEntries; + // If we don't have numbered entries, we need to sort the entries before adding them: + if (style.isSortByPosition()) { + // Use the received map directly + correctEntries = entries; + } else { + // Sort map + Map newMap = new TreeMap<>(entryComparator); + newMap.putAll(entries); + correctEntries = newMap; + } + int number = 1; + for (Map.Entry entry : correctEntries.entrySet()) { + if (entry.getKey() instanceof UndefinedBibtexEntry) { + continue; + } + OOUtil.insertParagraphBreak(text, cursor); + if (style.isNumberEntries()) { + int minGroupingCount = style.getIntCitProperty(OOBibStyle.MINIMUM_GROUPING_COUNT); + OOUtil.insertTextAtCurrentLocation(text, cursor, + style.getNumCitationMarker(Collections.singletonList(number++), minGroupingCount, true), Collections.emptyList()); + } + Layout layout = style.getReferenceFormat(entry.getKey().getType()); + layout.setPostFormatter(POSTFORMATTER); + OOUtil.insertFullReferenceAtCurrentLocation(text, cursor, layout, parFormat, entry.getKey(), + entry.getValue(), uniquefiers.get(entry.getKey().getCitationKey().orElse(null))); + } + } + + private void createBibTextSection2(boolean end) + throws IllegalArgumentException, CreationException { + + XTextCursor mxDocCursor = text.createTextCursor(); + if (end) { + mxDocCursor.gotoEnd(false); + } + OOUtil.insertParagraphBreak(text, mxDocCursor); + // Create a new TextSection from the document factory and access it's XNamed interface + XNamed xChildNamed; + try { + xChildNamed = UnoRuntime.queryInterface(XNamed.class, + mxDocFactory.createInstance("com.sun.star.text.TextSection")); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + // Set the new sections name to 'Child_Section' + xChildNamed.setName(OOBibBase.BIB_SECTION_NAME); + // Access the Child_Section's XTextContent interface and insert it into the document + XTextContent xChildSection = UnoRuntime.queryInterface(XTextContent.class, xChildNamed); + text.insertTextContent(mxDocCursor, xChildSection, false); + } + + private void clearBibTextSectionContent2() + throws NoSuchElementException, WrappedTargetException, IllegalArgumentException, CreationException { + + // Check if the section exists: + XTextSectionsSupplier supplier = UnoRuntime.queryInterface(XTextSectionsSupplier.class, mxDoc); + if (supplier.getTextSections().hasByName(OOBibBase.BIB_SECTION_NAME)) { + XTextSection section = (XTextSection) ((Any) supplier.getTextSections().getByName(OOBibBase.BIB_SECTION_NAME)) + .getObject(); + // Clear it: + XTextCursor cursor = text.createTextCursorByRange(section.getAnchor()); + cursor.gotoRange(section.getAnchor(), false); + cursor.setString(""); + } else { + createBibTextSection2(atEnd); + } + } + + private void populateBibTextSection(Map entries, OOBibStyle style) + throws NoSuchElementException, WrappedTargetException, PropertyVetoException, + UnknownPropertyException, UndefinedParagraphFormatException, IllegalArgumentException, CreationException { + XTextSectionsSupplier supplier = UnoRuntime.queryInterface(XTextSectionsSupplier.class, mxDoc); + XTextSection section = (XTextSection) ((Any) supplier.getTextSections().getByName(OOBibBase.BIB_SECTION_NAME)) + .getObject(); + XTextCursor cursor = text.createTextCursorByRange(section.getAnchor()); + OOUtil.insertTextAtCurrentLocation(text, cursor, (String) style.getProperty(OOBibStyle.TITLE), + (String) style.getProperty(OOBibStyle.REFERENCE_HEADER_PARAGRAPH_FORMAT)); + insertFullReferenceAtCursor(cursor, entries, style, + (String) style.getProperty(OOBibStyle.REFERENCE_PARAGRAPH_FORMAT)); + insertBookMark(OOBibBase.BIB_SECTION_END_NAME, cursor); + } + + private XTextContent insertBookMark(String name, XTextCursor position) + throws IllegalArgumentException, CreationException { + Object bookmark; + try { + bookmark = mxDocFactory.createInstance("com.sun.star.text.Bookmark"); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + // name the bookmark + XNamed xNamed = UnoRuntime.queryInterface(XNamed.class, bookmark); + xNamed.setName(name); + // get XTextContent interface + XTextContent xTextContent = UnoRuntime.queryInterface(XTextContent.class, bookmark); + // insert bookmark at the end of the document + // instead of mxDocText.getEnd you could use a text cursor's XTextRange interface or any XTextRange + text.insertTextContent(position, xTextContent, true); + position.collapseToEnd(); + return xTextContent; + } + + private void insertReferenceMark(String name, String citationText, XTextCursor position, boolean withText, + OOBibStyle style) + throws UnknownPropertyException, WrappedTargetException, + PropertyVetoException, IllegalArgumentException, UndefinedCharacterFormatException, CreationException { + + // Check if there is "page info" stored for this citation. If so, insert it into + // the citation text before inserting the citation: + Optional pageInfo = getCustomProperty(name); + String citText; + if ((pageInfo.isPresent()) && !pageInfo.get().isEmpty()) { + citText = style.insertPageInfo(citationText, pageInfo.get()); + } else { + citText = citationText; + } + + Object bookmark; + try { + bookmark = mxDocFactory.createInstance("com.sun.star.text.ReferenceMark"); + } catch (Exception e) { + throw new CreationException(e.getMessage()); + } + // Name the reference + XNamed xNamed = UnoRuntime.queryInterface(XNamed.class, bookmark); + xNamed.setName(name); + + if (withText) { + position.setString(citText); + XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, position); + + // Set language to [None]: + xCursorProps.setPropertyValue("CharLocale", new Locale("zxx", "", "")); + if (style.isFormatCitations()) { + String charStyle = style.getCitationCharacterFormat(); + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | + WrappedTargetException ex) { + throw new UndefinedCharacterFormatException(charStyle); + } + } + } else { + position.setString(""); + } + + // get XTextContent interface + XTextContent xTextContent = UnoRuntime.queryInterface(XTextContent.class, bookmark); + + position.getText().insertTextContent(position, xTextContent, true); + + // Check if we should italicize the "et al." string in citations: + boolean italicize = style.getBooleanCitProperty(OOBibStyle.ITALIC_ET_AL); + if (italicize) { + String etAlString = style.getStringCitProperty(OOBibStyle.ET_AL_STRING); + int index = citText.indexOf(etAlString); + if (index >= 0) { + italicizeOrBold(position, true, index, index + etAlString.length()); + } + } + + position.collapseToEnd(); + } + + private void removeReferenceMark(String name) throws NoSuchElementException, WrappedTargetException { + XNameAccess xReferenceMarks = getReferenceMarks(); + if (xReferenceMarks.hasByName(name)) { + Object referenceMark = xReferenceMarks.getByName(name); + XTextContent bookmark = UnoRuntime.queryInterface(XTextContent.class, referenceMark); + text.removeTextContent(bookmark); + } + } + + /** + * Get the XTextRange corresponding to the named bookmark. + * + * @param name The name of the bookmark to find. + * @return The XTextRange for the bookmark. + * @throws WrappedTargetException + * @throws NoSuchElementException + */ + private XTextRange getBookmarkRange(String name) throws NoSuchElementException, WrappedTargetException { + XNameAccess xNamedBookmarks = getBookmarks(); + + // retrieve bookmark by name + if (!xNamedBookmarks.hasByName(name)) { + return null; + } + Object foundBookmark = xNamedBookmarks.getByName(name); + XTextContent xFoundBookmark = UnoRuntime.queryInterface(XTextContent.class, foundBookmark); + return xFoundBookmark.getAnchor(); + } + + private XNameAccess getBookmarks() { + // query XBookmarksSupplier from document model and get bookmarks collection + XBookmarksSupplier xBookmarksSupplier = UnoRuntime.queryInterface(XBookmarksSupplier.class, xCurrentComponent); + XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks(); + return xNamedBookmarks; + } + + private void italicizeOrBold(XTextCursor position, boolean italicize, int start, int end) + throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException { + XTextRange range = position.getStart(); + XTextCursor cursor = position.getText().createTextCursorByRange(range); + cursor.goRight((short) start, false); + cursor.goRight((short) (end - start), true); + XPropertySet xcp = UnoRuntime.queryInterface(XPropertySet.class, cursor); + if (italicize) { + xcp.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC); + } else { + xcp.setPropertyValue("CharWeight", com.sun.star.awt.FontWeight.BOLD); + } + } + + public void combineCiteMarkers(List databases, OOBibStyle style) + throws IOException, WrappedTargetException, NoSuchElementException, IllegalArgumentException, + UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException, + BibEntryNotFoundException { + XNameAccess nameAccess = getReferenceMarks(); + // TODO: doesn't work for citations in footnotes/tables + List names = getSortedReferenceMarks(nameAccess); + + final XTextRangeCompare compare = UnoRuntime.queryInterface(XTextRangeCompare.class, text); + + int piv = 0; + boolean madeModifications = false; + while (piv < (names.size() - 1)) { + XTextRange range1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv))) + .getAnchor().getEnd(); + XTextRange range2 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(piv + 1))) + .getAnchor().getStart(); + if (range1.getText() != range2.getText()) { + piv++; + continue; + } + XTextCursor mxDocCursor = range1.getText().createTextCursorByRange(range1); + mxDocCursor.goRight((short) 1, true); + boolean couldExpand = true; + while (couldExpand && (compare.compareRegionEnds(mxDocCursor, range2) > 0)) { + couldExpand = mxDocCursor.goRight((short) 1, true); + } + String cursorText = mxDocCursor.getString(); + // Check if the string contains no line breaks and only whitespace: + if ((cursorText.indexOf('\n') == -1) && cursorText.trim().isEmpty()) { + + // If we are supposed to set character format for citations, test this before + // making any changes. This way we can throw an exception before any reference + // marks are removed, preventing damage to the user's document: + if (style.isFormatCitations()) { + XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, mxDocCursor); + String charStyle = style.getCitationCharacterFormat(); + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | + WrappedTargetException ex) { + // Setting the character format failed, so we throw an exception that + // will result in an error message for the user: + throw new UndefinedCharacterFormatException(charStyle); + } + } + + List keys = parseRefMarkName(names.get(piv)); + keys.addAll(parseRefMarkName(names.get(piv + 1))); + removeReferenceMark(names.get(piv)); + removeReferenceMark(names.get(piv + 1)); + List entries = new ArrayList<>(); + for (String key : keys) { + for (BibDatabase database : databases) { + Optional entry = database.getEntryByCitationKey(key); + if (entry.isPresent()) { + entries.add(entry.get()); + break; + } + } + } + Collections.sort(entries, new FieldComparator(StandardField.YEAR)); + String keyString = String.join(",", entries.stream().map(entry -> entry.getCitationKey().orElse("")) + .collect(Collectors.toList())); + // Insert bookmark: + String bName = getUniqueReferenceMarkName(keyString, OOBibBase.AUTHORYEAR_PAR); + insertReferenceMark(bName, "tmp", mxDocCursor, true, style); + names.set(piv + 1, bName); + madeModifications = true; + } + piv++; + } + if (madeModifications) { + updateSortedReferenceMarks(); + refreshCiteMarkers(databases, style); + } + } + + /** + * Do the opposite of combineCiteMarkers. + * Combined markers are split, with a space inserted between. + */ + public void unCombineCiteMarkers(List databases, OOBibStyle style) + throws IOException, WrappedTargetException, NoSuchElementException, IllegalArgumentException, + UndefinedCharacterFormatException, UnknownPropertyException, PropertyVetoException, CreationException, + BibEntryNotFoundException { + XNameAccess nameAccess = getReferenceMarks(); + List names = getSortedReferenceMarks(nameAccess); + + final XTextRangeCompare compare = UnoRuntime.queryInterface(XTextRangeCompare.class, text); + + int pivot = 0; + boolean madeModifications = false; + while (pivot < (names.size())) { + XTextRange range1 = UnoRuntime.queryInterface(XTextContent.class, nameAccess.getByName(names.get(pivot))) + .getAnchor(); + + XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); + + // If we are supposed to set character format for citations, test this before + // making any changes. This way we can throw an exception before any reference + // marks are removed, preventing damage to the user's document: + if (style.isFormatCitations()) { + XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, textCursor); + String charStyle = style.getCitationCharacterFormat(); + try { + xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle); + } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException | + WrappedTargetException ex) { + // Setting the character format failed, so we throw an exception that + // will result in an error message for the user: + throw new UndefinedCharacterFormatException(charStyle); + } + } + + List keys = parseRefMarkName(names.get(pivot)); + if (keys.size() > 1) { + removeReferenceMark(names.get(pivot)); + + // Insert bookmark for each key + int last = keys.size() - 1; + int i = 0; + for (String key : keys) { + String newName = getUniqueReferenceMarkName(key, OOBibBase.AUTHORYEAR_PAR); + insertReferenceMark(newName, "tmp", textCursor, true, style); + textCursor.collapseToEnd(); + if (i != last) { + textCursor.setString(" "); + textCursor.collapseToEnd(); + } + i++; + } + madeModifications = true; + } + pivot++; + } + if (madeModifications) { + updateSortedReferenceMarks(); + refreshCiteMarkers(databases, style); + } + } + + public BibDatabase generateDatabase(List databases) + throws NoSuchElementException, WrappedTargetException { + BibDatabase resultDatabase = new BibDatabase(); + List cited = findCitedKeys(); + List entriesToInsert = new ArrayList<>(); + + // For each cited key + for (String key : cited) { + // Loop through the available databases + for (BibDatabase loopDatabase : databases) { + Optional entry = loopDatabase.getEntryByCitationKey(key); + // If entry found + if (entry.isPresent()) { + BibEntry clonedEntry = (BibEntry) entry.get().clone(); + // Insert a copy of the entry + entriesToInsert.add(clonedEntry); + // Check if the cloned entry has a crossref field + clonedEntry.getField(StandardField.CROSSREF).ifPresent(crossref -> { + // If the crossref entry is not already in the database + if (!resultDatabase.getEntryByCitationKey(crossref).isPresent()) { + // Add it if it is in the current library + loopDatabase.getEntryByCitationKey(crossref).ifPresent(entriesToInsert::add); + } + }); + + // Be happy with the first found BibEntry and move on to next key + break; + } + } + } + resultDatabase.insertEntries(entriesToInsert); + return resultDatabase; + } + + private static class ComparableMark implements Comparable { + + private final String name; + private final Point position; + + public ComparableMark(String name, Point position) { + this.name = name; + this.position = position; + } + + @Override + public int compareTo(ComparableMark other) { + if (position.Y == other.position.Y) { + return position.X - other.position.X; + } else { + return position.Y - other.position.Y; + } + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (o instanceof ComparableMark) { + ComparableMark other = (ComparableMark) o; + return (this.position.X == other.position.X) && (this.position.Y == other.position.Y) + && Objects.equals(this.name, other.name); + } + return false; + } + + public String getName() { + return name; + } + + @Override + public int hashCode() { + return Objects.hash(position, name); + } + } + + private class DocumentTitleViewModel { + + private final XTextDocument xTextDocument; + private final String description; + + public DocumentTitleViewModel(XTextDocument xTextDocument) { + this.xTextDocument = xTextDocument; + this.description = getDocumentTitle(xTextDocument).orElse(""); + } + + public XTextDocument getXtextDocument() { + return xTextDocument; + } + + @Override + public String toString() { + return description; + } + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java new file mode 100644 index 00000000000..9efab82773c --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -0,0 +1,285 @@ +package org.jabref.logic.openoffice; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jabref.architecture.AllowedToUseAwt; +import org.jabref.logic.layout.Layout; +import org.jabref.model.database.BibDatabase; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; +import org.jabref.model.entry.field.UnknownField; + +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.text.ControlCharacter; +import com.sun.star.text.XParagraphCursor; +import com.sun.star.text.XText; +import com.sun.star.text.XTextCursor; +import com.sun.star.uno.UnoRuntime; + +/** + * Utility methods for processing OO Writer documents. + */ +@AllowedToUseAwt("Requires AWT for changing document properties") +public class OOUtil { + + private static final String CHAR_STRIKEOUT = "CharStrikeout"; + private static final String CHAR_UNDERLINE = "CharUnderline"; + private static final String PARA_STYLE_NAME = "ParaStyleName"; + private static final String CHAR_CASE_MAP = "CharCaseMap"; + private static final String CHAR_POSTURE = "CharPosture"; + private static final String CHAR_WEIGHT = "CharWeight"; + private static final String CHAR_ESCAPEMENT_HEIGHT = "CharEscapementHeight"; + private static final String CHAR_ESCAPEMENT = "CharEscapement"; + + public enum Formatting { + BOLD, + ITALIC, + SMALLCAPS, + SUPERSCRIPT, + SUBSCRIPT, + UNDERLINE, + STRIKEOUT, + MONOSPACE + } + + private static final Pattern HTML_TAG = Pattern.compile(""); + + private static final Field UNIQUEFIER_FIELD = new UnknownField("uniq"); + + private OOUtil() { + // Just to hide the public constructor + } + + /** + * Insert a reference, formatted using a Layout, at the position of a given cursor. + * + * @param text The text to insert in. + * @param cursor The cursor giving the insert location. + * @param layout The Layout to format the reference with. + * @param parStyle The name of the paragraph style to use. + * @param entry The entry to insert. + * @param database The database the entry belongs to. + * @param uniquefier Uniqiefier letter, if any, to append to the entry's year. + */ + public static void insertFullReferenceAtCurrentLocation(XText text, XTextCursor cursor, + Layout layout, String parStyle, BibEntry entry, BibDatabase database, String uniquefier) + throws UndefinedParagraphFormatException, UnknownPropertyException, PropertyVetoException, + WrappedTargetException, IllegalArgumentException { + + // Backup the value of the uniq field, just in case the entry already has it: + Optional oldUniqVal = entry.getField(UNIQUEFIER_FIELD); + + // Set the uniq field with the supplied uniquefier: + if (uniquefier == null) { + entry.clearField(UNIQUEFIER_FIELD); + } else { + entry.setField(UNIQUEFIER_FIELD, uniquefier); + } + + // Do the layout for this entry: + String formattedText = layout.doLayout(entry, database); + + // Afterwards, reset the old value: + if (oldUniqVal.isPresent()) { + entry.setField(UNIQUEFIER_FIELD, oldUniqVal.get()); + } else { + entry.clearField(UNIQUEFIER_FIELD); + } + + // Insert the formatted text: + OOUtil.insertOOFormattedTextAtCurrentLocation(text, cursor, formattedText, parStyle); + } + + /** + * Insert a text with formatting indicated by HTML-like tags, into a text at the position given by a cursor. + * + * @param text The text to insert in. + * @param cursor The cursor giving the insert location. + * @param lText The marked-up text to insert. + * @param parStyle The name of the paragraph style to use. + * @throws WrappedTargetException + * @throws PropertyVetoException + * @throws UnknownPropertyException + * @throws IllegalArgumentException + */ + public static void insertOOFormattedTextAtCurrentLocation(XText text, XTextCursor cursor, String lText, + String parStyle) throws UndefinedParagraphFormatException, UnknownPropertyException, PropertyVetoException, + WrappedTargetException, IllegalArgumentException { + + XParagraphCursor parCursor = UnoRuntime.queryInterface( + XParagraphCursor.class, cursor); + XPropertySet props = UnoRuntime.queryInterface( + XPropertySet.class, parCursor); + + try { + props.setPropertyValue(PARA_STYLE_NAME, parStyle); + } catch (com.sun.star.lang.IllegalArgumentException ex) { + throw new UndefinedParagraphFormatException(parStyle); + } + + List formatting = new ArrayList<>(); + // We need to extract formatting. Use a simple regexp search iteration: + int piv = 0; + Matcher m = OOUtil.HTML_TAG.matcher(lText); + while (m.find()) { + String currentSubstring = lText.substring(piv, m.start()); + if (!currentSubstring.isEmpty()) { + OOUtil.insertTextAtCurrentLocation(text, cursor, currentSubstring, formatting); + } + String tag = m.group(); + // Handle tags: + if ("".equals(tag)) { + formatting.add(Formatting.BOLD); + } else if ("".equals(tag)) { + formatting.remove(Formatting.BOLD); + } else if ("".equals(tag) || "".equals(tag)) { + formatting.add(Formatting.ITALIC); + } else if ("".equals(tag) || "".equals(tag)) { + formatting.remove(Formatting.ITALIC); + } else if ("".equals(tag)) { + formatting.add(Formatting.MONOSPACE); + } else if ("".equals(tag)) { + formatting.remove(Formatting.MONOSPACE); + } else if ("".equals(tag)) { + formatting.add(Formatting.SMALLCAPS); + } else if ("".equals(tag)) { + formatting.remove(Formatting.SMALLCAPS); + } else if ("".equals(tag)) { + formatting.add(Formatting.SUPERSCRIPT); + } else if ("".equals(tag)) { + formatting.remove(Formatting.SUPERSCRIPT); + } else if ("".equals(tag)) { + formatting.add(Formatting.SUBSCRIPT); + } else if ("".equals(tag)) { + formatting.remove(Formatting.SUBSCRIPT); + } else if ("".equals(tag)) { + formatting.add(Formatting.UNDERLINE); + } else if ("".equals(tag)) { + formatting.remove(Formatting.UNDERLINE); + } else if ("".equals(tag)) { + formatting.add(Formatting.STRIKEOUT); + } else if ("".equals(tag)) { + formatting.remove(Formatting.STRIKEOUT); + } + + piv = m.end(); + } + + if (piv < lText.length()) { + OOUtil.insertTextAtCurrentLocation(text, cursor, lText.substring(piv), formatting); + } + + cursor.collapseToEnd(); + } + + public static void insertParagraphBreak(XText text, XTextCursor cursor) throws IllegalArgumentException { + text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); + cursor.collapseToEnd(); + } + + public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, String string, + List formatting) + throws UnknownPropertyException, PropertyVetoException, WrappedTargetException, + IllegalArgumentException { + text.insertString(cursor, string, true); + // Access the property set of the cursor, and set the currently selected text + // (which is the string we just inserted) to be bold + XPropertySet xCursorProps = UnoRuntime.queryInterface( + XPropertySet.class, cursor); + if (formatting.contains(Formatting.BOLD)) { + xCursorProps.setPropertyValue(CHAR_WEIGHT, + com.sun.star.awt.FontWeight.BOLD); + } else { + xCursorProps.setPropertyValue(CHAR_WEIGHT, + com.sun.star.awt.FontWeight.NORMAL); + } + + if (formatting.contains(Formatting.ITALIC)) { + xCursorProps.setPropertyValue(CHAR_POSTURE, + com.sun.star.awt.FontSlant.ITALIC); + } else { + xCursorProps.setPropertyValue(CHAR_POSTURE, + com.sun.star.awt.FontSlant.NONE); + } + + if (formatting.contains(Formatting.SMALLCAPS)) { + xCursorProps.setPropertyValue(CHAR_CASE_MAP, + com.sun.star.style.CaseMap.SMALLCAPS); + } else { + xCursorProps.setPropertyValue(CHAR_CASE_MAP, + com.sun.star.style.CaseMap.NONE); + } + + // TODO: the tag doesn't work + /* + if (formatting.contains(Formatting.MONOSPACE)) { + xCursorProps.setPropertyValue("CharFontPitch", + com.sun.star.awt.FontPitch.FIXED); + } + else { + xCursorProps.setPropertyValue("CharFontPitch", + com.sun.star.awt.FontPitch.VARIABLE); + } */ + if (formatting.contains(Formatting.SUBSCRIPT)) { + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, + (byte) -101); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, + (byte) 58); + } else if (formatting.contains(Formatting.SUPERSCRIPT)) { + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, + (byte) 101); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, + (byte) 58); + } else { + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT, + (byte) 0); + xCursorProps.setPropertyValue(CHAR_ESCAPEMENT_HEIGHT, + (byte) 100); + } + + if (formatting.contains(Formatting.UNDERLINE)) { + xCursorProps.setPropertyValue(CHAR_UNDERLINE, com.sun.star.awt.FontUnderline.SINGLE); + } else { + xCursorProps.setPropertyValue(CHAR_UNDERLINE, com.sun.star.awt.FontUnderline.NONE); + } + + if (formatting.contains(Formatting.STRIKEOUT)) { + xCursorProps.setPropertyValue(CHAR_STRIKEOUT, com.sun.star.awt.FontStrikeout.SINGLE); + } else { + xCursorProps.setPropertyValue(CHAR_STRIKEOUT, com.sun.star.awt.FontStrikeout.NONE); + } + cursor.collapseToEnd(); + } + + public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, String string, String parStyle) + throws WrappedTargetException, PropertyVetoException, UnknownPropertyException, + UndefinedParagraphFormatException { + text.insertString(cursor, string, true); + XParagraphCursor parCursor = UnoRuntime.queryInterface( + XParagraphCursor.class, cursor); + // Access the property set of the cursor, and set the currently selected text + // (which is the string we just inserted) to be bold + XPropertySet props = UnoRuntime.queryInterface( + XPropertySet.class, parCursor); + try { + props.setPropertyValue(PARA_STYLE_NAME, parStyle); + } catch (IllegalArgumentException ex) { + throw new UndefinedParagraphFormatException(parStyle); + } + cursor.collapseToEnd(); + } + + public static Object getProperty(Object o, String property) + throws UnknownPropertyException, WrappedTargetException { + XPropertySet props = UnoRuntime.queryInterface( + XPropertySet.class, o); + return props.getPropertyValue(property); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UndefinedBibtexEntry.java b/src/main/java/org/jabref/logic/openoffice/UndefinedBibtexEntry.java new file mode 100644 index 00000000000..8a1a7cf5e8f --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UndefinedBibtexEntry.java @@ -0,0 +1,22 @@ +package org.jabref.logic.openoffice; + +import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.StandardField; + +/** + * Subclass of BibEntry for representing entries referenced in a document that can't be found in JabRef's current database. + */ +public class UndefinedBibtexEntry extends BibEntry { + + private final String key; + + public UndefinedBibtexEntry(String key) { + this.key = key; + setField(StandardField.AUTHOR, OOBibStyle.UNDEFINED_CITATION_MARKER); + } + + public String getKey() { + return key; + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/UndefinedParagraphFormatException.java b/src/main/java/org/jabref/logic/openoffice/UndefinedParagraphFormatException.java new file mode 100644 index 00000000000..361f8d44f54 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/UndefinedParagraphFormatException.java @@ -0,0 +1,18 @@ +package org.jabref.logic.openoffice; + +/** + * Exception used to indicate that the plugin attempted to set a paragraph format that is not defined in the current OpenOffice document. + */ +public class UndefinedParagraphFormatException extends Exception { + + private final String formatName; + + public UndefinedParagraphFormatException(String formatName) { + super(); + this.formatName = formatName; + } + + public String getFormatName() { + return formatName; + } +} From efa4a0dc02e27c4e9d4652135e100da48d439ddc Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 8 Jun 2021 17:16:17 +0200 Subject: [PATCH 0966/1068] merge bach to H --- .../openoffice/ManageCitationsDialogView.java | 16 +- .../ManageCitationsDialogViewModel.java | 45 ++- .../gui/openoffice/OpenOfficePanel.java | 355 ++++++++++-------- .../UndefinedCharacterFormatException.java | 19 + .../logic/openoffice/action/EditSeparate.java | 4 + .../logic/openoffice/style/OOBibStyle.java | 97 +++-- src/main/resources/l10n/JabRef_en.properties | 13 +- 7 files changed, 347 insertions(+), 202 deletions(-) create mode 100644 src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index 872d1f8adc0..a312a4ef375 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -19,13 +19,16 @@ import org.jabref.model.strings.StringUtil; import com.airhacks.afterburner.views.ViewLoader; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; public class ManageCitationsDialogView extends BaseDialog { private static final String HTML_BOLD_END_TAG = "
"; private static final String HTML_BOLD_START_TAG = ""; - private final OOBibBase2 ooBase; + private final OOBibBase ooBase; @FXML private TableView citationsTableView; @FXML private TableColumn citation; @@ -35,7 +38,7 @@ public class ManageCitationsDialogView extends BaseDialog { private ManageCitationsDialogViewModel viewModel; - public ManageCitationsDialogView(OOBibBase2 ooBase) { + public ManageCitationsDialogView(OOBibBase ooBase) { this.ooBase = ooBase; ViewLoader.view(this) @@ -53,7 +56,7 @@ public ManageCitationsDialogView(OOBibBase2 ooBase) { } @FXML - private void initialize() { + private void initialize() throws NoSuchElementException, WrappedTargetException, UnknownPropertyException { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); @@ -87,11 +90,4 @@ private Node getText(String citationContext) { FlowPane flow = new FlowPane(startText, inBetweenText, endText); return flow; } - - public boolean isOkToShowThisDialog() { - if (viewModel == null || viewModel.failedToGetCitationEntries) { - return false; - } - return true; - } } diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index b854a445fa9..40cee65036f 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -9,26 +9,40 @@ import javafx.collections.FXCollections; import org.jabref.gui.DialogService; +import org.jabref.logic.l10n.Localization; import org.jabref.model.openoffice.CitationEntry; +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.WrappedTargetException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class ManageCitationsDialogViewModel { - public final boolean failedToGetCitationEntries; + private static final Logger LOGGER = LoggerFactory.getLogger(ManageCitationsDialogViewModel.class); + private final ListProperty citations = new SimpleListProperty<>(FXCollections.observableArrayList()); - private final OOBibBase2 ooBase; + private final OOBibBase ooBase; private final DialogService dialogService; - public ManageCitationsDialogViewModel(OOBibBase2 ooBase, DialogService dialogService) { + public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) throws NoSuchElementException, WrappedTargetException, UnknownPropertyException { this.ooBase = ooBase; this.dialogService = dialogService; - Optional> citationEntries = ooBase.guiActionGetCitationEntries(); - this.failedToGetCitationEntries = citationEntries.isEmpty(); - if (citationEntries.isEmpty()) { - return; - } + XNameAccess nameAccess = ooBase.getReferenceMarks(); + List names = ooBase.getJabRefReferenceMarks(nameAccess); + for (String name : names) { + + CitationEntry entry = new CitationEntry(name, + ooBase.getCitationContext(nameAccess, name, 30, 30, true), + ooBase.getCustomProperty(name)); - for (CitationEntry entry : citationEntries.get()) { CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); } @@ -36,7 +50,18 @@ public ManageCitationsDialogViewModel(OOBibBase2 ooBase, DialogService dialogSer public void storeSettings() { List ciationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); - ooBase.guiActionApplyCitationEntries(ciationEntries); + try { + for (CitationEntry entry : ciationEntries) { + Optional pageInfo = entry.getPageInfo(); + if (pageInfo.isPresent()) { + ooBase.setCustomProperty(entry.getRefMarkName(), pageInfo.get()); + } + } + } catch (UnknownPropertyException | NotRemoveableException | PropertyExistException | IllegalTypeException | + IllegalArgumentException ex) { + LOGGER.warn("Problem modifying citation", ex); + dialogService.showErrorDialogAndWait(Localization.lang("Problem modifying citation"), ex); + } } public ListProperty citationsProperty() { diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index 8b8f398c1ff..367855a4b37 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -1,5 +1,6 @@ package org.jabref.gui.openoffice; +import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; @@ -45,17 +46,24 @@ import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; -import org.jabref.logic.openoffice.action.Update; +import org.jabref.logic.openoffice.UndefinedParagraphFormatException; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.StyleLoader; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; -import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.preferences.PreferencesService; +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyExistException; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; import com.sun.star.comp.helper.BootstrapException; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.WrappedTargetException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -89,7 +97,7 @@ public class OpenOfficePanel { private final TaskExecutor taskExecutor; private final StyleLoader loader; private OpenOfficePreferences ooPrefs; - private OOBibBase2 ooBase; + private OOBibBase ooBase; private OOBibStyle style; public OpenOfficePanel(JabRefFrame frame, PreferencesService preferencesService, OpenOfficePreferences ooPrefs, KeyBindingRepository keyBindingRepository) { @@ -134,40 +142,23 @@ public Node getContent() { return vbox; } - /* Note: the style may still be null on return. - * - * Return true if failed. In this case the dialog is already shown. - */ - private boolean getOrUpdateTheStyle(String title) { - final boolean FAIL = true; - final boolean PASS = false; - - if (style == null) { - style = loader.getUsedStyle(); - } else { - try { - style.ensureUpToDate(); - } catch (IOException ex) { - LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", ex); - String msg = (Localization.lang("Unable to reload style file") - + "'" + style.getPath() + "'" - + "\n" + ex.getMessage()); - new OOError(title, msg, ex).showErrorDialog(dialogService); - return FAIL; - } - } - return PASS; - } - private void initPanel() { connect.setOnAction(e -> connectAutomatically()); manualConnect.setOnAction(e -> connectManually()); selectDocument.setTooltip(new Tooltip(Localization.lang("Select which open Writer document to work on"))); - selectDocument.setOnAction(e -> { - ooBase.guiActionSelectDocument(false); + + try { + ooBase.selectDocument(); + dialogService.notify(Localization.lang("Connected to document") + ": " + + ooBase.getCurrentDocumentTitle().orElse("")); + } catch (WrappedTargetException | IndexOutOfBoundsException | + NoSuchElementException | NoDocumentException ex) { + LOGGER.warn("Problem connecting", ex); + dialogService.showErrorDialogAndWait(ex); + } }); setStyleFile.setMaxWidth(Double.MAX_VALUE); @@ -185,39 +176,85 @@ private void initPanel() { }); pushEntries.setTooltip(new Tooltip(Localization.lang("Cite selected entries between parenthesis"))); - pushEntries.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_PAR, false)); + pushEntries.setOnAction(e -> pushEntries(true, true, false)); pushEntries.setMaxWidth(Double.MAX_VALUE); pushEntriesInt.setTooltip(new Tooltip(Localization.lang("Cite selected entries with in-text citation"))); - pushEntriesInt.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_INTEXT, false)); + pushEntriesInt.setOnAction(e -> pushEntries(false, true, false)); pushEntriesInt.setMaxWidth(Double.MAX_VALUE); pushEntriesEmpty.setTooltip(new Tooltip(Localization.lang("Insert a citation without text (the entry will appear in the reference list)"))); - pushEntriesEmpty.setOnAction(e -> pushEntries(CitationType.INVISIBLE_CIT, false)); + pushEntriesEmpty.setOnAction(e -> pushEntries(false, false, false)); pushEntriesEmpty.setMaxWidth(Double.MAX_VALUE); pushEntriesAdvanced.setTooltip(new Tooltip(Localization.lang("Cite selected entries with extra information"))); - pushEntriesAdvanced.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_INTEXT, true)); + pushEntriesAdvanced.setOnAction(e -> pushEntries(false, true, true)); pushEntriesAdvanced.setMaxWidth(Double.MAX_VALUE); update.setTooltip(new Tooltip(Localization.lang("Ensure that the bibliography is up-to-date"))); update.setOnAction(event -> { - String title = Localization.lang("Could not update bibliography"); - if (getOrUpdateTheStyle(title)) { - return; + try { + if (style == null) { + style = loader.getUsedStyle(); + } else { + style.ensureUpToDate(); + } + + ooBase.updateSortedReferenceMarks(); + + List databases = getBaseList(); + List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style); + ooBase.rebuildBibTextSection(databases, style); + if (!unresolvedKeys.isEmpty()) { + dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), + Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", + unresolvedKeys.get(0))); + } + } catch (UndefinedCharacterFormatException ex) { + reportUndefinedCharacterFormat(ex); + } catch (UndefinedParagraphFormatException ex) { + reportUndefinedParagraphFormat(ex); + } catch (ConnectionLostException ex) { + showConnectionLostErrorMessage(); + } catch (IOException ex) { + LOGGER.warn("Problem with style file", ex); + dialogService.showErrorDialogAndWait(Localization.lang("No valid style file defined"), + Localization.lang("You must select either a valid style file, or use one of the default styles.")); + } catch (BibEntryNotFoundException ex) { + LOGGER.debug("BibEntry not found", ex); + dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), Localization.lang( + "Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", + ex.getCitationKey())); + } catch (com.sun.star.lang.IllegalArgumentException | PropertyVetoException | UnknownPropertyException | WrappedTargetException | NoSuchElementException | + CreationException ex) { + LOGGER.warn("Could not update bibliography", ex); } - List databases = getBaseList(); - ooBase.guiActionUpdateDocument(databases, style); }); merge.setMaxWidth(Double.MAX_VALUE); merge.setTooltip(new Tooltip(Localization.lang("Combine pairs of citations that are separated by spaces only"))); merge.setOnAction(e -> { - ooBase.guiActionMergeCitationGroups(getBaseList(), style); + try { + ooBase.combineCiteMarkers(getBaseList(), style); + } catch (UndefinedCharacterFormatException ex) { + reportUndefinedCharacterFormat(ex); + } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | + CreationException | NoSuchElementException | WrappedTargetException | IOException | + BibEntryNotFoundException ex) { + LOGGER.warn("Problem combining cite markers", ex); + } }); unmerge.setMaxWidth(Double.MAX_VALUE); unmerge.setTooltip(new Tooltip(Localization.lang("Separate merged citations"))); unmerge.setOnAction(e -> { - ooBase.guiActionSeparateCitations(getBaseList(), style); + try { + ooBase.unCombineCiteMarkers(getBaseList(), style); + } catch (UndefinedCharacterFormatException ex) { + reportUndefinedCharacterFormat(ex); + } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | + CreationException | NoSuchElementException | WrappedTargetException | IOException | + BibEntryNotFoundException ex) { + LOGGER.warn("Problem uncombining cite markers", ex); + } }); ContextMenu settingsMenu = createSettingsPopup(); @@ -226,16 +263,22 @@ private void initPanel() { settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { - ManageCitationsDialogView dialog = new ManageCitationsDialogView(ooBase); - if (dialog.isOkToShowThisDialog()) { - dialogService.showCustomDialogAndWait(dialog); - } + dialogService.showCustomDialogAndWait(new ManageCitationsDialogView(ooBase)); }); exportCitations.setMaxWidth(Double.MAX_VALUE); exportCitations.setOnAction(event -> exportEntries()); - updateButtonAvailability(); + selectDocument.setDisable(true); + pushEntries.setDisable(true); + pushEntriesInt.setDisable(true); + pushEntriesEmpty.setDisable(true); + pushEntriesAdvanced.setDisable(true); + update.setDisable(true); + merge.setDisable(true); + unmerge.setDisable(true); + manageCitations.setDisable(true); + exportCitations.setDisable(true); HBox hbox = new HBox(); hbox.getChildren().addAll(connect, manualConnect, selectDocument, update, help); @@ -255,13 +298,36 @@ private void initPanel() { } private void exportEntries() { - final String title = Localization.lang("Problem generating new database."); - List databases = getBaseList(); - boolean returnPartialResult = false; - Optional newDatabase = ooBase.exportCitedHelper(databases, returnPartialResult); - if (newDatabase.isPresent()) { - BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase.get()); + try { + if (style == null) { + style = loader.getUsedStyle(); + } else { + style.ensureUpToDate(); + } + + ooBase.updateSortedReferenceMarks(); + + List databases = getBaseList(); + List unresolvedKeys = ooBase.refreshCiteMarkers(databases, style); + BibDatabase newDatabase = ooBase.generateDatabase(databases); + if (!unresolvedKeys.isEmpty()) { + + dialogService.showErrorDialogAndWait(Localization.lang("Unable to generate new library"), + Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", + unresolvedKeys.get(0))); + } + + BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase); this.frame.addTab(databaseContext, true); + } catch (BibEntryNotFoundException ex) { + LOGGER.debug("BibEntry not found", ex); + dialogService.showErrorDialogAndWait(Localization.lang("Unable to synchronize bibliography"), + Localization.lang("Your OpenOffice/LibreOffice document references the citation key '%0', which could not be found in your current library.", + ex.getCitationKey())); + } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | + UndefinedCharacterFormatException | NoSuchElementException | WrappedTargetException | IOException | + CreationException e) { + LOGGER.warn("Problem generating new database.", e); } } @@ -272,10 +338,7 @@ private List getBaseList() { databases.add(libraryTab.getDatabase()); } } else { - LibraryTab libraryTab = frame.getCurrentLibraryTab(); - if (libraryTab != null) { - databases.add(libraryTab.getDatabase()); - } + databases.add(frame.getCurrentLibraryTab().getDatabase()); } return databases; @@ -342,39 +405,13 @@ private void connectManually() { } } - private void updateButtonAvailability() { - boolean isConnected = (ooBase != null); - boolean isConnectedToDocument = isConnected && !ooBase.isDocumentConnectionMissing(); - - // For these, we need to watch something - boolean hasStyle = true; // (style != null); - boolean hasDatabase = true; // !getBaseList().isEmpty(); - boolean hasSelectedBibEntry = true; - - selectDocument.setDisable(!(isConnected)); - pushEntries.setDisable(!(isConnectedToDocument && hasStyle && hasDatabase)); - - boolean canCite = isConnectedToDocument && hasStyle && hasSelectedBibEntry; - pushEntriesInt.setDisable(!canCite); - pushEntriesEmpty.setDisable(!canCite); - pushEntriesAdvanced.setDisable(!canCite); - - boolean canRefreshDocument = isConnectedToDocument && hasStyle; - update.setDisable(!canRefreshDocument); - merge.setDisable(!canRefreshDocument); - unmerge.setDisable(!canRefreshDocument); - manageCitations.setDisable(!canRefreshDocument); - - exportCitations.setDisable(!(isConnectedToDocument && hasDatabase)); - } - private void connect() { ooPrefs = preferencesService.getOpenOfficePreferences(); - Task connectTask = new Task<>() { + Task connectTask = new Task<>() { @Override - protected OOBibBase2 call() throws Exception { + protected OOBibBase call() throws Exception { updateProgress(ProgressBar.INDETERMINATE_PROGRESS, ProgressBar.INDETERMINATE_PROGRESS); var path = Path.of(ooPrefs.getExecutablePath()); @@ -385,12 +422,29 @@ protected OOBibBase2 call() throws Exception { connectTask.setOnSucceeded(value -> { ooBase = connectTask.getValue(); - ooBase.guiActionSelectDocument(true); + try { + ooBase.selectDocument(); + } catch (NoSuchElementException | WrappedTargetException | NoDocumentException ex) { + dialogService.showErrorDialogAndWait(Localization.lang("Error connecting to Writer document"), Localization.lang("You need to open Writer with a document before connecting"), ex); + LOGGER.error("Error connecting to writer document", ex); + } + + if (ooBase.isConnectedToDocument()) { + dialogService.notify(Localization.lang("Connected to document") + ": " + ooBase.getCurrentDocumentTitle().orElse("")); + } // Enable actions that depend on Connect: - updateButtonAvailability(); + selectDocument.setDisable(false); + pushEntries.setDisable(false); + pushEntriesInt.setDisable(false); + pushEntriesEmpty.setDisable(false); + pushEntriesAdvanced.setDisable(false); + update.setDisable(false); + merge.setDisable(false); + unmerge.setDisable(false); + manageCitations.setDisable(false); + exportCitations.setDisable(false); }); - connectTask.setOnFailed(value -> { Throwable ex = connectTask.getException(); if (ex instanceof UnsatisfiedLinkError) { @@ -416,63 +470,20 @@ protected OOBibBase2 call() throws Exception { taskExecutor.execute(connectTask); } - private OOBibBase2 createBibBase(Path loPath) throws IOException, InvocationTargetException, IllegalAccessException, + private OOBibBase createBibBase(Path loPath) throws IOException, InvocationTargetException, IllegalAccessException, BootstrapException, CreationException, ClassNotFoundException { - return new OOBibBase2(loPath, dialogService); + return new OOBibBase(loPath, true, dialogService); } - /** - * Given the withText and inParenthesis options, - * return the corresponding citationType. - * - * @param withText False means invisible citation (no text). - * @param inParenthesis True means "(Au and Thor 2000)". - * False means "Au and Thor (2000)". - */ - private static CitationType citationTypeFromOptions(boolean withText, boolean inParenthesis) { - if (!withText) { - return CitationType.INVISIBLE_CIT; - } - return (inParenthesis - ? CitationType.AUTHORYEAR_PAR - : CitationType.AUTHORYEAR_INTEXT); - } - - private void pushEntries(CitationType citationType, boolean addPageInfo) { - final String title = Localization.lang("Error pushing entries"); - - LibraryTab libraryTab = frame.getCurrentLibraryTab(); - if (libraryTab == null) { - OOError.noDataBaseIsOpenForCiting() - .setTitle(title) - .showErrorDialog(dialogService); - return; - } - - final BibDatabase database = libraryTab.getDatabase(); - if (database == null) { - OOError.noDataBaseIsOpenForCiting() - .setTitle(title) - .showErrorDialog(dialogService); - return; - } - - List entries = libraryTab.getSelectedEntries(); - if (entries.isEmpty()) { - OOError.noEntriesSelectedForCitation() - .setTitle(title) - .showErrorDialog(dialogService); - return; - } - - if (getOrUpdateTheStyle(title)) { + private void pushEntries(boolean inParenthesisIn, boolean withText, boolean addPageInfo) { + if (!ooBase.isConnectedToDocument()) { + dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"), Localization.lang("Not connected to any Writer document. Please" + " make sure a document is open, and use the 'Select Writer document' button to connect to it.")); return; } + Boolean inParenthesis = inParenthesisIn; String pageInfo = null; if (addPageInfo) { - Boolean inParenthesis = citationType.inParenthesis(); - boolean withText = citationType.withText(); Optional citeDialogViewModel = dialogService.showCustomDialogAndWait(new AdvancedCiteDialogView()); if (citeDialogViewModel.isPresent()) { @@ -482,29 +493,42 @@ private void pushEntries(CitationType citationType, boolean addPageInfo) { pageInfo = model.pageInfoProperty().getValue(); } inParenthesis = model.citeInParProperty().getValue(); - citationType = citationTypeFromOptions(withText, inParenthesis); - } else { - // user canceled - return; } } - if (!checkThatEntriesHaveKeys(entries)) { - // Not all entries have keys and key generation was declined. - return; - } + LibraryTab libraryTab = frame.getCurrentLibraryTab(); + if (libraryTab != null) { + final BibDatabase database = libraryTab.getDatabase(); + List entries = libraryTab.getSelectedEntries(); + if (!entries.isEmpty() && checkThatEntriesHaveKeys(entries)) { - Optional syncOptions = - (ooPrefs.getSyncWhenCiting() - ? Optional.of(new Update.SyncOptions(getBaseList())) - : Optional.empty()); - - ooBase.guiActionInsertEntry(entries, - database, - style, - citationType, - pageInfo, - syncOptions); + try { + if (style == null) { + style = loader.getUsedStyle(); + } + ooBase.insertEntry(entries, database, getBaseList(), style, inParenthesis, withText, pageInfo, + ooPrefs.getSyncWhenCiting()); + } catch (FileNotFoundException ex) { + + dialogService.showErrorDialogAndWait( + Localization.lang("No valid style file defined"), + Localization.lang("You must select either a valid style file, or use one of the default styles.")); + + LOGGER.warn("Problem with style file", ex); + } catch (ConnectionLostException ex) { + showConnectionLostErrorMessage(); + } catch (UndefinedCharacterFormatException ex) { + reportUndefinedCharacterFormat(ex); + } catch (UndefinedParagraphFormatException ex) { + reportUndefinedParagraphFormat(ex); + } catch (com.sun.star.lang.IllegalArgumentException | UnknownPropertyException | PropertyVetoException | + CreationException | NoSuchElementException | WrappedTargetException | IOException | + BibEntryNotFoundException | IllegalTypeException | PropertyExistException | + NotRemoveableException ex) { + LOGGER.warn("Could not insert entry", ex); + } + } + } } /** @@ -559,6 +583,27 @@ private boolean checkThatEntriesHaveKeys(List entries) { } } + private void showConnectionLostErrorMessage() { + dialogService.showErrorDialogAndWait(Localization.lang("Connection lost"), + Localization.lang("Connection to OpenOffice/LibreOffice has been lost. " + "Please make sure OpenOffice/LibreOffice is running, and try to reconnect.")); + } + + private void reportUndefinedParagraphFormat(UndefinedParagraphFormatException ex) { + dialogService.showErrorDialogAndWait(Localization.lang("Undefined paragraph format"), + Localization.lang("Your style file specifies the paragraph format '%0', " + + "which is undefined in your current OpenOffice/LibreOffice document.", + ex.getFormatName()) + "\n" + Localization.lang("The paragraph format is controlled by the property 'ReferenceParagraphFormat' or 'ReferenceHeaderParagraphFormat' in the style file.")); + } + + private void reportUndefinedCharacterFormat(UndefinedCharacterFormatException ex) { + dialogService.showErrorDialogAndWait(Localization.lang("Undefined character format"), + Localization.lang("Your style file specifies the character format '%0', " + + "which is undefined in your current OpenOffice/LibreOffice document.", + ex.getFormatName()) + "\n" + Localization.lang("The character format is controlled by the citation property 'CitationCharacterFormat' in the style file.") + + ); + } + private ContextMenu createSettingsPopup() { ContextMenu contextMenu = new ContextMenu(); diff --git a/src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java b/src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java new file mode 100644 index 00000000000..4ab29ca2fa5 --- /dev/null +++ b/src/main/java/org/jabref/gui/openoffice/UndefinedCharacterFormatException.java @@ -0,0 +1,19 @@ +package org.jabref.gui.openoffice; + +/** + * Exception used to indicate that the plugin attempted to set a character format that is + * not defined in the current OpenOffice document. + */ +class UndefinedCharacterFormatException extends Exception { + + private final String formatName; + + public UndefinedCharacterFormatException(String formatName) { + super(); + this.formatName = formatName; + } + + public String getFormatName() { + return formatName; + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index 76774ef90fe..2809ff2f99c 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -49,6 +49,10 @@ public static boolean separateCitations(XTextDocument doc, boolean madeModifications = false; + // To reduce surprises in JabRef52 mode, impose localOrder to + // decide the visually last Citation in the group. Unless the + // style changed since refresh this is the last on the screen + // as well. fr.citationGroups.lookupCitations(databases); fr.citationGroups.imposeLocalOrder(OOProcess.comparatorForMulticite(style)); diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index 44416ea0a29..6ab425ace1b 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -513,30 +513,8 @@ public String getNumCitationMarker(List number, int minGroupingCount, b } sb.append(bracketAfter); return sb.toString(); - } - /* end_old */ - - /** - * Format a number-based citation marker for the given entries. - * - * @return The text for the citation. - */ - public OOText getNumCitationMarker2(List entries) { - final int minGroupingCount = this.getMinimumGroupingCount(); - return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, - entries, - minGroupingCount); - } - - /** - * For some tests we need to override minGroupingCount. - */ - public OOText getNumCitationMarker2(List entries, - int minGroupingCount) { - return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, - entries, - minGroupingCount); } + /* end_old */ /* begin_old */ public String getCitationMarker(List entries, Map database, boolean inParenthesis, @@ -605,6 +583,14 @@ public String getCitationMarker(List entries, Map entries, String[] uniquefiers, int from, int to) { String separator = getStringCitProperty(UNIQUEFIER_SEPARATOR); StringBuilder sb = new StringBuilder(uniquefiers[from]); @@ -618,6 +604,14 @@ private void group(List entries, String[] uniquefiers, int from, int t /* end_old */ /* begin_old */ + /** + * This method produces (Author, year) style citation strings in many different forms. + * + * @param entries The list of BibEntry to get fields from. + * @param database A map of BibEntry-BibDatabase pairs. + * @param uniquifiers Optional parameter to separate similar citations. Elements can be null if not needed. + * @return The formatted citation. + */ private String getAuthorYearParenthesisMarker(List entries, Map database, String[] uniquifiers, int[] unlimAuthors) { @@ -664,6 +658,14 @@ private String getAuthorYearParenthesisMarker(List entries, Map entries, Map database, String[] uniquefiers, int[] unlimAuthors) { @@ -717,6 +719,16 @@ private String getAuthorYearInTextMarker(List entries, Map entries) { + final int minGroupingCount = this.getMinimumGroupingCount(); + return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, + entries, + minGroupingCount); + } + + /** + * For some tests we need to override minGroupingCount. + */ + public OOText getNumCitationMarker2(List entries, + int minGroupingCount) { + return OOBibStyleGetNumCitationMarker.getNumCitationMarker2(this, + entries, + minGroupingCount); + } + /** * Format a number-based bibliography label for the given number. */ diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index 8e48a2486bd..bf4c349bb76 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1022,6 +1022,7 @@ Problem\ modifying\ citation=Problem modifying citation Problem\ collecting\ citations=Problem collecting citations Citation=Citation Connecting...=Connecting... +Could\ not\ resolve\ BibTeX\ entry\ for\ citation\ marker\ '%0'.=Could not resolve BibTeX entry for citation marker '%0'. Select\ style=Select style Journals=Journals Cite=Cite @@ -1055,12 +1056,11 @@ Combine\ pairs\ of\ citations\ that\ are\ separated\ by\ spaces\ only=Combine pa Autodetection\ failed=Autodetection failed Please\ wait...=Please wait... Connection\ lost=Connection lost +The\ paragraph\ format\ is\ controlled\ by\ the\ property\ 'ReferenceParagraphFormat'\ or\ 'ReferenceHeaderParagraphFormat'\ in\ the\ style\ file.=The paragraph format is controlled by the property 'ReferenceParagraphFormat' or 'ReferenceHeaderParagraphFormat' in the style file. +The\ character\ format\ is\ controlled\ by\ the\ citation\ property\ 'CitationCharacterFormat'\ in\ the\ style\ file.=The character format is controlled by the citation property 'CitationCharacterFormat' in the style file. -Could\ not\ update\ bibliography=Could not update bibliography Not\ connected\ to\ document=Not connected to document Problem\ combining\ cite\ markers=Problem combining cite markers -Problem\ generating\ new\ database.=Problem generating new database. -Unable\ to\ reload\ style\ file=Unable to reload style file Problem\ during\ separating\ cite\ markers=Problem during separating cite markers @@ -1174,6 +1174,8 @@ To\ disable\ the\ memory\ stick\ mode\ rename\ or\ remove\ the\ jabref.xml\ file Unable\ to\ connect.\ One\ possible\ reason\ is\ that\ JabRef\ and\ OpenOffice/LibreOffice\ are\ not\ both\ running\ in\ either\ 32\ bit\ mode\ or\ 64\ bit\ mode.=Unable to connect. One possible reason is that JabRef and OpenOffice/LibreOffice are not both running in either 32 bit mode or 64 bit mode. Delimiter(s)=Delimiter(s) When\ downloading\ files,\ or\ moving\ linked\ files\ to\ the\ file\ directory,\ prefer\ the\ BIB\ file\ location\ rather\ than\ the\ file\ directory\ set\ above=When downloading files, or moving linked files to the file directory, prefer the BIB file location rather than the file directory set above +Your\ style\ file\ specifies\ the\ character\ format\ '%0',\ which\ is\ undefined\ in\ your\ current\ OpenOffice/LibreOffice\ document.=Your style file specifies the character format '%0', which is undefined in your current OpenOffice/LibreOffice document. +Your\ style\ file\ specifies\ the\ paragraph\ format\ '%0',\ which\ is\ undefined\ in\ your\ current\ OpenOffice/LibreOffice\ document.=Your style file specifies the paragraph format '%0', which is undefined in your current OpenOffice/LibreOffice document. Searching...=Searching... Please\ enter\ a\ search\ string=Please enter a search string @@ -1843,6 +1845,9 @@ Could\ not\ connect\ to\ Vim\ server.\ Make\ sure\ that\ Vim\ is\ running\ with\ Could\ not\ connect\ to\ a\ running\ gnuserv\ process.\ Make\ sure\ that\ Emacs\ or\ XEmacs\ is\ running,\ and\ that\ the\ server\ has\ been\ started\ (by\ running\ the\ command\ 'server-start'/'gnuserv-start').=Could not connect to a running gnuserv process. Make sure that Emacs or XEmacs is running, and that the server has been started (by running the command 'server-start'/'gnuserv-start'). Error\ pushing\ entries=Error pushing entries +Undefined\ character\ format=Undefined character format +Undefined\ paragraph\ format=Undefined paragraph format + Edit\ Preamble=Edit Preamble Markings=Markings Use\ selected\ instance=Use selected instance @@ -2328,6 +2333,8 @@ Separate\ merged\ citations=Separate merged citations Separate\ citations=Separate citations Unprotect\ terms=Unprotect terms +Error\ connecting\ to\ Writer\ document=Error connecting to Writer document +You\ need\ to\ open\ Writer\ with\ a\ document\ before\ connecting=You need to open Writer with a document before connecting Generate\ a\ new\ key\ for\ imported\ entries\ (overwriting\ their\ default)=Generate a new key for imported entries (overwriting their default) Import\ settings=Import settings From 10d2feead28a9e14885ecca8f236068d6d363ed7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 10 Jun 2021 19:25:04 +0200 Subject: [PATCH 0967/1068] Makefile --- Makefile | 47 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 7 deletions(-) diff --git a/Makefile b/Makefile index d18e1e84b19..c18197073c3 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,23 @@ .PHONY: all assemble build build-notest clean check test run tmp-clean checkstyle +## https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties +## GRADLE_USER_HOME=/tmp/jabref-home +## default: ~/.gradle + +# None of these helped in getting temporary files under /tmp/jabref +# +# TMPDIR=/tmp/jabref +# TEMP=/tmp/jabref +# GRADLE_OPTS=-Djava.io.tmpdir=/tmp/jabref +# JAVA_OPTS=-Djava.io.tmpdir=/tmp/jabref +# JVM_OPTS=-Djava.io.tmpdir=/tmp/jabref +# ./gradlew -Djava.io.tmpdir=/tmp/jabref + + +GRADLE = ./gradlew + + all: build # https://devdocs.jabref.org/getting-into-the-code/guidelines-for-setting-up-a-local-workspace @@ -10,45 +27,61 @@ all: build # assemble: ./gradlew assemble +# build: - make checkstyle make tmp-clean - ./gradlew build + make checkstyle + $(GRADLE) build make tmp-clean +# build-notest: make checkstyle make tmp-clean - ./gradlew build -x test + $(GRADLE) build -x test make tmp-clean +# clean: - ./gradlew clean + $(GRADLE) clean make tmp-clean +# check: + make tmp-clean make checkstyle + $(GRADLE) check make tmp-clean - ./gradlew check +# test: + make tmp-clean make checkstyle + $(GRADLE) test make tmp-clean - ./gradlew test +# run: + make tmp-clean make checkstyle - ./gradlew run + $(GRADLE) run + make tmp-clean +# + tmp-clean: + +old-tmp-clean: rm -rf /tmp/journal[0-9][0-9][0-9][0-9][0-9][0-9]* \ /tmp/junit[0-9][0-9][0-9][0-9][0-9][0-9]* \ /tmp/gradle-worker-* \ /tmp/LICENSE*.md \ /tmp/INPROC-2016*.pdf \ /tmp/[0-9][0-9][0-9][0-9][0-9][0-9][0-9]*.tmp +# checkstyle: ./gradlew checkstyleMain 2>&1 | sed -e 's|[[]ant[:]checkstyle] [[]ERROR] ||g' ./gradlew checkstyletest 2>&1 | sed -e 's|[[]ant[:]checkstyle] [[]ERROR] ||g' +# From 0582d5630d595b8a753ff1cd074af151f6925872 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 10 Jun 2021 19:25:28 +0200 Subject: [PATCH 0968/1068] build.gradle --- build.gradle | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index ec4eebcce1a..db6652c5df6 100644 --- a/build.gradle +++ b/build.gradle @@ -71,8 +71,7 @@ modularity.disableEffectiveArgumentsAdjustment() tasks.withType(JavaCompile) { options.compilerArgs += [ - // "-Xlint:deprecation", - // "-Xlint:unchecked" + // "-Xlint:deprecation", "-Xlint:unchecked", "-Xlint:removal" ] } From f63d8cf6ac09002959c102ec58738313a12ac0d2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 10 Jun 2021 19:26:33 +0200 Subject: [PATCH 0969/1068] Short(short) is deprecated --- .../java/org/jabref/model/openoffice/uno/UnoCrossRef.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java index 02aba5afc1b..ac15137e1ec 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java @@ -57,10 +57,10 @@ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, // specify that the source is a reference mark (could also be a footnote, // bookmark or sequence field) - xFieldProps.setPropertyValue("ReferenceFieldSource", new Short(ReferenceFieldSource.REFERENCE_MARK)); + xFieldProps.setPropertyValue("ReferenceFieldSource", Short.valueOf​(ReferenceFieldSource.REFERENCE_MARK)); // We want the reference displayed as page number - xFieldProps.setPropertyValue("ReferenceFieldPart", new Short(ReferenceFieldPart.PAGE)); + xFieldProps.setPropertyValue("ReferenceFieldPart", Short.valueOf​(ReferenceFieldPart.PAGE)); // Get the XTextContent interface of the GetReference text field XTextContent xRefContent = (XTextContent) UnoCast.unoQI(XTextContent.class, xFieldProps); From 4e8f1eeac20451a2952adae891395d86aa4ea199 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 10 Jun 2021 21:13:59 +0200 Subject: [PATCH 0970/1068] cleanup tempfiles --- .../org/jabref/logic/journals/JournalAbbreviationLoader.java | 5 ++++- src/main/java/org/jabref/logic/net/URLDownload.java | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/journals/JournalAbbreviationLoader.java b/src/main/java/org/jabref/logic/journals/JournalAbbreviationLoader.java index 72f0664b046..cf7d6a177ed 100644 --- a/src/main/java/org/jabref/logic/journals/JournalAbbreviationLoader.java +++ b/src/main/java/org/jabref/logic/journals/JournalAbbreviationLoader.java @@ -25,9 +25,12 @@ public static JournalAbbreviationRepository loadRepository(JournalAbbreviationPr JournalAbbreviationRepository repository; // Initialize with built-in list try { - Path tempJournalList = Files.createTempDirectory("journal").resolve("journalList.mv"); + Path tempDir = Files.createTempDirectory("jabref-journal"); + Path tempJournalList = tempDir.resolve("journalList.mv"); Files.copy(JournalAbbreviationRepository.class.getResourceAsStream("/journals/journalList.mv"), tempJournalList); repository = new JournalAbbreviationRepository(tempJournalList); + tempDir.toFile().deleteOnExit(); + tempJournalList.toFile().deleteOnExit(); } catch (IOException e) { LOGGER.error("Error while copying journal list", e); return null; diff --git a/src/main/java/org/jabref/logic/net/URLDownload.java b/src/main/java/org/jabref/logic/net/URLDownload.java index de94af68dc5..f0c5f778d08 100644 --- a/src/main/java/org/jabref/logic/net/URLDownload.java +++ b/src/main/java/org/jabref/logic/net/URLDownload.java @@ -305,11 +305,12 @@ public Path toTemporaryFile() throws IOException { // Take everything after the last '/' as name + extension String fileNameWithExtension = sourcePath.substring(sourcePath.lastIndexOf('/') + 1); - String fileName = FileUtil.getBaseName(fileNameWithExtension); + String fileName = "jabref-" + FileUtil.getBaseName(fileNameWithExtension); String extension = "." + FileHelper.getFileExtension(fileNameWithExtension).orElse("tmp"); // Create temporary file and download to it Path file = Files.createTempFile(fileName, extension); + file.toFile().deleteOnExit(); toFile(file); return file; From 0a25497051de1649cfbb75bf9b85e314359cb584 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 10 Jun 2021 23:08:56 +0200 Subject: [PATCH 0971/1068] Exception -> com.sun.star.uno.Exception --- src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 03765f8ffd8..b7c84cb2c4f 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -72,7 +72,7 @@ private XDesktop simpleBootstrap(Path loPath) Object desktop; try { desktop = sem.createInstanceWithContext("com.sun.star.frame.Desktop", context); - } catch (Exception e) { + } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } return UnoCast.unoQI(XDesktop.class, desktop); From 8a3a446e3a70aba24e37758040a5843ca66de597 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 11 Jun 2021 11:58:51 +0200 Subject: [PATCH 0972/1068] Exception -> com.sun.star.uno.Exception --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++---- .../java/org/jabref/model/openoffice/uno/UnoNamed.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 540c5f9216b..3559cc55526 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -245,7 +245,7 @@ private XDesktop simpleBootstrap(Path loPath) Object desktop; try { desktop = xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext); - } catch (Exception e) { + } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } XDesktop resultDesktop = UnoRuntime.queryInterface(XDesktop.class, desktop); @@ -1010,7 +1010,7 @@ private void createBibTextSection2(boolean end) try { xChildNamed = UnoRuntime.queryInterface(XNamed.class, mxDocFactory.createInstance("com.sun.star.text.TextSection")); - } catch (Exception e) { + } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } // Set the new sections name to 'Child_Section' @@ -1056,7 +1056,7 @@ private XTextContent insertBookMark(String name, XTextCursor position) Object bookmark; try { bookmark = mxDocFactory.createInstance("com.sun.star.text.Bookmark"); - } catch (Exception e) { + } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } // name the bookmark @@ -1089,7 +1089,7 @@ private void insertReferenceMark(String name, String citationText, XTextCursor p Object bookmark; try { bookmark = mxDocFactory.createInstance("com.sun.star.text.ReferenceMark"); - } catch (Exception e) { + } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } // Name the reference diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java b/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java index 0d4b5ed92ce..a7515c78435 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java @@ -46,7 +46,7 @@ static XNamed insertNamedTextContent(XTextDocument doc, Object xObject; try { xObject = msf.createInstance(service); - } catch (Exception e) { + } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } From 6914b633899d02956ad90bd16bdbc13c37794d01 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 11 Jun 2021 11:59:44 +0200 Subject: [PATCH 0973/1068] rename optUnoQI -> cast, drop unoQI --- .../gui/openoffice/OOBibBaseConnect.java | 10 ++++---- .../model/openoffice/ootext/OOTextIntoOO.java | 24 +++++++++---------- .../rangesort/RangeOverlapBetween.java | 2 +- .../rangesort/RangeOverlapWithin.java | 4 ++-- .../model/openoffice/rangesort/RangeSort.java | 2 +- .../model/openoffice/uno/UnoBookmark.java | 2 +- .../jabref/model/openoffice/uno/UnoCast.java | 10 +++----- .../model/openoffice/uno/UnoCrossRef.java | 8 +++---- .../model/openoffice/uno/UnoCursor.java | 2 +- .../model/openoffice/uno/UnoNameAccess.java | 2 +- .../jabref/model/openoffice/uno/UnoNamed.java | 10 +++++--- .../model/openoffice/uno/UnoProperties.java | 2 +- .../model/openoffice/uno/UnoRedlines.java | 16 ++++++++----- .../openoffice/uno/UnoReferenceMark.java | 2 +- .../model/openoffice/uno/UnoSelection.java | 16 ++++++------- .../jabref/model/openoffice/uno/UnoStyle.java | 11 ++++----- .../model/openoffice/uno/UnoTextDocument.java | 4 ++-- .../model/openoffice/uno/UnoTextRange.java | 12 +++++----- .../model/openoffice/uno/UnoTextSection.java | 2 +- .../jabref/model/openoffice/uno/UnoUndo.java | 2 +- 20 files changed, 73 insertions(+), 70 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index b7c84cb2c4f..c9f6246062b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -75,7 +75,7 @@ private XDesktop simpleBootstrap(Path loPath) } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } - return UnoCast.unoQI(XDesktop.class, desktop); + return UnoCast.cast(XDesktop.class, desktop).get(); } private static List getTextDocuments(XDesktop desktop) @@ -90,10 +90,10 @@ private static List getTextDocuments(XDesktop desktop) while (compEnum.hasMoreElements()) { Object next = compEnum.nextElement(); - XComponent comp = UnoCast.unoQI(XComponent.class, next); - XTextDocument doc = UnoCast.unoQI(XTextDocument.class, comp); - if (doc != null) { - result.add(doc); + XComponent comp = UnoCast.cast(XComponent.class, next).get(); + Optional doc = UnoCast.cast(XTextDocument.class, comp); + if (doc.isPresent()) { + result.add(doc.get()); } } return result; diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index c02183bdecd..94eb457c56a 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -351,10 +351,10 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) */ public static void removeDirectFormatting(XTextCursor cursor) { - XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); + XMultiPropertyStates mpss = UnoCast.cast(XMultiPropertyStates.class, cursor).get(); - XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); - XPropertyState xPropertyState = UnoCast.unoQI(XPropertyState.class, cursor); + XPropertySet propertySet = UnoCast.cast(XPropertySet.class, cursor).get(); + XPropertyState xPropertyState = UnoCast.cast(XPropertyState.class, cursor).get(); try { // Special handling @@ -388,7 +388,7 @@ public static void removeDirectFormatting(XTextCursor cursor) { "ParaStyleName"); // query again, just in case it matters - propertySet = UnoCast.unoQI(XPropertySet.class, cursor); + propertySet = UnoCast.cast(XPropertySet.class, cursor).get(); XPropertySetInfo propertySetInfo = propertySet.getPropertySetInfo(); // check the result @@ -480,7 +480,7 @@ static class MyPropertyStack { MyPropertyStack(XTextCursor cursor) throws UnknownPropertyException { - XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, cursor); + XPropertySet propertySet = UnoCast.cast(XPropertySet.class, cursor).get(); XPropertySetInfo propertySetInfo = propertySet.getPropertySetInfo(); /* @@ -516,10 +516,10 @@ static class MyPropertyStack { /* * Get the initial state of the properties and add add the first layer. */ - XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); + XMultiPropertyStates mpss = UnoCast.cast(XMultiPropertyStates.class, cursor).get(); PropertyState[] propertyStates = mpss.getPropertyStates(goodNames); - XMultiPropertySet mps = UnoCast.unoQI(XMultiPropertySet.class, cursor); + XMultiPropertySet mps = UnoCast.cast(XMultiPropertySet.class, cursor).get(); Object[] initialValues = mps.getPropertyValues(goodNames); ArrayList> initialValuesOpt = new ArrayList<>(goodSize); @@ -575,8 +575,8 @@ void popLayer() { * The idea is to minimize the number of calls to OpenOffice. */ void apply(XTextCursor cursor) { - XMultiPropertySet mps = UnoCast.unoQI(XMultiPropertySet.class, cursor); - XMultiPropertyStates mpss = UnoCast.unoQI(XMultiPropertyStates.class, cursor); + XMultiPropertySet mps = UnoCast.cast(XMultiPropertySet.class, cursor).get(); + XMultiPropertyStates mpss = UnoCast.cast(XMultiPropertyStates.class, cursor).get(); ArrayList> topLayer = layers.peek(); try { // select values to be set @@ -645,7 +645,7 @@ private static List> parseAttributes(String s) { private static boolean isPropertyDefault(XTextCursor cursor, String propertyName) throws UnknownPropertyException { - XPropertyState xPropertyState = UnoCast.unoQI(XPropertyState.class, cursor); + XPropertyState xPropertyState = UnoCast.cast(XPropertyState.class, cursor).get(); PropertyState state = xPropertyState.getPropertyState(propertyName); if (state == PropertyState.AMBIGUOUS_VALUE) { throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE (expected properties for a homogeneous cursor)"); @@ -785,8 +785,8 @@ public static boolean setParagraphStyle(XTextCursor cursor, String paragraphStyl final boolean FAIL = true; final boolean PASS = false; - XParagraphCursor paragraphCursor = UnoCast.unoQI(XParagraphCursor.class, cursor); - XPropertySet propertySet = UnoCast.unoQI(XPropertySet.class, paragraphCursor); + XParagraphCursor paragraphCursor = UnoCast.cast(XParagraphCursor.class, cursor).get(); + XPropertySet propertySet = UnoCast.cast(XPropertySet.class, paragraphCursor).get(); try { propertySet.setPropertyValue(PARA_STYLE_NAME, paragraphStyle); return PASS; diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java index 152483c585c..282bb44e6c0 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java @@ -41,7 +41,7 @@ List> findFirst(XTextDocument doc, for (V aHolder : fewHolders) { XText aText = aHolder.getRange().getText(); fewTuples.add(new OOTuple3<>(aText, - UnoCast.unoQI(XTextRangeCompare.class, aText), + UnoCast.cast(XTextRangeCompare.class, aText).get(), aHolder)); } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java index b5015fca69d..cd3d693fd9d 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java @@ -61,8 +61,8 @@ List> findOverlappingRanges(RangeSort.RangePartitions input, if (partition.size() == 0) { continue; } - XTextRangeCompare cmp = UnoCast.unoQI(XTextRangeCompare.class, - partition.get(0).getRange().getText()); + XTextRangeCompare cmp = UnoCast.cast(XTextRangeCompare.class, + partition.get(0).getRange().getText()).get(); for (int i = 0; i < (partition.size() - 1); i++) { V aHolder = partition.get(i); diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java index 98573e780f0..e2683369cb3 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -23,7 +23,7 @@ public static class HolderComparatorWithinPartition implements Comparator T unoQI(Class zInterface, Object object) { - return UnoRuntime.queryInterface(zInterface, object); - } - - public static Optional optUnoQI(Class zInterface, Object object) { + public static Optional cast(Class zInterface, Object object) { return Optional.ofNullable(UnoRuntime.queryInterface(zInterface, object)); } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java index ac15137e1ec..6d2ef9f675d 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java @@ -21,7 +21,7 @@ private UnoCrossRef() { } */ public static void refresh(XTextDocument doc) { // Refresh the document - XRefreshable xRefresh = UnoCast.unoQI(XRefreshable.class, doc); + XRefreshable xRefresh = UnoCast.cast(XRefreshable.class, doc).get(); xRefresh.refresh(); } @@ -41,13 +41,13 @@ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, WrappedTargetException { // based on: https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Reference_Marks - XMultiServiceFactory msf = UnoCast.unoQI(XMultiServiceFactory.class, doc); + 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 = (XPropertySet) UnoCast.unoQI(XPropertySet.class, msf.createInstance(name)); + xFieldProps = UnoCast.cast(XPropertySet.class, msf.createInstance(name)).get(); } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } @@ -63,7 +63,7 @@ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, xFieldProps.setPropertyValue("ReferenceFieldPart", Short.valueOf​(ReferenceFieldPart.PAGE)); // Get the XTextContent interface of the GetReference text field - XTextContent xRefContent = (XTextContent) UnoCast.unoQI(XTextContent.class, xFieldProps); + XTextContent xRefContent = UnoCast.cast(XTextContent.class, xFieldProps).get(); // Insert the text field cursor.getText().insertTextContent(cursor.getEnd(), xRefContent, false); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java index 193db1e3a68..1770b6957c5 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java @@ -18,7 +18,7 @@ private UnoCursor() { } */ public static Optional getViewCursor(XTextDocument doc) { return (UnoTextDocument.getCurrentController(doc) - .flatMap(e -> UnoCast.optUnoQI(XTextViewCursorSupplier.class, e)) + .flatMap(e -> UnoCast.cast(XTextViewCursorSupplier.class, e)) .map(XTextViewCursorSupplier::getViewCursor)); } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java b/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java index 6df243a604e..243c136f382 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java @@ -18,7 +18,7 @@ public static Optional getTextContentByName(XNameAccess nameAccess throws WrappedTargetException { try { - return UnoCast.optUnoQI(XTextContent.class, nameAccess.getByName(name)); + return UnoCast.cast(XTextContent.class, nameAccess.getByName(name)); } catch (NoSuchElementException ex) { return Optional.empty(); } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java b/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java index a7515c78435..f92fb35fbbd 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java @@ -1,5 +1,7 @@ package org.jabref.model.openoffice.uno; +import java.lang.IllegalArgumentException; + import com.sun.star.container.XNamed; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.text.XTextContent; @@ -41,7 +43,7 @@ static XNamed insertNamedTextContent(XTextDocument doc, throws CreationException { - XMultiServiceFactory msf = UnoCast.unoQI(XMultiServiceFactory.class, doc); + XMultiServiceFactory msf = UnoCast.cast(XMultiServiceFactory.class, doc).get(); Object xObject; try { @@ -50,11 +52,13 @@ static XNamed insertNamedTextContent(XTextDocument doc, throw new CreationException(e.getMessage()); } - XNamed xNamed = UnoCast.unoQI(XNamed.class, xObject); + XNamed xNamed = (UnoCast.cast(XNamed.class, xObject) + .orElseThrow(() -> new IllegalArgumentException("Service is not an XNamed"))); xNamed.setName(name); // get XTextContent interface - XTextContent xTextContent = UnoCast.unoQI(XTextContent.class, xObject); + XTextContent xTextContent = (UnoCast.cast(XTextContent.class, xObject) + .orElseThrow(() -> new IllegalArgumentException("Service is not an XTextContent"))); range.getText().insertTextContent(range, xTextContent, absorb); return xNamed; } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java b/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java index 07a6de1374d..3a47818cf8b 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java @@ -26,7 +26,7 @@ private UnoProperties() { } */ public static Optional asPropertySet(XPropertyContainer propertyContainer) { - return UnoCast.optUnoQI(XPropertySet.class, propertyContainer); + return UnoCast.cast(XPropertySet.class, propertyContainer); } /* diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java b/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java index a5f5ce7c6d1..c9036e9cd73 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java @@ -1,5 +1,7 @@ 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; @@ -22,19 +24,21 @@ public static boolean getRecordChanges(XTextDocument doc) // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Settings // "Properties of com.sun.star.text.TextDocument" - XPropertySet propertySet = (UnoCast.optUnoQI(XPropertySet.class, doc) - .orElseThrow(RuntimeException::new)); + XPropertySet propertySet = UnoCast.cast(XPropertySet.class, doc).get(); return (boolean) propertySet.getPropertyValue("RecordChanges"); } - private static XRedlinesSupplier getRedlinesSupplier(XTextDocument doc) { - return UnoCast.unoQI(XRedlinesSupplier.class, doc); + private static Optional getRedlinesSupplier(XTextDocument doc) { + return UnoCast.cast(XRedlinesSupplier.class, doc); } public static int countRedlines(XTextDocument doc) { - XRedlinesSupplier supplier = getRedlinesSupplier(doc); - XEnumerationAccess enumerationAccess = supplier.getRedlines(); + Optional supplier = getRedlinesSupplier(doc); + if (supplier.isEmpty()) { + return 0; + } + XEnumerationAccess enumerationAccess = supplier.get().getRedlines(); XEnumeration enumeration = enumerationAccess.createEnumeration(); if (enumeration == null) { return 0; diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java b/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java index 1009665384d..bb24eeb1b38 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java @@ -29,7 +29,7 @@ public static XNameAccess getNameAccess(XTextDocument doc) throws NoDocumentException { - XReferenceMarksSupplier supplier = UnoCast.unoQI(XReferenceMarksSupplier.class, doc); + XReferenceMarksSupplier supplier = UnoCast.cast(XReferenceMarksSupplier.class, doc).get(); try { return supplier.getReferenceMarks(); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoSelection.java b/src/main/java/org/jabref/model/openoffice/uno/UnoSelection.java index 0ef750b9983..43d89ed157b 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoSelection.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoSelection.java @@ -29,12 +29,12 @@ private static Optional getSelectionSupplier(XTextDocument d LOGGER.warn("UnoSelection.getSelectionSupplier: getCurrentController(doc) returned empty"); return Optional.empty(); } - XSelectionSupplier supplier = UnoCast.unoQI(XSelectionSupplier.class, controller.get()); - if (supplier == null) { - LOGGER.warn("UnoSelection.getSelectionSupplier: unoQI(XSelectionSupplier) returned null"); + Optional supplier = UnoCast.cast(XSelectionSupplier.class, controller.get()); + if (supplier.isEmpty()) { + LOGGER.warn("UnoSelection.getSelectionSupplier: cast to XSelectionSupplier returned empty"); return Optional.empty(); } - return Optional.of(supplier); + return supplier; } /** @@ -91,12 +91,12 @@ public static Optional getSelectionAsXServiceInfo(XTextDocument do if (selection == null) { return Optional.empty(); } - XServiceInfo result = UnoCast.unoQI(XServiceInfo.class, selection); - if (result == null) { - LOGGER.warn("unoQI(XServiceInfo) returned null"); + Optional result = UnoCast.cast(XServiceInfo.class, selection); + if (result.isEmpty()) { + LOGGER.warn("cast to XServiceInfo returned empty"); return Optional.empty(); } - return Optional.of(result); + return result; } /** diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java index 2281bcfbd59..a7b54256a02 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java @@ -26,20 +26,19 @@ private static Optional getStyleFromFamily(XTextDocument doc, throws WrappedTargetException { - XStyleFamiliesSupplier fss = UnoCast.unoQI(XStyleFamiliesSupplier.class, doc); - XNameAccess fs = UnoCast.unoQI(XNameAccess.class, fss.getStyleFamilies()); + XStyleFamiliesSupplier fss = UnoCast.cast(XStyleFamiliesSupplier.class, doc).get(); + XNameAccess fs = UnoCast.cast(XNameAccess.class, fss.getStyleFamilies()).get(); XNameContainer xFamily; try { - xFamily = UnoCast.unoQI(XNameContainer.class, fs.getByName(familyName)); + xFamily = UnoCast.cast(XNameContainer.class, fs.getByName(familyName)).get(); } catch (NoSuchElementException ex) { String msg = String.format("Style family name '%s' is not recognized", familyName); throw new RuntimeException(msg, ex); } try { - Object s = xFamily.getByName(styleName); - XStyle xs = (XStyle) UnoCast.unoQI(XStyle.class, s); - return Optional.ofNullable(xs); + Object style = xFamily.getByName(styleName); + return UnoCast.cast(XStyle.class, style); } catch (NoSuchElementException ex) { return Optional.empty(); } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java index ae3bfdcb62d..21d461928d0 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java @@ -64,7 +64,7 @@ public static Optional getFrameTitle(XTextDocument doc) { return Optional.empty(); } - Optional propertySet = UnoCast.optUnoQI(XPropertySet.class, frame.get()); + Optional propertySet = UnoCast.cast(XPropertySet.class, frame.get()); if (propertySet.isEmpty()) { return Optional.empty(); } @@ -85,7 +85,7 @@ public static Optional getFrameTitle(XTextDocument doc) { static Optional getDocumentProperties(XTextDocument doc) { return (Optional.ofNullable(doc) - .map(e -> UnoCast.unoQI(XDocumentPropertiesSupplier.class, e)) + .flatMap(e -> UnoCast.cast(XDocumentPropertiesSupplier.class, e)) .map(XDocumentPropertiesSupplier::getDocumentProperties)); } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java index b44ed6ce38b..4e9bdf581dc 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java @@ -17,12 +17,12 @@ private UnoTextRange() { } * Returns Optional.empty if not in a footnote. */ public static Optional getFootnoteMarkRange(XTextRange original) { - XFootnote footer = UnoCast.unoQI(XFootnote.class, original.getText()); - if (footer != null) { + Optional footer = UnoCast.cast(XFootnote.class, original.getText()); + if (footer.isPresent()) { // If we are inside a footnote, // find the linking footnote marker: // The footnote's anchor gives the correct position in the text: - return Optional.ofNullable(footer.getAnchor()); + return Optional.ofNullable(footer.get().getAnchor()); } return Optional.empty(); } @@ -48,7 +48,7 @@ public static int compareStarts(XTextRange a, XTextRange b) { if (!comparables(a, b)) { throw new RuntimeException("compareStarts: got incomparable regions"); } - final XTextRangeCompare compare = UnoCast.unoQI(XTextRangeCompare.class, a.getText()); + final XTextRangeCompare compare = UnoCast.cast(XTextRangeCompare.class, a.getText()).get(); return compareStartsUnsafe(compare, a, b); } @@ -61,7 +61,7 @@ public static int compareEnds(XTextRange a, XTextRange b) { if (!comparables(a, b)) { throw new RuntimeException("compareEnds: got incomparable regions"); } - final XTextRangeCompare compare = UnoCast.unoQI(XTextRangeCompare.class, a.getText()); + final XTextRangeCompare compare = UnoCast.cast(XTextRangeCompare.class, a.getText()).get(); return (-1) * compare.compareRegionEnds(a, b); } @@ -80,7 +80,7 @@ public static int compareStartsThenEnds(XTextRange a, XTextRange b) { if (!comparables(a, b)) { throw new RuntimeException("compareStartsThenEnds: got incomparable regions"); } - final XTextRangeCompare compare = UnoCast.unoQI(XTextRangeCompare.class, a.getText()); + final XTextRangeCompare compare = UnoCast.cast(XTextRangeCompare.class, a.getText()).get(); return compareStartsThenEndsUnsafe(compare, a, b); } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java index daaad560a11..60a74905684 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java @@ -24,7 +24,7 @@ public static XNameAccess getNameAccess(XTextDocument doc) throws NoDocumentException { - XTextSectionsSupplier supplier = UnoCast.unoQI(XTextSectionsSupplier.class, doc); + XTextSectionsSupplier supplier = UnoCast.cast(XTextSectionsSupplier.class, doc).get(); try { return supplier.getTextSections(); } catch (DisposedException ex) { diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java index 0aebadb1b7e..4ec9087cfdd 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java @@ -16,7 +16,7 @@ private UnoUndo() { } public static Optional getXUndoManager(XTextDocument doc) { // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html - return (UnoCast.optUnoQI(XUndoManagerSupplier.class, doc) + return (UnoCast.cast(XUndoManagerSupplier.class, doc) .map(XUndoManagerSupplier::getUndoManager)); } From e28a22c685693ed6ad58bbaab3346a7b0afcd8ca Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 11 Jun 2021 14:09:37 +0200 Subject: [PATCH 0974/1068] no need to import from java.lang --- src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java b/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java index f92fb35fbbd..5f1f50c873d 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java @@ -1,7 +1,5 @@ package org.jabref.model.openoffice.uno; -import java.lang.IllegalArgumentException; - import com.sun.star.container.XNamed; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.text.XTextContent; From 79b165b6130d7a92a7f9db2f4be4db7498f5dfb3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 11 Jun 2021 18:09:28 +0200 Subject: [PATCH 0975/1068] do not throw RuntimeException, review exceptions thrown in model/openoffice/uno --- .../org/jabref/gui/openoffice/OOBibBase2.java | 22 +++++------ .../logic/openoffice/action/EditInsert.java | 2 +- .../logic/openoffice/action/EditMerge.java | 8 ++-- .../logic/openoffice/action/EditSeparate.java | 2 +- .../logic/openoffice/backend/Backend52.java | 24 ++++++------ .../logic/openoffice/backend/Codec52.java | 4 +- .../backend/NamedRangeReferenceMark.java | 35 ++++++++--------- .../logic/openoffice/frontend/OOFrontend.java | 8 ++-- .../frontend/UpdateBibliography.java | 11 ++---- .../frontend/UpdateCitationMarkers.java | 2 +- .../logic/openoffice/style/OOBibStyle.java | 2 +- .../style/OOBibStyleGetCitationMarker.java | 12 +++--- .../style/OOBibStyleGetNumCitationMarker.java | 15 ++++---- .../style/OOFormatBibliography.java | 13 ++++--- .../logic/openoffice/style/OOProcess.java | 6 +-- .../model/openoffice/ootext/OOFormat.java | 7 ++++ .../model/openoffice/ootext/OOTextIntoOO.java | 38 ++++++++++--------- .../openoffice/rangesort/RangeSortVisual.java | 8 ++-- .../model/openoffice/style/Citation.java | 2 +- .../openoffice/style/CitationGroups.java | 24 ++++-------- .../model/openoffice/style/CitedKey.java | 6 +-- .../model/openoffice/uno/UnoBookmark.java | 11 +++--- .../model/openoffice/uno/UnoCrossRef.java | 36 +++++++++++++----- .../model/openoffice/uno/UnoRedlines.java | 7 +++- .../openoffice/uno/UnoReferenceMark.java | 16 ++++---- .../jabref/model/openoffice/uno/UnoStyle.java | 6 +-- .../model/openoffice/uno/UnoTextDocument.java | 3 +- .../model/openoffice/uno/UnoTextRange.java | 6 +-- .../model/openoffice/uno/UnoTextSection.java | 2 - .../jabref/model/openoffice/uno/UnoUndo.java | 2 +- .../uno/UnoUserDefinedProperty.java | 32 +++++++--------- .../style/OOBibStyleTestHelper.java | 8 ++-- 32 files changed, 192 insertions(+), 188 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index b3d368b79dc..f196bae6bc4 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -322,7 +322,7 @@ private static OOVoidResult checkIfOpenOfficeIsRecordingChanges(XTextDo } return OOVoidResult.error(new OOError(title, msg)); } - } catch (UnknownPropertyException | WrappedTargetException ex) { + } catch (WrappedTargetException ex) { String msg = Localization.lang("Error while checking if Writer" + " is recording changes or has recorded changes."); return OOVoidResult.error(new OOError(title, msg, ex)); @@ -372,10 +372,10 @@ OOVoidResult selectedBibEntryIsRequired(List entries, * Checks existence and also checks if it is not an internal name. */ private OOVoidResult checkStyleExistsInTheDocument(String familyName, - String styleName, - XTextDocument doc, - String labelInJstyleFile, - String pathToStyleFile) + String styleName, + XTextDocument doc, + String labelInJstyleFile, + String pathToStyleFile) throws NoSuchElementException, WrappedTargetException { @@ -394,9 +394,9 @@ private OOVoidResult checkStyleExistsInTheDocument(String familyName, labelInJstyleFile, styleName); default -> - throw new RuntimeException("Expected " + UnoStyle.CHARACTER_STYLES - + " or " + UnoStyle.PARAGRAPH_STYLES - + " for familyName"); + throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES + + " or " + UnoStyle.PARAGRAPH_STYLES + + " for familyName"); } + "\n" + Localization.lang("Please create it in the document or change in the file:") @@ -419,9 +419,9 @@ private OOVoidResult checkStyleExistsInTheDocument(String familyName, styleName, internalName.get()); default -> - throw new RuntimeException("Expected " + UnoStyle.CHARACTER_STYLES - + " or " + UnoStyle.PARAGRAPH_STYLES - + " for familyName"); + throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES + + " or " + UnoStyle.PARAGRAPH_STYLES + + " for familyName"); } + "\n" + Localization.lang("Please use the latter in the style file below" diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index 7b81c2465c2..1345f1f2a99 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -50,7 +50,7 @@ public class EditInsert { private static String insertEntryGetCitationKey(BibEntry entry) { Optional key = entry.getCitationKey(); if (key.isEmpty()) { - throw new RuntimeException("insertEntryGetCitationKey: cannot cite entries without citation key"); + throw new IllegalArgumentException("insertEntryGetCitationKey: cannot cite entries without citation key"); } return key.get(); } diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index bd639c64351..4cd225eb1a8 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -217,7 +217,7 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { String msg = ("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end"); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } /* @@ -249,7 +249,7 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR // These two should move in sync: if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { String msg = ("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end (during expand)"); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } } @@ -293,7 +293,7 @@ private static void addToCurrentGroup(ScanState state, CitationGroup cg, XTextRa if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { String msg = ("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end"); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } /* Store data about last entry in currentGroup */ @@ -320,7 +320,7 @@ private static List scan(XTextDocument doc, OOFrontend fr) for (CitationGroup cg : cgs) { XTextRange currentRange = (fr.getMarkRange(doc, cg) - .orElseThrow(RuntimeException::new)); + .orElseThrow(IllegalStateException::new)); /* * Decide if we add cg to the group. False when the group is empty. diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index 2809ff2f99c..0293159d34f 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -65,7 +65,7 @@ public static boolean separateCitations(XTextDocument doc, XTextRange range1 = (fr .getMarkRange(doc, cg) - .orElseThrow(RuntimeException::new)); + .orElseThrow(IllegalStateException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); List cits = cg.citationsInStorageOrder; diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index a6f98583b47..cf91ad1043e 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -204,7 +204,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, Objects.requireNonNull(pageInfos); if (pageInfos.size() != citationKeys.size()) { - throw new RuntimeException("pageInfos.size != citationKeys.size"); + throw new IllegalArgumentException("pageInfos.size != citationKeys.size"); } // Get a new refMarkName @@ -255,7 +255,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, if (pageInfo.isPresent()) { String pageInfoString = OOText.toString(pageInfo.get()); - UnoUserDefinedProperty.createStringProperty(doc, refMarkName, pageInfoString); + UnoUserDefinedProperty.setStringProperty(doc, refMarkName, pageInfoString); } else { // do not inherit from trash UnoUserDefinedProperty.removeIfExists(doc, refMarkName); @@ -267,7 +267,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, this.cgidToNamedRange.put(cgid, namedRange); return cg; default: - throw new RuntimeException("Backend52 requires JabRef52 dataModel"); + throw new IllegalStateException("Backend52 requires JabRef52 dataModel"); } } @@ -306,7 +306,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, .map(Citation::getPageInfo))) .collect(Collectors.toList())); default: - throw new RuntimeException("unhandled dataModel here"); + throw new IllegalArgumentException("unhandled dataModel here"); } } @@ -320,8 +320,8 @@ public List> combinePageInfos(List joinableGroup private NamedRange getNamedRangeOrThrow(CitationGroup cg) { NamedRange namedRange = this.cgidToNamedRange.get(cg.cgid); if (namedRange == null) { - LOGGER.warn("getNamedRange: could not lookup namedRange"); - throw new RuntimeException("getNamedRange: could not lookup namedRange"); + String msg = "getNamedRange: could not lookup namedRange"; + throw new IllegalStateException("getNamedRange: could not lookup namedRange"); } return namedRange; } @@ -405,7 +405,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups String name = cg.cgid.citationGroupIdAsString(); XTextCursor cursor = (this .getRawCursorForCitationGroup(cg, doc) - .orElseThrow(RuntimeException::new)); + .orElseThrow(IllegalStateException::new)); String context = GetContext.getCursorStringWithContext(cursor, 30, 30, true); Optional pageInfo = (cg.numberOfCitations() > 0 ? (getPageInfoFromData(cg) @@ -417,9 +417,9 @@ public List getCitationEntries(XTextDocument doc, CitationGroups return citations; case JabRef60: // xx - throw new RuntimeException("getCitationEntries for JabRef60 is not implemented yet"); + throw new IllegalStateException("getCitationEntries for JabRef60 is not implemented yet"); default: - throw new RuntimeException("getCitationEntries: unhandled dataModel "); + throw new IllegalStateException("getCitationEntries: unhandled dataModel "); } } @@ -444,15 +444,15 @@ public void applyCitationEntries(XTextDocument doc, List citation pageInfo = PageInfo.normalizePageInfo(pageInfo); if (pageInfo.isPresent()) { String name = entry.getRefMarkName(); - UnoUserDefinedProperty.createStringProperty(doc, name, pageInfo.get().toString()); + UnoUserDefinedProperty.setStringProperty(doc, name, pageInfo.get().toString()); } } break; case JabRef60: // xx - throw new RuntimeException("applyCitationEntries for JabRef60 is not implemented yet"); + throw new IllegalStateException("applyCitationEntries for JabRef60 is not implemented yet"); default: - throw new RuntimeException("applyCitationEntries: unhandled dataModel "); + throw new IllegalStateException("applyCitationEntries: unhandled dataModel "); } } diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index 8a8b6aa6ff2..e4405dc6115 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -56,7 +56,7 @@ public static CitationType CitationTypeFromInt(int i) { case 3: return CitationType.INVISIBLE_CIT; default: - throw new RuntimeException("Invalid CitationType code"); + throw new IllegalArgumentException("Invalid CitationType code"); } } @@ -69,7 +69,7 @@ public static int CitationTypeToInt(CitationType i) { case INVISIBLE_CIT: return 3; default: - throw new RuntimeException("Invalid CitationType"); + throw new IllegalArgumentException("Invalid CitationType"); } } diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index ad3a29cdb7a..63d5f917fc5 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -153,7 +153,7 @@ public void nrRemoveFromDocument(XTextDocument doc) WrappedTargetException, NoDocumentException, NoSuchElementException { - UnoReferenceMark.remove(doc, this.nrGetRangeName()); + UnoReferenceMark.removeIfExists(doc, this.nrGetRangeName()); } @Override @@ -236,13 +236,13 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) if (markAsTextContent.isEmpty()) { String msg = String.format("nrGetFillCursor: markAsTextContent(%s).isEmpty (attempt %d)", name, i); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()).orElse(null); if (full == null) { String msg = String.format("nrGetFillCursor: full == null (attempt %d)", i); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } fullText = full.getString(); @@ -256,18 +256,13 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) // (fullText.length() < 2) if (i == 2) { String msg = String.format("nrGetFillCursor: (fullText.length() < 2) (attempt %d)", i); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } // too short, recreate LOGGER.warn("nrGetFillCursor: too short, recreate"); full.setString(""); - try { - UnoReferenceMark.remove(doc, name); - } catch (NoSuchElementException ex) { - String msg = String.format("nrGetFillCursor got NoSuchElementException for '%s'", name); - LOGGER.warn(msg); - } + UnoReferenceMark.removeIfExists(doc, name); final boolean insertSpaceAfter = false; final boolean withoutBrackets = false; @@ -276,15 +271,15 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) } if (full == null) { - throw new RuntimeException("nrGetFillCursorFor: full == null (after loop)"); + throw new IllegalStateException("nrGetFillCursorFor: full == null (after loop)"); } if (fullText == null) { - throw new RuntimeException("nrGetFillCursor: fullText == null (after loop)"); + throw new IllegalStateException("nrGetFillCursor: fullText == null (after loop)"); } fullText = full.getString(); if (fullText.length() < 2) { - throw new RuntimeException("nrGetFillCursor: fullText.length() < 2 (after loop)'%n"); + throw new IllegalStateException("nrGetFillCursor: fullText.length() < 2 (after loop)'%n"); } XTextCursor beta = full.getText().createTextCursorByRange(full); beta.collapseToStart(); @@ -352,7 +347,7 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) } /* - * Throw RuntimeException if the brackets are not there. + * Throw IllegalStateException if the brackets are not there. */ public static void checkFillCursor(XTextCursor cursor) { final String left = REFERENCE_MARK_LEFT_BRACKET; @@ -372,7 +367,7 @@ public static void checkFillCursor(XTextCursor cursor) { String msg = String.format("checkFillCursor:" + " ('%s') is not prefixed with REFERENCE_MARK_LEFT_BRACKET, has '%s'", cursor.getString(), alpha.getString()); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } } @@ -382,7 +377,7 @@ public static void checkFillCursor(XTextCursor cursor) { String msg = String.format("checkFillCursor:" + " ('%s') is not followed by REFERENCE_MARK_RIGHT_BRACKET, has '%s'", cursor.getString(), omega.getString()); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } } } @@ -414,24 +409,24 @@ public void nrCleanFillCursor(XTextDocument doc) String name = this.nrGetRangeName(); - XTextCursor full = this.nrGetRawCursor(doc).orElseThrow(RuntimeException::new); + XTextCursor full = this.nrGetRawCursor(doc).orElseThrow(IllegalStateException::new); final String fullText = full.getString(); final int fullTextLength = fullText.length(); if (!fullText.startsWith(left)) { String msg = String.format("nrCleanFillCursor: (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", name); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } if (!fullText.endsWith(right)) { String msg = String.format("nrCleanFillCursor: (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", name); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } final int contentLength = (fullTextLength - (leftLength + rightLength)); if (contentLength < 0) { String msg = String.format("nrCleanFillCursor: length(%s) < 0", name); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } boolean removeRight = ((contentLength >= 1) diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 22b9f13034e..2a46d49f448 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -128,7 +128,7 @@ public Optional healthReport(XTextDocument doc) for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { XTextRange range = (this .getMarkRange(doc, cg) - .orElseThrow(RuntimeException::new)); + .orElseThrow(IllegalStateException::new)); sortables.add(new RangeSortEntry<>(range, 0, cg)); } @@ -267,7 +267,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, Objects.requireNonNull(pageInfos); if (pageInfos.size() != citationKeys.size()) { - throw new RuntimeException("pageInfos.size != citationKeys.size"); + throw new IllegalArgumentException("pageInfos.size != citationKeys.size"); } CitationGroup cg = backend.createCitationGroup(doc, citationKeys, @@ -357,8 +357,8 @@ public List> citationRanges(XTextDocument new ArrayList<>(citationGroups.numberOfCitationGroups()); for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { - XTextRange range = this.getMarkRange(doc, cg).orElseThrow(RuntimeException::new); - String description = cg.cgid.citationGroupIdAsString(); // cg.cgRangeStorage.nrGetRangeName(); + XTextRange range = this.getMarkRange(doc, cg).orElseThrow(IllegalStateException::new); + String description = cg.cgid.citationGroupIdAsString(); result.add(new RangeForOverlapCheck<>(range, cg.cgid, RangeForOverlapCheck.REFERENCE_MARK_KIND, diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java index ef1a4c42dc5..2d0de320ca6 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java @@ -47,7 +47,6 @@ public static void rebuildBibTextSection(XTextDocument doc, throws NoSuchElementException, WrappedTargetException, - IllegalArgumentException, CreationException, PropertyVetoException, UnknownPropertyException, @@ -69,8 +68,7 @@ public static void rebuildBibTextSection(XTextDocument doc, */ private static void createBibTextSection2(XTextDocument doc) throws - CreationException, - IllegalArgumentException { + CreationException { // Always creating at the end of the document. // Alternatively, we could receive a cursor. @@ -89,7 +87,6 @@ private static void createBibTextSection2(XTextDocument doc) private static void clearBibTextSectionContent2(XTextDocument doc) throws CreationException, - IllegalArgumentException, NoDocumentException, WrappedTargetException { @@ -124,7 +121,7 @@ private static void populateBibTextSection(XTextDocument doc, UnknownPropertyException, WrappedTargetException { - XTextRange sectionRange = getBibliographyRange(doc).orElseThrow(RuntimeException::new); + XTextRange sectionRange = getBibliographyRange(doc).orElseThrow(IllegalStateException::new); XTextCursor cursor = doc.getText().createTextCursorByRange(sectionRange); @@ -138,13 +135,13 @@ private static void populateBibTextSection(XTextDocument doc, cursor.collapseToEnd(); // remove the inital empty paragraph from the section. - sectionRange = getBibliographyRange(doc).orElseThrow(RuntimeException::new); + sectionRange = getBibliographyRange(doc).orElseThrow(IllegalStateException::new); XTextCursor initialParagraph = doc.getText().createTextCursorByRange(sectionRange); initialParagraph.collapseToStart(); initialParagraph.goRight((short) 1, true); initialParagraph.setString(""); - UnoBookmark.remove(doc, BIB_SECTION_END_NAME); + UnoBookmark.removeIfExists(doc, BIB_SECTION_END_NAME); UnoBookmark.create(doc, BIB_SECTION_END_NAME, cursor, true); cursor.collapseToEnd(); diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index 3f2be8254ec..b3f90d380a7 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -150,7 +150,7 @@ public static void createAndFillCitationGroup(OOFrontend fr, Objects.requireNonNull(pageInfos); if (pageInfos.size() != citationKeys.size()) { - throw new RuntimeException("pageInfos.size != citationKeys.size"); + throw new IllegalArgumentException("pageInfos.size != citationKeys.size"); } CitationGroup cg = fr.createCitationGroup(doc, citationKeys, diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index 6ab425ace1b..feccb727f53 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -1101,7 +1101,7 @@ public OOText getNumCitationMarkerForBibliography(CitationMarkerNumericBibEntry // not null, check size if (pageInfos.size() != nCitations) { - throw new RuntimeException("normalizePageInfos: pageInfos.size() != nCitations"); + throw new IllegalArgumentException("normalizePageInfos: pageInfos.size() != nCitations"); } // not null, normalize elementwise diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java index ee2bba27e7e..e501cd4aaaf 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java @@ -65,10 +65,10 @@ private static String markupAuthorName(OOBibStyle style, String name) { * to mark their omission. * Set to -1 to write out all authors. * - * maxAuthors=0 is pointless, now throws RuntimeException + * maxAuthors=0 is pointless, now throws IllegalArgumentException * (Earlier it behaved as maxAuthors=1) * - * maxAuthors less than -1 : throw RuntimeException + * maxAuthors less than -1 : throw IllegalArgumentException * * @param andString For "A, B[ and ]C" * @@ -129,10 +129,10 @@ private static String formatAuthorList(OOBibStyle style, // To reduce ambiguity, throw on unexpected values of maxAuthors if (maxAuthors == 0 && nAuthors != 0) { - throw new RuntimeException("maxAuthors = 0 in formatAuthorList"); + throw new IllegalArgumentException("maxAuthors = 0 in formatAuthorList"); } if (maxAuthors < -1) { - throw new RuntimeException("maxAuthors < -1 in formatAuthorList"); + throw new IllegalArgumentException("maxAuthors < -1 in formatAuthorList"); } // emitAllAuthors == false means use "et al." @@ -724,8 +724,8 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, if (uniqueLetterDoesNotMakeUnique && nonUniqueCitationMarkerHandling.equals(NonUniqueCitationMarker.THROWS)) { - throw new RuntimeException("different citation keys," - + " but same normalizedMarker and uniqueLetter"); + throw new IllegalArgumentException("different citation keys," + + " but same normalizedMarker and uniqueLetter"); } final boolean pageInfoInhibitsJoin = (bothPageInfosAreEmpty diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java index 376c4478421..8d8422fbc51 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java @@ -91,7 +91,7 @@ private static void emitBlock(List block, final int blockSize = block.size(); if (blockSize == 0) { - throw new RuntimeException("The block is empty"); + throw new IllegalArgumentException("The block is empty"); } if (blockSize == 1) { @@ -117,17 +117,16 @@ private static void emitBlock(List block, */ if (block.stream().anyMatch(x -> x.getPageInfo().isPresent())) { - throw new RuntimeException("Found pageInfo in a block with more than one elements"); + throw new IllegalArgumentException("Found pageInfo in a block with more than one elements"); } if (block.stream().anyMatch(x -> x.getNumber().isEmpty())) { - throw new RuntimeException("Found unresolved entry" - + " in a block with more than one elements"); + throw new IllegalArgumentException("Found unresolved entry in a block with more than one elements"); } for (int j = 1; j < blockSize; j++) { if ((block.get(j).getNumber().get() - block.get(j - 1).getNumber().get()) != 1) { - throw new RuntimeException("Numbers are not consecutive"); + throw new IllegalArgumentException("Numbers are not consecutive"); } } @@ -139,7 +138,7 @@ private static void emitBlock(List block, int first = block.get(0).getNumber().get(); int last = block.get(blockSize - 1).getNumber().get(); if (last != (first + blockSize - 1)) { - throw new RuntimeException("blockSize and length of num range differ"); + throw new IllegalArgumentException("blockSize and length of num range differ"); } // Emit: "first-last" @@ -221,7 +220,7 @@ public static OOText getNumCitationMarker2(OOBibStyle style, final CitationMarkerNumericEntry current = sorted.get(i); if (current.getNumber().isPresent() && current.getNumber().get() < 0) { - throw new RuntimeException("getNumCitationMarker2: found negative value"); + throw new IllegalArgumentException("getNumCitationMarker2: found negative number"); } if (currentBlock.size() == 0) { @@ -259,7 +258,7 @@ public static OOText getNumCitationMarker2(OOBibStyle style, } if (nextBlock.size() != 0) { - throw new RuntimeException("impossible: (nextBlock.size() != 0) after loop"); + throw new IllegalStateException("impossible: (nextBlock.size() != 0) after loop"); } if (currentBlock.size() > 0) { diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index 58bbb5fdeeb..6c22c8abb09 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -169,14 +169,17 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { List citationGroups = new ArrayList<>(); for (CitationPath p : ck.getCitationPaths()) { CitationGroupId cgid = p.group; - CitationGroup cg = cgs.getCitationGroupOrThrow(cgid); - citationGroups.add(cg); + Optional cg = cgs.getCitationGroup(cgid); + if (cg.isEmpty()) { + throw new IllegalStateException(); + } + citationGroups.add(cg.get()); } // sort the citationGroups according to their indexInGlobalOrder citationGroups.sort((a, b) -> { - Integer aa = a.getIndexInGlobalOrder().orElseThrow(RuntimeException::new); - Integer bb = b.getIndexInGlobalOrder().orElseThrow(RuntimeException::new); + Integer aa = a.getIndexInGlobalOrder().orElseThrow(IllegalStateException::new); + Integer bb = b.getIndexInGlobalOrder().orElseThrow(IllegalStateException::new); return (aa.compareTo(bb)); }); @@ -185,7 +188,7 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { if (i > 0) { sb.append(", "); } - String markName = cg.getReferenceMarkNameForLinking().orElseThrow(RuntimeException::new); + String markName = cg.getReferenceMarkNameForLinking().orElseThrow(IllegalStateException::new); OOText xref = OOFormat.formatReferenceToPageNumberOfReferenceMark(markName); sb.append(xref.toString()); i++; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java index 6f7709aac10..05475fcdfac 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java @@ -66,12 +66,10 @@ public static Comparator comparatorForMulticite(OOBibStyle style) { * Fill cgs.bibliography and cgs.citationGroupsUnordered//CitationMarker * according to style. */ - public static void produceCitationMarkers(CitationGroups cgs, - List databases, - OOBibStyle style) { + public static void produceCitationMarkers(CitationGroups cgs, List databases, OOBibStyle style) { if (!cgs.hasGlobalOrder()) { - throw new RuntimeException("produceCitationMarkers: globalOrder is misssing in cgs"); + throw new IllegalStateException("produceCitationMarkers: globalOrder is misssing in cgs"); } cgs.lookupCitations(databases); diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java index 2c48a36f9b9..be5ee399e55 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java @@ -1,5 +1,12 @@ package org.jabref.model.openoffice.ootext; +/** + * Helper functions to produce some of the markup as understood by OOTextIntoOO.write + * + * These do not cover all tags, only those needed to embed markup + * from Layout and citation marker formatters into citation markers and + * bibliography. + */ public class OOFormat { /** diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index 94eb457c56a..41b7ceae806 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -32,7 +32,6 @@ import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; import com.sun.star.beans.XPropertyState; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.Locale; import com.sun.star.lang.WrappedTargetException; import com.sun.star.style.CaseMap; @@ -148,11 +147,8 @@ private OOTextIntoOO() { */ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) throws - UnknownPropertyException, PropertyVetoException, WrappedTargetException, - IllegalArgumentException, - NoSuchElementException, CreationException { Objects.requireNonNull(doc); @@ -362,7 +358,6 @@ public static void removeDirectFormatting(XTextCursor cursor) { xPropertyState.setPropertyToDefault("CharCaseMap"); } catch (UnknownPropertyException | PropertyVetoException | - IllegalArgumentException | WrappedTargetException ex) { LOGGER.warn("exception caught", ex); } @@ -401,7 +396,7 @@ public static void removeDirectFormatting(XTextCursor cursor) { continue; } } catch (UnknownPropertyException ex) { - throw new RuntimeException("Unexpected UnknownPropertyException"); + throw new java.lang.IllegalStateException("Unexpected UnknownPropertyException"); } if (knownToFail.contains(p.Name)) { continue; @@ -477,8 +472,7 @@ static class MyPropertyStack { */ final Stack>> layers; - MyPropertyStack(XTextCursor cursor) - throws UnknownPropertyException { + MyPropertyStack(XTextCursor cursor) { XPropertySet propertySet = UnoCast.cast(XPropertySet.class, cursor).get(); XPropertySetInfo propertySetInfo = propertySet.getPropertySetInfo(); @@ -517,7 +511,12 @@ static class MyPropertyStack { * Get the initial state of the properties and add add the first layer. */ XMultiPropertyStates mpss = UnoCast.cast(XMultiPropertyStates.class, cursor).get(); - PropertyState[] propertyStates = mpss.getPropertyStates(goodNames); + PropertyState[] propertyStates = null; + try { + propertyStates = mpss.getPropertyStates(goodNames); + } catch (UnknownPropertyException ex) { + throw new java.lang.IllegalStateException("Caught unexpected UnknownPropertyException"); + } XMultiPropertySet mps = UnoCast.cast(XMultiPropertySet.class, cursor).get(); Object[] initialValues = mps.getPropertyValues(goodNames); @@ -601,8 +600,6 @@ void apply(XTextCursor cursor) { LOGGER.warn("UnknownPropertyException in MyPropertyStack.apply", ex); } catch (PropertyVetoException ex) { LOGGER.warn("PropertyVetoException in MyPropertyStack.apply"); - } catch (IllegalArgumentException ex) { - LOGGER.warn("IllegalArgumentException in MyPropertyStack.apply"); } catch (WrappedTargetException ex) { LOGGER.warn("WrappedTargetException in MyPropertyStack.apply"); } @@ -648,7 +645,8 @@ private static boolean isPropertyDefault(XTextCursor cursor, String propertyName XPropertyState xPropertyState = UnoCast.cast(XPropertyState.class, cursor).get(); PropertyState state = xPropertyState.getPropertyState(propertyName); if (state == PropertyState.AMBIGUOUS_VALUE) { - throw new RuntimeException("PropertyState.AMBIGUOUS_VALUE (expected properties for a homogeneous cursor)"); + throw new java.lang.IllegalArgumentException("PropertyState.AMBIGUOUS_VALUE" + + " (expected properties for a homogeneous cursor)"); } return state == PropertyState.DEFAULT_VALUE; } @@ -712,7 +710,7 @@ private static List> setCharLocale(Locale value) { */ private static List> setCharLocale(String value) { if (value == null || "".equals(value)) { - throw new RuntimeException("setCharLocale \"\" or null"); + throw new java.lang.IllegalArgumentException("setCharLocale \"\" or null"); } String[] parts = value.split("-"); String language = (parts.length > 0) ? parts[0] : ""; @@ -792,15 +790,21 @@ public static boolean setParagraphStyle(XTextCursor cursor, String paragraphStyl return PASS; } catch (UnknownPropertyException | PropertyVetoException - | IllegalArgumentException + | com.sun.star.lang.IllegalArgumentException | WrappedTargetException ex) { return FAIL; } } - private static void insertParagraphBreak(XText text, XTextCursor cursor) - throws IllegalArgumentException { - text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); + private static void insertParagraphBreak(XText text, XTextCursor cursor) { + try { + text.insertControlCharacter(cursor, ControlCharacter.PARAGRAPH_BREAK, true); + } catch (com.sun.star.lang.IllegalArgumentException ex) { + // Assuming it means wrong code for ControlCharacter. + // https://api.libreoffice.org/docs/idl/ref/ does not tell. + // If my assumption is correct, we never get here. + throw new java.lang.IllegalArgumentException("Caught unexpected com.sun.star.lang.IllegalArgumentException", ex); + } } } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index cadbada7dc1..969f9fed44e 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -49,7 +49,7 @@ public static List> visualSort(List> input if (UnoScreenRefresh.hasControllersLocked(doc)) { final String msg = "visualSort: with ControllersLocked, viewCursor.gotoRange is probably useless"; LOGGER.warn(msg); - throw new RuntimeException(msg); + throw new IllegalStateException(msg); } XTextViewCursor viewCursor = fcursor.getViewCursor(); @@ -62,7 +62,7 @@ public static List> visualSort(List> input fcursor.restore(doc); if (positions.size() != inputSize) { - throw new RuntimeException("visualSort: positions.size() != inputSize"); + throw new IllegalStateException("visualSort: positions.size() != inputSize"); } // order by position @@ -76,7 +76,7 @@ public static List> visualSort(List> input Collections.sort(set); if (set.size() != inputSize) { - throw new RuntimeException("visualSort: set.size() != inputSize"); + throw new IllegalStateException("visualSort: set.size() != inputSize"); } // collect ordered result @@ -86,7 +86,7 @@ public static List> visualSort(List> input } if (result.size() != inputSize) { - throw new RuntimeException("visualSort: result.size() != inputSize"); + throw new IllegalStateException("visualSort: result.size() != inputSize"); } return result; diff --git a/src/main/java/org/jabref/model/openoffice/style/Citation.java b/src/main/java/org/jabref/model/openoffice/style/Citation.java index f0b732a9240..3f949237e07 100644 --- a/src/main/java/org/jabref/model/openoffice/style/Citation.java +++ b/src/main/java/org/jabref/model/openoffice/style/Citation.java @@ -112,7 +112,7 @@ public void setUniqueLetter(Optional uniqueLetter) { public void setPageInfo(Optional v) { Optional vv = PageInfo.normalizePageInfo(v); if (!vv.equals(v)) { - throw new RuntimeException("setPageInfo argument is not normalized"); + throw new IllegalArgumentException("setPageInfo argument is not normalized"); } this.pageInfo = vv; } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index 398964c9de1..bd0cca64e13 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -113,7 +113,7 @@ public List getCitationGroupsUnordered() { */ public List getCitationGroupsInGlobalOrder() { if (globalOrder.isEmpty()) { - throw new RuntimeException("getCitationGroupsInGlobalOrder: not ordered yet"); + throw new IllegalStateException("getCitationGroupsInGlobalOrder: not ordered yet"); } return OOListUtil.map(globalOrder.get(), cgid -> citationGroupsUnordered.get(cgid)); } @@ -127,7 +127,7 @@ public List getCitationGroupsInGlobalOrder() { public void setGlobalOrder(List globalOrder) { Objects.requireNonNull(globalOrder); if (globalOrder.size() != numberOfCitationGroups()) { - throw new RuntimeException("setGlobalOrder: globalOrder.size() != numberOfCitationGroups()"); + throw new IllegalStateException("setGlobalOrder: globalOrder.size() != numberOfCitationGroups()"); } this.globalOrder = Optional.of(globalOrder); @@ -180,7 +180,7 @@ public CitedKeys getCitedKeysUnordered() { public CitedKeys getCitedKeysSortedInOrderOfAppearance() { LinkedHashMap res = new LinkedHashMap<>(); if (!hasGlobalOrder()) { - throw new RuntimeException("getSortedCitedKeys: no globalOrder"); + throw new IllegalStateException("getSortedCitedKeys: no globalOrder"); } for (CitationGroup cg : getCitationGroupsInGlobalOrder()) { for (int i : cg.getLocalOrder()) { @@ -219,7 +219,8 @@ public List getUnresolvedKeys() { public void createNumberedBibliographySortedInOrderOfAppearance() { if (!bibliography.isEmpty()) { - throw new RuntimeException("createNumberedBibliographySortedInOrderOfAppearance: already have a bibliography"); + throw new IllegalStateException("createNumberedBibliographySortedInOrderOfAppearance:" + + " already have a bibliography"); } CitedKeys citedKeys = getCitedKeysSortedInOrderOfAppearance(); citedKeys.numberCitedKeysInCurrentOrder(); @@ -232,7 +233,7 @@ public void createNumberedBibliographySortedInOrderOfAppearance() { */ public void createPlainBibliographySortedByComparator(Comparator entryComparator) { if (!bibliography.isEmpty()) { - throw new RuntimeException("createPlainBibliographySortedByComparator: already have a bibliography"); + throw new IllegalStateException("createPlainBibliographySortedByComparator: already have a bibliography"); } CitedKeys citedKeys = getCitedKeysUnordered(); citedKeys.sortByComparator(entryComparator); @@ -244,7 +245,7 @@ public void createPlainBibliographySortedByComparator(Comparator entry */ public void createNumberedBibliographySortedByComparator(Comparator entryComparator) { if (!bibliography.isEmpty()) { - throw new RuntimeException("createNumberedBibliographySortedByComparator: already have a bibliography"); + throw new IllegalStateException("createNumberedBibliographySortedByComparator: already have a bibliography"); } CitedKeys citedKeys = getCitedKeysUnordered(); citedKeys.sortByComparator(entryComparator); @@ -262,17 +263,6 @@ public Optional getCitationGroup(CitationGroupId cgid) { return Optional.ofNullable(cg); } - /** - * Call this when the citation group is unquestionably there. - */ - public CitationGroup getCitationGroupOrThrow(CitationGroupId cgid) { - CitationGroup cg = citationGroupsUnordered.get(cgid); - if (cg == null) { - throw new RuntimeException("getCitationGroupOrThrow: the requested CitationGroup is not available"); - } - return cg; - } - /* * @return true if all citation groups have referenceMarkNameForLinking */ diff --git a/src/main/java/org/jabref/model/openoffice/style/CitedKey.java b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java index bc032fb46ac..f577867c539 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java @@ -105,13 +105,13 @@ void addPath(CitationPath p, Citation cit) { // Check consistency if (!cit.getLookupResult().equals(this.db)) { - throw new RuntimeException("CitedKey.addPath: mismatch on cit.db"); + throw new IllegalStateException("CitedKey.addPath: mismatch on cit.db"); } if (!cit.getNumber().equals(this.number)) { - throw new RuntimeException("CitedKey.addPath: mismatch on cit.number"); + throw new IllegalStateException("CitedKey.addPath: mismatch on cit.number"); } if (!cit.getUniqueLetter().equals(this.uniqueLetter)) { - throw new RuntimeException("CitedKey.addPath: mismatch on cit.uniqueLetter"); + throw new IllegalStateException("CitedKey.addPath: mismatch on cit.uniqueLetter"); } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java b/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java index a44d5600592..fdbbb0dd1c6 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java @@ -6,7 +6,6 @@ import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; import com.sun.star.lang.DisposedException; -import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XTextContent; @@ -64,7 +63,6 @@ public static Optional getAnchor(XTextDocument doc, String name) */ public static XNamed create(XTextDocument doc, String name, XTextRange range, boolean absorb) throws - IllegalArgumentException, CreationException { return UnoNamed.insertNamedTextContent(doc, "com.sun.star.text.Bookmark", name, range, absorb); } @@ -72,10 +70,9 @@ public static XNamed create(XTextDocument doc, String name, XTextRange range, bo /** * Remove the named bookmark if it exists. */ - public static void remove(XTextDocument doc, String name) + public static void removeIfExists(XTextDocument doc, String name) throws NoDocumentException, - NoSuchElementException, WrappedTargetException { XNameAccess marks = UnoBookmark.getNameAccess(doc); @@ -85,7 +82,11 @@ public static void remove(XTextDocument doc, String name) if (mark.isEmpty()) { return; } - doc.getText().removeTextContent(mark.get()); + try { + doc.getText().removeTextContent(mark.get()); + } catch (NoSuchElementException ex) { + // The caller gets what it expects. + } } } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java index 6d2ef9f675d..37dc580a1fb 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java @@ -36,8 +36,6 @@ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, XTextRange cursor) throws CreationException, - UnknownPropertyException, - PropertyVetoException, WrappedTargetException { // based on: https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Reference_Marks @@ -52,15 +50,35 @@ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, throw new CreationException(e.getMessage()); } - // Set the SourceName of the GetReference text field to the referenceMarkName - xFieldProps.setPropertyValue("SourceName", referenceMarkName); + 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'"); + } - // specify that the source is a reference mark (could also be a footnote, - // bookmark or sequence field) - xFieldProps.setPropertyValue("ReferenceFieldSource", Short.valueOf​(ReferenceFieldSource.REFERENCE_MARK)); + try { + // specify that the source is a reference mark (could also be a footnote, + // bookmark or sequence field) + xFieldProps.setPropertyValue("ReferenceFieldSource", Short.valueOf​(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'"); + } - // We want the reference displayed as page number - xFieldProps.setPropertyValue("ReferenceFieldPart", Short.valueOf​(ReferenceFieldPart.PAGE)); + try { + // We want the reference displayed as page number + xFieldProps.setPropertyValue("ReferenceFieldPart", Short.valueOf​(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(); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java b/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java index c9036e9cd73..2c408648d6f 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java @@ -18,7 +18,6 @@ public class UnoRedlines { public static boolean getRecordChanges(XTextDocument doc) throws - UnknownPropertyException, WrappedTargetException { // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Settings @@ -26,7 +25,11 @@ public static boolean getRecordChanges(XTextDocument doc) XPropertySet propertySet = UnoCast.cast(XPropertySet.class, doc).get(); - return (boolean) propertySet.getPropertyValue("RecordChanges"); + try { + return (boolean) propertySet.getPropertyValue("RecordChanges"); + } catch (UnknownPropertyException ex) { + throw new java.lang.IllegalStateException("Caught UnknownPropertyException on 'RecordChanges'"); + } } private static Optional getRedlinesSupplier(XTextDocument doc) { diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java b/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java index bb24eeb1b38..7a719042d79 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java @@ -59,11 +59,10 @@ public static List getListOfNames(XTextDocument doc) * * Removes both the text and the mark itself. */ - public static void remove(XTextDocument doc, String name) + public static void removeIfExists(XTextDocument doc, String name) throws WrappedTargetException, - NoDocumentException, - NoSuchElementException { + NoDocumentException { XNameAccess xReferenceMarks = UnoReferenceMark.getNameAccess(doc); @@ -72,7 +71,11 @@ public static void remove(XTextDocument doc, String name) if (mark.isEmpty()) { return; } - doc.getText().removeTextContent(mark.get()); + try { + doc.getText().removeTextContent(mark.get()); + } catch (NoSuchElementException ex) { + // The caller gets what it expects. + } } } @@ -114,10 +117,7 @@ public static Optional getAnchor(XTextDocument doc, String name) * @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) + 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); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java index a7b54256a02..dece8978713 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java @@ -20,9 +20,7 @@ public class UnoStyle { private UnoStyle() { } - private static Optional getStyleFromFamily(XTextDocument doc, - String familyName, - String styleName) + private static Optional getStyleFromFamily(XTextDocument doc, String familyName, String styleName) throws WrappedTargetException { @@ -33,7 +31,7 @@ private static Optional getStyleFromFamily(XTextDocument doc, xFamily = UnoCast.cast(XNameContainer.class, fs.getByName(familyName)).get(); } catch (NoSuchElementException ex) { String msg = String.format("Style family name '%s' is not recognized", familyName); - throw new RuntimeException(msg, ex); + throw new java.lang.IllegalArgumentException(msg, ex); } try { diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java index 21d461928d0..c7e94e6bb4c 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java @@ -70,8 +70,7 @@ public static Optional getFrameTitle(XTextDocument doc) { } try { - Optional frameTitleObj = - UnoProperties.getValueAsObject(propertySet.get(), "Title"); + Optional frameTitleObj = UnoProperties.getValueAsObject(propertySet.get(), "Title"); if (frameTitleObj.isEmpty()) { return Optional.empty(); } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java index 4e9bdf581dc..56cb1498e2a 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java @@ -46,7 +46,7 @@ public static int compareStartsUnsafe(XTextRangeCompare compare, XTextRange a, X public static int compareStarts(XTextRange a, XTextRange b) { if (!comparables(a, b)) { - throw new RuntimeException("compareStarts: got incomparable regions"); + throw new java.lang.IllegalArgumentException("compareStarts: got incomparable regions"); } final XTextRangeCompare compare = UnoCast.cast(XTextRangeCompare.class, a.getText()).get(); return compareStartsUnsafe(compare, a, b); @@ -59,7 +59,7 @@ public static int compareStarts(XTextRange a, XTextRange b) { */ public static int compareEnds(XTextRange a, XTextRange b) { if (!comparables(a, b)) { - throw new RuntimeException("compareEnds: got incomparable regions"); + 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); @@ -78,7 +78,7 @@ public static int compareStartsThenEndsUnsafe(XTextRangeCompare compare, XTextRa public static int compareStartsThenEnds(XTextRange a, XTextRange b) { if (!comparables(a, b)) { - throw new RuntimeException("compareStartsThenEnds: got incomparable regions"); + throw new java.lang.IllegalArgumentException("compareStartsThenEnds: got incomparable regions"); } final XTextRangeCompare compare = UnoCast.cast(XTextRangeCompare.class, a.getText()).get(); return compareStartsThenEndsUnsafe(compare, a, b); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java index 60a74905684..3b9797f553e 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java @@ -6,7 +6,6 @@ import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; import com.sun.star.lang.DisposedException; -import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextDocument; @@ -73,7 +72,6 @@ public static Optional getAnchor(XTextDocument doc, String name) */ public static XNamed create(XTextDocument doc, String name, XTextRange range, boolean absorb) throws - IllegalArgumentException, CreationException { return UnoNamed.insertNamedTextContent(doc, "com.sun.star.text.TextSection", name, range, absorb); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java index 4ec9087cfdd..b75bee17f3e 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java @@ -37,7 +37,7 @@ public static void leaveUndoContext(XTextDocument doc) { try { um.get().leaveUndoContext(); } catch (InvalidStateException ex) { - throw new RuntimeException("leaveUndoContext reported InvalidStateException"); + throw new IllegalStateException("leaveUndoContext reported InvalidStateException"); } } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java index 1c0a3494e7a..634edb0c57b 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java @@ -15,7 +15,6 @@ import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; import com.sun.star.document.XDocumentProperties; -import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; import com.sun.star.uno.Any; @@ -59,7 +58,7 @@ public static Optional getStringValue(XTextDocument doc, String property Optional propertySet = (UnoUserDefinedProperty.getPropertyContainer(doc) .flatMap(UnoProperties::asPropertySet)); if (propertySet.isEmpty()) { - throw new RuntimeException("getting UserDefinedProperties as XPropertySet failed"); + throw new java.lang.IllegalArgumentException("getting UserDefinedProperties as XPropertySet failed"); } try { String v = propertySet.get().getPropertyValue(property).toString(); @@ -75,12 +74,9 @@ public static Optional getStringValue(XTextDocument doc, String property * * @param value The value to be stored. */ - public static void createStringProperty(XTextDocument doc, String property, String value) + public static void setStringProperty(XTextDocument doc, String property, String value) throws - NotRemoveableException, - PropertyExistException, IllegalTypeException, - IllegalArgumentException, PropertyVetoException, WrappedTargetException { @@ -90,12 +86,12 @@ public static void createStringProperty(XTextDocument doc, String property, Stri Optional container = UnoUserDefinedProperty.getPropertyContainer(doc); if (container.isEmpty()) { - throw new RuntimeException("UnoUserDefinedProperty.getPropertyContainer failed"); + throw new java.lang.IllegalArgumentException("UnoUserDefinedProperty.getPropertyContainer failed"); } Optional propertySet = container.flatMap(UnoProperties::asPropertySet); if (propertySet.isEmpty()) { - throw new RuntimeException("asPropertySet failed"); + throw new java.lang.IllegalArgumentException("asPropertySet failed"); } XPropertySetInfo propertySetInfo = propertySet.get().getPropertySetInfo(); @@ -109,7 +105,11 @@ public static void createStringProperty(XTextDocument doc, String property, Stri } } - container.get().addProperty(property, PropertyAttribute.REMOVEABLE, new Any(Type.STRING, value)); + 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"); + } } /** @@ -119,17 +119,14 @@ public static void createStringProperty(XTextDocument doc, String property, Stri */ public static void remove(XTextDocument doc, String property) throws - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException { + NotRemoveableException { Objects.requireNonNull(property); Optional container = UnoUserDefinedProperty.getPropertyContainer(doc); if (container.isEmpty()) { - throw new RuntimeException("getUserDefinedPropertiesAsXPropertyContainer failed"); + throw new java.lang.IllegalArgumentException("getUserDefinedPropertiesAsXPropertyContainer failed"); } try { @@ -147,17 +144,14 @@ public static void remove(XTextDocument doc, String property) */ public static void removeIfExists(XTextDocument doc, String property) throws - NotRemoveableException, - PropertyExistException, - IllegalTypeException, - IllegalArgumentException { + NotRemoveableException { Objects.requireNonNull(property); Optional container = UnoUserDefinedProperty.getPropertyContainer(doc); if (container.isEmpty()) { - throw new RuntimeException("getUserDefinedPropertiesAsXPropertyContainer failed"); + throw new java.lang.IllegalArgumentException("getUserDefinedPropertiesAsXPropertyContainer failed"); } try { diff --git a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java index 2d480d496fa..ae5e83abd2f 100644 --- a/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java +++ b/src/test/java/org/jabref/logic/openoffice/style/OOBibStyleTestHelper.java @@ -98,8 +98,8 @@ static String runGetNumCitationMarker2a(OOBibStyle style, List num, int minGroupingCount, boolean inList) { if (inList) { if (num.size() != 1) { - throw new RuntimeException("Numeric label for the bibliography with " - + String.valueOf(num.size()) + " numbers?"); + throw new IllegalArgumentException("Numeric label for the bibliography with " + + String.valueOf(num.size()) + " numbers?"); } int n = num.get(0); CitationMarkerNumericBibEntryImpl x = @@ -146,8 +146,8 @@ static CitationMarkerEntry makeCitationMarkerEntry(BibEntry entry, String uniqueLetterQ, String pageInfoQ, boolean isFirstAppearanceOfSource) { - if (!entry.getCitationKey().isPresent()) { - throw new RuntimeException("!entry.getCitationKey().isPresent()"); + if (entry.getCitationKey().isEmpty()) { + throw new IllegalArgumentException("entry.getCitationKey() is empty"); } String citationKey = entry.getCitationKey().get(); Citation result = new Citation(citationKey); From ddac1bf59c21e55d6f52d80695274da3e1795429 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 12 Jun 2021 19:35:12 +0200 Subject: [PATCH 0976/1068] description in docs --- docs/SUMMARY.md | 4 + docs/openoffice/.gitignore | 2 - docs/openoffice/README.md | 4 - docs/openoffice/code-reorganization.md | 176 ++++++++++++++ docs/openoffice/order-of-appearance.md | 120 ++++++++-- docs/openoffice/overview.md | 317 ++++++++++++++----------- docs/openoffice/problems.md | 99 ++++++++ 7 files changed, 563 insertions(+), 159 deletions(-) delete mode 100644 docs/openoffice/.gitignore create mode 100644 docs/openoffice/code-reorganization.md create mode 100644 docs/openoffice/problems.md diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index 491ecca47f7..dcd6ca4ccf2 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -20,3 +20,7 @@ * [Readings on JavaFX](readings-on-coding/javafx.md) * [Useful development tooling](readings-on-coding/tools.md) * [The OpenOffice/LibreOffice panel](openoffice/README.md) + * [Overview](openoffice/overview.md) + * [Order of appearance of citation groups](openoffice/order-of-appearance.md) + * [Problems](openoffice/problems.md) + * [Code reorganization](openoffice/code-reorganization.md) diff --git a/docs/openoffice/.gitignore b/docs/openoffice/.gitignore deleted file mode 100644 index 5c96c8016d7..00000000000 --- a/docs/openoffice/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# -*.html diff --git a/docs/openoffice/README.md b/docs/openoffice/README.md index 97ccc6f07c8..5587cc8291e 100644 --- a/docs/openoffice/README.md +++ b/docs/openoffice/README.md @@ -1,5 +1 @@ - # OpenOffice/LibreOffice integration - -- [Overview](overview.md) - diff --git a/docs/openoffice/code-reorganization.md b/docs/openoffice/code-reorganization.md new file mode 100644 index 00000000000..f59f624b1ba --- /dev/null +++ b/docs/openoffice/code-reorganization.md @@ -0,0 +1,176 @@ + +# Code reorganization + +Why + +- Separate backend +- Separate GUI code (dialogs) and logic +- Data is now organized around `Citation`, `CitationGroup` instead of arrays for citation group + fields, and arrays of arrays for citation fields.
+ Also take `citationKey` as the central data unit, this is what we start with: unresolved `citationKeys` + do not stop processing. Although we cannot sort them by author and year, we can still emit a marker + that acts as a placeholder and shows the user the problematic key. + +Result: + +- model + - util : general utilities + - (OOPair, OOTuple3) collect two or three objects without creating a new class + - OOResult : while an Optional.empty can comunicate failure, it cannot provide details.
+ OOResult allows an arbitrary error object to be provided in case of failure.
+ - OOVoidResult : for functions returning no result on success, only diagnostics on failure. + - OOListUtil: some utilities working on List + - uno : helpers for various tasks via UNO.
+ These are conceptually independent of JabRef code and logic. + - ootext : to separate decisions on the format of references and citation marks from + the actual insertion into the document, the earlier method + [OOUtil.insertOOFormattedTextAtCurrentLocation](https://github.com/JabRef/jabref/blob/475b2989ffa8ec61c3327c62ed8f694149f83220/src/main/java/org/jabref/logic/openoffice/OOUtil.java#L112) + was extended to handle new tags that describe actions earlier done in code. + - This became [OOTextIntoOO.write](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java#L149) + - `(change)` Now all output to the document goes through this, not only those from Layout. This allows the citation markers and `jstyle:Title` to use these tags. + - This allows some backward-compatible extensions to jstyle.
+ `(change)` [Added](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java#L92) + some extra keywords, in `{prefix}_MARKUP_BEFORE`, `{prefix}_MARKUP_AFTER` pairs to allow bracketing some parts of citation marks with text and/or open/close tag pairs. + - [OOFormat](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java) + contains helpers to create the appropriate tags + - [OOText](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/model/openoffice/ootext/OOText.java) formalizes + the distinction from `String`. I did not change `String` to `OOText` in old code, (in particular in OOStyle). + - rangesort : ordering objects that have an XTextRange, optionally with an extra integer to break ties. + - RangeSort.partitionAndSortRanges : since XTextRangeCompare can only compare XTextRange values in + the same XText, we partition them accordingly and only sort within each partiion. + - RangeSortable (interface), RangeSortEntry (implements) :
+ When we replace XTextRange of citation marks in footnotes with the range of the footnote mark, + multiple citation marks may be mapped to the same location. To preserve the order between these, + RangeSortable allows this order to be indicated by returning appropriate indices from `getIndexInPosition` + - RangeSortVisual : sort in top-to-bottom left-to-right order.
+ Needs a functional XTextViewCursor.
+ Works on RangeSortable values. + - FunctionalTextViewCursor : helper to get a functional XTextViewCursor (cannot always) + - RangeOverlapWithin : check for overlaps within a set of XTextRange values. Probably O(n*log(n)). Used for all-to-all check of protected ranges. + - RangeOverlapBetween : check for overlaps between two sets of XTextRange values. Assumes one set is small. O(n*k). + Used for checking if the cursor is in a protected range. + - backend: interfaces to be provided by backends.
+ May change as new backends may need different APIs. + - style : data structures and interfaces used while going from ordered list of citation groups + to formatted citation markers and bibliography. Does not communicate with the document. Too long to fit here, starting a new section. + +## model/style + +At the core, +- we have `Citation` values + - represented in the document by their `citationKey` + - each may have a `pageInfo` +- A citation group (`CitationGroup`) has + - a list of citations (`citationsInStorageOrder`) + - an identifier `CitationGroupId cgid` + - this allows to refer to the group + - also used to associate the group to its citation markers location (outside the style part) + - `OODataModel dataModel` is here, in order to handle old (Jabref5.2) structure where pageInfo belonged to + CitationGroup not Citation + - `referenceMarkNameForLinking` is optional: can be used to crosslink to the citation marker + from the bibliography. +- `CitationGroups` represents the collection of citation groups. + +Processing starts with creating these. + +- `CitedKey` represents a cited source, with ordered backreferences (using `CitationPath`) to the correponding +citations. + +- `CitedKeys` is just an order-preserving collection of `CitedKeys` that also supports +lookup by `citationKey`. + +Common processing steps: + +- We need `globalOrder` for the citation groups (provided externally) +`CitationGroups.setGlobalOrder()` +- We need to look up each citationKey in the bibliography databases: + - `CitationGroups.lookupCitations` collects the cited keys, + looks up each, then distributes the results to the citations. + Uses a temporary `CitedKeys` instance, based on unsorted citations and citation groups. +- `CitationGroups.imposeLocalOrder` fills `localOrder` in each `CitationGroup` + +- Now we have order of appearance for the citations (`globalOrder` and `localOrder`). + We can create a `CitedKeys` instance (`bibliography`) according to this order. + +- For citations numbered in order of first appearance we number the sources and distribute the numbers +to the corresponding citations. +- For citations numbered in order of bibliography, we sort the bibliography, number, distribute. + +- For author-year citations we have to decide on the letters `uniqueLetter` used to distinguish +sources. This needs order of first appearance of the sources and recognizing clashing citation markers. +This is done in logic, in [`OOProcessAuthorYearMarkers.createUniqueLetters()`](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java#L49) + + +The entry point for this processing is: `OOProcess.produceCitationMarkers` It fills +- each `CitationGroup.citationMarker` +- `CitationGroups.bibliography` + - From bibliography `OOFormatBibliography.formatBibliography()` creates an `OOText` + ready to be written to the document. + + +## logic/style + +- StyleLoader : not changed (knows about default styles) Used by GUI +- OOPreFormatter : LaTeX code to unicode and OOText tags. (not changed) +- OOBibStyle : is mostly concerned by loading/parsing jstyle files and presenting its pieces +to the rest. Originally it also contains code to format numeric and author-year citation markers. + - Details of their new implementations are in + [`OOBibStyleGetNumCitationMarker`](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java) and + [`OOBibStyleGetCitationMarker`](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java) + - The new implementations + - support pageInfo for each citation + - support unresolved citations + - instead of `List` and (`List` plus arrays and database) they expect + more self-contained entries `List`, `List`. + - We have distinct methods for `getNormalizedCitationMarker(CitationMarkerNormEntry)` and + `getNumCitationMarkerForBibliography(CitationMarkerNumericBibEntry)`. + - The corresponding interfaces in model: + - `CitationMarkerNumericEntry` + - `CitationMarkerEntry` + - `CitationMarkerNumericBibEntry` + - `CitationMarkerNormEntry`
+ describe their expected input entries +- `OOProcess` : the main entry point for style application. Calls to specific implementations +in `OOProcessCitationKeyMarkers`, `OOProcessNumericMarkers` and `OOProcessAuthorYearMarkers` +according to jstyle flags. + +## logic/backend + +Details of encoding and retrieving data stored in a document as well as +the citation maker locations. Also contains dataModel-dependent code +(which could probably be moved out once the datamodel is settled). + +Creating and finding the bibliography (providing a cursor to write at) should be here too.
+These are currently in `UpdateBibliography` + +## logic/frontend + +- `OOFrontend` : has a `Backend` and `CitationGroups` + - Its constructor creates a backend, reads data from the document and creates a CitationGroups instance. + - provides functionality that requires both access to the document and the CitationGroups instance +- `RangeForOverlapCheck` used in `OOFrontend` +- `UpdateBibliography` : Create, find and update the bibliography in the document using output from + `produceCitationMarkers()` +- `UpdateCitationMarkers` create `CitationGroup`, update citation markers using output from + `produceCitationMarkers()` + + +## logic/action + +GUI-independent part of implementations of GUI actions. + +## gui + +- `OOError` : common error messages and dialog titles + - adds `title` to `Jabrefexception` + - converts from some common exception types using type-specific message + - contains some dialog messages that do not correspond to exceptions + +- `OOBibBase2` : most activity was moved out from here to parts discussed above. + - connecting / selecting a document moved to `OOBibBaseConnect` + - the rest connects higher parts of the GUI to actions in logic + - does argument and precondition checking + - catches all exceptions + - shows error and warning dialogs + + diff --git a/docs/openoffice/order-of-appearance.md b/docs/openoffice/order-of-appearance.md index 27d9d6e7da3..9dfd08cb76d 100644 --- a/docs/openoffice/order-of-appearance.md +++ b/docs/openoffice/order-of-appearance.md @@ -1,28 +1,116 @@ -## Order of appearance of citation groups +## Order of appearance of citation groups (`globalOrder`) -This seems trivial at first. Take the textual order of citation markers, and +The order of appearance of citations is decided on +two levels: -In the presence of figures, tables, footnotes/endnotes, tables with -footnotes possibly either far from the location they are referred to -in the text, or wrapped around with text it becomes obvious what is -the correct order. +1. their order within each citation group (`localOrder`), and +2. the order of the citation +groups that appear as citation markers in the text (`globalOrder`). -For example: +This page is about the latter: how to decide the order of appearance (numbering sequence) of a set +of citation markers? -- In a two-column layout, a text frame or figure mostly, but not fully - in the second column: shall we consider it part of the second column? +### Conceptually +In a continuous text it is easy: take the textual order of citation markers. -Technically LibreOffice allows several types of +In the presence of figures, tables, footnotes/endnotes possibly far from the location they are +referred to in the text or wrapped around with text it becomes less obvious what is the correct +order. + +Examples: + +- References in footnotes: are they *after* the page content, or number them as if they appeared at + the footnote mark? (JabRef does the latter) +- A figure with references in its caption. Text may flow on either or both sides.
+ Where should we insert these in the sequence? +- In a two-column layout, a text frame or figure mostly, but not fully in the second column: shall + we consider it part of the second column? + + +### Technically + + +In LibreOffice, a document has a main text that supports the +[XText](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XText.html) +interface.
+This allows several types of [XTextContent](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextContent.html) to be inserted. - Some of these allow text inside with further insertions. -- Many, but not all of them supports getting a "technical" insertion point or text range -through [getAnchor](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextContent.html#ae82a8b42f6b2578549b68b4483a877d3). In Libreoffice positioning both anchors and for example a frame seems hard, moving the frame -tends to also move the anchor. -- Consequence: producing an order of appearance for the citation - groups requires to handle many cases, may still turn out - insufficient and may require the user to + +#### Anchors + +- Many, but not all XTextContent types support getting a "technical" insertion point or text range + through [getAnchor](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextContent.html#ae82a8b42f6b2578549b68b4483a877d3). +- In Libreoffice positioning both a frame and its anchor seems hard: moving the frame tends to also + move the anchor. +- Consequence: producing an order of appearance for the citation groups based solely on `getAnchor` + calls may be impossible. + + - Allowing or requiring the user to insert "logical anchors" for frames and other "floating" parts + might help to alleviate these problems. + +#### Sorting within a `Text` + +The text ranges occupied by the citation markers support the +[XTextRange](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextRange.html) +interface. + +- These provide access to the XText they are contained in. +- The [Text](https://api.libreoffice.org/docs/idl/ref/servicecom_1_1sun_1_1star_1_1text_1_1Text.html) service +may support (optional) the [XTextRangeCompare](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextRangeCompare.html) +interface, that allows two XTextRange values to be compared if both belong to this `Text` + +#### Visual ordering + +- The cursor used by the user is available as an + [XTextViewCursor](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextViewCursor.html) +- If we can get it and can set its position in the document to each XTextRange to be sorted, and ask its + [getPosition](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextViewCursor.html#a9b2bafd342ef75b5d504a9313dbb1389) + to provide coordinates "relative to the top left position of the first page of the document.", + then we can sort by these coordinates in top-to-bottom left-to-right order. +- Note: in some cases, for example when the cursor is in a comment (as in + `Libreoffice:[menu:Insert]/[Comment]`), the XTextViewCursor is not available (I know of no way to + get it). +- In some other cases, for example when an image is selected, the XTextViewCursor we normally receive is not 'functional': +we cannot position it for getting coordinates for the citation marks. +The [FunctionalTextViewCursor](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java) +class can solve this case by accessing and manipulating the cursor through [XSelectionSupplier](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1view_1_1XSelectionSupplier.html) + +Consequences of getting these visual coordinates and using them to order the citation markers + +- allows uniform handling of the markers. Works in footnotes, tables, frames (apparently anywhere) +- requires moving the user visible cursor to each position and with [screen + refresh](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/model/openoffice/uno/UnoScreenRefresh.java) + enabled.
+ `(problem)` This results in some user-visible flashing and scrolling around in the document view. +- The expression "relative to the top left position of the first page of the document" is + understood literally, "as on the screen".
+ `(problem)` Showing pages side by side or using a two-column layout + will result in markers in the top half of the second column or page to be sorted before those on the bottom + of the first column of the first page. + + +### JabRef + +Jabref uses the following steps for sorting sorting citation markers (providing `globalOrder`): +1. the textranges of citation marks in footnotes are replaced by the textranges of the footnote + marks. +2. get the positions (coordinates) of these marks +3. sort in top-to-botton left-to-right order + + +`(problem)` In JabRef5.2 the positions of citation marks within the same footnote become +indistinguishable, thus their order after sorting may differ from their order in the footnote text.
+This caused problems for +1. numbering order
+ `(solved)` by keeping track of the order-in-footnote of citation markers during sorting using + [getIndexInPosition](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java#L21)) +2. `click:Merge`: It examines *consecutive* pairs of citation groups if they can be merged. Wrong +order may result in not discovering some mergeable pairs or attempting to merge in wrong order.
+`(solved)` by not using visual order, only XTextRangeCompare-based order within each XText +[here](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java#L325)) diff --git a/docs/openoffice/overview.md b/docs/openoffice/overview.md index 6f180650653..4eec99d2fee 100644 --- a/docs/openoffice/overview.md +++ b/docs/openoffice/overview.md @@ -4,110 +4,132 @@ This is a partial overview of the OpenOffice/LibreOffice panel and the code behind. +- To access the panel: `JabRef:/[menu:View]/[OpenOffice/LibreOffice]` +- The user documentation is at +[https://docs.jabref.org/cite/openofficeintegration](https://docs.jabref.org/cite/openofficeintegration) + + I am going to refer to OpenOffice Writer and LibreOffice Writer as LibreOffice or LO: their UNO APIs are still mostly identical, but I only tested with LibreOffice and differences do exist. -- What is stored in a document, how. -- Generating citation markers and bibliography (excluding the - bibliography entries, which is delegated to the layout module) -- How to access: `JabRef/[menu:View]/[OpenOffice/LibreOffice]` to show the panel. -- The user documentation is at -[https://docs.jabref.org/cite/openofficeintegration](https://docs.jabref.org/cite/openofficeintegration) +### Subject -### Purpose - - 1. Allow the user to insert **citations** in a LibreOffice writer - document. - - Automatically format these according to some prescribed style as **citation markers**. - - Generate a **bibliography**, also formatted according to the style. - - The bibliography consists of a title (e.g. "References") and a sorted list - of formatted bibliography entries, possibly prefixed with a marker (e.g. "[1]") - - 2. Citations (actually citation groups, see below) have three types - depending on how the citation marker is intended to appear in the - text: - - **Parenthesized**: "(Smith, 2000)" - - **In-text**: "Smith (2000)" - - **Invisible**: these have a location in the document, but no - visible citation mark generated. - - This lets the user to use any form for the citation - by taking control (and responsibility) back from the style. - - In the bibliography these behave as the other two citation types. - - - These citation types correspond to `\citep{Smith2000}`, - `\citet{Smith2000}` in - [natbib](http://tug.ctan.org/macros/latex/contrib/natbib/natnotes.pdf) - and `\nocite{Smith2000}` - - 3. The citations can be augmented with a string detailing which part - of a document is cited, for example "page 11" or "chapter 2". - - Sample citation markers (with LaTeX pseudocode): - - - `\citep[page 11]{Smith2000}` "(Smith, 2000; page 11)" - - `\citet[page 11]{Smith2000}` "Smith (2000; page 11)" - - `\nocite[page 11]{Smith2000}` "" - - - This string is referred to as **`pageInfo`** in the code. - - In the GUI the labels "Cite special", "Extra information - (e.g. page number)" are used. - - 4. Citations can be grouped. - - A group of parenthesized citations share the parentheses around, - like this: "(Smith, 2000; Jones 2001)". - - - Examples with pseudocode: - - `\citep{Smith2000,Jones2001}` "(Smith, 2000; Jones 2001)" - - `\citet{Smith2000,Jones2001}` "Smith (2000); Jones (2001)" - - `\nocite{Smith2000,Jones2001}` "" - - - From the user's point of view, citation groups can be created by - 1. Selecting multiple entries in a bibliography database, then - - `[click:Cite]` or - - `[click:Cite in-text]` or - - `[click:Cite special]` or - - `[click:Insert empty citation]` in the panel. - - This method allows any of the citation types to be used. - - 2. `[click:Merge]` finds all sets of consecutive citations in the text and - replaces each with a group. - - The new code only merges consecutive parenthesized citations. - - This is inconsistent with the solution used in `[click:Cite]` - - My impression is that - - groups of in-text or invisible citations are probably not useful - - mixed groups are even less. However, with a numbered style - there is no visual difference between parenthesized and in-text - citations, the user may be left wondering why did merge not work. - - One way out could be to merge as a "parenthesized" - group. But then users switching between styles get a - surprise, we have unexpectedly overridden their choice. - - I would prefer a visible log-like warning that does not require - a click to close and lets me see multiple warnings. - Could the main window have such an area at the bottom? - - Starting with JabRef 5.3 there is also `[click:Separate]` - that breaks all groups to single citations. - - This allows moving individual citations around (between citation groups). - - (Copy does not work.) - - (Moving a citation within a group has no effect on the final output - due to sorting of citations within groups. See [Sorting within a citation group](#localOrder)) +- What is stored in a document, how. +- Generating citation markers and bibliography + - (excluding the bibliography entries, which is delegated to the layout module) + + +### The purpose of the panel + +- Allow the user to insert **citations** in a LibreOffice writer document. +- Automatically format these according to some prescribed style as **citation markers**. +- Generate a **bibliography**, also formatted according to the style. + - The bibliography consists of a title (e.g. "References") and a sorted list + of formatted bibliography entries, possibly prefixed with a marker (e.g. "[1]") +- It also allows some related activities: connect to a document, select a style, group ("Merge") the + citations for nicer output, ungroup ("Separate") them to move or delete them individually, + edit ("Manage") their page-info parts, and collect the database entries of cited sources + to a new database. + +### Citation types +Citations (actually citation groups, see below) have three types +depending on how the citation marker is intended to appear in the +text: + - **Parenthesized**: "(Smith, 2000)" + - **In-text**: "Smith (2000)" + - **Invisible**: no visible citation mark. + - An invisible citation mark lets the user to use any form for the citation + by taking control (and responsibility) back from the style. + - Like the other two citation types, they have a location in the document. + - In the bibliography these behave as the other two citation types. + - In LibreOffice (`LibreOffice:[Ctrl-F8]` or`LibreOffice:[menu:View]/[Field Shadings]`) + shows reference marks with gray background. Invisible citation marks appear as a thin gray rectangle. + + - These citation types correspond to `\citep{Smith2000}`, + `\citet{Smith2000}` in + [natbib](http://tug.ctan.org/macros/latex/contrib/natbib/natnotes.pdf) + and `\nocite{Smith2000}`. I will use `\citep`, `\citet` and `\citen` in "LaTeX pseudocode" below. + +### PageInfo + +The citations can be augmented with a string detailing which part +of a document is cited, for example "page 11" or "chapter 2". + +Sample citation markers (with LaTeX pseudocode): + + - `\citep[page 11]{Smith2000}` "(Smith, 2000; page 11)" + - `\citet[page 11]{Smith2000}` "Smith (2000; page 11)" + - `\citen[page 11]{Smith2000}` "" + +- This string is referred to as **`pageInfo`** in the code. +- In the GUI the labels "Cite special", "Extra information + (e.g. page number)" are used. + +### Citation groups + +Citations can be grouped. + +A group of parenthesized citations share the parentheses around, like this:
+ "(Smith, 2000; Jones 2001)". + + - Examples with pseudocode: + - `\citep{Smith2000,Jones2001}` "(Smith, 2000; Jones 2001)" + - `\citet{Smith2000,Jones2001}` "Smith (2000); Jones (2001)" + - `\citen{Smith2000,Jones2001}` "" + +From the user's point of view, citation groups can be created by + + 1. Selecting multiple entries in a bibliography database, then + - `[click:Cite]` or + - `[click:Cite in-text]` or + - `[click:Cite special]` or + - `[click:Insert empty citation]` in the panel. + + This method allows any of the citation types to be used. + + 2. `[click:Merge citations]` finds all sets of consecutive citations in the text and + replaces each with a group. + - `(change)` The new code only merges consecutive [parenthesized](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java#L183) citations. + - This is inconsistent with the solution used in `[click:Cite]` + - My impression is that + - groups of in-text or invisible citations are probably not useful + - mixed groups are even less. However, with a numbered style + there is no visual difference between parenthesized and in-text + citations, the user may be left wondering why did merge not work. + - One way out could be to merge as a "parenthesized" + group. But then users switching between styles get a + surprise, we have unexpectedly overridden their choice. + - I would prefer a visible log-like warning that does not require + a click to close and lets me see multiple warnings. + Could the main window have such an area at the bottom? + - Starting with JabRef 5.3 there is also `[click:Separate citations]` + that breaks all groups to single citations. + - This allows + - deleting individual citations + - moving individual citations around (between citation groups) + - (copy does not work) + - (Moving a citation within a group has no effect on the final output + due to sorting of citations within groups. See [Sorting within a citation group](#localOrder)) - In order to manage single citations and groups uniformly, we - consider each citation in the document to belong to a citation - group, even if it means a group containing a single citation. - - 5. The details of how to format the bibliography and the citation markers are described - in a text file. - - - These normally use `.jstyle` extension, and I will refer to them - as jstyle files. - - See the [User documentation](https://docs.jabref.org/cite/openofficeintegration#the-style-file) - for details. - - I will refer to keywords in jstyle files as `jstyle:keyword` below. - +In order to manage single citations and groups uniformly, we +consider each citation in the document to belong to a citation +group, even if it means a group containing a single citation. + +Citation groups correspond to citation markers in the document. The latter is empty for invisible +citation groups. When creating the citation markers, the citations in the group +are processed together. + ## Citation styles +The details of how to format the bibliography and the citation markers are described in a text file. + +- These normally use `.jstyle` extension, and I will refer to them as jstyle files. +- See the [User documentation](https://docs.jabref.org/cite/openofficeintegration#the-style-file) + for details. +- I will refer to keywords in jstyle files as `jstyle:keyword` below. + + Four major types citation of styles can be described by a jstyle. - (1) `jstyle:BibTeXKeyCitations` @@ -127,7 +149,7 @@ Four major types citation of styles can be described by a jstyle. - makes the citation keys visible to the user - can work without knowing the order of appearance of citation groups - In case we expect to handle larger documents, a "draft mode" - minimizing work during "click:Cite" may be useful. + minimizing work during `[click:Cite]` may be useful. - There are two types of numbered (`jstyle:IsNumberEntries`) citation styles: @@ -136,16 +158,25 @@ Four major types citation of styles can be described by a jstyle. - (4) Author-year styles -### Sorting +## Sorting -#### Sorting te bibliography +### Sorting te bibliography The bibliography is sorted in (author, year, title) order - except for `jstyle:IsSortByPosition`, that uses the order of first appearance of the cited sources. -#### Sorting within a citation group +### Ordering the citations + +The order of appearance of citations (as considered during numbering and adding letters after the +year to ensure that citation markers uniquely identify sources in the bibliography) is decided on +two levels. + +1. Their order within each citation group (`localOrder`), and +2. the order of the citation groups (citation markers) in the text (`globalOrder`). + +#### Sorting within a citation group (`localOrder`) The order of citations within a citation group is controlled by `jstyle:MultiCiteChronological`. @@ -153,10 +184,9 @@ The order of citations within a citation group is controlled by - true asks for (year, author, title) ordering, - false for (author, year, title). - (There is no option for "in the order provided by the user"). + -In the code I referred to this order as `localOrder`. - -This ordering is used directly in author-year citation styles. +For author-year citation styles this ordering is used directly. - The (author, year, title) order promotes discovering citations sharing authors and year and emitting them in a shorter form. For @@ -164,33 +194,27 @@ This ordering is used directly in author-year citation styles. For numbered styles, the citations within a group are sorted again during generation of the citation marker, now by the numbers -themselves. This promotes discovering duplicates and ranges of -consecutive numbers, allowing for example "[1-7; 11]" to be emitted -instead of an exhaustive list of the citation numbers. - - - Note: the numbering itself is based the first sort (localOrder), - this second sorting does not override that. - - The result of the second sorting is not stored. +themselves. The result of this sorting is not saved, only affects the citation marker. + - Series of consecutive number are replaced with ranges: for example "[1-5; 11]" -#### Order of the citation groups +#### Order of the citation groups (`globalOrder`) The location of each citation group in the document is provided by the user. In a text with no insets, footnotes, figures etc. this directly provides the order. In the presence of these, it becomes more complicated, see [Order of appearance of -citation groups](order-of-appearance.md). In the code I referred to -this order as `globalOrder`. +citation groups](order-of-appearance.md). #### Order of the citations -- `globalOrder` and `localOrder` together fix the order of appearance of -citations (for author-year styles literally, for numbered styles less so). +- `globalOrder` and `localOrder` together provide the order of appearance of +citations - This also provides the order of first appearance of the cited sources. First appearance order of sources is used - in `jstyle:IsSortByPosition` numbered styles - in author-year styles: first appearance of "Smith200a" - should precede that of "Smith200b". + should precede that of "Smith200b".
To achieve this, the sources get the letters according the order of their first appearance. - This seems to contradict the statement "The bibliography is @@ -206,12 +230,18 @@ citations (for author-year styles literally, for numbered styles less so). -### What is stored in a document (JabRef5.2) +## What is stored in a document (JabRef5.2) + +- Each group of citations has a reference mark. -- Each group of citations has a reference mark. Its purposes: + (Reference marks are shown in LibreOffice in Navigator, under "References".
+ To show the Navigator: `LibreOffice:[menu:View]/[Navigator]` or `LibreOffice:[key:F5]`) - 1. The text range of the reference mark tells where to write or update the text of the citation. + Its purposes: + + 1. The text range of the reference mark tells where to write or update the citation mark. 2. The name of the reference mark + - Lets us select only those reference marks that belong to us - Encodes the citation type - Contains the list of citation keys that belong to this group @@ -222,35 +252,48 @@ citations (for author-year styles literally, for numbered styles less so). - `{citationKeys}` contains the comma-separated list of citation keys - Examples: - `JR_cite_1_Smith2000` (empty number part, parenthesized, single citation) - - `JR_cite0_2_Smith2000,Jones2001` (number part is 0, two citations) - - `JR_cite1_3_Smith2000,Jones2001` (number part is 1) + - `JR_cite0_2_Smith2000,Jones2001` (number part is 0, in-text, two citations) + - `JR_cite1_3_Smith2000,Jones2001` (number part is 1, invisible, two citations) - Each group of citations may have an associated pageInfo. - - In LibreOffice, these can be found at - `[LibreOffice]/[menu:File]/[Properties]/[Custom Properties]` + - In LibreOffice, these can be found at
+ `LibreOffice:/[menu:File]/[Properties]/[Custom Properties]` - The property names are identical to the name of the reference mark corresponding to the citation group. - - JabRef 5.2 never cleans up these, they are left around. New citations may - "pick up" these unexpectedly. + - JabRef 5.2 never cleans up these, they are left around.
+ `(problem)` New citations may "pick up" these unexpectedly. - The bibliography, if not found, is created at the end of the document. - - The location and extent of the bibliography is marked by the Section (in LibreOffice sense) - named `"JR_bib"`. + - The location and extent of the bibliography is the content of the Section named `"JR_bib"`.
+ (In LibreOffice Sections are listed in the Navigator panel, under "Sections") + - JabRef 5.2 also creates a bookmark named `"JR_bib_end"`, but does not use it. During bibliography update it attempts to create it again without removing the old bookmark. The result is a new bookmark, with a number appended to its name (by LibreOffice, to ensure unique names of bookmarks). - -### How does it work? - -- An important limitation is that we (I mean the jabref program) are -only loosely coupled to the document. Between two GUI actions we do -not receive any information from LibreOffice. We do not distinguish -between the user changing a single character in the document or -rewriting everything. Getting all the information we need from the -document, including consistency checking has to fit in a limited time -frame. + - [Correction in new code](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java#L147): + remove the old before creating the new. + +## How does it interact with the document? + +- "stateless"
+ JabRef is only loosely coupled to the document.
+ Between two GUI actions it does not receive any information from LibreOffice.
+ It cannot distinguish between the user changing a single character in the document or rewriting everything. + +- Access data
+ - During a `[click:cite]` or `[click:Update]` we need the reference mark names. + - Get all reference mark names + - Filter (only ours) + - Parse: gives citation type (for the group), citation keys + - Access/store pageInfo: based on reference mark name and property name being equal + - Creating a citation group: (`[click:cite]`) + - Creates a reference mark at the cursor, with a name as described above. +- Update (refreshing citation markers and bibliography): + - citation markers: the content of the reference mark + - bibliography: the content of the Section (in LibreOffice sense) + named `"JR_bib"`. diff --git a/docs/openoffice/problems.md b/docs/openoffice/problems.md new file mode 100644 index 00000000000..1aca43ca1e9 --- /dev/null +++ b/docs/openoffice/problems.md @@ -0,0 +1,99 @@ +# Problems in JabRef 5.2 + +## pageInfo should belong to citations, not citation groups + +- Creating `[click:Separate]` revealed
+ a `(problem)`: pageInfo strings are conceptually associated with + citations, but the implementation associates them to citation groups.
+ The number of available + pageInfo slots changes during`[click:Merge]` and `[click:Separate]` while the number of citations + remains fixed. + - The proposed solution was to change the association. + - Not only reference marks (citation groups) need unique identifiers, but also citations.
+ Possible encoding for reference mark names:
+ `JR_cite{type}_{number1}_{citationKey1},{number2}_{citationKey2}`
+ where `{type}` encodes the citation type (for the group), `{citationKey1}` is made unique by choosing an appropriate number for `{number1}`
+ This would allow + `JR_cite_{number1}_{citationKey1}` to be used as a property name for storing the pageInfo. + + Changes required to + - reference mark search, name generation and parsing + - name generation and parsing for properties storing pageInfo values + - in-memory representation
+ - JabRef 5.2 does not collect pageInfo values, accesses only when needed.
+ So it would be change to code accessing them. + - The proposed representation does collect, to allow separation of getting from the document + and processing + - insertion of pageInfo into citation markers: JabRef 5.2 injects a single before the closing parenthesis, + now we need to handle several values + - `[click:Manage citations]` should work on citations, not citation groups. + + +## Backend + +The choice of how do we represent the data and the citation marks in the document has consequences +on usability. + +Reference marks have some features that make it easy to mess up citations in a document + +- They are **not visible** by default, the user is not aware of their boundaries
+(`LO:[key:Ctrl-F8]`, `LO:[View]/[Field shadings]` helps) + +- They are **not atomic**: + - the user can edit the content. This will be lost on `[click:Update]`
+ If an `As character` or `To character` anchor is inserted, the corresponding frame or footnote is deleted. + - by pressing Enter within, the user can break a reference mark into two parts.
+ The second part is now outside the reference mark: `[click:Update]` will leave it as is, and replace the first part + with the full text for the citation mark. + - If the space separating to citation marks is deleted, the user cannot reliably type between the + marks.
+ The text typed usually becomes part of one of the marks. No visual clue as to which one.
+ Note: `[click:Merge]` then `[click:Separate]` adds a single space between. The user can + position the cursor before or after it. In either case the cursor is on a boundary: it is not + clear if it is in or out of a reference mark.
+ Special case: a reference mark at the start or end of a paragraph: the cursor is usually considered to be within at the coresponding edge. +- (good) They can be moved (Ctrl-X,Ctrl-V) +- They cannot be copied. (Ctrl-C, Ctrl-V) copies the text without the reference mark. +- Reference marks are lost if the document is saved as docx. + +- I know of no way to insert text into an empty text range denoted by a reference mark + - JabRef 5.3 recreates the reference mark (using [insertReferenceMark](https://github.com/JabRef/jabref/blob/475b2989ffa8ec61c3327c62ed8f694149f83220/src/main/java/org/jabref/gui/openoffice/OOBibBase.java#L1072)) + [here](https://github.com/JabRef/jabref/blob/475b2989ffa8ec61c3327c62ed8f694149f83220/src/main/java/org/jabref/gui/openoffice/OOBibBase.java#L706) + - `(change)` I preferred to (try to) avoid this: + [NamedRangeReferenceMark.nrGetFillCursor](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java#L225) + returns a cursor between two invisible + spaces, to provide the caller a location it can safely write some text. [NamedRangeReferenceMark.nrCleanFillCursor](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java#L432) + removes these invisible spaces unless the content would become empty or a single character. By + keeping the content at least two characters, we avoid the ambiguity at the edges: a cursor + positioned between two characters inside is always within the reference mark. (At the edges it + may or may not be inside.) + +- `(change)` `[click:Cite]` at reference mark edges: [safeInsertSpacesBetweenReferenceMarks](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java#L67) ensures the we are not inside, by starting two new paragraphs, inserting two spaces between them, then removing the new paragraph marks. +- `(change)` [guiActionInsertEntry](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java#L624) +checks if the cursor is in a citation mark or the bibliography. + +- `(change)` `[click:Update]` does an [exhaustive check](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java#L927) +for overlaps between protected ranges (citation marks and bibliography). This can become slow if there are many citations. + + +It would be nice if we could have a backend with better properties. We probably need multiple +backends for different purposes. This would be made easier if the backend were separated from the +rest of the code. This would be the purpose of +[logic/openoffice/backend](https://github.com/antalk2/jabref/tree/improve-reversibility-rebased-03/src/main/java/org/jabref/logic/openoffice/backend). + +## Undo + +- JabRef 5.3 does not collect the effects of GUI actions on the document into larger Undo actions.
+This makes the Undo functionality of LO impractial. +- `(change)` collect the effects of GUI actions into large chunks: now a GUI action can be undone +with a single click. + - except the effect on pageInfo: that is stored at the document level and is not restored by Undo. + +## Block screen refresh + +- LibreOffice has support in [XModel](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1frame_1_1XModel.html#a7b7d36374033ee9210ec0ac5c1a90d9f) +to "suspend some notifications to the controllers which are used for display updates." + +- `(change)` Now we are using this facility. + + From fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 13 Jun 2021 18:45:03 +0200 Subject: [PATCH 0977/1068] add figure, more markup --- docs/openoffice/code-reorganization.md | 66 +- docs/openoffice/layers-v1.svg | 915 +++++++++++++++++++++++++ 2 files changed, 951 insertions(+), 30 deletions(-) create mode 100644 docs/openoffice/layers-v1.svg diff --git a/docs/openoffice/code-reorganization.md b/docs/openoffice/code-reorganization.md index f59f624b1ba..aa5ed366f8e 100644 --- a/docs/openoffice/code-reorganization.md +++ b/docs/openoffice/code-reorganization.md @@ -11,18 +11,23 @@ Why do not stop processing. Although we cannot sort them by author and year, we can still emit a marker that acts as a placeholder and shows the user the problematic key. -Result: - -- model - - util : general utilities - - (OOPair, OOTuple3) collect two or three objects without creating a new class - - OOResult : while an Optional.empty can comunicate failure, it cannot provide details.
- OOResult allows an arbitrary error object to be provided in case of failure.
- - OOVoidResult : for functions returning no result on success, only diagnostics on failure. - - OOListUtil: some utilities working on List - - uno : helpers for various tasks via UNO.
+## Result + +### Layers + + +### By directories + +- `model` + - `util` : general utilities + - (`OOPair`, `OOTuple3`) collect two or three objects without creating a new class + - `OOResult` : while an Optional.empty can comunicate failure, it cannot provide details.
+ `OOResult` allows an arbitrary error object to be provided in case of failure.
+ - `OOVoidResult` : for functions returning no result on success, only diagnostics on failure. + - `OOListUtil`: some utilities working on List + - `uno` : helpers for various tasks via UNO.
These are conceptually independent of JabRef code and logic. - - ootext : to separate decisions on the format of references and citation marks from + - `ootext` : to separate decisions on the format of references and citation marks from the actual insertion into the document, the earlier method [OOUtil.insertOOFormattedTextAtCurrentLocation](https://github.com/JabRef/jabref/blob/475b2989ffa8ec61c3327c62ed8f694149f83220/src/main/java/org/jabref/logic/openoffice/OOUtil.java#L112) was extended to handle new tags that describe actions earlier done in code. @@ -35,23 +40,23 @@ Result: contains helpers to create the appropriate tags - [OOText](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/model/openoffice/ootext/OOText.java) formalizes the distinction from `String`. I did not change `String` to `OOText` in old code, (in particular in OOStyle). - - rangesort : ordering objects that have an XTextRange, optionally with an extra integer to break ties. - - RangeSort.partitionAndSortRanges : since XTextRangeCompare can only compare XTextRange values in - the same XText, we partition them accordingly and only sort within each partiion. - - RangeSortable (interface), RangeSortEntry (implements) :
- When we replace XTextRange of citation marks in footnotes with the range of the footnote mark, + - `rangesort` : ordering objects that have an `XTextRange`, optionally with an extra integer to break ties. + - `RangeSort.partitionAndSortRanges` : since `XTextRangeCompare` can only compare `XTextRange` values in + the same `XText`, we partition them accordingly and only sort within each partiion. + - `RangeSortable` (interface), `RangeSortEntry` (implements) :
+ When we replace `XTextRange` of citation marks in footnotes with the range of the footnote mark, multiple citation marks may be mapped to the same location. To preserve the order between these, - RangeSortable allows this order to be indicated by returning appropriate indices from `getIndexInPosition` - - RangeSortVisual : sort in top-to-bottom left-to-right order.
- Needs a functional XTextViewCursor.
- Works on RangeSortable values. - - FunctionalTextViewCursor : helper to get a functional XTextViewCursor (cannot always) - - RangeOverlapWithin : check for overlaps within a set of XTextRange values. Probably O(n*log(n)). Used for all-to-all check of protected ranges. - - RangeOverlapBetween : check for overlaps between two sets of XTextRange values. Assumes one set is small. O(n*k). + `RangeSortable` allows this order to be indicated by returning appropriate indices from `getIndexInPosition` + - `RangeSortVisual` : sort in top-to-bottom left-to-right order.
+ Needs a functional `XTextViewCursor`.
+ Works on `RangeSortable` values. + - `FunctionalTextViewCursor` : helper to get a functional `XTextViewCursor` (cannot always) + - `RangeOverlapWithin` : check for overlaps within a set of `XTextRange` values. Probably O(n*log(n)). Used for all-to-all check of protected ranges. + - `RangeOverlapBetween` : check for overlaps between two sets of `XTextRange` values. Assumes one set is small. O(n*k). Used for checking if the cursor is in a protected range. - - backend: interfaces to be provided by backends.
+ - `backend` : interfaces to be provided by backends.
May change as new backends may need different APIs. - - style : data structures and interfaces used while going from ordered list of citation groups + - `style` : data structures and interfaces used while going from ordered list of citation groups to formatted citation markers and bibliography. Does not communicate with the document. Too long to fit here, starting a new section. ## model/style @@ -69,15 +74,16 @@ At the core, CitationGroup not Citation - `referenceMarkNameForLinking` is optional: can be used to crosslink to the citation marker from the bibliography. -- `CitationGroups` represents the collection of citation groups. - -Processing starts with creating these. +- `CitationGroups` represents the collection of citation groups.
+Processing starts with creating a `CitationGroups` instance from the data stored in the document. - `CitedKey` represents a cited source, with ordered backreferences (using `CitationPath`) to the correponding citations. -- `CitedKeys` is just an order-preserving collection of `CitedKeys` that also supports -lookup by `citationKey`. +- `CitedKeys` is just an order-preserving collection of `CitedKeys` that also supports lookup by +`citationKey`. While producing citation markers, we also create a corresponding `CitedKeys` +instance, and store it in `CitationGroups.bibliography`. This is already sorted, its entries have +`uniqueLetter` or `number` assigned, but not converted to markup yet. Common processing steps: diff --git a/docs/openoffice/layers-v1.svg b/docs/openoffice/layers-v1.svg new file mode 100644 index 00000000000..f9b8239d504 --- /dev/null +++ b/docs/openoffice/layers-v1.svg @@ -0,0 +1,915 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + document content (UNO) + + frontend + + actions + + OOBibBase2 + + backend + + style + + OOTextIntoOO + + rangesort + data in doc, ranges + order ranges + fill ranges + markup text + XTextDocument + Backend, CitationGroups + + + + GUI: + BibEntry, BibDatabase, OOBibStyle + provides input in terms of these types + + provides connection to doc + Cite, Update, Merge, Separate, Manage, Export + Connect + Load Style + Create OOFrontend instance + Catch exceptions, Undo + Forward requests to actions + Check preconditions + + locations + citation keys + pageInfo + citation type + + + lookup, localOrder, number, + uniqueLetter, sort bibliography, + format citationMarkers, + format bibliography + + + or visually + within XText + + checkRangeOverlaps, checkRangeOverlapsWithCursor + connects the parts below + getVisuallySortedCitationGroups, imposeGlobalOrder + UpdateCitationMarkers, UpdateBibliography + lock screen refresh + GUI-independent part of actions + + + From e6afe6feb8cd57b7f3616be1f2397f3781e4d0d2 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 13 Jun 2021 20:23:12 +0200 Subject: [PATCH 0978/1068] more markup --- docs/openoffice/code-reorganization.md | 24 ++++++++++++++---------- docs/openoffice/problems.md | 2 +- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/docs/openoffice/code-reorganization.md b/docs/openoffice/code-reorganization.md index aa5ed366f8e..93f6b827e38 100644 --- a/docs/openoffice/code-reorganization.md +++ b/docs/openoffice/code-reorganization.md @@ -69,7 +69,8 @@ At the core, - a list of citations (`citationsInStorageOrder`) - an identifier `CitationGroupId cgid` - this allows to refer to the group - - also used to associate the group to its citation markers location (outside the style part) + - also used to associate the group to its citation markers location (outside the style part, + in [Backend](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java#L46)) - `OODataModel dataModel` is here, in order to handle old (Jabref5.2) structure where pageInfo belonged to CitationGroup not Citation - `referenceMarkNameForLinking` is optional: can be used to crosslink to the citation marker @@ -95,7 +96,7 @@ Common processing steps: Uses a temporary `CitedKeys` instance, based on unsorted citations and citation groups. - `CitationGroups.imposeLocalOrder` fills `localOrder` in each `CitationGroup` -- Now we have order of appearance for the citations (`globalOrder` and `localOrder`). +- Now we have order of appearance for the citations (`globalOrder` and `localOrder`).
We can create a `CitedKeys` instance (`bibliography`) according to this order. - For citations numbered in order of first appearance we number the sources and distribute the numbers @@ -105,9 +106,10 @@ to the corresponding citations. - For author-year citations we have to decide on the letters `uniqueLetter` used to distinguish sources. This needs order of first appearance of the sources and recognizing clashing citation markers. This is done in logic, in [`OOProcessAuthorYearMarkers.createUniqueLetters()`](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java#L49) +- We also mark first appearance of each source ([`setIsFirstAppearanceOfSourceInCitations`](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java#L146)) - -The entry point for this processing is: `OOProcess.produceCitationMarkers` It fills +The entry point for this processing is: [`OOProcess.produceCitationMarkers`](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java#L69).
+It fills - each `CitationGroup.citationMarker` - `CitationGroups.bibliography` - From bibliography `OOFormatBibliography.formatBibliography()` creates an `OOText` @@ -116,9 +118,9 @@ The entry point for this processing is: `OOProcess.produceCitationMarkers` It fi ## logic/style -- StyleLoader : not changed (knows about default styles) Used by GUI -- OOPreFormatter : LaTeX code to unicode and OOText tags. (not changed) -- OOBibStyle : is mostly concerned by loading/parsing jstyle files and presenting its pieces +- `StyleLoader` : not changed (knows about default styles) Used by GUI +- `OOPreFormatter` : LaTeX code to unicode and OOText tags. (not changed) +- `OOBibStyle` : is mostly concerned by loading/parsing jstyle files and presenting its pieces to the rest. Originally it also contains code to format numeric and author-year citation markers. - Details of their new implementations are in [`OOBibStyleGetNumCitationMarker`](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java) and @@ -130,13 +132,14 @@ to the rest. Originally it also contains code to format numeric and author-year more self-contained entries `List`, `List`. - We have distinct methods for `getNormalizedCitationMarker(CitationMarkerNormEntry)` and `getNumCitationMarkerForBibliography(CitationMarkerNumericBibEntry)`. - - The corresponding interfaces in model: + - The corresponding interfaces in model/style: - `CitationMarkerNumericEntry` - `CitationMarkerEntry` - `CitationMarkerNumericBibEntry` - `CitationMarkerNormEntry`
- describe their expected input entries -- `OOProcess` : the main entry point for style application. Calls to specific implementations + describe their expected input entries. +- [`OOProcess.produceCitationMarkers`](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java#L69) +is the main entry point for style application. Calls to specific implementations in `OOProcessCitationKeyMarkers`, `OOProcessNumericMarkers` and `OOProcessAuthorYearMarkers` according to jstyle flags. @@ -178,5 +181,6 @@ GUI-independent part of implementations of GUI actions. - does argument and precondition checking - catches all exceptions - shows error and warning dialogs + - adds `enterUndoContext`, `leaveUndoContext` around action code diff --git a/docs/openoffice/problems.md b/docs/openoffice/problems.md index 1aca43ca1e9..7961c331ba6 100644 --- a/docs/openoffice/problems.md +++ b/docs/openoffice/problems.md @@ -24,7 +24,7 @@ So it would be change to code accessing them. - The proposed representation does collect, to allow separation of getting from the document and processing - - insertion of pageInfo into citation markers: JabRef 5.2 injects a single before the closing parenthesis, + - insertion of pageInfo into citation markers: JabRef 5.2 injects a single pageInfo before the closing parenthesis, now we need to handle several values - `[click:Manage citations]` should work on citations, not citation groups. From e97c9bf3bb694820e693d5667418925f95effc40 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 18 Jun 2021 20:00:08 +0200 Subject: [PATCH 0979/1068] drop duplicate 'add' in comment --- .../java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index 41b7ceae806..d441ed198e1 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -508,7 +508,7 @@ static class MyPropertyStack { } /* - * Get the initial state of the properties and add add the first layer. + * Get the initial state of the properties and add the first layer. */ XMultiPropertyStates mpss = UnoCast.cast(XMultiPropertyStates.class, cursor).get(); PropertyState[] propertyStates = null; From 0fd7eb83b4a44547f6dd1938e27df7426d63ddbe Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 18 Jun 2021 20:54:40 +0200 Subject: [PATCH 0980/1068] use UnoTextRange.compareXXXUnsafe --- .../model/openoffice/rangesort/RangeOverlapBetween.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java index 282bb44e6c0..c8a9f52bb77 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java @@ -59,16 +59,16 @@ List> findFirst(XTextDocument doc, if (aText != bText) { continue; } - int abEndToStart = -1 * cmp.compareRegionStarts(aRange.getEnd(), bRangeStart); + int abEndToStart = UnoTextRange.compareStartsUnsafe(cmp, aRange.getEnd(), bRangeStart); if (abEndToStart < 0 || (!includeTouching && (abEndToStart == 0))) { continue; } - int baEndToStart = -1 * cmp.compareRegionStarts(bRangeEnd, aRange.getStart()); + int baEndToStart = UnoTextRange.compareStartsUnsafe(cmp, bRangeEnd, aRange.getStart()); if (baEndToStart < 0 || (!includeTouching && (baEndToStart == 0))) { continue; } - boolean equal = UnoTextRange.compareStartsThenEnds(aRange, bRange) == 0; + boolean equal = UnoTextRange.compareStartsThenEndsUnsafe(cmp, aRange, bRange) == 0; boolean touching = (abEndToStart == 0 || baEndToStart == 0); // In case of two equal collapsed ranges there is an ambiguity : TOUCH or From 92f40144f254d59adf4c87ae76fcc3e288db0a8f Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 18 Jun 2021 21:15:48 +0200 Subject: [PATCH 0981/1068] format (use longer lines), comments --- .../rangesort/RangeOverlapBetween.java | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java index c8a9f52bb77..9a3ef1c9968 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java @@ -35,16 +35,22 @@ List> findFirst(XTextDocument doc, return result; } - List> fewTuples = - new ArrayList<>(fewHolders.size()); - - for (V aHolder : fewHolders) { - XText aText = aHolder.getRange().getText(); - fewTuples.add(new OOTuple3<>(aText, - UnoCast.cast(XTextRangeCompare.class, aText).get(), - aHolder)); + /* + * Cache all we need to know about fewHolders. We are trying to minimize the number of calls + * to LO. + */ + List> fewTuples = new ArrayList<>(fewHolders.size()); + + for (V aHolder : fewHolders) { + XText aText = aHolder.getRange().getText(); + fewTuples.add(new OOTuple3<>(aText, + UnoCast.cast(XTextRangeCompare.class, aText).get(), + aHolder)); } + /* + * We only go through manyHolders once: fewTuples is in the inner loop. + */ for (V bHolder : manyHolders) { XTextRange bRange = bHolder.getRange(); XText bText = bRange.getText(); @@ -71,8 +77,7 @@ List> findFirst(XTextDocument doc, boolean equal = UnoTextRange.compareStartsThenEndsUnsafe(cmp, aRange, bRange) == 0; boolean touching = (abEndToStart == 0 || baEndToStart == 0); - // In case of two equal collapsed ranges there is an ambiguity : TOUCH or - // EQUAL_RANGE ? + // In case of two equal collapsed ranges there is an ambiguity : TOUCH or EQUAL_RANGE ? // // We return EQUAL_RANGE RangeOverlapKind kind = (equal ? RangeOverlapKind.EQUAL_RANGE From 50dc9f2f27fa64c6f7d2183b1e930e6c047740a7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 18 Jun 2021 21:49:37 +0200 Subject: [PATCH 0982/1068] reviewed RangeHolder.getRange() use It is called many times during sort. Luckily both RangeSortEntry and RangeForOverlapCheck stores a copy of the range, does not need to ask the document. RangeHolder.getRange().getText() is still called a few (up to about 3?) times. We might gain some speed if it is very costly. But the time used is probably dominated by the range comparisons. --- .../org/jabref/logic/openoffice/frontend/OOFrontend.java | 2 +- .../model/openoffice/rangesort/RangeOverlapWithin.java | 6 ++++++ .../org/jabref/model/openoffice/rangesort/RangeSort.java | 8 ++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 2a46d49f448..3baf4d25765 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -174,7 +174,7 @@ public Optional healthReport(XTextDocument doc) } } result.add(sortable); - } + } } return result.stream().map(e -> e).collect(Collectors.toList()); } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java index cd3d693fd9d..e4df2d8278c 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java @@ -20,6 +20,12 @@ private RangeOverlapWithin() { } * For overlapping and touching, only report consecutive ranges and only with a single sample of * otherwise identical ranges. * + * @param rangeHolders represent the ranges to be checked. + * + * Note: for each rangeHolder, rangeHolder.getRange() is called multiple times. + * To avoid repeated work, they should keep a copy of the range instead of + * getting it each time from the document. + * * @param reportAtMost Limit the number of records returned to atMost. * Zero {@code reportAtMost} means no limit. * diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java index e2683369cb3..1b4fc327598 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -35,6 +35,11 @@ public int compare(RangeHolder a, RangeHolder b) { } } + /* + * Sort a list of RangeHolder values known to share the same getText(). + * + * Note: RangeHolder.getRange() is called many times. + */ public static void sortWithinPartition(List rangeHolders) { if (rangeHolders.isEmpty()) { return; @@ -77,6 +82,9 @@ public static RangePartitions partitionRanges(List return result; } + /* + * Note: RangeHolder.getRange() is called many times. + */ public static RangePartitions partitionAndSortRanges(List holders) { RangePartitions result = partitionRanges(holders); for (List partition : result.getPartitions()) { From 5930444a798919549bdb792b5df0897b4b79ca87 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 18 Jun 2021 23:14:55 +0200 Subject: [PATCH 0983/1068] adjust dir-locals (it should set fill-column) --- .dir-locals.el | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.dir-locals.el b/.dir-locals.el index 82f64f5cbcf..919a64e576e 100644 --- a/.dir-locals.el +++ b/.dir-locals.el @@ -1,7 +1,7 @@ ((nil . ((fill-column . 100) )) - (c-mode . ((fill-column . 50))) +;; (c-mode . ((fill-column . 50))) (java-mode . ((fill-column . 100) - ;; (add-hook 'java-mode-hook (lambda () (set-fill-column 120))) + (add-hook 'java-mode-hook (lambda () (set-fill-column 100))) )) ) From f96b1f97319e3d006cbcb473a4fbac448b4ec979 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 18 Jun 2021 23:17:11 +0200 Subject: [PATCH 0984/1068] add comment on RangeSet.add costs --- .../org/jabref/model/openoffice/rangesort/RangeSet.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java index f7fbe37ba25..e389c902b90 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java @@ -29,7 +29,12 @@ public boolean contains(XTextRange range) { return partitions.get(partitionKey).contains(range); } - /* return false if already contained */ + /* + * return false if already contained + * + * Beware: using UnoTextRange::compareStartsThenEnds as comparator involves range.getText() + * twice on each comparison. This makes it costly to use this class. + */ public boolean add(XTextRange range) { TreeSet partition = partitions.get(range.getText()); if (partition == null) { From aa05917c22515857f188dd09d41779a201a1d8c7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 18 Jun 2021 23:18:28 +0200 Subject: [PATCH 0985/1068] add alternative implementation to footnoteMarkRanges This would avoid using RangeSet. Unfortunately I have no 'integrated' branch now, so this implementation is not tested. --- .../logic/openoffice/frontend/OOFrontend.java | 68 ++++++++++++++----- 1 file changed, 52 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 3baf4d25765..5852e137a8b 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -418,38 +418,74 @@ public List> viewCursorRanges(XTextDocumen * structure those ranges. */ public List> - footnoteMarkRanges(XTextDocument doc, - List> citationRanges) + footnoteMarkRanges(XTextDocument doc, List> citationRanges) throws NoDocumentException, WrappedTargetException { - // Avoid inserting the same mark twice. - // Could use RangeSet if we had that. - RangeSet seen = new RangeSet(); + if (false) { + // Avoid inserting the same mark twice. + RangeSet seen = new RangeSet(); - List> result = new ArrayList<>(); + List> result = new ArrayList<>(); + + for (RangeForOverlapCheck citationRange : citationRanges) { - for (RangeForOverlapCheck citationRange : citationRanges) { + Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(citationRange.range); - Optional footnoteMarkRange = - UnoTextRange.getFootnoteMarkRange(citationRange.range); + if (footnoteMarkRange.isEmpty()) { + // not in footnote + continue; + } - if (footnoteMarkRange.isEmpty()) { - // not in footnote - continue; + boolean seenContains = seen.contains(footnoteMarkRange.get()); + if (!seenContains) { + seen.add(footnoteMarkRange.get()); + result.add(new RangeForOverlapCheck<>(footnoteMarkRange.get(), + citationRange.idWithinKind, + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + citationRange.format())); + } } + return result; + } else { + + // RangeSet.add involves a few comparisons anf getText, which is probably costly. + // + // (On the other hand we only insert ranges of footnotes, which probably limits the sizes + // of its partitions) + // + // We can avoid using RangeSet by partitioning only and using a single range from + // each partition to get at the corresponding footnotemark range. + + List> result = new ArrayList<>(); + RangeSort.RangePartitions> partitions = + RangeSort.partitionRanges(citationRanges); + + // Now it is sufficient to check a single entry from each partition. + // Each partition corresponds to an XText, and each footnote has a single XText. + // (This latter ignores the possibility of XTextContents inserted into footnotes.) + // Also: different footnotes cannot share a footnotemark range, we are not creating duplicates. + for (List> partition : partitions.getPartitions()) { + if (partition.isEmpty()) { + continue; + } + RangeForOverlapCheck citationRange = partition.get(0); + + Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(citationRange.range); + + if (footnoteMarkRange.isEmpty()) { + // not in footnote + continue; + } - boolean seenContains = seen.contains(footnoteMarkRange.get()); - if (!seenContains) { - seen.add(footnoteMarkRange.get()); result.add(new RangeForOverlapCheck<>(footnoteMarkRange.get(), citationRange.idWithinKind, RangeForOverlapCheck.FOOTNOTE_MARK_KIND, "FootnoteMark for " + citationRange.format())); } + return result; } - return result; } static String From 34147fffecd15ff9e3d93547d4fed034f4f882e0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 18 Jun 2021 23:21:09 +0200 Subject: [PATCH 0986/1068] use longer lines in OOFrontend.java --- .../logic/openoffice/frontend/OOFrontend.java | 176 ++++++++---------- 1 file changed, 73 insertions(+), 103 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 5852e137a8b..6a4f741b793 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -57,9 +57,7 @@ public OOFrontend(XTextDocument doc) NoDocumentException, WrappedTargetException { - // TODO: dataModel should come from looking at the - // document and preferences. - // + // TODO: dataModel should come from looking at the document and preferences. this.backend = new Backend52(); // Get the citationGroupNames @@ -98,24 +96,19 @@ public Optional healthReport(XTextDocument doc) } /** - * Creates a list of {@code RangeSortable} values for - * our {@code CitationGroup} values. Originally designed to be - * passed to {@code visualSort}. + * Creates a list of {@code RangeSortable} values for our {@code CitationGroup} + * values. Originally designed to be passed to {@code visualSort}. * - * The elements of the returned list are actually of type - * {@code RangeSortEntry}. + * The elements of the returned list are actually of type {@code RangeSortEntry}. * - * The result is sorted within {@code XTextRange.getText()} - * partitions of the citation groups according to their {@code XTextRange} - * (before mapping to footnote marks). + * The result is sorted within {@code XTextRange.getText()} partitions of the citation groups + * according to their {@code XTextRange} (before mapping to footnote marks). * - * In the result, RangeSortable.getIndexInPosition() contains - * unique indexes within the original partition (not after - * mapFootnotesToFootnoteMarks). + * In the result, RangeSortable.getIndexInPosition() contains unique indexes within the original + * partition (not after mapFootnotesToFootnoteMarks). * - * @param mapFootnotesToFootnoteMarks If true, replace ranges in - * footnotes with the range of the corresponding footnote - * mark. This is used for numbering the citations. + * @param mapFootnotesToFootnoteMarks If true, replace ranges in footnotes with the range of the + * corresponding footnote mark. This is used for numbering the citations. * */ private List> @@ -135,20 +128,17 @@ public Optional healthReport(XTextDocument doc) /* * At this point we are almost ready to return sortables. * - * But we may want to number citations in a footnote - * as if it appeared where the footnote mark is. + * But we may want to number citations in a footnote as if it appeared where the footnote + * mark is. * - * The following code replaces ranges within footnotes with - * the range for the corresponding footnote mark. + * The following code replaces ranges within footnotes with the range for the corresponding + * footnote mark. * - * This brings further ambiguity if we have multiple - * citation groups within the same footnote: for the comparison - * they become indistinguishable. Numbering between them is - * not controlled. Also combineCiteMarkers will see them in - * the wrong order (if we use this comparison), and will not - * be able to merge. To avoid these, we sort textually within - * each .getText() partition and add indexInPosition - * accordingly. + * This brings further ambiguity if we have multiple citation groups within the same + * footnote: for the comparison they become indistinguishable. Numbering between them is + * not controlled. Also combineCiteMarkers will see them in the wrong order (if we use this + * comparison), and will not be able to merge. To avoid these, we sort textually within + * each .getText() partition and add indexInPosition accordingly. * */ @@ -180,47 +170,39 @@ public Optional healthReport(XTextDocument doc) } /** - * @param mapFootnotesToFootnoteMarks If true, sort reference - * marks in footnotes as if they appeared at the - * corresponding footnote mark. + * @param mapFootnotesToFootnoteMarks If true, sort reference marks in footnotes as if they + * appeared at the corresponding footnote mark. * * @return citation groups sorted by their visual positions. * - * Limitation: for two column layout visual (top-down, - * left-right) order does not match the expected (textual) - * order. + * Limitation: for two column layout visual (top-down, left-right) order does not match the + * expected (textual) order. * */ - private List - getVisuallySortedCitationGroups(XTextDocument doc, - boolean mapFootnotesToFootnoteMarks, - FunctionalTextViewCursor fcursor) + private List getVisuallySortedCitationGroups(XTextDocument doc, + boolean mapFootnotesToFootnoteMarks, + FunctionalTextViewCursor fcursor) throws WrappedTargetException, NoDocumentException, JabRefException { - List> sortables = - createVisualSortInput(doc, mapFootnotesToFootnoteMarks); + List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); - List> sorted = - RangeSortVisual.visualSort(sortables, - doc, - fcursor); + List> sorted = RangeSortVisual.visualSort(sortables, doc, fcursor); - List result = - (sorted.stream().map(RangeSortable::getContent).collect(Collectors.toList())); + List result = (sorted.stream() + .map(RangeSortable::getContent) + .collect(Collectors.toList())); return result; } /** - * Return citation groups in visual order within (but not across) - * XText partitions. + * Return citation groups in visual order within (but not across) XText partitions. * - * This is (1) sufficient for combineCiteMarkers which looks for - * consecutive XTextRanges within each XText, (2) not confused by - * multicolumn layout or multipage display. + * This is (1) sufficient for combineCiteMarkers which looks for consecutive XTextRanges within + * each XText, (2) not confused by multicolumn layout or multipage display. */ public List getCitationGroupsSortedWithinPartitions(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) @@ -236,19 +218,17 @@ public Optional healthReport(XTextDocument doc) } /** - * Create a citation group for the given citation keys, at the - * end of position. + * Create a citation group for the given citation keys, at the end of position. * - * On return {@code position} is collapsed, and is after the - * inserted space, or at the end of the reference mark. + * On return {@code position} is collapsed, and is after the inserted space, or at the end of + * the reference mark. * * @param citationKeys In storage order * @param pageInfos In storage order * @param citationType * @param position Collapsed to its end. - * @param insertSpaceAfter If true, we insert a space after the mark, that - * carries on format of characters from - * the original position. + * @param insertSpaceAfter If true, we insert a space after the mark, that carries on format of + * characters from the original position. */ public CitationGroup createCitationGroup(XTextDocument doc, List citationKeys, @@ -404,18 +384,15 @@ public List> viewCursorRanges(XTextDocumen } /** - * @return A range for each footnote mark where the footnote - * contains at least one citation group. + * @return A range for each footnote mark where the footnote contains at least one citation group. * - * Purpose: We do not want markers of footnotes containing - * reference marks to overlap with reference - * marks. Overwriting these footnote marks might kill our - * reference marks in the footnote. + * Purpose: We do not want markers of footnotes containing reference marks to overlap with + * reference marks. Overwriting these footnote marks might kill our reference marks in the + * footnote. * - * Note: Here we directly communicate to the document, not - * through the backend. This is because mapping ranges to - * footnote marks does not depend on how do we mark or - * structure those ranges. + * Note: Here we directly communicate to the document, not through the backend. This is because + * mapping ranges to footnote marks does not depend on how do we mark or structure those + * ranges. */ public List> footnoteMarkRanges(XTextDocument doc, List> citationRanges) @@ -488,8 +465,7 @@ public List> viewCursorRanges(XTextDocumen } } - static String - rangeOverlapsToMessage(List>> overlaps) { + static String rangeOverlapsToMessage(List>> overlaps) { if (overlaps.size() == 0) { return "(*no overlaps*)"; @@ -517,6 +493,7 @@ public List> viewCursorRanges(XTextDocumen * Check for any overlap between userRanges and protected ranges. * * Assume userRanges is small (usually 1 elements for checking the cursor) + * * Returns on first problem found. */ public OOVoidResult @@ -536,11 +513,10 @@ public List> viewCursorRanges(XTextDocumen ranges.addAll(footnoteMarkRanges(doc, citationRanges)); List>> overlaps = - RangeOverlapBetween.findFirst( - doc, - userRanges, - ranges, - requireSeparation); + RangeOverlapBetween.findFirst(doc, + userRanges, + ranges, + requireSeparation); if (overlaps.size() == 0) { return OOVoidResult.ok(); @@ -554,11 +530,10 @@ public List> viewCursorRanges(XTextDocumen * @param reportAtMost Limit number of overlaps reported (0 for no limit) * */ - public OOVoidResult - checkRangeOverlaps(XTextDocument doc, - List> userRanges, - boolean requireSeparation, - int reportAtMost) + public OOVoidResult checkRangeOverlaps(XTextDocument doc, + List> userRanges, + boolean requireSeparation, + int reportAtMost) throws NoDocumentException, WrappedTargetException { @@ -586,33 +561,29 @@ public List> viewCursorRanges(XTextDocumen * * Called from: ManageCitationsDialogViewModel constructor. * - * @return A list with entries corresponding to citations in the - * text, in arbitrary order (same order as from - * getJabRefReferenceMarkNames). + * @return A list with entries corresponding to citations in the text, in arbitrary order (same + * order as from getJabRefReferenceMarkNames). * - * Note: visual or alphabetic order could be more - * manageable for the user. We could provide these - * here, but switching between them needs change on - * GUI (adding a toggle or selector). + * Note: visual or alphabetic order could be more manageable for the user. We + * could provide these here, but switching between them needs change on GUI + * (adding a toggle or selector). * - * Note: CitationEntry implements Comparable, where - * compareTo() and equals() are based on refMarkName. - * The order used in the "Manage citations" dialog + * Note: CitationEntry implements Comparable, where compareTo() and equals() are + * based on refMarkName. The order used in the "Manage citations" dialog * does not seem to use that. * - * The 1st is labeled "Citation" (show citation in bold, - * and some context around it). + * The 1st is labeled "Citation" (show citation in bold, and some context + * around it). * - * The columns can be sorted by clicking on the column title. - * For the "Citation" column, the sorting is based on the content, - * (the context before the citation), not on the citation itself. + * The columns can be sorted by clicking on the column title. For the + * "Citation" column, the sorting is based on the content, (the context + * before the citation), not on the citation itself. * - * In the "Extra information ..." column some visual indication - * of the editable part could be helpful. + * In the "Extra information ..." column some visual indication of the + * editable part could be helpful. * - * Wish: selecting an entry (or a button in the line) in - * the GUI could move the cursor in the document to - * the entry. + * Wish: selecting an entry (or a button in the line) in the GUI could move the cursor + * in the document to the entry. */ public List getCitationEntries(XTextDocument doc) throws @@ -644,8 +615,7 @@ public void imposeGlobalOrder(XTextDocument doc, FunctionalTextViewCursor fcurso boolean mapFootnotesToFootnoteMarks = true; List sortedCitationGroups = getVisuallySortedCitationGroups(doc, mapFootnotesToFootnoteMarks, fcursor); - List sortedCitationGroupIds = - OOListUtil.map(sortedCitationGroups, cg -> cg.cgid); + List sortedCitationGroupIds = OOListUtil.map(sortedCitationGroups, cg -> cg.cgid); citationGroups.setGlobalOrder(sortedCitationGroupIds); } } From 355f111b9e36889aa004443a3154c03f3dc4874c Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 18 Jun 2021 23:27:47 +0200 Subject: [PATCH 0987/1068] use longer lines in OOTextIntoOO.java --- .../jabref/model/openoffice/ootext/OOTextIntoOO.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index d441ed198e1..0758d515446 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -44,8 +44,7 @@ import org.slf4j.LoggerFactory; /** - * Interpret OOText into an OpenOffice or LibreOffice writer - * document. + * Interpret OOText into an OpenOffice or LibreOffice writer document. */ @AllowedToUseAwt("Requires AWT for changing document properties") public class OOTextIntoOO { @@ -365,8 +364,8 @@ public static void removeDirectFormatting(XTextCursor cursor) { mpss.setAllPropertiesToDefault(); /* - * Now that we have called setAllPropertiesToDefault, check which properties - * are not set to default and try to correct what we can and seem necessary. + * Now that we have called setAllPropertiesToDefault, check which properties are not set to + * default and try to correct what we can and seem necessary. * * Note: tested with LibreOffice : 6.4.6.2 */ @@ -408,8 +407,8 @@ public static void removeDirectFormatting(XTextCursor cursor) { static class MyPropertyStack { /* - * We only try to control these. Should include all character - * properties we set, and maybe their interdependencies. + * We only try to control these. Should include all character properties we set, and maybe + * their interdependencies. * * For a list of properties see: * https://www.openoffice.org/api/docs/common/ref/com/sun/star/style/CharacterProperties.html From 505dfce9ac9b0a3773abda0e3c51221aeab864ba Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 19 Jun 2021 09:41:47 +0200 Subject: [PATCH 0988/1068] x --- .dir-locals.el | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 .dir-locals.el diff --git a/.dir-locals.el b/.dir-locals.el deleted file mode 100644 index 919a64e576e..00000000000 --- a/.dir-locals.el +++ /dev/null @@ -1,7 +0,0 @@ -((nil . ((fill-column . 100) - )) -;; (c-mode . ((fill-column . 50))) - (java-mode . ((fill-column . 100) - (add-hook 'java-mode-hook (lambda () (set-fill-column 100))) - )) - ) From 2a019b5af04bc2bb2b786a07e968fffebd4f21cd Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 19 Jun 2021 12:04:50 +0200 Subject: [PATCH 0989/1068] undo changes to src/main/java/org/jabref/gui/openoffice/OOBibBase.java They are not bad, but I want to keep it as is, unmodified. No point in reviewing chanegs in a file that is going to be removed. --- src/main/java/org/jabref/gui/openoffice/OOBibBase.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 3559cc55526..540c5f9216b 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -245,7 +245,7 @@ private XDesktop simpleBootstrap(Path loPath) Object desktop; try { desktop = xServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xContext); - } catch (com.sun.star.uno.Exception e) { + } catch (Exception e) { throw new CreationException(e.getMessage()); } XDesktop resultDesktop = UnoRuntime.queryInterface(XDesktop.class, desktop); @@ -1010,7 +1010,7 @@ private void createBibTextSection2(boolean end) try { xChildNamed = UnoRuntime.queryInterface(XNamed.class, mxDocFactory.createInstance("com.sun.star.text.TextSection")); - } catch (com.sun.star.uno.Exception e) { + } catch (Exception e) { throw new CreationException(e.getMessage()); } // Set the new sections name to 'Child_Section' @@ -1056,7 +1056,7 @@ private XTextContent insertBookMark(String name, XTextCursor position) Object bookmark; try { bookmark = mxDocFactory.createInstance("com.sun.star.text.Bookmark"); - } catch (com.sun.star.uno.Exception e) { + } catch (Exception e) { throw new CreationException(e.getMessage()); } // name the bookmark @@ -1089,7 +1089,7 @@ private void insertReferenceMark(String name, String citationText, XTextCursor p Object bookmark; try { bookmark = mxDocFactory.createInstance("com.sun.star.text.ReferenceMark"); - } catch (com.sun.star.uno.Exception e) { + } catch (Exception e) { throw new CreationException(e.getMessage()); } // Name the reference From e74a5c7087e23cd7d870a272d7eb3f4b330b62c0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 19 Jun 2021 14:54:55 +0200 Subject: [PATCH 0990/1068] do not use RangeSet --- .../logic/openoffice/frontend/OOFrontend.java | 81 ++++++------------- 1 file changed, 23 insertions(+), 58 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 6a4f741b793..967a8cf084d 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -17,7 +17,6 @@ import org.jabref.model.openoffice.rangesort.RangeOverlap; import org.jabref.model.openoffice.rangesort.RangeOverlapBetween; import org.jabref.model.openoffice.rangesort.RangeOverlapWithin; -import org.jabref.model.openoffice.rangesort.RangeSet; import org.jabref.model.openoffice.rangesort.RangeSort; import org.jabref.model.openoffice.rangesort.RangeSortEntry; import org.jabref.model.openoffice.rangesort.RangeSortVisual; @@ -400,69 +399,35 @@ public List> viewCursorRanges(XTextDocumen NoDocumentException, WrappedTargetException { - if (false) { - // Avoid inserting the same mark twice. - RangeSet seen = new RangeSet(); + // We partition by XText and use a single range from + // each partition to get at the corresponding footnotemark range. - List> result = new ArrayList<>(); - - for (RangeForOverlapCheck citationRange : citationRanges) { - - Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(citationRange.range); - - if (footnoteMarkRange.isEmpty()) { - // not in footnote - continue; - } - - boolean seenContains = seen.contains(footnoteMarkRange.get()); - if (!seenContains) { - seen.add(footnoteMarkRange.get()); - result.add(new RangeForOverlapCheck<>(footnoteMarkRange.get(), - citationRange.idWithinKind, - RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + citationRange.format())); - } + List> result = new ArrayList<>(); + RangeSort.RangePartitions> partitions = + RangeSort.partitionRanges(citationRanges); + + // Each partition corresponds to an XText, and each footnote has a single XText. + // (This latter ignores the possibility of XTextContents inserted into footnotes.) + // Also: different footnotes cannot share a footnotemark range, we are not creating duplicates. + for (List> partition : partitions.getPartitions()) { + if (partition.isEmpty()) { + continue; } - return result; - } else { - - // RangeSet.add involves a few comparisons anf getText, which is probably costly. - // - // (On the other hand we only insert ranges of footnotes, which probably limits the sizes - // of its partitions) - // - // We can avoid using RangeSet by partitioning only and using a single range from - // each partition to get at the corresponding footnotemark range. - - List> result = new ArrayList<>(); - RangeSort.RangePartitions> partitions = - RangeSort.partitionRanges(citationRanges); - - // Now it is sufficient to check a single entry from each partition. - // Each partition corresponds to an XText, and each footnote has a single XText. - // (This latter ignores the possibility of XTextContents inserted into footnotes.) - // Also: different footnotes cannot share a footnotemark range, we are not creating duplicates. - for (List> partition : partitions.getPartitions()) { - if (partition.isEmpty()) { - continue; - } - RangeForOverlapCheck citationRange = partition.get(0); - - Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(citationRange.range); + RangeForOverlapCheck citationRange = partition.get(0); - if (footnoteMarkRange.isEmpty()) { - // not in footnote - continue; - } + Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(citationRange.range); - result.add(new RangeForOverlapCheck<>(footnoteMarkRange.get(), - citationRange.idWithinKind, - RangeForOverlapCheck.FOOTNOTE_MARK_KIND, - "FootnoteMark for " + citationRange.format())); + if (footnoteMarkRange.isEmpty()) { + // not in footnote + continue; } - return result; + + result.add(new RangeForOverlapCheck<>(footnoteMarkRange.get(), + citationRange.idWithinKind, + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + citationRange.format())); } + return result; } static String rangeOverlapsToMessage(List>> overlaps) { From f52e68df38b1ea6a79d86eb481279a06c7472abd Mon Sep 17 00:00:00 2001 From: Antal K Date: Sat, 19 Jun 2021 15:11:31 +0200 Subject: [PATCH 0991/1068] deleted src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java --- .../model/openoffice/rangesort/RangeSet.java | 53 ------------------- 1 file changed, 53 deletions(-) delete mode 100644 src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java deleted file mode 100644 index e389c902b90..00000000000 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSet.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.jabref.model.openoffice.rangesort; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.TreeSet; - -import org.jabref.model.openoffice.uno.UnoTextRange; - -import com.sun.star.text.XText; -import com.sun.star.text.XTextRange; - -public class RangeSet { - - private final Map> partitions; - - public RangeSet() { - this.partitions = new HashMap<>(); - } - - public boolean contains(XTextRange range) { - Objects.requireNonNull(range); - XText partitionKey = range.getText(); - if (!this.partitions.containsKey(partitionKey)) { - return false; - } - return partitions.get(partitionKey).contains(range); - } - - /* - * return false if already contained - * - * Beware: using UnoTextRange::compareStartsThenEnds as comparator involves range.getText() - * twice on each comparison. This makes it costly to use this class. - */ - public boolean add(XTextRange range) { - TreeSet partition = partitions.get(range.getText()); - if (partition == null) { - partition = new TreeSet<>(UnoTextRange::compareStartsThenEnds); - partitions.put(range.getText(), partition); - } - return partition.add(range); - } - - /** - * @return A list of the partitions. - */ - public List> partitionValues() { - return new ArrayList<>(partitions.values()); - } -} From 51c3d1e9d3101e1df294da1cd8f28d94bda1e573 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 20 Jun 2021 15:11:51 +0200 Subject: [PATCH 0992/1068] try to make markdown-lint happy (happier) https://github.com/updownpress/markdown-lint/tree/master/rules --- docs/openoffice/code-reorganization.md | 52 +++--- docs/openoffice/order-of-appearance.md | 24 +-- docs/openoffice/overview.md | 218 +++++++++++++------------ docs/openoffice/problems.md | 36 ++-- 4 files changed, 168 insertions(+), 162 deletions(-) diff --git a/docs/openoffice/code-reorganization.md b/docs/openoffice/code-reorganization.md index 93f6b827e38..b91aa53984c 100644 --- a/docs/openoffice/code-reorganization.md +++ b/docs/openoffice/code-reorganization.md @@ -6,7 +6,7 @@ Why - Separate backend - Separate GUI code (dialogs) and logic - Data is now organized around `Citation`, `CitationGroup` instead of arrays for citation group - fields, and arrays of arrays for citation fields.
+ fields, and arrays of arrays for citation fields. Also take `citationKey` as the central data unit, this is what we start with: unresolved `citationKeys` do not stop processing. Although we cannot sort them by author and year, we can still emit a marker that acts as a placeholder and shows the user the problematic key. @@ -14,18 +14,19 @@ Why ## Result ### Layers - + +![Layers](layers-v1.svg) ### By directories - `model` - `util` : general utilities - (`OOPair`, `OOTuple3`) collect two or three objects without creating a new class - - `OOResult` : while an Optional.empty can comunicate failure, it cannot provide details.
- `OOResult` allows an arbitrary error object to be provided in case of failure.
+ - `OOResult` : while an Optional.empty can comunicate failure, it cannot provide details. + `OOResult` allows an arbitrary error object to be provided in case of failure. - `OOVoidResult` : for functions returning no result on success, only diagnostics on failure. - `OOListUtil`: some utilities working on List - - `uno` : helpers for various tasks via UNO.
+ - `uno` : helpers for various tasks via UNO. These are conceptually independent of JabRef code and logic. - `ootext` : to separate decisions on the format of references and citation marks from the actual insertion into the document, the earlier method @@ -33,7 +34,7 @@ Why was extended to handle new tags that describe actions earlier done in code. - This became [OOTextIntoOO.write](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java#L149) - `(change)` Now all output to the document goes through this, not only those from Layout. This allows the citation markers and `jstyle:Title` to use these tags. - - This allows some backward-compatible extensions to jstyle.
+ - This allows some backward-compatible extensions to jstyle. `(change)` [Added](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java#L92) some extra keywords, in `{prefix}_MARKUP_BEFORE`, `{prefix}_MARKUP_AFTER` pairs to allow bracketing some parts of citation marks with text and/or open/close tag pairs. - [OOFormat](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java) @@ -43,25 +44,26 @@ Why - `rangesort` : ordering objects that have an `XTextRange`, optionally with an extra integer to break ties. - `RangeSort.partitionAndSortRanges` : since `XTextRangeCompare` can only compare `XTextRange` values in the same `XText`, we partition them accordingly and only sort within each partiion. - - `RangeSortable` (interface), `RangeSortEntry` (implements) :
+ - `RangeSortable` (interface), `RangeSortEntry` (implements) : When we replace `XTextRange` of citation marks in footnotes with the range of the footnote mark, multiple citation marks may be mapped to the same location. To preserve the order between these, `RangeSortable` allows this order to be indicated by returning appropriate indices from `getIndexInPosition` - - `RangeSortVisual` : sort in top-to-bottom left-to-right order.
- Needs a functional `XTextViewCursor`.
+ - `RangeSortVisual` : sort in top-to-bottom left-to-right order. + Needs a functional `XTextViewCursor`. Works on `RangeSortable` values. - `FunctionalTextViewCursor` : helper to get a functional `XTextViewCursor` (cannot always) - `RangeOverlapWithin` : check for overlaps within a set of `XTextRange` values. Probably O(n*log(n)). Used for all-to-all check of protected ranges. - `RangeOverlapBetween` : check for overlaps between two sets of `XTextRange` values. Assumes one set is small. O(n*k). Used for checking if the cursor is in a protected range. - - `backend` : interfaces to be provided by backends.
+ - `backend` : interfaces to be provided by backends. May change as new backends may need different APIs. - `style` : data structures and interfaces used while going from ordered list of citation groups to formatted citation markers and bibliography. Does not communicate with the document. Too long to fit here, starting a new section. - + ## model/style -At the core, +At the core, + - we have `Citation` values - represented in the document by their `citationKey` - each may have a `pageInfo` @@ -75,7 +77,7 @@ At the core, CitationGroup not Citation - `referenceMarkNameForLinking` is optional: can be used to crosslink to the citation marker from the bibliography. -- `CitationGroups` represents the collection of citation groups.
+- `CitationGroups` represents the collection of citation groups. Processing starts with creating a `CitationGroups` instance from the data stored in the document. - `CitedKey` represents a cited source, with ordered backreferences (using `CitationPath`) to the correponding @@ -90,13 +92,13 @@ Common processing steps: - We need `globalOrder` for the citation groups (provided externally) `CitationGroups.setGlobalOrder()` -- We need to look up each citationKey in the bibliography databases: +- We need to look up each citationKey in the bibliography databases: - `CitationGroups.lookupCitations` collects the cited keys, looks up each, then distributes the results to the citations. Uses a temporary `CitedKeys` instance, based on unsorted citations and citation groups. - `CitationGroups.imposeLocalOrder` fills `localOrder` in each `CitationGroup` -- Now we have order of appearance for the citations (`globalOrder` and `localOrder`).
+- Now we have order of appearance for the citations (`globalOrder` and `localOrder`). We can create a `CitedKeys` instance (`bibliography`) according to this order. - For citations numbered in order of first appearance we number the sources and distribute the numbers @@ -108,13 +110,13 @@ sources. This needs order of first appearance of the sources and recognizing cla This is done in logic, in [`OOProcessAuthorYearMarkers.createUniqueLetters()`](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java#L49) - We also mark first appearance of each source ([`setIsFirstAppearanceOfSourceInCitations`](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java#L146)) -The entry point for this processing is: [`OOProcess.produceCitationMarkers`](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java#L69).
-It fills +The entry point for this processing is: [`OOProcess.produceCitationMarkers`](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java#L69). +It fills - each `CitationGroup.citationMarker` - `CitationGroups.bibliography` - From bibliography `OOFormatBibliography.formatBibliography()` creates an `OOText` ready to be written to the document. - + ## logic/style @@ -122,7 +124,7 @@ It fills - `OOPreFormatter` : LaTeX code to unicode and OOText tags. (not changed) - `OOBibStyle` : is mostly concerned by loading/parsing jstyle files and presenting its pieces to the rest. Originally it also contains code to format numeric and author-year citation markers. - - Details of their new implementations are in + - Details of their new implementations are in [`OOBibStyleGetNumCitationMarker`](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java) and [`OOBibStyleGetCitationMarker`](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java) - The new implementations @@ -136,9 +138,9 @@ to the rest. Originally it also contains code to format numeric and author-year - `CitationMarkerNumericEntry` - `CitationMarkerEntry` - `CitationMarkerNumericBibEntry` - - `CitationMarkerNormEntry`
+ - `CitationMarkerNormEntry` describe their expected input entries. -- [`OOProcess.produceCitationMarkers`](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java#L69) +- [`OOProcess.produceCitationMarkers`](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java#L69) is the main entry point for style application. Calls to specific implementations in `OOProcessCitationKeyMarkers`, `OOProcessNumericMarkers` and `OOProcessAuthorYearMarkers` according to jstyle flags. @@ -149,7 +151,7 @@ Details of encoding and retrieving data stored in a document as well as the citation maker locations. Also contains dataModel-dependent code (which could probably be moved out once the datamodel is settled). -Creating and finding the bibliography (providing a cursor to write at) should be here too.
+Creating and finding the bibliography (providing a cursor to write at) should be here too. These are currently in `UpdateBibliography` ## logic/frontend @@ -162,8 +164,8 @@ These are currently in `UpdateBibliography` `produceCitationMarkers()` - `UpdateCitationMarkers` create `CitationGroup`, update citation markers using output from `produceCitationMarkers()` - - + + ## logic/action GUI-independent part of implementations of GUI actions. @@ -174,7 +176,7 @@ GUI-independent part of implementations of GUI actions. - adds `title` to `Jabrefexception` - converts from some common exception types using type-specific message - contains some dialog messages that do not correspond to exceptions - + - `OOBibBase2` : most activity was moved out from here to parts discussed above. - connecting / selecting a document moved to `OOBibBaseConnect` - the rest connects higher parts of the GUI to actions in logic diff --git a/docs/openoffice/order-of-appearance.md b/docs/openoffice/order-of-appearance.md index 9dfd08cb76d..a59846af16c 100644 --- a/docs/openoffice/order-of-appearance.md +++ b/docs/openoffice/order-of-appearance.md @@ -6,7 +6,7 @@ two levels: 1. their order within each citation group (`localOrder`), and 2. the order of the citation -groups that appear as citation markers in the text (`globalOrder`). +groups that appear as citation markers in the text (`globalOrder`). This page is about the latter: how to decide the order of appearance (numbering sequence) of a set of citation markers? @@ -23,7 +23,7 @@ Examples: - References in footnotes: are they *after* the page content, or number them as if they appeared at the footnote mark? (JabRef does the latter) -- A figure with references in its caption. Text may flow on either or both sides.
+- A figure with references in its caption. Text may flow on either or both sides. Where should we insert these in the sequence? - In a two-column layout, a text frame or figure mostly, but not fully in the second column: shall we consider it part of the second column? @@ -34,7 +34,7 @@ Examples: In LibreOffice, a document has a main text that supports the [XText](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XText.html) -interface.
+interface. This allows several types of [XTextContent](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextContent.html) to be inserted. @@ -44,7 +44,7 @@ to be inserted. #### Anchors - Many, but not all XTextContent types support getting a "technical" insertion point or text range - through [getAnchor](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextContent.html#ae82a8b42f6b2578549b68b4483a877d3). + through [getAnchor](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextContent.html#ae82a8b42f6b2578549b68b4483a877d3). - In Libreoffice positioning both a frame and its anchor seems hard: moving the frame tends to also move the anchor. - Consequence: producing an order of appearance for the citation groups based solely on `getAnchor` @@ -74,7 +74,7 @@ interface, that allows two XTextRange values to be compared if both belong to th then we can sort by these coordinates in top-to-bottom left-to-right order. - Note: in some cases, for example when the cursor is in a comment (as in `Libreoffice:[menu:Insert]/[Comment]`), the XTextViewCursor is not available (I know of no way to - get it). + get it). - In some other cases, for example when an image is selected, the XTextViewCursor we normally receive is not 'functional': we cannot position it for getting coordinates for the citation marks. The [FunctionalTextViewCursor](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/model/openoffice/rangesort/FunctionalTextViewCursor.java) @@ -85,10 +85,10 @@ Consequences of getting these visual coordinates and using them to order the cit - allows uniform handling of the markers. Works in footnotes, tables, frames (apparently anywhere) - requires moving the user visible cursor to each position and with [screen refresh](https://github.com/antalk2/jabref/blob/improve-reversibility-rebased-03/src/main/java/org/jabref/model/openoffice/uno/UnoScreenRefresh.java) - enabled.
+ enabled. `(problem)` This results in some user-visible flashing and scrolling around in the document view. - The expression "relative to the top left position of the first page of the document" is - understood literally, "as on the screen".
+ understood literally, "as on the screen". `(problem)` Showing pages side by side or using a two-column layout will result in markers in the top half of the second column or page to be sorted before those on the bottom of the first column of the first page. @@ -97,20 +97,22 @@ Consequences of getting these visual coordinates and using them to order the cit ### JabRef Jabref uses the following steps for sorting sorting citation markers (providing `globalOrder`): + 1. the textranges of citation marks in footnotes are replaced by the textranges of the footnote marks. 2. get the positions (coordinates) of these marks 3. sort in top-to-botton left-to-right order - + `(problem)` In JabRef5.2 the positions of citation marks within the same footnote become -indistinguishable, thus their order after sorting may differ from their order in the footnote text.
+indistinguishable, thus their order after sorting may differ from their order in the footnote text. This caused problems for -1. numbering order
+ +1. numbering order `(solved)` by keeping track of the order-in-footnote of citation markers during sorting using [getIndexInPosition](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java#L21)) 2. `click:Merge`: It examines *consecutive* pairs of citation groups if they can be merged. Wrong -order may result in not discovering some mergeable pairs or attempting to merge in wrong order.
+order may result in not discovering some mergeable pairs or attempting to merge in wrong order. `(solved)` by not using visual order, only XTextRangeCompare-based order within each XText [here](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java#L325)) diff --git a/docs/openoffice/overview.md b/docs/openoffice/overview.md index 4eec99d2fee..df8a5cef5b2 100644 --- a/docs/openoffice/overview.md +++ b/docs/openoffice/overview.md @@ -1,5 +1,5 @@ -## Overview +# Overview This is a partial overview of the OpenOffice/LibreOffice panel and the code behind. @@ -13,14 +13,14 @@ I am going to refer to OpenOffice Writer and LibreOffice Writer as LibreOffice or LO: their UNO APIs are still mostly identical, but I only tested with LibreOffice and differences do exist. -### Subject +## Subject - What is stored in a document, how. - Generating citation markers and bibliography - (excluding the bibliography entries, which is delegated to the layout module) -### The purpose of the panel +## The purpose of the panel - Allow the user to insert **citations** in a LibreOffice writer document. - Automatically format these according to some prescribed style as **citation markers**. @@ -32,47 +32,49 @@ only tested with LibreOffice and differences do exist. edit ("Manage") their page-info parts, and collect the database entries of cited sources to a new database. -### Citation types +## Citation types + Citations (actually citation groups, see below) have three types depending on how the citation marker is intended to appear in the text: - - **Parenthesized**: "(Smith, 2000)" - - **In-text**: "Smith (2000)" - - **Invisible**: no visible citation mark. - - An invisible citation mark lets the user to use any form for the citation - by taking control (and responsibility) back from the style. - - Like the other two citation types, they have a location in the document. - - In the bibliography these behave as the other two citation types. - - In LibreOffice (`LibreOffice:[Ctrl-F8]` or`LibreOffice:[menu:View]/[Field Shadings]`) - shows reference marks with gray background. Invisible citation marks appear as a thin gray rectangle. - - - These citation types correspond to `\citep{Smith2000}`, - `\citet{Smith2000}` in - [natbib](http://tug.ctan.org/macros/latex/contrib/natbib/natnotes.pdf) - and `\nocite{Smith2000}`. I will use `\citep`, `\citet` and `\citen` in "LaTeX pseudocode" below. - -### PageInfo + +- **Parenthesized**: "(Smith, 2000)" +- **In-text**: "Smith (2000)" +- **Invisible**: no visible citation mark. + - An invisible citation mark lets the user to use any form for the citation + by taking control (and responsibility) back from the style. + - Like the other two citation types, they have a location in the document. + - In the bibliography these behave as the other two citation types. + - In LibreOffice (`LibreOffice:[Ctrl-F8]` or`LibreOffice:[menu:View]/[Field Shadings]`) + shows reference marks with gray background. Invisible citation marks appear as a thin gray rectangle. + +- These citation types correspond to `\citep{Smith2000}`, + `\citet{Smith2000}` in + [natbib](http://tug.ctan.org/macros/latex/contrib/natbib/natnotes.pdf) + and `\nocite{Smith2000}`. I will use `\citep`, `\citet` and `\citen` in "LaTeX pseudocode" below. + +## PageInfo The citations can be augmented with a string detailing which part of a document is cited, for example "page 11" or "chapter 2". Sample citation markers (with LaTeX pseudocode): - - `\citep[page 11]{Smith2000}` "(Smith, 2000; page 11)" - - `\citet[page 11]{Smith2000}` "Smith (2000; page 11)" - - `\citen[page 11]{Smith2000}` "" +- `\citep[page 11]{Smith2000}` "(Smith, 2000; page 11)" +- `\citet[page 11]{Smith2000}` "Smith (2000; page 11)" +- `\citen[page 11]{Smith2000}` "" - This string is referred to as **`pageInfo`** in the code. - In the GUI the labels "Cite special", "Extra information (e.g. page number)" are used. -### Citation groups +## Citation groups Citations can be grouped. -A group of parenthesized citations share the parentheses around, like this:
+A group of parenthesized citations share the parentheses around, like this: "(Smith, 2000; Jones 2001)". - + - Examples with pseudocode: - `\citep{Smith2000,Jones2001}` "(Smith, 2000; Jones 2001)" - `\citet{Smith2000,Jones2001}` "Smith (2000); Jones (2001)" @@ -80,38 +82,38 @@ A group of parenthesized citations share the parentheses around, like this:
From the user's point of view, citation groups can be created by - 1. Selecting multiple entries in a bibliography database, then - - `[click:Cite]` or - - `[click:Cite in-text]` or - - `[click:Cite special]` or - - `[click:Insert empty citation]` in the panel. - - This method allows any of the citation types to be used. - - 2. `[click:Merge citations]` finds all sets of consecutive citations in the text and - replaces each with a group. - - `(change)` The new code only merges consecutive [parenthesized](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java#L183) citations. - - This is inconsistent with the solution used in `[click:Cite]` - - My impression is that - - groups of in-text or invisible citations are probably not useful - - mixed groups are even less. However, with a numbered style - there is no visual difference between parenthesized and in-text - citations, the user may be left wondering why did merge not work. - - One way out could be to merge as a "parenthesized" - group. But then users switching between styles get a - surprise, we have unexpectedly overridden their choice. - - I would prefer a visible log-like warning that does not require - a click to close and lets me see multiple warnings. - Could the main window have such an area at the bottom? - - Starting with JabRef 5.3 there is also `[click:Separate citations]` - that breaks all groups to single citations. - - This allows - - deleting individual citations - - moving individual citations around (between citation groups) - - (copy does not work) - - (Moving a citation within a group has no effect on the final output - due to sorting of citations within groups. See [Sorting within a citation group](#localOrder)) - +1. Selecting multiple entries in a bibliography database, then + - `[click:Cite]` or + - `[click:Cite in-text]` or + - `[click:Cite special]` or + - `[click:Insert empty citation]` in the panel. + + This method allows any of the citation types to be used. + +2. `[click:Merge citations]` finds all sets of consecutive citations in the text and + replaces each with a group. + - `(change)` The new code only merges consecutive [parenthesized](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java#L183) citations. + - This is inconsistent with the solution used in `[click:Cite]` + - My impression is that + - groups of in-text or invisible citations are probably not useful + - mixed groups are even less. However, with a numbered style + there is no visual difference between parenthesized and in-text + citations, the user may be left wondering why did merge not work. + - One way out could be to merge as a "parenthesized" + group. But then users switching between styles get a + surprise, we have unexpectedly overridden their choice. + - I would prefer a visible log-like warning that does not require + a click to close and lets me see multiple warnings. + Could the main window have such an area at the bottom? + - Starting with JabRef 5.3 there is also `[click:Separate citations]` + that breaks all groups to single citations. + - This allows + - deleting individual citations + - moving individual citations around (between citation groups) + - (copy does not work) + - (Moving a citation within a group has no effect on the final output + due to sorting of citations within groups. See [Sorting within a citation group](#localOrder)) + In order to manage single citations and groups uniformly, we consider each citation in the document to belong to a citation group, even if it means a group containing a single citation. @@ -120,7 +122,7 @@ Citation groups correspond to citation markers in the document. The latter is e citation groups. When creating the citation markers, the citations in the group are processed together. -## Citation styles +# Citation styles The details of how to format the bibliography and the citation markers are described in a text file. @@ -128,28 +130,28 @@ The details of how to format the bibliography and the citation markers are descr - See the [User documentation](https://docs.jabref.org/cite/openofficeintegration#the-style-file) for details. - I will refer to keywords in jstyle files as `jstyle:keyword` below. - + Four major types citation of styles can be described by a jstyle. - (1) `jstyle:BibTeXKeyCitations` - - The citation markers show the citationKey. - - It is not fully implemented - - does not produce markers before the bibliography entries - - does not show pageInfo - - It is not advertised in the [User documentation](https://docs.jabref.org/cite/openofficeintegration#the-style-file). - - Its intended purpose may be - - - (likely) a proper style, with "[Smith2000]" style citation markers - - (possibly) a style for "draft mode" that - - can avoid lookup of citation markers in the database when only the - citation markers are updated - - can produce unique citation markers trivially (only needs local information) - - makes the citation keys visible to the user - - can work without knowing the order of appearance of citation groups - - In case we expect to handle larger documents, a "draft mode" - minimizing work during `[click:Cite]` may be useful. + - The citation markers show the citationKey. + - It is not fully implemented + - does not produce markers before the bibliography entries + - does not show pageInfo + - It is not advertised in the [User documentation](https://docs.jabref.org/cite/openofficeintegration#the-style-file). + - Its intended purpose may be + + - (likely) a proper style, with "[Smith2000]" style citation markers + - (possibly) a style for "draft mode" that + - can avoid lookup of citation markers in the database when only the + citation markers are updated + - can produce unique citation markers trivially (only needs local information) + - makes the citation keys visible to the user + - can work without knowing the order of appearance of citation groups + - In case we expect to handle larger documents, a "draft mode" + minimizing work during `[click:Cite]` may be useful. - There are two types of numbered (`jstyle:IsNumberEntries`) citation styles: @@ -158,16 +160,16 @@ Four major types citation of styles can be described by a jstyle. - (4) Author-year styles -## Sorting +# Sorting -### Sorting te bibliography +## Sorting te bibliography The bibliography is sorted in (author, year, title) order - except for `jstyle:IsSortByPosition`, that uses the order of first appearance of the cited sources. -### Ordering the citations +## Ordering the citations The order of appearance of citations (as considered during numbering and adding letters after the year to ensure that citation markers uniquely identify sources in the bibliography) is decided on @@ -176,28 +178,29 @@ two levels. 1. Their order within each citation group (`localOrder`), and 2. the order of the citation groups (citation markers) in the text (`globalOrder`). -#### Sorting within a citation group (`localOrder`) +### Sorting within a citation group (`localOrder`) The order of citations within a citation group is controlled by `jstyle:MultiCiteChronological`. - - true asks for (year, author, title) ordering, - - false for (author, year, title). - - (There is no option for "in the order provided by the user"). - - +- true asks for (year, author, title) ordering, +- false for (author, year, title). +- (There is no option for "in the order provided by the user"). + + For author-year citation styles this ordering is used directly. - - The (author, year, title) order promotes discovering citations - sharing authors and year and emitting them in a shorter form. For - example as "(Smith 2000a,b)". - +- The (author, year, title) order promotes discovering citations + sharing authors and year and emitting them in a shorter form. For + example as "(Smith 2000a,b)". + For numbered styles, the citations within a group are sorted again during generation of the citation marker, now by the numbers themselves. The result of this sorting is not saved, only affects the citation marker. + - Series of consecutive number are replaced with ranges: for example "[1-5; 11]" -#### Order of the citation groups (`globalOrder`) +### Order of the citation groups (`globalOrder`) The location of each citation group in the document is provided by the user. In a text with no insets, footnotes, figures etc. this directly @@ -205,22 +208,22 @@ provides the order. In the presence of these, it becomes more complicated, see [Order of appearance of citation groups](order-of-appearance.md). -#### Order of the citations +### Order of the citations - `globalOrder` and `localOrder` together provide the order of appearance of -citations + citations - This also provides the order of first appearance of the cited sources. First appearance order of sources is used - in `jstyle:IsSortByPosition` numbered styles - in author-year styles: first appearance of "Smith200a" - should precede that of "Smith200b".
+ should precede that of "Smith200b". To achieve this, the sources get the letters according the order of their first appearance. - This seems to contradict the statement "The bibliography is - sorted in (author, year, title) order" above. -
It does not. As of JabRef 5.3 both are true. -
Consequence: in the references + sorted in (author, year, title) order" above. + It does not. As of JabRef 5.3 both are true. + Consequence: in the references Smith2000b may precede Smith2000a. ([reported](https://github.com/JabRef/jabref/issues/7805)) - Some author-year citation styles prescribe a higher threshold on @@ -230,11 +233,11 @@ citations -## What is stored in a document (JabRef5.2) +# What is stored in a document (JabRef5.2) - Each group of citations has a reference mark. - (Reference marks are shown in LibreOffice in Navigator, under "References".
+ (Reference marks are shown in LibreOffice in Navigator, under "References". To show the Navigator: `LibreOffice:[menu:View]/[Navigator]` or `LibreOffice:[key:F5]`) Its purposes: @@ -254,20 +257,19 @@ citations - `JR_cite_1_Smith2000` (empty number part, parenthesized, single citation) - `JR_cite0_2_Smith2000,Jones2001` (number part is 0, in-text, two citations) - `JR_cite1_3_Smith2000,Jones2001` (number part is 1, invisible, two citations) - + - Each group of citations may have an associated pageInfo. - - In LibreOffice, these can be found at
+ - In LibreOffice, these can be found at `LibreOffice:/[menu:File]/[Properties]/[Custom Properties]` - The property names are identical to the name of the reference mark corresponding to the citation group. - - JabRef 5.2 never cleans up these, they are left around.
+ - JabRef 5.2 never cleans up these, they are left around. `(problem)` New citations may "pick up" these unexpectedly. - The bibliography, if not found, is created at the end of the document. - - The location and extent of the bibliography is the content of the Section named `"JR_bib"`.
+ - The location and extent of the bibliography is the content of the Section named `"JR_bib"`. (In LibreOffice Sections are listed in the Navigator panel, under "Sections") - - JabRef 5.2 also creates a bookmark named `"JR_bib_end"`, but does not use it. During bibliography update it attempts to create it again without removing the old bookmark. The result is a new bookmark, with a number appended to its name @@ -275,14 +277,14 @@ citations - [Correction in new code](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java#L147): remove the old before creating the new. -## How does it interact with the document? +# How does it interact with the document? -- "stateless"
- JabRef is only loosely coupled to the document.
- Between two GUI actions it does not receive any information from LibreOffice.
+- "stateless" + JabRef is only loosely coupled to the document. + Between two GUI actions it does not receive any information from LibreOffice. It cannot distinguish between the user changing a single character in the document or rewriting everything. -- Access data
+- Access data - During a `[click:cite]` or `[click:Update]` we need the reference mark names. - Get all reference mark names - Filter (only ours) diff --git a/docs/openoffice/problems.md b/docs/openoffice/problems.md index 7961c331ba6..0492c041e4e 100644 --- a/docs/openoffice/problems.md +++ b/docs/openoffice/problems.md @@ -2,25 +2,25 @@ ## pageInfo should belong to citations, not citation groups -- Creating `[click:Separate]` revealed
+- Creating `[click:Separate]` revealed a `(problem)`: pageInfo strings are conceptually associated with - citations, but the implementation associates them to citation groups.
+ citations, but the implementation associates them to citation groups. The number of available pageInfo slots changes during`[click:Merge]` and `[click:Separate]` while the number of citations remains fixed. - The proposed solution was to change the association. - - Not only reference marks (citation groups) need unique identifiers, but also citations.
- Possible encoding for reference mark names:
- `JR_cite{type}_{number1}_{citationKey1},{number2}_{citationKey2}`
- where `{type}` encodes the citation type (for the group), `{citationKey1}` is made unique by choosing an appropriate number for `{number1}`
+ - Not only reference marks (citation groups) need unique identifiers, but also citations. + Possible encoding for reference mark names: + `JR_cite{type}_{number1}_{citationKey1},{number2}_{citationKey2}` + where `{type}` encodes the citation type (for the group), `{citationKey1}` is made unique by choosing an appropriate number for `{number1}` This would allow `JR_cite_{number1}_{citationKey1}` to be used as a property name for storing the pageInfo. - + Changes required to - reference mark search, name generation and parsing - name generation and parsing for properties storing pageInfo values - - in-memory representation
- - JabRef 5.2 does not collect pageInfo values, accesses only when needed.
+ - in-memory representation + - JabRef 5.2 does not collect pageInfo values, accesses only when needed. So it would be change to code accessing them. - The proposed representation does collect, to allow separation of getting from the document and processing @@ -36,21 +36,21 @@ on usability. Reference marks have some features that make it easy to mess up citations in a document -- They are **not visible** by default, the user is not aware of their boundaries
+- They are **not visible** by default, the user is not aware of their boundaries (`LO:[key:Ctrl-F8]`, `LO:[View]/[Field shadings]` helps) - They are **not atomic**: - - the user can edit the content. This will be lost on `[click:Update]`
+ - the user can edit the content. This will be lost on `[click:Update]` If an `As character` or `To character` anchor is inserted, the corresponding frame or footnote is deleted. - - by pressing Enter within, the user can break a reference mark into two parts.
+ - by pressing Enter within, the user can break a reference mark into two parts. The second part is now outside the reference mark: `[click:Update]` will leave it as is, and replace the first part with the full text for the citation mark. - If the space separating to citation marks is deleted, the user cannot reliably type between the - marks.
- The text typed usually becomes part of one of the marks. No visual clue as to which one.
+ marks. + The text typed usually becomes part of one of the marks. No visual clue as to which one. Note: `[click:Merge]` then `[click:Separate]` adds a single space between. The user can position the cursor before or after it. In either case the cursor is on a boundary: it is not - clear if it is in or out of a reference mark.
+ clear if it is in or out of a reference mark. Special case: a reference mark at the start or end of a paragraph: the cursor is usually considered to be within at the coresponding edge. - (good) They can be moved (Ctrl-X,Ctrl-V) - They cannot be copied. (Ctrl-C, Ctrl-V) copies the text without the reference mark. @@ -67,9 +67,9 @@ Reference marks have some features that make it easy to mess up citations in a d keeping the content at least two characters, we avoid the ambiguity at the edges: a cursor positioned between two characters inside is always within the reference mark. (At the edges it may or may not be inside.) - + - `(change)` `[click:Cite]` at reference mark edges: [safeInsertSpacesBetweenReferenceMarks](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java#L67) ensures the we are not inside, by starting two new paragraphs, inserting two spaces between them, then removing the new paragraph marks. -- `(change)` [guiActionInsertEntry](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java#L624) +- `(change)` [guiActionInsertEntry](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java#L624) checks if the cursor is in a citation mark or the bibliography. - `(change)` `[click:Update]` does an [exhaustive check](https://github.com/antalk2/jabref/blob/122d5133fa6c7b44245c5ba5600d398775718664/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java#L927) @@ -83,7 +83,7 @@ rest of the code. This would be the purpose of ## Undo -- JabRef 5.3 does not collect the effects of GUI actions on the document into larger Undo actions.
+- JabRef 5.3 does not collect the effects of GUI actions on the document into larger Undo actions. This makes the Undo functionality of LO impractial. - `(change)` collect the effects of GUI actions into large chunks: now a GUI action can be undone with a single click. From 5038421d3340c037daa523c70fa8a3533741ca62 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 22 Jun 2021 14:12:49 +0200 Subject: [PATCH 0993/1068] use StringUtil.isNullOrEmpty --- .../java/org/jabref/model/openoffice/ootext/OOFormat.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java index be5ee399e55..4bfba9e5baf 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java @@ -1,5 +1,7 @@ package org.jabref.model.openoffice.ootext; +import org.jabref.model.strings.StringUtil; + /** * Helper functions to produce some of the markup as understood by OOTextIntoOO.write * @@ -54,7 +56,7 @@ public static OOText setCharStyle(OOText ootext, String charStyle) { * Mark {@code ootext} as part of a paragraph with style {@code paraStyle} */ public static OOText paragraph(OOText ootext, String paraStyle) { - if (paraStyle == null || "".equals(paraStyle)) { + if (StringUtil.isNullOrEmpty(paraStyle)) { return paragraph(ootext); } String startTag = String.format("

", paraStyle); From 694fd9e52622365b3a1f63ad5281f1f05c9d2993 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 22 Jun 2021 15:37:27 +0200 Subject: [PATCH 0994/1068] no natural order for ComparableMark, use compareTopToBottomLeftToRight instead --- .../openoffice/rangesort/RangeSortVisual.java | 48 +++++-------------- 1 file changed, 13 insertions(+), 35 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index 969f9fed44e..e971e7ea67c 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -3,7 +3,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.Objects; import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.uno.UnoScreenRefresh; @@ -73,7 +72,7 @@ public static List> visualSort(List> input input.getIndexInPosition(), input)); } - Collections.sort(set); + Collections.sort(set, RangeSortVisual::compareTopToBottomLeftToRight); if (set.size() != inputSize) { throw new IllegalStateException("visualSort: set.size() != inputSize"); @@ -115,6 +114,17 @@ private static Point findPositionOfTextRange(XTextRange range, XTextViewCursor c return cursor.getPosition(); } + private static int compareTopToBottomLeftToRight(ComparableMark a, ComparableMark b) { + + if (a.position.Y != b.position.Y) { + return a.position.Y - b.position.Y; + } + if (a.position.X != b.position.X) { + return a.position.X - b.position.X; + } + return a.indexInPosition - b.indexInPosition; + } + /** * A reference mark name paired with its visual position. * @@ -123,7 +133,7 @@ private static Point findPositionOfTextRange(XTextRange range, XTextViewCursor c * * Used for sorting reference marks by their visual positions. */ - private static class ComparableMark implements Comparable> { + private static class ComparableMark { private final Point position; private final int indexInPosition; @@ -135,42 +145,10 @@ public ComparableMark(Point position, int indexInPosition, T content) { this.content = content; } - @Override - public int compareTo(ComparableMark other) { - - if (position.Y != other.position.Y) { - return position.Y - other.position.Y; - } - if (position.X != other.position.X) { - return position.X - other.position.X; - } - return indexInPosition - other.indexInPosition; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (o instanceof ComparableMark) { - ComparableMark other = (ComparableMark) o; - return ((this.position.X == other.position.X) - && (this.position.Y == other.position.Y) - && (this.indexInPosition == other.indexInPosition) - && Objects.equals(this.content, other.content)); - } - return false; - } - public T getContent() { return content; } - @Override - public int hashCode() { - return Objects.hash(position, indexInPosition, content); - } } } From 69f7be4215bdbb21789a7946c08bc8a9db4c8719 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 23 Jun 2021 15:29:07 +0200 Subject: [PATCH 0995/1068] add docs/openoffice/ooresult-*.md --- docs/SUMMARY.md | 2 + docs/openoffice/ooresult-alternatives.md | 503 +++++++++++++++++++++++ docs/openoffice/ooresult-ooerror.md | 232 +++++++++++ 3 files changed, 737 insertions(+) create mode 100644 docs/openoffice/ooresult-alternatives.md create mode 100644 docs/openoffice/ooresult-ooerror.md diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index dcd6ca4ccf2..f1e8d4a7013 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -24,3 +24,5 @@ * [Order of appearance of citation groups](openoffice/order-of-appearance.md) * [Problems](openoffice/problems.md) * [Code reorganization](openoffice/code-reorganization.md) + * [About `OOError`, `OOResult` and `OOVoidResult`](openoffice/ooresult-ooerror.md) + * [Alternatives to using OOResult and OOVoidResult in OOBibBase](openoffice/ooresult-alternatives.md) diff --git a/docs/openoffice/ooresult-alternatives.md b/docs/openoffice/ooresult-alternatives.md new file mode 100644 index 00000000000..83f8ca67232 --- /dev/null +++ b/docs/openoffice/ooresult-alternatives.md @@ -0,0 +1,503 @@ + +# Alternatives to `OOResult` during precondition checking in `OOBibBase` + +(Talk about ADRs prompted me to think about alternatives to what I used.) + +Situation: + +- some tests return no data, only report problems +- we may need to get some resources that might not be available + (for example: connection to a document, a functional textview cursor) +- some test depend on these resources + + +One strategy could be to use a single try-catch around the whole body, +then showing a message based on the type of exceptions thrown. + +**[base case]** +```java +try { + A a = f(); + B b = g(a); + realAction(a,b); +} catch (FirstExceptionType ex) { + showDialog( title, messageForFirstExceptionType(ex) ); +} catch (SecondExceptionType ex) { + showDialog( title, messageForSecondExceptionType(ex) ); +} catch (Exception ex) { + showDialog( title, messageForOtherExceptions(ex) ); +} +``` + +This our base case. + +It is not clear from the code, nor within the catch branches (unless +we start looking into stack traces) which call (`f()`, `g(a)` or +`realAction(a,b)`) resulted in the exception. This limits the +specificity of the message and makes it hard to think about the "why" +can we get this exception here? + +## Catch around each call? + +A more detailed strategy would be to try-catch around each call. +In case we need a result from the call, this means either increasingly indented +code (try-in-try). + +```java +try { + A a = f(); + try { + B b = g(a); + try { + realAction(ab); + } catch (...){ + showDialog(); + } + } catch (G ex) { + showDialog(title, ex); // title describes which GUI action we are in + } +} catch (F ex) { + // could an F be thrown in g? + showDialog( title, ex ); +} +``` + +or (declare and fill later) + +```java +A a = null; +try { + a = f(); +} catch (F ex) { + showDialog(title, ex); + return; +} +B b = null; +try { + b = g(a); +} catch (G ex) { + showDialog(title, ex); + return; +} +try { + realAction(ab); +} catch (...){ + showDialog(); +} +``` + +In either case, the code becomes littered with exception handling code. + +## Catch in wrappers? + +We might push the try-catch into its own function. +If the wrapper is called multiple times, this may reduce duplication of the +catch-and-assign-message part. + +We can show an error dialog here: `title` carries some information +from the caller, the exeption caught brings some from below. + +We still need to notify the action handler (the caller) about +failure. Since we have shown the dialog, we do not need to provide a +message. + +### Notify caller with `Optional` result. + +With `Optional` we get something like this: + +**[dialog in wrap, return Optional]** + +```java +Optional wrap_f(String title) { + try { + return Optional.of(f()); + } catch (F ex) { + showDialog(title, ex); + return Optional.empty(); + } +} + +Optional wrap_g(String title, A a) { + try { + return Optional.of(g(a)); + } catch (G ex) { + showDialog(title, ex); + return Optional.empty(); + } +} +``` + +and use it like this: + +```java +Optional a = wrap_f(title); +if (a.isEmpty()) { return; } + +Optional b = wrap_g(title, a.get()); +if (b.isEmpty()) { return; } + +try { + realAction(a.get(), b.get()); +} catch (...) { +} +``` + +This looks fairly regular. + +If `g` did not need `a`, we could simplify to + +```java +Optional a = wrap_f(title); +Optional b = wrap_g(title); +if (a.isEmpty() || b.isEmpty()) { return; } + +try { + realAction(a.get(), b.get()); +} catch (...) { +} +``` + +### Notify caller with `Result` result. + +With `Result` we get something like this: + +**[dialog in wrap, return OOResult]** + +```java +OOResult wrap_f() { + try { + return OOResult.ok(f()); + } catch (F ex) { + return OOResult.error(OOError.from(ex)); + } catch (F2 ex) { + String message = "..."; + return OOResult.error(new OOError(message, ex)); // [1] + } +} +// [1] : this OOError constructor (explicit message but no title) is missing + +Optional wrap_g(A a) { + try { + return OOResult.ok(g(a)); + } catch (G ex) { + return OOResult.error(OOError.from(ex)); + } +} +``` + +and use it like this: + +```java +OOResult a = wrap_f(); +if (testDialog(title, a)) { // [1] + return; +} + +// [1] needs boolean testDialog(String title, OOResultLike... a); +// where OOResultLike is an interface with `OOVoidResult asVoidResult()` +// and is implemented by OOResult and OOVoidResult + +OOResult b = wrap_g(a.get()); +if (testDialog(title, b)) { return; } // (checkstyle makes this 3 lines) + +try { + realAction(a.get(), b.get()); +} catch (...) { +} +``` + +If `g` did not need `a`, we could simplify to + +```java +Optional a = wrap_f(); +Optional b = wrap_g(); +if (testDialog(title, a, b)) { // a single dialog can show both messages + return; +} + +try { + realAction(a.get(), b.get()); +} catch (...) { +} +``` + + + +### Notify caller by throwing an exception + +Or we can throw an exception to notify the caller. + +To simplify code in the caller, I assume we are using an exception +type not used elsewhere, but shared by all precondition checks. + +**[dialog in wrap, PreconditionException]** + +```java +A wrap_f(String title) throws PreconditionException { + try { + return f(); + } catch (F ex) { + showDialog(title, ex) + throw new PreconditionException(); + } +} + +B wrap_g(String title, A a) throws PreconditionException { + try { + return g(a); + } catch (G ex) { + showDialog(title, ex); + throw new PreconditionException(); + } +} +``` + +use + +```java +try { + A a = wrap_f(title); + B b = wrap_g(title, a); + try { + realAction(a, b); + } catch (...) { + showDialog(...) + } +} catch( PreconditionException ) { + // Only precondition checks get us here. + return; +} +``` + +or (since PreconditionException is not thrown from realAction) + +```java +try { + A a = wrap_f(title); + B b = wrap_g(title, a); + realAction(a, b); +} catch (...) { + // Only realAction gets us here + showDialog(...) +} catch( PreconditionException ) { + // Only precondition checks get us here. + return; +} +``` + +or (separate try-catch for preconditions and realAction) + +```java +A a = null; +B b = null; +try { + a = wrap_f(title); + b = wrap_g(title, a); +} catch( PreconditionException ) { + return; +} +try { + realAction(a, b); +} catch (...) { +} +``` + +or to reduce passing around the title part: + +**[PreconditionException, dialog in catch]** + +```java +A wrap_f() throws PreconditionException { + try { + return f(); + } catch (F ex) { + throw new PreconditionException(message, ex); + } +} + +B wrap_g(A a) throws PreconditionException { + try { + return g(a); + } catch (G ex) { + throw new PreconditionException(message, ex); + } +} +``` + +use + +```java +try { + A a = wrap_f(); + B b = wrap_g(a); + try { + realAction(a, b); + } catch (...) { + showDialog(...); + } +} catch(PreconditionException ex) { + showDialog(title, ex.message ); + return; +} +``` + +or + +``` +try { + A a = wrap_f(); + B b = wrap_g(a); + realAction(a, b); +} catch (...) { + showDialog(...); +} catch(PreconditionException ex) { + showDialog(title, ex.message ); + return; +} +``` + + +## Push associating the message further down + +As [the developers guide](https://jabref.readthedocs.io/en/latest/getting-into-the-code/code-howtos/#throwing-and-catching-exceptions) +suggest, we could "Catch and wrap all API exceptions" and rethrow them +as a `JabRefException` or some exception derived from it. In this case the try-catch part goes even further down, and +in principle we could just + +```java +try { + A a = f(); + B b = g(a); + realAction(a, b); +} catch(JabRefException ex) { + showDialog(title, ex.message ); + return; +} +``` + +Constraints: + +- conversion to `JabRefException` cannot be done in `model` (since JabRefException is in `logic`) +- `JabRefException` expects a localized message. Or we need to remember +which `JabRefException` instances are localized and which need to be caught +for localizing the message. +- At the bottom we usually have very little information on higher level +contexts: at a failure like `NoSuchProperty` we cannot tell which set +of properties did we look in and why. +For messages originating too deeply, we might want to override or extend the message anyway. +- for each exeption we might want to handle programmatically, we need a variant based +on `JabRefException` + +So we might end up: + +```java +try { + A a = f(); + B b = g(a); + realAction(a, b); +} catch(FDerivedFromJabRefException ex) { + showDialog(title, messageForF ); +} catch(GDerivedFromJabRefException ex) { + showDialog(title, messageForG ); +} catch(JabRefException ex) { + showDialog(title, ex.message ); +} catch(Exception ex) { // [1] + showDialog(title, ex.message, ex ); + // [1] does "never catch Exception or Throwable" apply at this point? + // Probably should not: we are promising not to throw. +} +``` + +which looks very similar to the original version. + +This again loses the information: can `GDerivedFromJabRefException` +come from `realAction` or `f` or not? This is because we have pushed +down the last catch/throw indefinitely (eliminating `wrap_f`) into a +depth, where we cannot necessarily assign an appropriate message. + +To a lesser extent this also happens in `wrap_f`: it only knows about +the action that called it what we provide (`title` or nothing). It knows +the precondition it checks: probably an optimal location to assign a message. + +**Summary**: going from top to bottom, we move to increasingly more local context, +our knowledge shifts towards the "in which part of the code did we have a problem" +and away from the high level ("which action"). + +One natural point to meet information from these to levels +is the top level of action handlers. For precondition checking code +a wrapper around code elsewhere may be considered. +Using such wrappers may reduce duplication if called in multiple actions. + +We still have to signal failure to the action handler: the options considered +above were using an `Optional` and throwing an exception with the appropriate message. + +The more promising variants were + +- **[dialog in wrap, return Optional]** + `Optional wrap_f(String title)` (showDialog inside) + - pro: explicit return in caller + - con: explicit return in caller (boilerplate) + - con: passing in the title is repeated + - would be 'pro' if we wanted title to vary within an action + +- **[PreconditionException, dialog in catch]** + `A wrap_f() throws PreconditionException` + (with `showDialog` under `catch(PreconditionException ex)`) + - con: hidden control flow + - pro: no repeated `if(){return}` boilerplate + - pro: title used only once + +**[using OOResult]** +```java +final String title = "Could not insert citation"; + +OOResult odoc = getXTextDocument(); +if (testDialog(title, + odoc, + styleIsRequired(style), + selectedBibEntryIsRequired(entries, OOError::noEntriesSelectedForCitation))) { + return; +} +XTextDocument doc = odoc.get(); + +OOResult ofr = getFrontend(doc); +if (testDialog(title, ofr)) { + return; +} +OOFrontend fr = ofr.get(); + +OOResult cursor = getUserCursorForTextInsertion(doc); +if (testDialog(title, cursor)) { + return; +} +... +``` + + +**[using PreconditionException, dialog in catch]** +```java +final String title = "Could not insert citation"; + +try { + XTextDocument doc = getXTextDocument(); + styleIsRequired(style); + selectedBibEntryIsRequired(entries, OOError::noEntriesSelectedForCitation); + OOFrontend fr = getFrontend(doc); + XTextCursor cursor = getUserCursorForTextInsertion(doc); + ... +} catch (PreconditionException ex) { + showDialog(title, ex); +} catch (...) { +} +``` + +I would suggest using the latter, +- probably using `OOError` for `PreconditionException` + - In this case `OOError` being in `gui` becomes an asset: we can be sure + code in `logic` cannot throw it. +- We lose the capability to collect mmessages in a single dialog (we + stop processing at the first problem). +- The division between precondition checking (only throws + PreconditionException) and `realAction`becomes invisible in the + action code. + diff --git a/docs/openoffice/ooresult-ooerror.md b/docs/openoffice/ooresult-ooerror.md new file mode 100644 index 00000000000..ec243e0a0dc --- /dev/null +++ b/docs/openoffice/ooresult-ooerror.md @@ -0,0 +1,232 @@ +# About `OOError`, `OOResult` and `OOVoidResult` + +## Context + +### Relieve GUI panel code + +On the question of where should we catch exceptions in relation to GUI +code it was suggested (Jonatan Asketorp +https://github.com/koppor/jabref/pull/496#discussion_r629695493, "most +of them (all?) should be handled latest in the ViewModel.") that +catching them early could help simplifying the higher levels. + +### Same messages in different contexts + +Some types of exceptions are caught in *different GUI actions*, often +resulting in basically the same error dialog, possibly only differing in +the indicated context (which GUI action). + +Problems found during *precondition checking* (for example: do we have +a connection to a document) and error conditions (for example: lost +connection to a document during an action) can overlap. + +### OOBibBase as a precondition and exception handling layer + +Since most of the code originally in `OOBibBase` was moved to `logic` and +almost all GUI actions go through `OOBibBase`, it seemed a good location +to collect precondition checking and exception handling code. + +Note: some of the precondition checking still needs to stay in `OpenOfficePanel`: +for example to provide a list of selected `BibEntry` instances, it needs to go through some steps +from `frame.getCurrentLibraryTab()` to `(!entries.isEmpty() && checkThatEntriesHaveKeys(entries))` + +To avoid `OOBibBase` depending on the higher level `OpenOfficePanel` +message texts needed in `OOBibBase` were moved from `OpenOfficePanel` to `OOError`. +(Others stayed, but could be moved if that seems worthwile) + +## OOError + +- `OOError` is a collection of data used in error dialogs. + - It is a `JabRefException` with an added field: `localizedTitle` + - It can store: a dialog title, a localized message (optionally a non-localized message as well) and a `Throwable` + - I used it in `OOBibBase` as a unified format for errors to be shown in an error dialog. + - Static constructors in `OOError` provide uniform translation from some exception types to + `OOError` with the corresponding localized messages: + `public static OOError from(SomeException ex)` + There is also `public static OOError fromMisc(Exception ex)` for exception types + not handled individually. (It has a different name, to avoid ambiguity) + + - Another set of contructors provide messages for some preconditions. + For example `public static OOError noDataBaseIsOpenForCiting()` + +Some questions: + +- Should we use static data instead of static methods for the precondition-related messages? + - pro: why create a new instance for each error? + - con: `OOError.setTitle()` currently just sets `this.localizedTitle` and returns `this`. + For static instances this would modify a shared resource unless we create a new copy in `setTitle`. + However `setTitle` can be called repeatedly on the same object: as we bubble up, we can be more specific + about the context. + +- Should we remove title from `OOError`? + - pro: we almost always override its original value + - con: may need to duplicate the title in different files (preconditions for an action in OpenOfficePanel + and in OOBibBase) + +- Should we include `OOError.showErrorDialog` ? + - pro: since it was intended *for* error dialogs, it is nice to provide this. + - con: the reference to `DialogService` forces it to `gui`, thus it cannot be used in `logic` or `model` + +- Should we use `JabRefException` as base? + - pro: `JabRefException` is mentioned as the standard form of errors in the developers guide. + [All Exceptions we throw should be or extend JabRefException](https://jabref.readthedocs.io/en/latest/getting-into-the-code/code-howtos/#throwing-and-catching-exceptions) + - against: `JabRefException` is in `logic` cannot be used in model. + (Could this be resolved by moving `JabRefException` to `model`?) + +## OOResult + +During precondition checking + +1. some tests return no data, only report problems +2. we may need to get some resources that might not be available + (for example: connection to a document, a functional textview cursor) +3. some test depend on these resources + +While concentrating on these and on "do not throw exceptions here" +... using a https://en.wikipedia.org/wiki/Result_type as a return +value from precondition checking code seemed a good fit: + +- Instead of throwing an exception, we can return some data describing the problem. +- Conceptually it is a data structure that either holds the result (of a computation) or and error value. +- It can be considered as an extended `Optional`, that can provide details on "why empty"? +- It can be considered as an alternative to throwing an exception: we return an `error` instead. +- Methods throwing checked exceptions cannot be used with for example `List.map`. + Methods returning a Result could. + +- `Result` shares the problem (with any other solutions) that in a +function several types of errors may occur, but we can only return a +single error type. Java solves this using checked exceptions being all +descendants of Exception. (Also adds try/catch/catch to select cases +based on the exceptions type, and some checking against forgotten +cases of checked exception types) + +In `OOBibBase` I used `OOError` as the unified error type: it can +store error messages and wrap exceptions. It contains everything we need +for an error dialog. On the other hand it does not support programmatic +dissection. + +### Implementation + +Unlike `Optional` and `List`, `Result` (in the sense used here) did not get into +java standard libraries. There are some implementations of this idea for java on the net: + + * https://github.com/bgerstle/result-java/ + * https://github.com/MrKloan/result-type + * https://gist.github.com/david-bakin/35d55daeeaee1eb71cea + * https://www.baeldung.com/vavr-try + +Generics allow an implementation built around + +``` +class OOResult { + private final Optional result; + private final Optional error; +} +``` + +with an assumption that at any time exactly one of `result` and `error` is present. + +> `class X { boolean isOK; Object data; }` expresses this assumption more directly, +> (but omits the relation between the type parameters `` and the type in `data`) + +- Since `OOResult` encodes the state `isOK` in `result.isPresent()` (and equivalently in `errror.isEmpty()`), + we cannot allow construction of instances where both values are `isEmpty`. + In particular, `OOResult.ok(null)` and `OOResult.error(null)` are not + allowed: it would make the state `isOK` ambiguous. + It would also break the similarity to `Optional` to allow both `isEmpty` and `isOK` to be true. + +- Not allowing null, has a consequence on `OOResult` + According to + [baeldung.com/java-void-type](https://www.baeldung.com/java-void-type), + the only possible value for `Void` is `null` which we excluded. + + `OOResult.ok(null)` would look strange: in this case we need + `ok()` without arguments. + +To solve this problem, I introduced + +```java +class OOVoidResult { + private final Optional error; + ... +} +``` + +with methods on the error side similar to those in `OOError`, and +`OOVoidResult.ok()` to construct the success case with no data. + +### The relation between `Optional` and `OOVoidResult` + +* Both `Optional` and `OOVoidResult` can store 0 or 1 values, + in this respect they are equivalent + + * Actually, `OOVoidResult` is just a wrapper around an `Optional` + +* In terms of communication to human readers when used, their + connotation in respect to success and failure is the opposite: + + * `Optional.empty()` normally suggests failure, `OOVoidResult.ok()` mean success. + * `Optional.of(something)` probably means success, `OOVoidResult.error(something)` indicates failure. + * `OOVoidResult` is "the other half" (the failure branch) of `OOResult` + + * its content is accessed through `getError`, `mapError`, `ifError`, not `get`, `map`, `ifPresent` + +`OOVoidResult` allows + +* a clear distinction between success and failure when + calls to "get" something that might not be available (`Optional`) and + calls to precondition checking where we can only get reasons for failure + (`OOVoidResult`) + appear together. + Using `Optional` for both is possible, but is more error-prone. + +* it also allows using uniform verbs (`isError`, `getError`, + `ifError`, return `OO{Void}Result.error`) for "we have a problem" + when + + * checking preconditions (`OOVoidResult`) is mixed with + * "I need an X" orelse "we have a problem" (`OOResult`) + +* at a functions head: + + * `OOVoidResult function()` says: no result, but may get an error message + * `Optional function()` says: a `String` result or nothing. + +**Summary**: technically could use `Optional` for both situation, but it would be less precise, +leaving more room for confusion and bugs. `OOVoidResult` forces use of `getError` instead of `get`, +and `isError` or `isOk` instead of `isPresent`or `isEmpty`. + +## What does OOResult buy us? + + +The promise of `Result` is that we can avoid throwing exceptions and +return errors instead. This allows the caller to handle these latter +as data, for example may summarize / collect them for example into a single +message dialog. + +Handling the result needs some code in the caller. If we only needed checks that +return only errors (not results), the code could look like this (with possibly more tests listed): + +```java +OOResult odoc = getXTextDocument(); +if (testDialog(title, + odoc, + styleIsRequired(style), + selectedBibEntryIsRequired(entries, OOError::noEntriesSelectedForCitation))) { + return; +} +``` + +with a reasonably small footstep. + +Dependencies of tests on earlier results complicates this: now we repeat the + +```java +if (testDialog(title, + ...)) { + return; +} +``` + +part several times. + From 9712162599ffce437d5ba3a3f32d21110220c0dc Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 1 Jul 2021 21:26:24 +0200 Subject: [PATCH 0996/1068] copy docs/openoffice from J (for markdown lint changes) --- docs/README.md | 4 -- docs/openoffice/code-reorganization.md | 22 +++++----- docs/openoffice/ooresult-alternatives.md | 28 ++++++------ docs/openoffice/ooresult-ooerror.md | 56 ++++++++++++------------ docs/openoffice/order-of-appearance.md | 14 +++--- docs/openoffice/overview.md | 29 +++++------- docs/openoffice/problems.md | 4 +- 7 files changed, 74 insertions(+), 83 deletions(-) diff --git a/docs/README.md b/docs/README.md index 4e689cb2f71..9b92a91b440 100644 --- a/docs/README.md +++ b/docs/README.md @@ -51,7 +51,3 @@ For new ADRs, please use [template.md](https://github.com/JabRef/jabref/tree/3b3 Also filed as IntelliJ issue [IDEA-240250](https://youtrack.jetbrains.com/issue/IDEA-240250). -## About OpenOffice/LibreOffice - -[here](openoffice/README.md) - diff --git a/docs/openoffice/code-reorganization.md b/docs/openoffice/code-reorganization.md index b91aa53984c..a9d45418690 100644 --- a/docs/openoffice/code-reorganization.md +++ b/docs/openoffice/code-reorganization.md @@ -44,7 +44,7 @@ Why - `rangesort` : ordering objects that have an `XTextRange`, optionally with an extra integer to break ties. - `RangeSort.partitionAndSortRanges` : since `XTextRangeCompare` can only compare `XTextRange` values in the same `XText`, we partition them accordingly and only sort within each partiion. - - `RangeSortable` (interface), `RangeSortEntry` (implements) : + - `RangeSortable` (interface), `RangeSortEntry` (implements) : When we replace `XTextRange` of citation marks in footnotes with the range of the footnote mark, multiple citation marks may be mapped to the same location. To preserve the order between these, `RangeSortable` allows this order to be indicated by returning appropriate indices from `getIndexInPosition` @@ -59,7 +59,7 @@ Why May change as new backends may need different APIs. - `style` : data structures and interfaces used while going from ordered list of citation groups to formatted citation markers and bibliography. Does not communicate with the document. Too long to fit here, starting a new section. - + ## model/style At the core, @@ -112,6 +112,7 @@ This is done in logic, in [`OOProcessAuthorYearMarkers.createUniqueLetters()`](h The entry point for this processing is: [`OOProcess.produceCitationMarkers`](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java#L69). It fills + - each `CitationGroup.citationMarker` - `CitationGroups.bibliography` - From bibliography `OOFormatBibliography.formatBibliography()` creates an `OOText` @@ -138,7 +139,7 @@ to the rest. Originally it also contains code to format numeric and author-year - `CitationMarkerNumericEntry` - `CitationMarkerEntry` - `CitationMarkerNumericBibEntry` - - `CitationMarkerNormEntry` + - `CitationMarkerNormEntry` describe their expected input entries. - [`OOProcess.produceCitationMarkers`](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java#L69) is the main entry point for style application. Calls to specific implementations @@ -159,7 +160,7 @@ These are currently in `UpdateBibliography` - `OOFrontend` : has a `Backend` and `CitationGroups` - Its constructor creates a backend, reads data from the document and creates a CitationGroups instance. - provides functionality that requires both access to the document and the CitationGroups instance -- `RangeForOverlapCheck` used in `OOFrontend` +- `RangeForOverlapCheck` used in `OOFrontend` - `UpdateBibliography` : Create, find and update the bibliography in the document using output from `produceCitationMarkers()` - `UpdateCitationMarkers` create `CitationGroup`, update citation markers using output from @@ -178,11 +179,10 @@ GUI-independent part of implementations of GUI actions. - contains some dialog messages that do not correspond to exceptions - `OOBibBase2` : most activity was moved out from here to parts discussed above. - - connecting / selecting a document moved to `OOBibBaseConnect` - - the rest connects higher parts of the GUI to actions in logic - - does argument and precondition checking - - catches all exceptions - - shows error and warning dialogs - - adds `enterUndoContext`, `leaveUndoContext` around action code - + - connecting / selecting a document moved to `OOBibBaseConnect` + - the rest connects higher parts of the GUI to actions in logic + - does argument and precondition checking + - catches all exceptions + - shows error and warning dialogs + - adds `enterUndoContext`, `leaveUndoContext` around action code diff --git a/docs/openoffice/ooresult-alternatives.md b/docs/openoffice/ooresult-alternatives.md index 83f8ca67232..27d5dbb7e11 100644 --- a/docs/openoffice/ooresult-alternatives.md +++ b/docs/openoffice/ooresult-alternatives.md @@ -14,7 +14,8 @@ Situation: One strategy could be to use a single try-catch around the whole body, then showing a message based on the type of exceptions thrown. -**[base case]** +## [base case] + ```java try { A a = f(); @@ -101,11 +102,11 @@ We still need to notify the action handler (the caller) about failure. Since we have shown the dialog, we do not need to provide a message. -### Notify caller with `Optional` result. +### Notify caller with `Optional` result With `Optional` we get something like this: -**[dialog in wrap, return Optional]** +#### [dialog in wrap, return Optional] ```java Optional wrap_f(String title) { @@ -157,11 +158,11 @@ try { } ``` -### Notify caller with `Result` result. +### Notify caller with `Result` result With `Result` we get something like this: -**[dialog in wrap, return OOResult]** +#### [dialog in wrap, return OOResult] ```java OOResult wrap_f() { @@ -221,8 +222,6 @@ try { } ``` - - ### Notify caller by throwing an exception Or we can throw an exception to notify the caller. @@ -230,7 +229,7 @@ Or we can throw an exception to notify the caller. To simplify code in the caller, I assume we are using an exception type not used elsewhere, but shared by all precondition checks. -**[dialog in wrap, PreconditionException]** +#### [dialog in wrap, PreconditionException] ```java A wrap_f(String title) throws PreconditionException { @@ -304,7 +303,7 @@ try { or to reduce passing around the title part: -**[PreconditionException, dialog in catch]** +#### [PreconditionException, dialog in catch] ```java A wrap_f() throws PreconditionException { @@ -343,7 +342,7 @@ try { or -``` +```java try { A a = wrap_f(); B b = wrap_g(a); @@ -447,7 +446,8 @@ The more promising variants were - pro: no repeated `if(){return}` boilerplate - pro: title used only once -**[using OOResult]** +### [using OOResult] + ```java final String title = "Could not insert citation"; @@ -474,7 +474,8 @@ if (testDialog(title, cursor)) { ``` -**[using PreconditionException, dialog in catch]** +### [using PreconditionException, dialog in catch] + ```java final String title = "Could not insert citation"; @@ -491,7 +492,8 @@ try { } ``` -I would suggest using the latter, +I would suggest using the latter, + - probably using `OOError` for `PreconditionException` - In this case `OOError` being in `gui` becomes an asset: we can be sure code in `logic` cannot throw it. diff --git a/docs/openoffice/ooresult-ooerror.md b/docs/openoffice/ooresult-ooerror.md index ec243e0a0dc..867ee55d009 100644 --- a/docs/openoffice/ooresult-ooerror.md +++ b/docs/openoffice/ooresult-ooerror.md @@ -6,7 +6,7 @@ On the question of where should we catch exceptions in relation to GUI code it was suggested (Jonatan Asketorp -https://github.com/koppor/jabref/pull/496#discussion_r629695493, "most +[here](https://github.com/koppor/jabref/pull/496#discussion_r629695493), "most of them (all?) should be handled latest in the ViewModel.") that catching them early could help simplifying the higher levels. @@ -48,7 +48,7 @@ message texts needed in `OOBibBase` were moved from `OpenOfficePanel` to `OOErro - Another set of contructors provide messages for some preconditions. For example `public static OOError noDataBaseIsOpenForCiting()` - + Some questions: - Should we use static data instead of static methods for the precondition-related messages? @@ -57,12 +57,12 @@ Some questions: For static instances this would modify a shared resource unless we create a new copy in `setTitle`. However `setTitle` can be called repeatedly on the same object: as we bubble up, we can be more specific about the context. - + - Should we remove title from `OOError`? - pro: we almost always override its original value - con: may need to duplicate the title in different files (preconditions for an action in OpenOfficePanel and in OOBibBase) - + - Should we include `OOError.showErrorDialog` ? - pro: since it was intended *for* error dialogs, it is nice to provide this. - con: the reference to `DialogService` forces it to `gui`, thus it cannot be used in `logic` or `model` @@ -83,7 +83,7 @@ During precondition checking 3. some test depend on these resources While concentrating on these and on "do not throw exceptions here" -... using a https://en.wikipedia.org/wiki/Result_type as a return +... using a [Result type](https://en.wikipedia.org/wiki/Result_type) as a return value from precondition checking code seemed a good fit: - Instead of throwing an exception, we can return some data describing the problem. @@ -102,7 +102,7 @@ cases of checked exception types) In `OOBibBase` I used `OOError` as the unified error type: it can store error messages and wrap exceptions. It contains everything we need -for an error dialog. On the other hand it does not support programmatic +for an error dialog. On the other hand it does not support programmatic dissection. ### Implementation @@ -110,14 +110,14 @@ dissection. Unlike `Optional` and `List`, `Result` (in the sense used here) did not get into java standard libraries. There are some implementations of this idea for java on the net: - * https://github.com/bgerstle/result-java/ - * https://github.com/MrKloan/result-type - * https://gist.github.com/david-bakin/35d55daeeaee1eb71cea - * https://www.baeldung.com/vavr-try +- [bgerstle/result-java](https://github.com/bgerstle/result-java/) +- [MrKloan/result-type](https://github.com/MrKloan/result-type) +- [david-bakin](https://gist.github.com/david-bakin/35d55daeeaee1eb71cea) +- [vavr-try](https://www.baeldung.com/vavr-try) Generics allow an implementation built around -``` +```java class OOResult { private final Optional result; private final Optional error; @@ -143,7 +143,7 @@ with an assumption that at any time exactly one of `result` and `error` is prese `OOResult.ok(null)` would look strange: in this case we need `ok()` without arguments. -To solve this problem, I introduced +To solve this problem, I introduced ```java class OOVoidResult { @@ -157,40 +157,40 @@ with methods on the error side similar to those in `OOError`, and ### The relation between `Optional` and `OOVoidResult` -* Both `Optional` and `OOVoidResult` can store 0 or 1 values, +- Both `Optional` and `OOVoidResult` can store 0 or 1 values, in this respect they are equivalent - * Actually, `OOVoidResult` is just a wrapper around an `Optional` + - Actually, `OOVoidResult` is just a wrapper around an `Optional` -* In terms of communication to human readers when used, their +- In terms of communication to human readers when used, their connotation in respect to success and failure is the opposite: - * `Optional.empty()` normally suggests failure, `OOVoidResult.ok()` mean success. - * `Optional.of(something)` probably means success, `OOVoidResult.error(something)` indicates failure. - * `OOVoidResult` is "the other half" (the failure branch) of `OOResult` - - * its content is accessed through `getError`, `mapError`, `ifError`, not `get`, `map`, `ifPresent` + - `Optional.empty()` normally suggests failure, `OOVoidResult.ok()` mean success. + - `Optional.of(something)` probably means success, `OOVoidResult.error(something)` indicates failure. + - `OOVoidResult` is "the other half" (the failure branch) of `OOResult` + + - its content is accessed through `getError`, `mapError`, `ifError`, not `get`, `map`, `ifPresent` `OOVoidResult` allows -* a clear distinction between success and failure when +- a clear distinction between success and failure when calls to "get" something that might not be available (`Optional`) and calls to precondition checking where we can only get reasons for failure (`OOVoidResult`) appear together. Using `Optional` for both is possible, but is more error-prone. -* it also allows using uniform verbs (`isError`, `getError`, +- it also allows using uniform verbs (`isError`, `getError`, `ifError`, return `OO{Void}Result.error`) for "we have a problem" when - * checking preconditions (`OOVoidResult`) is mixed with - * "I need an X" orelse "we have a problem" (`OOResult`) + - checking preconditions (`OOVoidResult`) is mixed with + - "I need an X" orelse "we have a problem" (`OOResult`) -* at a functions head: +- at a functions head: - * `OOVoidResult function()` says: no result, but may get an error message - * `Optional function()` says: a `String` result or nothing. + - `OOVoidResult function()` says: no result, but may get an error message + - `Optional function()` says: a `String` result or nothing. **Summary**: technically could use `Optional` for both situation, but it would be less precise, leaving more room for confusion and bugs. `OOVoidResult` forces use of `getError` instead of `get`, @@ -228,5 +228,5 @@ if (testDialog(title, } ``` -part several times. +part several times. diff --git a/docs/openoffice/order-of-appearance.md b/docs/openoffice/order-of-appearance.md index a59846af16c..e43009b9f93 100644 --- a/docs/openoffice/order-of-appearance.md +++ b/docs/openoffice/order-of-appearance.md @@ -1,5 +1,5 @@ -## Order of appearance of citation groups (`globalOrder`) +# Order of appearance of citation groups (`globalOrder`) The order of appearance of citations is decided on two levels: @@ -11,7 +11,7 @@ groups that appear as citation markers in the text (`globalOrder`). This page is about the latter: how to decide the order of appearance (numbering sequence) of a set of citation markers? -### Conceptually +## Conceptually In a continuous text it is easy: take the textual order of citation markers. @@ -29,7 +29,7 @@ Examples: we consider it part of the second column? -### Technically +## Technically In LibreOffice, a document has a main text that supports the @@ -41,7 +41,7 @@ to be inserted. - Some of these allow text inside with further insertions. -#### Anchors +### Anchors - Many, but not all XTextContent types support getting a "technical" insertion point or text range through [getAnchor](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextContent.html#ae82a8b42f6b2578549b68b4483a877d3). @@ -53,7 +53,7 @@ to be inserted. - Allowing or requiring the user to insert "logical anchors" for frames and other "floating" parts might help to alleviate these problems. -#### Sorting within a `Text` +### Sorting within a `Text` The text ranges occupied by the citation markers support the [XTextRange](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextRange.html) @@ -64,7 +64,7 @@ interface. may support (optional) the [XTextRangeCompare](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextRangeCompare.html) interface, that allows two XTextRange values to be compared if both belong to this `Text` -#### Visual ordering +### Visual ordering - The cursor used by the user is available as an [XTextViewCursor](https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XTextViewCursor.html) @@ -94,7 +94,7 @@ Consequences of getting these visual coordinates and using them to order the cit of the first column of the first page. -### JabRef +## JabRef Jabref uses the following steps for sorting sorting citation markers (providing `globalOrder`): diff --git a/docs/openoffice/overview.md b/docs/openoffice/overview.md index df8a5cef5b2..f3a6ed251f6 100644 --- a/docs/openoffice/overview.md +++ b/docs/openoffice/overview.md @@ -75,10 +75,10 @@ Citations can be grouped. A group of parenthesized citations share the parentheses around, like this: "(Smith, 2000; Jones 2001)". - - Examples with pseudocode: - - `\citep{Smith2000,Jones2001}` "(Smith, 2000; Jones 2001)" - - `\citet{Smith2000,Jones2001}` "Smith (2000); Jones (2001)" - - `\citen{Smith2000,Jones2001}` "" +- Examples with pseudocode: + - `\citep{Smith2000,Jones2001}` "(Smith, 2000; Jones 2001)" + - `\citet{Smith2000,Jones2001}` "Smith (2000); Jones (2001)" + - `\citen{Smith2000,Jones2001}` "" From the user's point of view, citation groups can be created by @@ -198,7 +198,7 @@ For numbered styles, the citations within a group are sorted again during generation of the citation marker, now by the numbers themselves. The result of this sorting is not saved, only affects the citation marker. - - Series of consecutive number are replaced with ranges: for example "[1-5; 11]" +- Series of consecutive number are replaced with ranges: for example "[1-5; 11]" ### Order of the citation groups (`globalOrder`) @@ -220,19 +220,18 @@ citation groups](order-of-appearance.md). should precede that of "Smith200b". To achieve this, the sources get the letters according the order of their first appearance. - - This seems to contradict the statement "The bibliography is - sorted in (author, year, title) order" above. - It does not. As of JabRef 5.3 both are true. - Consequence: in the references - Smith2000b may precede Smith2000a. - ([reported](https://github.com/JabRef/jabref/issues/7805)) + - This seems to contradict the statement "The bibliography is + sorted in (author, year, title) order" above. + It does not. As of JabRef 5.3 both are true. + Consequence: in the references + Smith2000b may precede Smith2000a. + ([reported](https://github.com/JabRef/jabref/issues/7805)) - Some author-year citation styles prescribe a higher threshold on the number of authors for switching to "FirstAuthor et al." form (`jstyle:MaxAuthors`) at the first citation of a source (`jstyle:MaxAuthorsFirst`) - # What is stored in a document (JabRef5.2) - Each group of citations has a reference mark. @@ -279,7 +278,7 @@ citation groups](order-of-appearance.md). # How does it interact with the document? -- "stateless" +- "stateless" JabRef is only loosely coupled to the document. Between two GUI actions it does not receive any information from LibreOffice. It cannot distinguish between the user changing a single character in the document or rewriting everything. @@ -296,7 +295,3 @@ citation groups](order-of-appearance.md). - citation markers: the content of the reference mark - bibliography: the content of the Section (in LibreOffice sense) named `"JR_bib"`. - - - - diff --git a/docs/openoffice/problems.md b/docs/openoffice/problems.md index 0492c041e4e..c23b39a7d25 100644 --- a/docs/openoffice/problems.md +++ b/docs/openoffice/problems.md @@ -40,7 +40,7 @@ Reference marks have some features that make it easy to mess up citations in a d (`LO:[key:Ctrl-F8]`, `LO:[View]/[Field shadings]` helps) - They are **not atomic**: - - the user can edit the content. This will be lost on `[click:Update]` + - the user can edit the content. This will be lost on `[click:Update]` If an `As character` or `To character` anchor is inserted, the corresponding frame or footnote is deleted. - by pressing Enter within, the user can break a reference mark into two parts. The second part is now outside the reference mark: `[click:Update]` will leave it as is, and replace the first part @@ -95,5 +95,3 @@ with a single click. to "suspend some notifications to the controllers which are used for display updates." - `(change)` Now we are using this facility. - - From fe5a4bc181fcffc54884f97f15d7a65eea0915af Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 7 Jul 2021 20:17:54 +0200 Subject: [PATCH 0997/1068] in response to review https://github.com/JabRef/jabref/pull/7788#pullrequestreview-698494039 - more use of StringUtil.isNullOrEmpty - private final XTextRangeCompare cmp; - List partition = partitions.computeIfAbsent(partitionKey, _key -> new ArrayList<>()); - visualSort does not throw WrappedTargetException, NoDocumentException - set renamed to comparableMarks --- .../model/openoffice/ootext/OOFormat.java | 4 +-- .../model/openoffice/ootext/OOText.java | 5 ++- .../model/openoffice/ootext/OOTextIntoOO.java | 9 ++--- .../model/openoffice/rangesort/RangeSort.java | 36 +++++++++++-------- .../openoffice/rangesort/RangeSortVisual.java | 25 ++++--------- 5 files changed, 36 insertions(+), 43 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java index 4bfba9e5baf..f502922f818 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java @@ -73,8 +73,8 @@ public static OOText paragraph(OOText ootext) { /** * Format an OO cross-reference showing the target's page number as label to a reference mark. */ - public static OOText formatReferenceToPageNumberOfReferenceMark(String referencMarkName) { - String string = String.format("", referencMarkName); + public static OOText formatReferenceToPageNumberOfReferenceMark(String referenceMarkName) { + String string = String.format("", referenceMarkName); return OOText.fromString(string); } } diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java index ad0b9fb448d..f5142e8dc2e 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java @@ -17,7 +17,7 @@ private OOText(String data) { this.data = data; } - /* null input is passed through */ + /** @return null for null input, otherwise the argument wrapped into a new OOText */ public static OOText fromString(String string) { if (string == null) { return null; @@ -25,7 +25,7 @@ public static OOText fromString(String string) { return new OOText(string); } - /* null input is passed through */ + /** @return null for null input, otherwise the string inside the argument */ public static String toString(OOText ootext) { if (ootext == null) { return null; @@ -38,7 +38,6 @@ public String toString() { return data; } - /* Object.equals */ @Override public boolean equals(Object object) { diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index 0758d515446..caa78f07d2c 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -17,6 +17,7 @@ import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoCrossRef; import org.jabref.model.openoffice.util.OOPair; +import org.jabref.model.strings.StringUtil; import com.sun.star.awt.FontSlant; import com.sun.star.awt.FontStrikeout; @@ -181,7 +182,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) String endTagName = m.group(1); String startTagName = m.group(2); String attributeListPart = m.group(3); - boolean isStartTag = (endTagName == null) || "".equals(endTagName); + boolean isStartTag = StringUtil.isNullOrEmpty(endTagName); String tagName = isStartTag ? startTagName : endTagName; Objects.requireNonNull(tagName); @@ -231,7 +232,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) switch (key) { case "oo:ParaStyleName": //

- if (value != null && !value.equals("")) { + if (!StringUtil.isNullOrEmpty(value)) { if (setParagraphStyle(cursor, value)) { // Presumably tested already: LOGGER.debug(String.format("oo:ParaStyleName=\"%s\" failed", value)); @@ -689,7 +690,7 @@ private static List> setCharStrikeout(short value) { // CharStyleName private static List> setCharStyleName(String value) { List> settings = new ArrayList<>(); - if (value != null && value != "") { + if (!StringUtil.isNullOrEmpty(value)) { settings.add(new OOPair<>(CHAR_STYLE_NAME, value)); } else { LOGGER.warn("setCharStyleName: received null or empty value"); @@ -708,7 +709,7 @@ private static List> setCharLocale(Locale value) { * Locale from string encoding: language, language-country or language-country-variant */ private static List> setCharLocale(String value) { - if (value == null || "".equals(value)) { + if (StringUtil.isNullOrEmpty(value)) { throw new java.lang.IllegalArgumentException("setCharLocale \"\" or null"); } String[] parts = value.split("-"); diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java index 1b4fc327598..d5024d6d8e2 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -12,21 +12,29 @@ import com.sun.star.text.XText; import com.sun.star.text.XTextRangeCompare; +/** + * RangeSort provides sorting based on XTextRangeCompare, which only provides comparison + * between XTextRange values within the same XText. + */ public class RangeSort { - /* - * Sort within a partition + /** + * Compare two RangeHolders (using RangeHolder.getRange()) within an XText. + * + * Note: since we only look at the ranges, this comparison is generally not consistent with + * `equals` on the RangeHolders. Probably should not be used for key comparison in + * TreeMap<RangeHolder> or Set<RangeHolder> + * */ - public static class HolderComparatorWithinPartition implements Comparator { - XTextRangeCompare cmp; + private final XTextRangeCompare cmp; HolderComparatorWithinPartition(XText text) { cmp = UnoCast.cast(XTextRangeCompare.class, text).get(); } - /* + /** * Assumes a and b belong to the same XText as cmp. */ @Override @@ -35,7 +43,7 @@ public int compare(RangeHolder a, RangeHolder b) { } } - /* + /** * Sort a list of RangeHolder values known to share the same getText(). * * Note: RangeHolder.getRange() is called many times. @@ -48,10 +56,9 @@ public static void sortWithinPartition(List rangeHold rangeHolders.sort(new HolderComparatorWithinPartition(text)); } - /* - * Partitioning + /** + * Represent a partitioning of RangeHolders by XText */ - public static class RangePartitions { private final Map> partitions; @@ -61,11 +68,7 @@ public RangePartitions() { public void add(V holder) { XText partitionKey = holder.getRange().getText(); - List partition = partitions.get(partitionKey); - if (partition == null) { - partition = new ArrayList<>(); - partitions.put(partitionKey, partition); - } + List partition = partitions.computeIfAbsent(partitionKey, _key -> new ArrayList<>()); partition.add(holder); } @@ -74,6 +77,9 @@ public List> getPartitions() { } } + /** + * Partition RangeHolders by the corresponding XText. + */ public static RangePartitions partitionRanges(List holders) { RangePartitions result = new RangePartitions<>(); for (V holder : holders) { @@ -82,7 +88,7 @@ public static RangePartitions partitionRanges(List return result; } - /* + /** * Note: RangeHolder.getRange() is called many times. */ public static RangePartitions partitionAndSortRanges(List holders) { diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index e971e7ea67c..1f39427cf43 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -4,11 +4,9 @@ import java.util.Collections; import java.util.List; -import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.uno.UnoScreenRefresh; import com.sun.star.awt.Point; -import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextViewCursor; @@ -38,10 +36,7 @@ public class RangeSortVisual { */ public static List> visualSort(List> inputs, XTextDocument doc, - FunctionalTextViewCursor fcursor) - throws - WrappedTargetException, - NoDocumentException { + FunctionalTextViewCursor fcursor) { final int inputSize = inputs.size(); @@ -60,27 +55,19 @@ public static List> visualSort(List> input } fcursor.restore(doc); - if (positions.size() != inputSize) { - throw new IllegalStateException("visualSort: positions.size() != inputSize"); - } - // order by position - ArrayList>> set = new ArrayList<>(inputSize); + ArrayList>> comparableMarks = new ArrayList<>(inputSize); for (int i = 0; i < inputSize; i++) { RangeSortable input = inputs.get(i); - set.add(new ComparableMark<>(positions.get(i), + comparableMarks.add(new ComparableMark<>(positions.get(i), input.getIndexInPosition(), input)); } - Collections.sort(set, RangeSortVisual::compareTopToBottomLeftToRight); - - if (set.size() != inputSize) { - throw new IllegalStateException("visualSort: set.size() != inputSize"); - } + Collections.sort(comparableMarks, RangeSortVisual::compareTopToBottomLeftToRight); // collect ordered result - List> result = new ArrayList<>(set.size()); - for (ComparableMark> mark : set) { + List> result = new ArrayList<>(comparableMarks.size()); + for (ComparableMark> mark : comparableMarks) { result.add(mark.getContent()); } From f14e5f38ed57339652b7d0807bc240df2580bdf9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 12:02:17 +0200 Subject: [PATCH 0998/1068] use {@code } to avoid < > --- .../model/openoffice/ootext/OOTextIntoOO.java | 16 ++++++++-------- .../model/openoffice/rangesort/RangeSort.java | 2 +- .../model/openoffice/uno/UnoTextRange.java | 4 ++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index caa78f07d2c..23aaff669fb 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -112,29 +112,29 @@ private OOTextIntoOO() { * * - new tags: * - * - <span lang="zxx"> + * - {@code } * - earlier was applied from code * - * - <span oo:CharStyleName="CharStylename"> + * - {@code } * - earlier was applied from code, for "CitationCharacterFormat" * - * - <p> start new paragraph + * - {@code

} start new paragraph * - earlier was applied from code * - * - <p oo:ParaStyleName="ParStyleName"> : start new paragraph and apply ParStyleName + * - {@code

} : start new paragraph and apply ParStyleName * - earlier was applied from code * - * - <tt> + * - {@code } * - earlier: known, but ignored - * - now: equivalent to <span oo:CharStyleName="Example"> - * - <oo:referenceToPageNumberOfReferenceMark> (self-closing) + * - now: equivalent to {@code } + * - {@code } (self-closing) * * - closing tags try to properly restore state (in particular, the "not directly set" state) * instead of dictating an "off" state. This makes a difference when the value inherited from * another level (for example the paragraph) is not the "off" state. * * An example: a style with - * ReferenceParagraphFormat="JR_bibentry" + * {@code ReferenceParagraphFormat="JR_bibentry"} * Assume JR_bibentry in LibreOffice is a paragraph style that prescribes "bold" font. * LAYOUT only prescribes bold around year. * Which parts of the bibliography entries should come out as bold? diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java index d5024d6d8e2..bb39970f4ee 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -23,7 +23,7 @@ public class RangeSort { * * Note: since we only look at the ranges, this comparison is generally not consistent with * `equals` on the RangeHolders. Probably should not be used for key comparison in - * TreeMap<RangeHolder> or Set<RangeHolder> + * {@code TreeMap} or {@code Set} * */ public static class HolderComparatorWithinPartition implements Comparator { diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java index 56cb1498e2a..bcd8c1c9ddc 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java @@ -38,7 +38,7 @@ public static boolean comparables(XTextRange a, XTextRange b) { /** * @return follows java conventions * - * 1 if (a > b); (-1) if (a < b) + * 1 if {@code (a > b)}; (-1) if {@code (a < b)} */ public static int compareStartsUnsafe(XTextRangeCompare compare, XTextRange a, XTextRange b) { return (-1) * compare.compareRegionStarts(a, b); @@ -55,7 +55,7 @@ public static int compareStarts(XTextRange a, XTextRange b) { /** * @return follows java conventions * - * 1 if (a > b); (-1) if (a < b) + * 1 if {@code (a > b)}; (-1) if {@code (a < b)} */ public static int compareEnds(XTextRange a, XTextRange b) { if (!comparables(a, b)) { From 16034edc033f35d68e98788adfa4a26a5942029b Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 12:03:26 +0200 Subject: [PATCH 0999/1068] make HolderComparatorWithinPartition private --- .../java/org/jabref/model/openoffice/rangesort/RangeSort.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java index bb39970f4ee..ce5a88fe45e 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -26,7 +26,7 @@ public class RangeSort { * {@code TreeMap} or {@code Set} * */ - public static class HolderComparatorWithinPartition implements Comparator { + private static class HolderComparatorWithinPartition implements Comparator { private final XTextRangeCompare cmp; From 9e8d5b5e5c4b5591d2713e11f8948126fa98f0a7 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 13:25:15 +0200 Subject: [PATCH 1000/1068] throw explicitly --- .../java/org/jabref/model/openoffice/rangesort/RangeSort.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java index ce5a88fe45e..79c28439521 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -31,7 +31,8 @@ private static class HolderComparatorWithinPartition implements Comparator Date: Fri, 9 Jul 2021 13:26:14 +0200 Subject: [PATCH 1001/1068] use List.sort --- .../org/jabref/model/openoffice/rangesort/RangeSortVisual.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index 1f39427cf43..9a9d763ec6a 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -1,7 +1,6 @@ package org.jabref.model.openoffice.rangesort; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import org.jabref.model.openoffice.uno.UnoScreenRefresh; @@ -63,7 +62,7 @@ public static List> visualSort(List> input input.getIndexInPosition(), input)); } - Collections.sort(comparableMarks, RangeSortVisual::compareTopToBottomLeftToRight); + comparableMarks.sort(RangeSortVisual::compareTopToBottomLeftToRight); // collect ordered result List> result = new ArrayList<>(comparableMarks.size()); From 12c4538a1f5eb67aa7f9c8375d8f42ae2113f1df Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 13:26:40 +0200 Subject: [PATCH 1002/1068] format --- .../org/jabref/model/openoffice/rangesort/RangeSortVisual.java | 2 +- src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index 9a9d763ec6a..c9699632fd5 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -110,7 +110,7 @@ private static int compareTopToBottomLeftToRight(ComparableMark a, ComparableMar } return a.indexInPosition - b.indexInPosition; } - + /** * A reference mark name paired with its visual position. * diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java index bcd8c1c9ddc..c58ca96207f 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java @@ -65,7 +65,7 @@ public static int compareEnds(XTextRange a, XTextRange b) { 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) { From a6ff50a63f4d077f0231563c72defc763345366d Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 14:03:28 +0200 Subject: [PATCH 1003/1068] avoid raw generics --- .../org/jabref/model/openoffice/rangesort/RangeSortVisual.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index c9699632fd5..b3aea50a9b7 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -100,7 +100,7 @@ private static Point findPositionOfTextRange(XTextRange range, XTextViewCursor c return cursor.getPosition(); } - private static int compareTopToBottomLeftToRight(ComparableMark a, ComparableMark b) { + private static int compareTopToBottomLeftToRight(ComparableMark a, ComparableMark b) { if (a.position.Y != b.position.Y) { return a.position.Y - b.position.Y; From 591c31b7b26548f1935af282aa84798491388a49 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 14:03:43 +0200 Subject: [PATCH 1004/1068] add pmd rule to Makefile --- Makefile | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Makefile b/Makefile index c18197073c3..cb08c4bfa8f 100644 --- a/Makefile +++ b/Makefile @@ -85,3 +85,8 @@ checkstyle: ./gradlew checkstyleMain 2>&1 | sed -e 's|[[]ant[:]checkstyle] [[]ERROR] ||g' ./gradlew checkstyletest 2>&1 | sed -e 's|[[]ant[:]checkstyle] [[]ERROR] ||g' # + +pmd: + pmd -d src/main/java/org/jabref/model/openoffice + pmd -d src/main/java/org/jabref/logic/openoffice + pmd -d src/main/java/org/jabref/gui/openoffice From 04883ee163c1e3a6649c6f46f6f47d6fa404284a Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 17:51:17 +0200 Subject: [PATCH 1005/1068] PMD on TimeLap --- .../model/openoffice/notforproduction/TimeLap.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java b/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java index 8c927fe9e0a..53a1fc873d7 100644 --- a/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java +++ b/src/main/java/org/jabref/model/openoffice/notforproduction/TimeLap.java @@ -3,7 +3,11 @@ /* * Measure execution time. */ -public class TimeLap { +public final class TimeLap { + + private TimeLap() { + /**/ + } /* * Usage: @@ -19,10 +23,11 @@ public static long start() { } // return time (nanoSeconds) for next timing + @SuppressWarnings("PMD.SystemPrintln") public static long now(String label, long startTime) { long endTime = System.nanoTime(); long duration = (endTime - startTime); // divide by 1000000 to get milliseconds. - System.out.printf("%-40s: %10.3f ms\n", label, duration / 1000000.0); + System.out.printf("%-40s: %10.3f ms\n", label, duration / 1_000_000.0); return endTime; } } From ad8f57621c3524941a2cbda106856a60be735568 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 17:53:05 +0200 Subject: [PATCH 1006/1068] PMD on model/backend --- .../model/openoffice/backend/NamedRange.java | 12 ++++++------ .../openoffice/backend/NamedRangeManager.java | 14 +++++++------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java b/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java index d8e1832b6ef..5cdc15c2e08 100644 --- a/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java +++ b/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java @@ -13,12 +13,12 @@ public interface NamedRange { - public String nrGetRangeName(); + String nrGetRangeName(); /** * @return Optional.empty if the mark is missing from the document. */ - public Optional nrGetMarkRange(XTextDocument doc) + Optional nrGetMarkRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException; @@ -27,7 +27,7 @@ public Optional nrGetMarkRange(XTextDocument doc) * Cursor for the reference marks as is, not prepared for filling, but does not need * nrCleanFillCursor either. */ - public Optional nrGetRawCursor(XTextDocument doc) + Optional nrGetRawCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException; @@ -37,7 +37,7 @@ public Optional nrGetRawCursor(XTextDocument doc) * * Must be followed by nrCleanFillCursor() */ - public XTextCursor nrGetFillCursor(XTextDocument doc) + XTextCursor nrGetFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, @@ -48,7 +48,7 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) * single characer, leave the left bracket. * */ - public void nrCleanFillCursor(XTextDocument doc) + void nrCleanFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, @@ -57,7 +57,7 @@ public void nrCleanFillCursor(XTextDocument doc) /** * Note: create is in NamedRangeManager */ - public void nrRemoveFromDocument(XTextDocument doc) + void nrRemoveFromDocument(XTextDocument doc) throws WrappedTargetException, NoDocumentException, diff --git a/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java b/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java index f53fcc72527..536871b5c34 100644 --- a/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java +++ b/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java @@ -12,19 +12,19 @@ public interface NamedRangeManager { - public NamedRange nrmCreate(XTextDocument doc, - String markName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) + NamedRange nrmCreate(XTextDocument doc, + String markName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException; - public List nrmGetUsedNames(XTextDocument doc) + List nrmGetUsedNames(XTextDocument doc) throws NoDocumentException; - public Optional nrmGetFromDocument(XTextDocument doc, String markName) + Optional nrmGetFromDocument(XTextDocument doc, String markName) throws NoDocumentException, WrappedTargetException; From 0b60594e28d778d3ef4dc7d566d6ab9b571b3325 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 17:54:04 +0200 Subject: [PATCH 1007/1068] PMD on model/ootext --- .../model/openoffice/ootext/OOFormat.java | 4 ++ .../model/openoffice/ootext/OOText.java | 4 +- .../model/openoffice/ootext/OOTextIntoOO.java | 65 ++++++++++--------- 3 files changed, 39 insertions(+), 34 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java index f502922f818..6b4a96de644 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOFormat.java @@ -11,6 +11,10 @@ */ public class OOFormat { + private OOFormat() { + /* */ + } + /** * Mark {@code ootext} as using a character locale known to OO. * diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java index f5142e8dc2e..5b5fa4caba9 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOText.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOText.java @@ -49,9 +49,9 @@ public boolean equals(Object object) { return false; } - OOText c = (OOText) object; + OOText other = (OOText) object; - return data.equals(c.data); + return data.equals(other.data); } @Override diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index 23aaff669fb..e4764ca2fbe 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -168,20 +168,19 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) // We need to extract formatting. Use a simple regexp search iteration: int piv = 0; - Matcher m = HTML_TAG.matcher(lText); - while (m.find()) { + Matcher tagMatcher = HTML_TAG.matcher(lText); + while (tagMatcher.find()) { - String currentSubstring = lText.substring(piv, m.start()); + String currentSubstring = lText.substring(piv, tagMatcher.start()); if (!currentSubstring.isEmpty()) { cursor.setString(currentSubstring); } formatStack.apply(cursor); cursor.collapseToEnd(); - String fullTag = m.group(); - String endTagName = m.group(1); - String startTagName = m.group(2); - String attributeListPart = m.group(3); + String endTagName = tagMatcher.group(1); + String startTagName = tagMatcher.group(2); + String attributeListPart = tagMatcher.group(3); boolean isStartTag = StringUtil.isNullOrEmpty(endTagName); String tagName = isStartTag ? startTagName : endTagName; Objects.requireNonNull(tagName); @@ -232,13 +231,13 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) switch (key) { case "oo:ParaStyleName": //

- if (!StringUtil.isNullOrEmpty(value)) { + if (StringUtil.isNullOrEmpty(value)) { + LOGGER.debug(String.format("oo:ParaStyleName inherited")); + } else { if (setParagraphStyle(cursor, value)) { // Presumably tested already: LOGGER.debug(String.format("oo:ParaStyleName=\"%s\" failed", value)); } - } else { - LOGGER.debug(String.format("oo:ParaStyleName inherited")); } break; default: @@ -283,7 +282,7 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) break; case "style": // HTML-style small-caps - if (value.equals("font-variant: small-caps")) { + if ("font-variant: small-caps".equals(value)) { settings.addAll(setCharCaseMap(CaseMap.SMALLCAPS)); break; } @@ -317,9 +316,12 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) currentSubstring)); } break; + default: + LOGGER.warn(String.format("ignoring unknown tag '<%s>'", tagName)); + break; } - piv = m.end(); + piv = tagMatcher.end(); } if (piv < lText.length()) { @@ -396,7 +398,7 @@ public static void removeDirectFormatting(XTextCursor cursor) { continue; } } catch (UnknownPropertyException ex) { - throw new java.lang.IllegalStateException("Unexpected UnknownPropertyException"); + throw new IllegalStateException("Unexpected UnknownPropertyException", ex); } if (knownToFail.contains(p.Name)) { continue; @@ -511,11 +513,11 @@ static class MyPropertyStack { * Get the initial state of the properties and add the first layer. */ XMultiPropertyStates mpss = UnoCast.cast(XMultiPropertyStates.class, cursor).get(); - PropertyState[] propertyStates = null; + PropertyState[] propertyStates; try { propertyStates = mpss.getPropertyStates(goodNames); } catch (UnknownPropertyException ex) { - throw new java.lang.IllegalStateException("Caught unexpected UnknownPropertyException"); + throw new IllegalStateException("Caught unexpected UnknownPropertyException", ex); } XMultiPropertySet mps = UnoCast.cast(XMultiPropertySet.class, cursor).get(); @@ -546,13 +548,13 @@ void pushLayer(List> settings) { ArrayList> newLayer = new ArrayList<>(oldLayer); for (OOPair pair : settings) { String name = pair.a; - Integer i = goodNameToIndex.get(name); - if (i == null) { + Integer index = goodNameToIndex.get(name); + if (index == null) { LOGGER.warn(String.format("pushLayer: '%s' is not in goodNameToIndex", name)); continue; } Object newValue = pair.b; - newLayer.set(i, Optional.ofNullable(newValue)); + newLayer.set(index, Optional.ofNullable(newValue)); } layers.push(newLayer); } @@ -592,8 +594,8 @@ void apply(XTextCursor cursor) { } } // namesArray must be alphabetically sorted. - String[] namesArray = names.toArray(new String[names.size()]); - String[] delNamesArray = delNames.toArray(new String[delNames.size()]); + String[] namesArray = names.toArray(new String[0]); + String[] delNamesArray = delNames.toArray(new String[0]); mpss.setPropertiesToDefault(delNamesArray); mps.setPropertyValues(namesArray, values.toArray()); } catch (UnknownPropertyException ex) { @@ -608,10 +610,9 @@ void apply(XTextCursor cursor) { // Relative CharEscapement needs to know current values. Optional getPropertyValue(String name) { if (goodNameToIndex.containsKey(name)) { - int i = goodNameToIndex.get(name); + int index = goodNameToIndex.get(name); ArrayList> topLayer = layers.peek(); - Optional value = topLayer.get(i); - return value; + return topLayer.get(index); } return Optional.empty(); } @@ -620,15 +621,15 @@ Optional getPropertyValue(String name) { /** * Parse HTML-like attributes to a list of (name,value) pairs. */ - private static List> parseAttributes(String s) { + private static List> parseAttributes(String attributes) { List> res = new ArrayList<>(); - if (s == null) { + if (attributes == null) { return res; } - Matcher m = ATTRIBUTE_PATTERN.matcher(s); - while (m.find()) { - String key = m.group(1); - String value = m.group(2); + Matcher attributeMatcher = ATTRIBUTE_PATTERN.matcher(attributes); + while (attributeMatcher.find()) { + String key = attributeMatcher.group(1); + String value = attributeMatcher.group(2); res.add(new OOPair(key, value)); } return res; @@ -690,10 +691,10 @@ private static List> setCharStrikeout(short value) { // CharStyleName private static List> setCharStyleName(String value) { List> settings = new ArrayList<>(); - if (!StringUtil.isNullOrEmpty(value)) { - settings.add(new OOPair<>(CHAR_STYLE_NAME, value)); - } else { + if (StringUtil.isNullOrEmpty(value)) { LOGGER.warn("setCharStyleName: received null or empty value"); + } else { + settings.add(new OOPair<>(CHAR_STYLE_NAME, value)); } return settings; } From 53dba252fa689af9a0eceaa8f6023d098661ec4e Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 17:56:15 +0200 Subject: [PATCH 1008/1068] PMD on model/rangesort --- .../model/openoffice/rangesort/RangeOverlapBetween.java | 2 +- .../model/openoffice/rangesort/RangeOverlapWithin.java | 6 ++---- .../org/jabref/model/openoffice/rangesort/RangeSort.java | 6 +++++- .../jabref/model/openoffice/rangesort/RangeSortEntry.java | 8 ++++---- .../model/openoffice/rangesort/RangeSortVisual.java | 8 ++++++-- .../jabref/model/openoffice/rangesort/RangeSortable.java | 6 +++--- 6 files changed, 21 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java index 9a3ef1c9968..16b7735fb7a 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapBetween.java @@ -31,7 +31,7 @@ List> findFirst(XTextDocument doc, List> result = new ArrayList<>(); - if (fewHolders.size() == 0) { + if (fewHolders.isEmpty()) { return result; } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java index e4df2d8278c..a8534b630ae 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeOverlapWithin.java @@ -39,9 +39,7 @@ List> findOverlappingRanges(XTextDocument doc, RangeSort.RangePartitions partitions = RangeSort.partitionAndSortRanges(rangeHolders); - List> overlaps = findOverlappingRanges(partitions, reportAtMost, includeTouching); - - return overlaps; + return findOverlappingRanges(partitions, reportAtMost, includeTouching); } /** @@ -64,7 +62,7 @@ List> findOverlappingRanges(RangeSort.RangePartitions input, List> result = new ArrayList<>(); for (List partition : input.getPartitions()) { - if (partition.size() == 0) { + if (partition.isEmpty()) { continue; } XTextRangeCompare cmp = UnoCast.cast(XTextRangeCompare.class, diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java index 79c28439521..99ace5154e1 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSort.java @@ -18,6 +18,10 @@ */ public class RangeSort { + private RangeSort() { + /**/ + } + /** * Compare two RangeHolders (using RangeHolder.getRange()) within an XText. * @@ -69,7 +73,7 @@ public RangePartitions() { public void add(V holder) { XText partitionKey = holder.getRange().getText(); - List partition = partitions.computeIfAbsent(partitionKey, _key -> new ArrayList<>()); + List partition = partitions.computeIfAbsent(partitionKey, unused -> new ArrayList<>()); partition.add(holder); } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java index 4ed651e5396..0ed686ee901 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortEntry.java @@ -32,11 +32,11 @@ public T getContent() { return content; } - public void setRange(XTextRange r) { - range = r; + public void setRange(XTextRange range) { + this.range = range; } - public void setIndexInPosition(int i) { - indexInPosition = i; + public void setIndexInPosition(int indexInPosition) { + this.indexInPosition = indexInPosition; } } diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java index b3aea50a9b7..e412f4ade6c 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortVisual.java @@ -26,6 +26,10 @@ public class RangeSortVisual { private static final Logger LOGGER = LoggerFactory.getLogger(RangeSortVisual.class); + private RangeSortVisual() { + /**/ + } + /** * Sort the input {@code inputs} visually. * @@ -37,8 +41,6 @@ public static List> visualSort(List> input XTextDocument doc, FunctionalTextViewCursor fcursor) { - final int inputSize = inputs.size(); - if (UnoScreenRefresh.hasControllersLocked(doc)) { final String msg = "visualSort: with ControllersLocked, viewCursor.gotoRange is probably useless"; LOGGER.warn(msg); @@ -47,6 +49,8 @@ public static List> visualSort(List> input XTextViewCursor viewCursor = fcursor.getViewCursor(); + final int inputSize = inputs.size(); + // find coordinates List positions = new ArrayList<>(inputSize); for (RangeSortable v : inputs) { diff --git a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java index c3eab225889..59a4c3fa9af 100644 --- a/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java +++ b/src/main/java/org/jabref/model/openoffice/rangesort/RangeSortable.java @@ -11,12 +11,12 @@ public interface RangeSortable extends RangeHolder { * * For citation marks in footnotes this may be the range of the footnote mark. */ - public XTextRange getRange(); + XTextRange getRange(); /** * For citation marks in footnotes this may provide order within the footnote. */ - public int getIndexInPosition(); + int getIndexInPosition(); - public T getContent(); + T getContent(); } From 2354dae67bce313ff43e0540590c6d9fc7c34237 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 17:59:09 +0200 Subject: [PATCH 1009/1068] PMD on model/style --- .../model/openoffice/style/Citation.java | 30 +++++----- .../model/openoffice/style/CitationGroup.java | 4 +- .../openoffice/style/CitationGroups.java | 59 +++++++++---------- .../style/CitationLookupResult.java | 8 +-- .../model/openoffice/style/CitedKey.java | 8 +-- .../openoffice/style/ComparableCitation.java | 2 +- .../openoffice/style/ComparableCitedKey.java | 4 +- .../openoffice/style/CompareCitedKey.java | 6 +- .../model/openoffice/style/OODataModel.java | 4 +- .../model/openoffice/style/PageInfo.java | 11 ++-- 10 files changed, 67 insertions(+), 69 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/style/Citation.java b/src/main/java/org/jabref/model/openoffice/style/Citation.java index 3f949237e07..9b71a1051b2 100644 --- a/src/main/java/org/jabref/model/openoffice/style/Citation.java +++ b/src/main/java/org/jabref/model/openoffice/style/Citation.java @@ -93,8 +93,8 @@ public Optional getNumber() { return number; } - public void setNumber(Optional n) { - number = n; + public void setNumber(Optional number) { + this.number = number; } public int getNumberOrThrow() { @@ -109,12 +109,12 @@ public void setUniqueLetter(Optional uniqueLetter) { this.uniqueLetter = uniqueLetter; } - public void setPageInfo(Optional v) { - Optional vv = PageInfo.normalizePageInfo(v); - if (!vv.equals(v)) { + public void setPageInfo(Optional pageInfo) { + Optional normalizedPageInfo = PageInfo.normalizePageInfo(pageInfo); + if (!normalizedPageInfo.equals(pageInfo)) { throw new IllegalArgumentException("setPageInfo argument is not normalized"); } - this.pageInfo = vv; + this.pageInfo = normalizedPageInfo; } public void setIsFirstAppearanceOfSource(boolean value) { @@ -124,19 +124,19 @@ public void setIsFirstAppearanceOfSource(boolean value) { /* * Setters for CitationGroups.distribute() */ - public static void setLookupResult(OOPair> x) { - Citation cit = x.a; - cit.db = x.b; + public static void setLookupResult(OOPair> pair) { + Citation cit = pair.a; + cit.db = pair.b; } - public static void setNumber(OOPair> x) { - Citation cit = x.a; - cit.number = x.b; + public static void setNumber(OOPair> pair) { + Citation cit = pair.a; + cit.number = pair.b; } - public static void setUniqueLetter(OOPair> x) { - Citation cit = x.a; - cit.uniqueLetter = x.b; + public static void setUniqueLetter(OOPair> pair) { + Citation cit = pair.a; + cit.uniqueLetter = pair.b; } } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java index 2986a6f4501..3b9021eb73f 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java @@ -121,8 +121,8 @@ public List getCitationsInLocalOrder() { * indexInGlobalOrder */ - public void setIndexInGlobalOrder(Optional i) { - this.indexInGlobalOrder = i; + public void setIndexInGlobalOrder(Optional indexInGlobalOrder) { + this.indexInGlobalOrder = indexInGlobalOrder; } public Optional getIndexInGlobalOrder() { diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index bd0cca64e13..0bfe4a832d0 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -79,29 +79,28 @@ public void lookupCitations(List databases) { /* * It is not clear which of the two solutions below is better. */ - if (true) { - // 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); - } else { - // 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 cg : getCitationGroupsUnordered()) { - for (Citation cit : cg.citationsInStorageOrder) { - cit.lookupInDatabases(databases); - } - } - } + + // (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 cg : getCitationGroupsUnordered()) { + /// for (Citation cit : cg.citationsInStorageOrder) { + /// cit.lookupInDatabases(databases); + /// } + /// } } public List getCitationGroupsUnordered() { @@ -162,11 +161,11 @@ public CitedKeys getCitedKeysUnordered() { int storageIndexInGroup = 0; for (Citation cit : cg.citationsInStorageOrder) { String key = cit.citationKey; - CitationPath p = new CitationPath(cg.cgid, storageIndexInGroup); + CitationPath path = new CitationPath(cg.cgid, storageIndexInGroup); if (res.containsKey(key)) { - res.get(key).addPath(p, cit); + res.get(key).addPath(path, cit); } else { - res.put(key, new CitedKey(key, p, cit)); + res.put(key, new CitedKey(key, path, cit)); } storageIndexInGroup++; } @@ -178,19 +177,19 @@ public CitedKeys getCitedKeysUnordered() { * CitedKeys created iterating citations in (globalOrder,localOrder) */ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { - LinkedHashMap res = new LinkedHashMap<>(); if (!hasGlobalOrder()) { throw new IllegalStateException("getSortedCitedKeys: no globalOrder"); } + LinkedHashMap res = new LinkedHashMap<>(); for (CitationGroup cg : getCitationGroupsInGlobalOrder()) { for (int i : cg.getLocalOrder()) { Citation cit = cg.citationsInStorageOrder.get(i); String citationKey = cit.citationKey; - CitationPath p = new CitationPath(cg.cgid, i); + CitationPath path = new CitationPath(cg.cgid, i); if (res.containsKey(citationKey)) { - res.get(citationKey).addPath(p, cit); + res.get(citationKey).addPath(path, cit); } else { - res.put(citationKey, new CitedKey(citationKey, p, cit)); + res.put(citationKey, new CitedKey(citationKey, path, cit)); } } } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java b/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java index b17ec100ee2..86674583d1c 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java @@ -26,14 +26,14 @@ public CitationLookupResult(BibEntry entry, BibDatabase database) { * Since within each GUI call we use a fixed list of databases, it is OK. */ @Override - public boolean equals(Object o) { - if (o == this) { + public boolean equals(Object otherObject) { + if (otherObject == this) { return true; } - if (!(o instanceof CitationLookupResult)) { + if (!(otherObject instanceof CitationLookupResult)) { return false; } - CitationLookupResult that = (CitationLookupResult) o; + CitationLookupResult that = (CitationLookupResult) otherObject; return this.entry.equals(that.entry) && this.database.equals(that.database); } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitedKey.java b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java index f577867c539..785d828ce7e 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java @@ -27,11 +27,11 @@ public class CitedKey implements private Optional uniqueLetter; // For AuthorYear citation styles. private Optional normCitMarker; // For AuthorYear citation styles. - CitedKey(String citationKey, CitationPath p, Citation cit) { + CitedKey(String citationKey, CitationPath path, Citation cit) { this.citationKey = citationKey; this.where = new ArrayList<>(); // remember order - this.where.add(p); + this.where.add(path); // synchronized with Citation this.db = cit.getLookupResult(); @@ -100,8 +100,8 @@ public void setNormalizedCitationMarker(Optional normCitMarker) { /** * Appends to end of {@code where} */ - void addPath(CitationPath p, Citation cit) { - this.where.add(p); + void addPath(CitationPath path, Citation cit) { + this.where.add(path); // Check consistency if (!cit.getLookupResult().equals(this.db)) { diff --git a/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java b/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java index a6ac799b017..81120c09b2a 100644 --- a/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java +++ b/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java @@ -9,5 +9,5 @@ * Otherwise we sort citations as cited keys. */ public interface ComparableCitation extends ComparableCitedKey { - public Optional getPageInfo(); + Optional getPageInfo(); } diff --git a/src/main/java/org/jabref/model/openoffice/style/ComparableCitedKey.java b/src/main/java/org/jabref/model/openoffice/style/ComparableCitedKey.java index 0d4c8e2efce..23b3ffaba78 100644 --- a/src/main/java/org/jabref/model/openoffice/style/ComparableCitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/ComparableCitedKey.java @@ -9,8 +9,8 @@ */ public interface ComparableCitedKey { - public String getCitationKey(); + String getCitationKey(); - public Optional getBibEntry(); + Optional getBibEntry(); } diff --git a/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java b/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java index a5484560316..7f6d3adfab0 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java @@ -24,18 +24,16 @@ public int compare(ComparableCitedKey a, ComparableCitedKey b) { Optional bBibEntry = b.getBibEntry(); final int mul = unresolvedComesFirst ? (+1) : (-1); - int res = 0; if (aBibEntry.isEmpty() && bBibEntry.isEmpty()) { // Both are unresolved: compare them by citation key. - res = a.getCitationKey().compareTo(b.getCitationKey()); + return a.getCitationKey().compareTo(b.getCitationKey()); } else if (aBibEntry.isEmpty()) { return -mul; } else if (bBibEntry.isEmpty()) { return mul; } else { // Proper comparison of entries - res = entryComparator.compare(aBibEntry.get(), bBibEntry.get()); + return entryComparator.compare(aBibEntry.get(), bBibEntry.get()); } - return res; } } diff --git a/src/main/java/org/jabref/model/openoffice/style/OODataModel.java b/src/main/java/org/jabref/model/openoffice/style/OODataModel.java index 20b2365ebf2..835715dfca5 100644 --- a/src/main/java/org/jabref/model/openoffice/style/OODataModel.java +++ b/src/main/java/org/jabref/model/openoffice/style/OODataModel.java @@ -26,8 +26,8 @@ public static List> fakePageInfos(String pageInfo, int nCitatio } if (pageInfo != null) { final int last = nCitations - 1; - Optional pi = Optional.ofNullable(OOText.fromString(pageInfo)); - pageInfos.set(last, PageInfo.normalizePageInfo(pi)); + Optional optionalPageInfo = Optional.ofNullable(OOText.fromString(pageInfo)); + pageInfos.set(last, PageInfo.normalizePageInfo(optionalPageInfo)); } return pageInfos; } diff --git a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java index ace7eedae02..ec3a8436dcf 100644 --- a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java +++ b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java @@ -13,15 +13,16 @@ private PageInfo() { /* * pageInfo normalization */ - public static Optional normalizePageInfo(Optional o) { - if (o == null || o.isEmpty() || "".equals(OOText.toString(o.get()))) { + public static Optional normalizePageInfo(Optional optionalText) { + if (optionalText == null || optionalText.isEmpty() || "".equals(OOText.toString(optionalText.get()))) { return Optional.empty(); } - String s = OOText.toString(o.get()); - if (s.trim().equals("")) { + String str = OOText.toString(optionalText.get()); + String trimmed = str.trim(); + if (trimmed.equals("")) { return Optional.empty(); } - return Optional.of(OOText.fromString(s.trim())); + return Optional.of(OOText.fromString(trimmed)); } /** From 3057824a368c4ca369d18d31a4b8e5ed72cf5e98 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 19:23:42 +0200 Subject: [PATCH 1010/1068] PMD on logic/action --- .../org/jabref/logic/openoffice/action/EditInsert.java | 6 +++--- .../org/jabref/logic/openoffice/action/EditMerge.java | 6 +----- .../org/jabref/logic/openoffice/action/EditSeparate.java | 4 ++++ .../org/jabref/logic/openoffice/action/ExportCited.java | 4 ++++ .../jabref/logic/openoffice/action/ManageCitations.java | 4 ++++ .../java/org/jabref/logic/openoffice/action/Update.java | 8 ++++++-- 6 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index 1345f1f2a99..2df867a8e11 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -31,12 +31,12 @@ import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class EditInsert { - private static final Logger LOGGER = LoggerFactory.getLogger(EditInsert.class); + private EditInsert() { + /**/ + } /** * In insertEntry we receive BibEntry values from the GUI. diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index 4cd225eb1a8..9f2171dd59d 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -253,11 +253,7 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR } } - if (!couldExpand) { - return false; - } - - return true; + return couldExpand; } /** diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index 0293159d34f..7a361776ff2 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -29,6 +29,10 @@ public class EditSeparate { + private EditSeparate() { + /**/ + } + public static boolean separateCitations(XTextDocument doc, OOFrontend fr, List databases, diff --git a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java index ef7985d666a..de89030e373 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java @@ -20,6 +20,10 @@ public class ExportCited { + private ExportCited() { + /**/ + } + public static class GenerateDatabaseResult { /** * null: not done; isEmpty: no unresolved diff --git a/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java b/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java index 4046cbbe11b..9e70ba78379 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java @@ -16,6 +16,10 @@ public class ManageCitations { + private ManageCitations() { + /**/ + } + public static List getCitationEntries(XTextDocument doc) throws NoDocumentException, diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index 675afb2a79f..a95f7b6e771 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -25,6 +25,10 @@ */ public class Update { + private Update() { + /**/ + } + /** * @return the list of unresolved citation keys */ @@ -64,8 +68,8 @@ private static List updateDocument(XTextDocument doc, style, alwaysAddCitedOnPages); } - List result = fr.citationGroups.getUnresolvedKeys(); - return result; + + return fr.citationGroups.getUnresolvedKeys(); } finally { if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { UnoScreenRefresh.unlockControllers(doc); From 26ccf7ef1efcf1b68bf14f4ec98530f1a0389201 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 19:27:08 +0200 Subject: [PATCH 1011/1068] PMD on logic/backend --- .../logic/openoffice/backend/Backend52.java | 37 +++++++------------ .../logic/openoffice/backend/Codec52.java | 12 ++++-- .../backend/NamedRangeReferenceMark.java | 28 +++++++------- 3 files changed, 35 insertions(+), 42 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index cf91ad1043e..1c312b197ce 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -113,25 +113,17 @@ public Optional healthReport(XTextDocument doc) private static void setPageInfoInDataInitial(List citations, Optional pageInfo) { // attribute to last citation (initially localOrder == storageOrder) - if (citations.size() > 0) { - citations.get(citations.size() - 1).setPageInfo(pageInfo); - } - } - - private static void setPageInfoInData(CitationGroup cg, Optional pageInfo) { - List citations = cg.getCitationsInLocalOrder(); - if (citations.size() > 0) { + if (!citations.isEmpty()) { citations.get(citations.size() - 1).setPageInfo(pageInfo); } } private static Optional getPageInfoFromData(CitationGroup cg) { List citations = cg.getCitationsInLocalOrder(); - if (citations.size() > 0) { - return citations.get(citations.size() - 1).getPageInfo(); - } else { + if (citations.isEmpty()) { return Optional.empty(); } + return citations.get(citations.size() - 1).getPageInfo(); } /** @@ -143,20 +135,18 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str WrappedTargetException, NoDocumentException { - Optional op = Codec52.parseMarkName(refMarkName); - if (op.isEmpty()) { + Optional optionalParsed = Codec52.parseMarkName(refMarkName); + if (optionalParsed.isEmpty()) { throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" + " found unparsable referenceMarkName"); } - Codec52.ParsedMarkName ov = op.get(); - CitationGroupId cgid = new CitationGroupId(refMarkName); - List citations = (ov.citationKeys.stream() + Codec52.ParsedMarkName parsed = optionalParsed.get(); + List citations = (parsed.citationKeys.stream() .map(Citation::new) .collect(Collectors.toList())); - Optional pageInfo = - (UnoUserDefinedProperty.getStringValue(doc, refMarkName) - .map(OOText::fromString)); + Optional pageInfo = (UnoUserDefinedProperty.getStringValue(doc, refMarkName) + .map(OOText::fromString)); pageInfo = PageInfo.normalizePageInfo(pageInfo); setPageInfoInDataInitial(citations, pageInfo); @@ -168,9 +158,10 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str + " referenceMarkName is not in the document"); } + CitationGroupId cgid = new CitationGroupId(refMarkName); CitationGroup cg = new CitationGroup(OODataModel.JabRef52, cgid, - ov.citationType, + parsed.citationType, citations, Optional.of(refMarkName)); this.cgidToNamedRange.put(cgid, namedRange.get()); @@ -238,6 +229,8 @@ public CitationGroup createCitationGroup(XTextDocument doc, case JabRef60: cit.setPageInfo(pageInfo); break; + default: + throw new IllegalStateException("Unhandled dataModel in Backend52.createCitationGroup"); } } @@ -320,7 +313,6 @@ public List> combinePageInfos(List joinableGroup private NamedRange getNamedRangeOrThrow(CitationGroup cg) { NamedRange namedRange = this.cgidToNamedRange.get(cg.cgid); if (namedRange == null) { - String msg = "getNamedRange: could not lookup namedRange"; throw new IllegalStateException("getNamedRange: could not lookup namedRange"); } return namedRange; @@ -399,8 +391,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups case JabRef52: // One context per CitationGroup: Backend52 (DataModel.JabRef52) // For DataModel.JabRef60 (Backend60) we need one context per Citation - int n = cgs.numberOfCitationGroups(); - List citations = new ArrayList<>(n); + List citations = new ArrayList<>(cgs.numberOfCitationGroups()); for (CitationGroup cg : cgs.getCitationGroupsUnordered()) { String name = cg.cgid.citationGroupIdAsString(); XTextCursor cursor = (this diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index e4405dc6115..7c6ac737775 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -24,6 +24,10 @@ class Codec52 { // citationType is always "1" "2" or "3" Pattern.compile(BIB_CITATION + "(\\d*)_([123])_(.*)"); + private Codec52() { + /**/ + } + /** * This is what we get back from parsing a refMarkName. */ @@ -47,7 +51,7 @@ public static class ParsedMarkName { /** * Integer representation was written into the document in JabRef52, keep it for compatibility. */ - public static CitationType CitationTypeFromInt(int i) { + private static CitationType citationTypeFromInt(int i) { switch (i) { case 1: return CitationType.AUTHORYEAR_PAR; @@ -60,7 +64,7 @@ public static CitationType CitationTypeFromInt(int i) { } } - public static int CitationTypeToInt(CitationType i) { + private static int citationTypeToInt(CitationType i) { switch (i) { case AUTHORYEAR_PAR: return 1; @@ -91,7 +95,7 @@ public static String getUniqueMarkName(Set usedNames, NoDocumentException { int i = 0; - int citTypeCode = CitationTypeToInt(citationType); + int citTypeCode = citationTypeToInt(citationType); String name = BIB_CITATION + '_' + citTypeCode + '_' + bibtexKey; while (usedNames.contains(name)) { name = BIB_CITATION + i + '_' + citTypeCode + '_' + bibtexKey; @@ -116,7 +120,7 @@ public static Optional parseMarkName(String refMarkName) { List keys = Arrays.asList(citeMatcher.group(3).split(",")); String i = citeMatcher.group(1); int citTypeCode = Integer.parseInt(citeMatcher.group(2)); - CitationType citationType = CitationTypeFromInt(citTypeCode); + CitationType citationType = citationTypeFromInt(citTypeCode); return (Optional.of(new Codec52.ParsedMarkName(i, citationType, keys))); } diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index 63d5f917fc5..6a0ffe00c1c 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -57,24 +57,24 @@ String getId() { * {@code safeInsertSpaces(n): para, para, left, space(n), right-delete, left(n), left-delete} * * @param position Where to insert (at position.getStart()) - * @param n Number of spaces to insert. + * @param numSpaces Number of spaces to insert. * * @return a new cursor, covering the just-inserted spaces. * */ - private static XTextCursor safeInsertSpacesBetweenReferenceMarks(XTextRange position, int n) { + private static XTextCursor safeInsertSpacesBetweenReferenceMarks(XTextRange position, int numSpaces) { // Start with an empty cursor at position.getStart(); XText text = position.getText(); XTextCursor cursor = text.createTextCursorByRange(position.getStart()); text.insertString(cursor, "\r\r", false); // para, para cursor.goLeft((short) 1, false); // left - text.insertString(cursor, " ".repeat(n), false); // space(n) + text.insertString(cursor, " ".repeat(numSpaces), false); // space(numSpaces) cursor.goRight((short) 1, true); cursor.setString(""); // right-delete - cursor.goLeft((short) n, false); // left(n) + cursor.goLeft((short) numSpaces, false); // left(numSpaces) cursor.goLeft((short) 1, true); cursor.setString(""); // left-delete - cursor.goRight((short) n, true); // select the newly inserted spaces + cursor.goRight((short) numSpaces, true); // select the newly inserted spaces return cursor; } @@ -101,8 +101,6 @@ private static void createReprInDocument(XTextDocument doc, final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); String bracketedContent = (withoutBrackets ? "" : left + right); @@ -111,9 +109,11 @@ private static void createReprInDocument(XTextDocument doc, UnoReferenceMark.create(doc, refMarkName, cursor, true /* absorb */); + // eat the first inserted space cursorBefore.goRight((short) 1, true); cursorBefore.setString(""); if (!insertSpaceAfter) { + // eat the second inserted space cursorAfter.goLeft((short) 1, true); cursorAfter.setString(""); } @@ -193,7 +193,6 @@ public Optional nrGetRawCursor(XTextDocument doc) WrappedTargetException { String name = this.nrGetRangeName(); - Optional full = Optional.empty(); Optional markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name); @@ -202,10 +201,9 @@ public Optional nrGetRawCursor(XTextDocument doc) LOGGER.warn(msg); } - full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()); + Optional full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()); if (full.isEmpty()) { - String msg = "nrGetRawCursor: full.isEmpty()"; - LOGGER.warn(msg); + LOGGER.warn("nrGetRawCursor: full.isEmpty()"); return Optional.empty(); } return full; @@ -225,8 +223,6 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); final boolean debugThisFun = false; XTextCursor full = null; @@ -287,6 +283,7 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) beta.goRight((short) (fullText.length() - 2), true); LOGGER.debug("nrGetFillCursor: beta(1) covers '{}'", beta.getString()); + final short rightLength = (short) right.length(); if (fullText.startsWith(left) && fullText.endsWith(right)) { beta.setString(""); } else { @@ -335,6 +332,7 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) beta.setString(""); // should be OK now. if (debugThisFun) { + final short leftLength = (short) left.length(); alpha.goRight(leftLength, true); LOGGER.debug("nrGetFillCursor: alpha(7) covers '{}', should be '{}'", alpha.getString(), left); omega.goLeft(rightLength, true); @@ -352,8 +350,6 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) public static void checkFillCursor(XTextCursor cursor) { final String left = REFERENCE_MARK_LEFT_BRACKET; final String right = REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); XTextCursor alpha = cursor.getText().createTextCursorByRange(cursor); alpha.collapseToStart(); @@ -361,6 +357,7 @@ public static void checkFillCursor(XTextCursor cursor) { XTextCursor omega = cursor.getText().createTextCursorByRange(cursor); omega.collapseToEnd(); + final short leftLength = (short) left.length(); if (leftLength > 0) { alpha.goLeft(leftLength, true); if (!left.equals(alpha.getString())) { @@ -371,6 +368,7 @@ public static void checkFillCursor(XTextCursor cursor) { } } + final short rightLength = (short) right.length(); if (rightLength > 0) { omega.goRight(rightLength, true); if (!right.equals(omega.getString())) { From 9aaf742dd7980f94beea21a27791c5f5f652eb30 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 19:28:12 +0200 Subject: [PATCH 1012/1068] PMD on logic/frontend --- .../logic/openoffice/frontend/OOFrontend.java | 25 +++++++------------ .../frontend/UpdateBibliography.java | 7 ++++-- .../frontend/UpdateCitationMarkers.java | 8 ++++-- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 967a8cf084d..5e9d40c0e7f 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -43,11 +43,9 @@ import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class OOFrontend { - private static final Logger LOGGER = LoggerFactory.getLogger(OOFrontend.class); + public final Backend52 backend; public final CitationGroups citationGroups; @@ -86,8 +84,7 @@ public Optional healthReport(XTextDocument doc) NoDocumentException { Map citationGroups = new HashMap<>(); - for (int i = 0; i < citationGroupNames.size(); i++) { - final String name = citationGroupNames.get(i); + for (String name : citationGroupNames) { CitationGroup cg = backend.readCitationGroupFromDocumentOrThrow(doc, name); citationGroups.put(cg.cgid, cg); } @@ -150,9 +147,7 @@ public Optional healthReport(XTextDocument doc) for (List> partition : partitions.getPartitions()) { int indexInPartition = 0; - for (int i = 0; i < partition.size(); i++) { - RangeSortEntry sortable = partition.get(i); - XTextRange aRange = sortable.getRange(); + for (RangeSortEntry sortable : partition) { sortable.setIndexInPosition(indexInPartition++); if (mapFootnotesToFootnoteMarks) { Optional footnoteMarkRange = @@ -190,11 +185,9 @@ private List getVisuallySortedCitationGroups(XTextDocument doc, List> sorted = RangeSortVisual.visualSort(sortables, doc, fcursor); - List result = (sorted.stream() - .map(RangeSortable::getContent) - .collect(Collectors.toList())); - - return result; + return (sorted.stream() + .map(RangeSortable::getContent) + .collect(Collectors.toList())); } /** @@ -432,7 +425,7 @@ public List> viewCursorRanges(XTextDocumen static String rangeOverlapsToMessage(List>> overlaps) { - if (overlaps.size() == 0) { + if (overlaps.isEmpty()) { return "(*no overlaps*)"; } @@ -483,7 +476,7 @@ static String rangeOverlapsToMessage(List checkRangeOverlaps(XTextDocument doc, List>> overlaps = RangeOverlapWithin.findOverlappingRanges(doc, ranges, requireSeparation, reportAtMost); - if (overlaps.size() == 0) { + if (overlaps.isEmpty()) { return OOVoidResult.ok(); } return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges", diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java index 2d0de320ca6..f04afc410d0 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java @@ -28,12 +28,15 @@ public class UpdateBibliography { private static final String BIB_SECTION_NAME = "JR_bib"; private static final String BIB_SECTION_END_NAME = "JR_bib_end"; + private UpdateBibliography() { + /**/ + } + public static Optional getBibliographyRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - Optional sectionRange = UnoTextSection.getAnchor(doc, BIB_SECTION_NAME); - return sectionRange; + return UnoTextSection.getAnchor(doc, BIB_SECTION_NAME); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index b3f90d380a7..e4c4981cae5 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -33,6 +33,10 @@ public class UpdateCitationMarkers { private static final Logger LOGGER = LoggerFactory.getLogger(UpdateCitationMarkers.class); + private UpdateCitationMarkers() { + /**/ + } + /** * Visit each reference mark in referenceMarkNames, overwrite its * text content. @@ -162,9 +166,9 @@ public static void createAndFillCitationGroup(OOFrontend fr, final boolean withText = citationType.withText(); if (withText) { - XTextCursor c2 = fr.getFillCursorForCitationGroup(doc, cg); + XTextCursor fillCursor = fr.getFillCursorForCitationGroup(doc, cg); - UpdateCitationMarkers.fillCitationMarkInCursor(doc, c2, citationText, withText, style); + UpdateCitationMarkers.fillCitationMarkInCursor(doc, fillCursor, citationText, withText, style); fr.cleanFillCursorForCitationGroup(doc, cg); } From 66d3301329067b3559d2ec6c4170014a43fe0357 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 19:31:42 +0200 Subject: [PATCH 1013/1068] PMD on logic/style --- .../style/OOBibStyleGetCitationMarker.java | 74 ++++++++++--------- .../style/OOBibStyleGetNumCitationMarker.java | 6 +- .../logic/openoffice/style/OOProcess.java | 29 +++----- .../style/OOProcessAuthorYearMarkers.java | 4 + .../style/OOProcessCitationKeyMarkers.java | 5 ++ .../style/OOProcessNumericMarkers.java | 4 + 6 files changed, 66 insertions(+), 56 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java index e501cd4aaaf..4235841e426 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java @@ -22,6 +22,10 @@ class OOBibStyleGetCitationMarker { + private OOBibStyleGetCitationMarker() { + /**/ + } + /** * Look up the nth author and return the "proper" last name for * citation markers. @@ -29,23 +33,23 @@ class OOBibStyleGetCitationMarker { * Note: "proper" in the sense that it includes the "von" part * of the name (followed by a space) if there is one. * - * @param al The author list. + * @param authorList The author list. * @param number The number of the author to return. * @return The author name, or an empty String if inapplicable. */ - private static String getAuthorLastName(AuthorList al, int number) { + private static String getAuthorLastName(AuthorList authorList, int number) { StringBuilder sb = new StringBuilder(); - if (al.getNumberOfAuthors() > number) { - Author a = al.getAuthor(number); + if (authorList.getNumberOfAuthors() > number) { + Author author = authorList.getAuthor(number); // "von " if von exists - Optional von = a.getVon(); + Optional von = author.getVon(); if (von.isPresent() && !von.get().isEmpty()) { sb.append(von.get()); sb.append(' '); } // last name if it exists - sb.append(a.getLast().orElse("")); + sb.append(author.getLast().orElse("")); } return sb.toString(); @@ -306,23 +310,23 @@ private enum AuthorYearMarkerPurpose { } /** - * How many authors would be emitted for ce, considering - * style and ce.getIsFirstAppearanceOfSource() + * How many authors would be emitted for entry, considering + * style and entry.getIsFirstAppearanceOfSource() * - * If ce is unresolved, return 0. + * If entry is unresolved, return 0. */ - private static int calculateNAuthorsToEmit(OOBibStyle style, CitationMarkerEntry ce) { - - int maxAuthors = (ce.getIsFirstAppearanceOfSource() - ? style.getMaxAuthorsFirst() - : style.getMaxAuthors()); + private static int calculateNAuthorsToEmit(OOBibStyle style, CitationMarkerEntry entry) { - if (ce.getLookupResult().isEmpty()) { + if (entry.getLookupResult().isEmpty()) { // unresolved return 0; } - AuthorList authorList = getAuthorList(style, ce.getLookupResult().get()); + int maxAuthors = (entry.getIsFirstAppearanceOfSource() + ? style.getMaxAuthorsFirst() + : style.getMaxAuthors()); + + AuthorList authorList = getAuthorList(style, entry.getLookupResult().get()); int nAuthors = authorList.getNumberOfAuthors(); if (maxAuthors == -1) { @@ -342,21 +346,21 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, CitationMarkerEntry * ignores isFirstAppearanceOfSource (always * style.getMaxAuthors, not getMaxAuthorsFirst) * - * @param ces The list of CitationMarkerEntry values to process. + * @param entries The list of CitationMarkerEntry values to process. * * Here we do not check for duplicate entries: those * are handled by {@code getCitationMarker} by * omitting them from the list. * * Unresolved citations recognized by - * ce.getBibEntry() and/or - * ce.getDatabase() returning empty, and + * entry.getBibEntry() and/or + * entry.getDatabase() returning empty, and * emitted as "Unresolved${citationKey}". * * Neither uniqueLetter nor pageInfo are emitted * for unresolved citations. * - * @param startsNewGroup Should have the same length as {@code ces}, and + * @param startsNewGroup Should have the same length as {@code entries}, and * contain true for entries starting a new group, * false for those that only add a uniqueLetter to * the grouped presentation. @@ -370,7 +374,7 @@ private static int calculateNAuthorsToEmit(OOBibStyle style, CitationMarkerEntry */ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, AuthorYearMarkerPurpose purpose, - List ces, + List entries, boolean[] startsNewGroup, Optional maxAuthorsOverride) { @@ -409,14 +413,14 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, sb.append(startBrace); // shared parenthesis } - for (int j = 0; j < ces.size(); j++) { - CitationMarkerEntry ce = ces.get(j); + for (int j = 0; j < entries.size(); j++) { + CitationMarkerEntry entry = entries.get(j); boolean startingNewGroup = startsNewGroup[j]; - boolean endingAGroup = (j + 1 == ces.size()) || startsNewGroup[j + 1]; + boolean endingAGroup = (j + 1 == entries.size()) || startsNewGroup[j + 1]; if (!startingNewGroup) { // Just add our uniqueLetter - String uniqueLetter = ce.getUniqueLetter().orElse(null); + String uniqueLetter = entry.getUniqueLetter().orElse(null); if (uniqueLetter != null) { sb.append(uniquefierSeparator); sb.append(uniqueLetter); @@ -436,26 +440,26 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, StringBuilder pageInfoPart = new StringBuilder(""); if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { Optional pageInfo = - PageInfo.normalizePageInfo(ce.getPageInfo()); + PageInfo.normalizePageInfo(entry.getPageInfo()); if (pageInfo.isPresent()) { pageInfoPart.append(pageInfoSeparator); pageInfoPart.append(OOText.toString(pageInfo.get())); } } - final boolean isUnresolved = ce.getLookupResult().isEmpty(); + final boolean isUnresolved = entry.getLookupResult().isEmpty(); if (isUnresolved) { - sb.append(String.format("Unresolved(%s)", ce.getCitationKey())); + sb.append(String.format("Unresolved(%s)", entry.getCitationKey())); if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { sb.append(pageInfoPart); } } else { - CitationLookupResult db = ce.getLookupResult().get(); + CitationLookupResult db = entry.getLookupResult().get(); int maxAuthors = (purpose == AuthorYearMarkerPurpose.NORMALIZED ? style.getMaxAuthors() - : calculateNAuthorsToEmit(style, ce)); + : calculateNAuthorsToEmit(style, entry)); if (maxAuthorsOverride.isPresent()) { maxAuthors = maxAuthorsOverride.get(); @@ -476,7 +480,7 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, } if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { - String uniqueLetter = ce.getUniqueLetter().orElse(null); + String uniqueLetter = entry.getUniqueLetter().orElse(null); if (uniqueLetter != null) { sb.append(uniqueLetter); } @@ -547,10 +551,10 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, CitationMarkerNormEntry cne, Optional maxAuthorsOverride) { boolean[] startsNewGroup = {true}; - CitationMarkerEntry ce = new CitationMarkerNormEntryWrap(cne); + CitationMarkerEntry entry = new CitationMarkerNormEntryWrap(cne); return getAuthorYearParenthesisMarker2(style, AuthorYearMarkerPurpose.NORMALIZED, - Collections.singletonList(ce), + Collections.singletonList(entry), startsNewGroup, maxAuthorsOverride); } @@ -630,8 +634,8 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, int[] nAuthorsToEmit = new int[nEntries]; int[] nAuthorsToEmitRevised = new int[nEntries]; for (int i = 0; i < nEntries; i++) { - CitationMarkerEntry ce = citationMarkerEntries.get(i); - int n = calculateNAuthorsToEmit(style, ce); + CitationMarkerEntry entry = citationMarkerEntries.get(i); + int n = calculateNAuthorsToEmit(style, entry); nAuthorsToEmit[i] = n; nAuthorsToEmitRevised[i] = n; } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java index 8d8422fbc51..5dce4e8caa1 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java @@ -17,6 +17,10 @@ class OOBibStyleGetNumCitationMarker { */ public final static int UNRESOLVED_ENTRY_NUMBER = 0; + private OOBibStyleGetNumCitationMarker() { + /**/ + } + /** * Defines sort order for CitationMarkerNumericEntry. */ @@ -223,7 +227,7 @@ public static OOText getNumCitationMarker2(OOBibStyle style, throw new IllegalArgumentException("getNumCitationMarker2: found negative number"); } - if (currentBlock.size() == 0) { + if (currentBlock.isEmpty()) { currentBlock.add(current); } else { CitationMarkerNumericEntry prev = currentBlock.get(currentBlock.size() - 1); diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java index 05475fcdfac..e00650703fa 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java @@ -11,37 +11,26 @@ import org.jabref.model.entry.field.StandardField; import org.jabref.model.openoffice.style.CitationGroups; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class OOProcess { static final Comparator AUTHOR_YEAR_TITLE_COMPARATOR = makeAuthorYearTitleComparator(); static final Comparator YEAR_AUTHOR_TITLE_COMPARATOR = makeYearAuthorTitleComparator(); - private static final Logger LOGGER = LoggerFactory.getLogger(OOProcess.class); + private OOProcess() { + /**/ + } private static Comparator makeAuthorYearTitleComparator() { - FieldComparator a = new FieldComparator(StandardField.AUTHOR); - FieldComparator y = new FieldComparator(StandardField.YEAR); - FieldComparator t = new FieldComparator(StandardField.TITLE); - - List> ayt = new ArrayList<>(3); - ayt.add(a); - ayt.add(y); - ayt.add(t); + List> ayt = List.of(new FieldComparator(StandardField.AUTHOR), + new FieldComparator(StandardField.YEAR), + new FieldComparator(StandardField.TITLE)); return new FieldComparatorStack<>(ayt); } private static Comparator makeYearAuthorTitleComparator() { - FieldComparator y = new FieldComparator(StandardField.YEAR); - FieldComparator a = new FieldComparator(StandardField.AUTHOR); - FieldComparator t = new FieldComparator(StandardField.TITLE); - - List> yat = new ArrayList<>(3); - yat.add(y); - yat.add(a); - yat.add(t); + List> yat = List.of(new FieldComparator(StandardField.YEAR), + new FieldComparator(StandardField.AUTHOR), + new FieldComparator(StandardField.TITLE)); return new FieldComparatorStack<>(yat); } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index a55d59107a8..cbd03cd79c6 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -21,6 +21,10 @@ class OOProcessAuthorYearMarkers { + private OOProcessAuthorYearMarkers() { + /**/ + } + /** * Fills {@code sortedCitedKeys//normCitMarker} */ diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java index c63a4b3d0e4..9789d6c6caa 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java @@ -9,6 +9,11 @@ import org.jabref.model.openoffice.util.OOListUtil; class OOProcessCitationKeyMarkers { + + private OOProcessCitationKeyMarkers() { + /**/ + } + /** * Produce citation markers for the case when the citation * markers are the citation keys themselves, separated by commas. diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java index 4023ed0e028..589ebfb7a48 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java @@ -11,6 +11,10 @@ class OOProcessNumericMarkers { + private OOProcessNumericMarkers() { + /**/ + } + /** * Produce citation markers for the case of numbered citations * with bibliography sorted by first appearance in the text. From e4b5ca09e722bcda320af940c2c77bdfa2b9b929 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 19:48:21 +0200 Subject: [PATCH 1014/1068] drop unused LOGGER --- src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index c9f6246062b..1e1efeae3ad 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -33,8 +33,6 @@ */ class OOBibBaseConnect { - private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBaseConnect.class); - /* variables */ private final DialogService dialogService; private final XDesktop xDesktop; From ff92514e2971645ebb02f539d47bfc51aab0c2a0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 21:54:56 +0200 Subject: [PATCH 1015/1068] pmd rule in Makefile --- Makefile | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index cb08c4bfa8f..4629a6494f8 100644 --- a/Makefile +++ b/Makefile @@ -86,7 +86,10 @@ checkstyle: ./gradlew checkstyletest 2>&1 | sed -e 's|[[]ant[:]checkstyle] [[]ERROR] ||g' # + +PMD = pmd -f text -R ../tools/pmd/pmd-java-rules.xml -cache /tmp/pmd-jabref-cache + pmd: - pmd -d src/main/java/org/jabref/model/openoffice - pmd -d src/main/java/org/jabref/logic/openoffice - pmd -d src/main/java/org/jabref/gui/openoffice +# $(PMD) -d src/main/java/org/jabref/model/openoffice +# $(PMD) -d src/main/java/org/jabref/logic/openoffice + $(PMD) -d src/main/java/org/jabref/gui/openoffice From ab275fc0d5b6561d457e3f5932e0938c63488b40 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 23:01:59 +0200 Subject: [PATCH 1016/1068] cleanup: redundant throws clause (based on IntelliJ Idea) --- .../org/jabref/gui/openoffice/OOBibBase2.java | 50 ++----------------- .../gui/openoffice/OOBibBaseConnect.java | 2 - .../logic/openoffice/action/EditInsert.java | 10 +--- .../logic/openoffice/action/EditMerge.java | 10 ---- .../logic/openoffice/action/EditSeparate.java | 10 ---- .../logic/openoffice/action/ExportCited.java | 4 -- .../openoffice/action/ManageCitations.java | 7 --- .../logic/openoffice/action/Update.java | 16 ------ .../logic/openoffice/backend/Backend52.java | 18 +------ .../logic/openoffice/backend/Codec52.java | 5 +- .../logic/openoffice/backend/GetContext.java | 8 +-- .../backend/NamedRangeReferenceMark.java | 7 +-- .../logic/openoffice/frontend/OOFrontend.java | 38 +++----------- .../frontend/UpdateBibliography.java | 11 +--- .../frontend/UpdateCitationMarkers.java | 21 ++------ .../logic/openoffice/style/OOProcess.java | 1 - .../model/openoffice/backend/NamedRange.java | 9 ++-- .../model/openoffice/ootext/OOTextIntoOO.java | 1 - 18 files changed, 26 insertions(+), 202 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index f196bae6bc4..48079ba5760 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -40,16 +40,13 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.DisposedException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; -import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -263,13 +260,7 @@ private static OOVoidResult checkRangeOverlapsWithCursor(XTextDocument final String title = "checkRangeOverlapsWithCursor"; List> userRanges; - try { - userRanges = fr.viewCursorRanges(doc); - } catch (NoDocumentException ex) { - return OOVoidResult.error(OOError.from(ex).setTitle(title)); - } catch (WrappedTargetException ex) { - return OOVoidResult.error(OOError.fromMisc(ex).setTitle(title)); - } + userRanges = fr.viewCursorRanges(doc); boolean requireSeparation = false; OOVoidResult res; @@ -377,7 +368,6 @@ private OOVoidResult checkStyleExistsInTheDocument(String familyName, String labelInJstyleFile, String pathToStyleFile) throws - NoSuchElementException, WrappedTargetException { Optional internalName = UnoStyle.getInternalNameOfStyle(doc, familyName, styleName); @@ -456,8 +446,7 @@ public OOVoidResult checkStylesExistInTheDocument(OOBibStyle style, XTe "CitationCharacterFormat", pathToStyleFile)); } - } catch (NoSuchElementException - | WrappedTargetException ex) { + } catch (WrappedTargetException ex) { results.add(OOVoidResult.error(new OOError("Other error in checkStyleExistsInTheDocument", ex.getMessage(), ex))); @@ -497,8 +486,7 @@ public Optional> guiActionGetCitationEntries() { } catch (DisposedException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); return FAIL; - } catch (UnknownPropertyException - | WrappedTargetException ex) { + } catch (WrappedTargetException ex) { LOGGER.warn(title, ex); OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); return FAIL; @@ -548,10 +536,7 @@ public void guiActionApplyCitationEntries(List citationEntries) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); - } catch (UnknownPropertyException - | NotRemoveableException - | PropertyExistException - | PropertyVetoException + } catch (PropertyVetoException | IllegalTypeException | WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { @@ -675,16 +660,10 @@ public void guiActionInsertEntry(List entries, } catch (DisposedException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); return; - } catch (JabRefException ex) { - OOError.from(ex).setTitle(title).showErrorDialog(dialogService); - return; } catch (CreationException | IllegalTypeException - | NoSuchElementException | NotRemoveableException - | PropertyExistException | PropertyVetoException - | UnknownPropertyException | WrappedTargetException ex) { LOGGER.warn("Could not insert entry", ex); OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); @@ -735,16 +714,10 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); - } catch (JabRefException ex) { - OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (CreationException | IllegalTypeException - | InvalidStateException - | NoSuchElementException | NotRemoveableException - | PropertyExistException | PropertyVetoException - | UnknownPropertyException | WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Problem combining cite markers", ex); @@ -798,16 +771,10 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); - } catch (JabRefException ex) { - OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (CreationException | IllegalTypeException - | InvalidStateException - | NoSuchElementException | NotRemoveableException - | PropertyExistException | PropertyVetoException - | UnknownPropertyException | WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Problem during separating cite markers", ex); @@ -882,9 +849,7 @@ public Optional exportCitedHelper(List databases, OOError.from(ex).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); - } catch (NoSuchElementException - | UnknownPropertyException - | WrappedTargetException + } catch (WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Problem generating new database.", ex); OOError.fromMisc(ex).setTitle(title).showErrorDialog(dialogService); @@ -953,16 +918,11 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl return; } - } catch (JabRefException ex) { - OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (NoDocumentException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(title).showErrorDialog(dialogService); } catch (CreationException - | NoSuchElementException - | PropertyVetoException - | UnknownPropertyException | WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Could not update bibliography", ex); diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 1e1efeae3ad..728b5cf541e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -25,8 +25,6 @@ import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.text.XTextDocument; import com.sun.star.uno.XComponentContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Establish connection to a document opened in OpenOffice or LibreOffice. diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index 2df867a8e11..81491bd8590 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.Optional; -import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; @@ -24,10 +23,7 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; @@ -68,16 +64,12 @@ public static void insertCitationGroup(XTextDocument doc, CitationType citationType, String pageInfo) throws - UnknownPropertyException, NoDocumentException, NotRemoveableException, WrappedTargetException, PropertyVetoException, - PropertyExistException, - NoSuchElementException, CreationException, - IllegalTypeException, - JabRefException { + IllegalTypeException { List citationKeys = OOListUtil.map(entries, EditInsert::insertEntryGetCitationKey); diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index 9f2171dd59d..ac5de38551f 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -6,7 +6,6 @@ import java.util.Optional; import java.util.stream.Collectors; -import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; @@ -22,15 +21,11 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; -import com.sun.star.util.InvalidStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,14 +45,9 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBi CreationException, IllegalArgumentException, IllegalTypeException, - InvalidStateException, - JabRefException, NoDocumentException, - NoSuchElementException, NotRemoveableException, - PropertyExistException, PropertyVetoException, - UnknownPropertyException, WrappedTargetException { boolean madeModifications = false; diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index 7a361776ff2..19e9e756d1b 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -2,7 +2,6 @@ import java.util.List; -import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; import org.jabref.logic.openoffice.style.OOBibStyle; @@ -17,15 +16,11 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; -import com.sun.star.util.InvalidStateException; public class EditSeparate { @@ -40,14 +35,9 @@ public static boolean separateCitations(XTextDocument doc, throws CreationException, IllegalTypeException, - InvalidStateException, - JabRefException, NoDocumentException, - NoSuchElementException, NotRemoveableException, - PropertyExistException, PropertyVetoException, - UnknownPropertyException, WrappedTargetException, com.sun.star.lang.IllegalArgumentException { diff --git a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java index de89030e373..26ed654de21 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java @@ -13,8 +13,6 @@ import org.jabref.model.openoffice.style.CitedKeys; import org.jabref.model.openoffice.uno.NoDocumentException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; @@ -51,8 +49,6 @@ public static class GenerateDatabaseResult { public static GenerateDatabaseResult generateDatabase(XTextDocument doc, List databases) throws NoDocumentException, - NoSuchElementException, - UnknownPropertyException, WrappedTargetException { OOFrontend fr = new OOFrontend(doc); diff --git a/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java b/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java index 9e70ba78379..9782261f612 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java @@ -7,10 +7,7 @@ import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.beans.IllegalTypeException; -import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; @@ -23,7 +20,6 @@ private ManageCitations() { public static List getCitationEntries(XTextDocument doc) throws NoDocumentException, - UnknownPropertyException, WrappedTargetException { OOFrontend fr = new OOFrontend(doc); return fr.getCitationEntries(doc); @@ -32,9 +28,6 @@ public static List getCitationEntries(XTextDocument doc) public static void applyCitationEntries(XTextDocument doc, List citationEntries) throws NoDocumentException, - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, PropertyVetoException, IllegalTypeException, WrappedTargetException, diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index a95f7b6e771..49f79d6d2e7 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -2,7 +2,6 @@ import java.util.List; -import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.frontend.UpdateBibliography; import org.jabref.logic.openoffice.frontend.UpdateCitationMarkers; @@ -14,9 +13,6 @@ import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.uno.UnoScreenRefresh; -import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; @@ -41,11 +37,7 @@ private static List updateDocument(XTextDocument doc, boolean alwaysAddCitedOnPages) throws CreationException, - JabRefException, NoDocumentException, - NoSuchElementException, - PropertyVetoException, - UnknownPropertyException, WrappedTargetException, com.sun.star.lang.IllegalArgumentException { @@ -107,11 +99,7 @@ public static List synchronizeDocument(XTextDocument doc, SyncOptions syncOptions) throws CreationException, - JabRefException, NoDocumentException, - NoSuchElementException, - PropertyVetoException, - UnknownPropertyException, WrappedTargetException, com.sun.star.lang.IllegalArgumentException { @@ -133,11 +121,7 @@ public static List resyncDocument(XTextDocument doc, SyncOptions syncOptions) throws CreationException, - JabRefException, NoDocumentException, - NoSuchElementException, - PropertyVetoException, - UnknownPropertyException, WrappedTargetException, com.sun.star.lang.IllegalArgumentException { diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 1c312b197ce..878571090f0 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -28,10 +28,7 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; @@ -189,7 +186,6 @@ public CitationGroup createCitationGroup(XTextDocument doc, NoDocumentException, WrappedTargetException, NotRemoveableException, - PropertyExistException, PropertyVetoException, IllegalTypeException { @@ -322,11 +318,7 @@ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) throws WrappedTargetException, NoDocumentException, - NoSuchElementException, - NotRemoveableException, - IllegalTypeException, - PropertyExistException { - + NotRemoveableException { NamedRange namedRange = getNamedRangeOrThrow(cg); String refMarkName = namedRange.nrGetRangeName(); namedRange.nrRemoveFromDocument(doc); @@ -375,15 +367,13 @@ public XTextCursor getFillCursorForCitationGroup(CitationGroup cg, XTextDocument public void cleanFillCursorForCitationGroup(CitationGroup cg, XTextDocument doc) throws NoDocumentException, - WrappedTargetException, - CreationException { + WrappedTargetException { NamedRange namedRange = getNamedRangeOrThrow(cg); namedRange.nrCleanFillCursor(doc); } public List getCitationEntries(XTextDocument doc, CitationGroups cgs) throws - UnknownPropertyException, WrappedTargetException, NoDocumentException { @@ -419,13 +409,9 @@ public List getCitationEntries(XTextDocument doc, CitationGroups */ public void applyCitationEntries(XTextDocument doc, List citationEntries) throws - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, PropertyVetoException, IllegalTypeException, IllegalArgumentException, - NoDocumentException, WrappedTargetException { switch (dataModel) { diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index 7c6ac737775..f6d2b12245e 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -10,7 +10,6 @@ import java.util.stream.Collectors; import org.jabref.model.openoffice.style.CitationType; -import org.jabref.model.openoffice.uno.NoDocumentException; /** * How and what is encoded in a mark names. @@ -90,9 +89,7 @@ private static int citationTypeToInt(CitationType i) { */ public static String getUniqueMarkName(Set usedNames, String bibtexKey, - CitationType citationType) - throws - NoDocumentException { + CitationType citationType) { int i = 0; int citTypeCode = citationTypeToInt(citationType); diff --git a/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java b/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java index 4cde12ad236..ffce5b9553e 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/GetContext.java @@ -1,8 +1,5 @@ package org.jabref.logic.openoffice.backend; -import org.jabref.model.openoffice.uno.NoDocumentException; - -import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,10 +31,7 @@ private GetContext() { public static String getCursorStringWithContext(XTextCursor cursor, int charBefore, int charAfter, - boolean htmlMarkup) - throws - WrappedTargetException, - NoDocumentException { + boolean htmlMarkup) { String citPart = cursor.getString(); diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index 6a0ffe00c1c..8eae0c922f2 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -8,7 +8,6 @@ import org.jabref.model.openoffice.uno.UnoCursor; import org.jabref.model.openoffice.uno.UnoReferenceMark; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XText; import com.sun.star.text.XTextContent; @@ -151,8 +150,7 @@ static Optional getFromDocument(XTextDocument doc, Stri public void nrRemoveFromDocument(XTextDocument doc) throws WrappedTargetException, - NoDocumentException, - NoSuchElementException { + NoDocumentException { UnoReferenceMark.removeIfExists(doc, this.nrGetRangeName()); } @@ -390,8 +388,7 @@ public static void checkFillCursor(XTextCursor cursor) { public void nrCleanFillCursor(XTextDocument doc) throws NoDocumentException, - WrappedTargetException, - CreationException { + WrappedTargetException { // alwaysRemoveBrackets : full compatibility with JabRef 5.2: brackets are temporary, only // exist between nrGetFillCursor and nrCleanFillCursor. diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 5e9d40c0e7f..bd587bf9210 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -35,10 +35,7 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; @@ -178,8 +175,7 @@ private List getVisuallySortedCitationGroups(XTextDocument doc, FunctionalTextViewCursor fcursor) throws WrappedTargetException, - NoDocumentException, - JabRefException { + NoDocumentException { List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); @@ -233,7 +229,6 @@ public CitationGroup createCitationGroup(XTextDocument doc, NoDocumentException, WrappedTargetException, NotRemoveableException, - PropertyExistException, PropertyVetoException, IllegalTypeException { @@ -259,10 +254,7 @@ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) throws WrappedTargetException, NoDocumentException, - NoSuchElementException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException { + NotRemoveableException { backend.removeCitationGroup(cg, doc); this.citationGroups.afterRemoveCitationGroup(cg); @@ -272,10 +264,7 @@ public void removeCitationGroups(List cgs, XTextDocument doc) throws WrappedTargetException, NoDocumentException, - NoSuchElementException, - NotRemoveableException, - PropertyExistException, - IllegalTypeException { + NotRemoveableException { for (CitationGroup cg : cgs) { removeCitationGroup(cg, doc); @@ -309,8 +298,7 @@ public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGrou public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroup cg) throws NoDocumentException, - WrappedTargetException, - CreationException { + WrappedTargetException { backend.cleanFillCursorForCitationGroup(cg, doc); } @@ -357,10 +345,7 @@ public List> bibliographyRanges(XTextDocum return result; } - public List> viewCursorRanges(XTextDocument doc) - throws - NoDocumentException, - WrappedTargetException { + public List> viewCursorRanges(XTextDocument doc) { List> result = new ArrayList<>(); @@ -387,10 +372,7 @@ public List> viewCursorRanges(XTextDocumen * ranges. */ public List> - footnoteMarkRanges(XTextDocument doc, List> citationRanges) - throws - NoDocumentException, - WrappedTargetException { + footnoteMarkRanges(XTextDocument doc, List> citationRanges) { // We partition by XText and use a single range from // each partition to get at the corresponding footnotemark range. @@ -545,7 +527,6 @@ public OOVoidResult checkRangeOverlaps(XTextDocument doc, */ public List getCitationEntries(XTextDocument doc) throws - UnknownPropertyException, WrappedTargetException, NoDocumentException { return this.backend.getCitationEntries(doc, citationGroups); @@ -553,13 +534,9 @@ public List getCitationEntries(XTextDocument doc) public void applyCitationEntries(XTextDocument doc, List citationEntries) throws - UnknownPropertyException, - NotRemoveableException, - PropertyExistException, PropertyVetoException, IllegalTypeException, IllegalArgumentException, - NoDocumentException, WrappedTargetException { this.backend.applyCitationEntries(doc, citationEntries); } @@ -567,8 +544,7 @@ public void applyCitationEntries(XTextDocument doc, List citation public void imposeGlobalOrder(XTextDocument doc, FunctionalTextViewCursor fcursor) throws WrappedTargetException, - NoDocumentException, - JabRefException { + NoDocumentException { boolean mapFootnotesToFootnoteMarks = true; List sortedCitationGroups = diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java index f04afc410d0..f7b3d14def6 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java @@ -12,9 +12,6 @@ import org.jabref.model.openoffice.uno.UnoBookmark; import org.jabref.model.openoffice.uno.UnoTextSection; -import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; @@ -48,11 +45,8 @@ public static void rebuildBibTextSection(XTextDocument doc, OOBibStyle style, boolean alwaysAddCitedOnPages) throws - NoSuchElementException, WrappedTargetException, CreationException, - PropertyVetoException, - UnknownPropertyException, NoDocumentException { clearBibTextSectionContent2(doc); @@ -119,9 +113,6 @@ private static void populateBibTextSection(XTextDocument doc, CreationException, IllegalArgumentException, NoDocumentException, - NoSuchElementException, - PropertyVetoException, - UnknownPropertyException, WrappedTargetException { XTextRange sectionRange = getBibliographyRange(doc).orElseThrow(IllegalStateException::new); @@ -137,7 +128,7 @@ private static void populateBibTextSection(XTextDocument doc, OOTextIntoOO.write(doc, cursor, bibliographyText); cursor.collapseToEnd(); - // remove the inital empty paragraph from the section. + // remove the initial empty paragraph from the section. sectionRange = getBibliographyRange(doc).orElseThrow(IllegalStateException::new); XTextCursor initialParagraph = doc.getText().createTextCursorByRange(sectionRange); initialParagraph.collapseToStart(); diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index e4c4981cae5..ac497c49d8f 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -4,7 +4,6 @@ import java.util.Objects; import java.util.Optional; -import org.jabref.logic.JabRefException; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.openoffice.ootext.OOText; import org.jabref.model.openoffice.ootext.OOTextIntoOO; @@ -16,10 +15,7 @@ import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; -import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; @@ -52,12 +48,8 @@ private UpdateCitationMarkers() { public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, OOBibStyle style) throws NoDocumentException, - UnknownPropertyException, CreationException, - WrappedTargetException, - PropertyVetoException, - NoSuchElementException, - JabRefException { + WrappedTargetException { CitationGroups citationGroups = fr.citationGroups; @@ -90,11 +82,8 @@ public static void fillCitationMarkInCursor(XTextDocument doc, OOText citationText, boolean withText, OOBibStyle style) - throws - UnknownPropertyException, - PropertyVetoException, + throws WrappedTargetException, - NoSuchElementException, CreationException, IllegalArgumentException { @@ -140,17 +129,13 @@ public static void createAndFillCitationGroup(OOFrontend fr, OOBibStyle style, boolean insertSpaceAfter) throws - UnknownPropertyException, NotRemoveableException, - PropertyExistException, - PropertyVetoException, WrappedTargetException, PropertyVetoException, IllegalArgumentException, CreationException, NoDocumentException, - IllegalTypeException, - NoSuchElementException { + IllegalTypeException { Objects.requireNonNull(pageInfos); if (pageInfos.size() != citationKeys.size()) { diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java index e00650703fa..f8f7de6c7b7 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcess.java @@ -1,6 +1,5 @@ package org.jabref.logic.openoffice.style; -import java.util.ArrayList; import java.util.Comparator; import java.util.List; diff --git a/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java b/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java index 5cdc15c2e08..aa09f36edef 100644 --- a/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java +++ b/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java @@ -5,7 +5,6 @@ import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; -import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; @@ -45,14 +44,13 @@ XTextCursor nrGetFillCursor(XTextDocument doc) /** * Remove brackets, but if the result would become empty, leave them; if the result would be a - * single characer, leave the left bracket. + * single character, leave the left bracket. * */ void nrCleanFillCursor(XTextDocument doc) throws NoDocumentException, - WrappedTargetException, - CreationException; + WrappedTargetException; /** * Note: create is in NamedRangeManager @@ -60,6 +58,5 @@ void nrCleanFillCursor(XTextDocument doc) void nrRemoveFromDocument(XTextDocument doc) throws WrappedTargetException, - NoDocumentException, - NoSuchElementException; + NoDocumentException; } diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index e4764ca2fbe..6e61faed147 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -147,7 +147,6 @@ private OOTextIntoOO() { */ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) throws - PropertyVetoException, WrappedTargetException, CreationException { From 5fae2125f446d45e3a0e7ab9a881b680cbfb1611 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 9 Jul 2021 23:16:11 +0200 Subject: [PATCH 1017/1068] restore UnoTextRange.java --- .../java/org/jabref/model/openoffice/uno/UnoTextRange.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java index c58ca96207f..56cb1498e2a 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java @@ -38,7 +38,7 @@ public static boolean comparables(XTextRange a, XTextRange b) { /** * @return follows java conventions * - * 1 if {@code (a > b)}; (-1) if {@code (a < b)} + * 1 if (a > b); (-1) if (a < b) */ public static int compareStartsUnsafe(XTextRangeCompare compare, XTextRange a, XTextRange b) { return (-1) * compare.compareRegionStarts(a, b); @@ -55,7 +55,7 @@ public static int compareStarts(XTextRange a, XTextRange b) { /** * @return follows java conventions * - * 1 if {@code (a > b)}; (-1) if {@code (a < b)} + * 1 if (a > b); (-1) if (a < b) */ public static int compareEnds(XTextRange a, XTextRange b) { if (!comparables(a, b)) { @@ -65,7 +65,7 @@ public static int compareEnds(XTextRange a, XTextRange b) { 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) { From 2ea5c5d2dba40b6e91cb2d8ce935c89f32ff2c99 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 08:57:21 +0200 Subject: [PATCH 1018/1068] replaced single-character names in OOBibStyle.java (in changed part) --- .../logic/openoffice/style/OOBibStyle.java | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index feccb727f53..c612f179540 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -1019,36 +1019,36 @@ protected Map getCitProperties() { return citProperties; } - protected void addJournal(String s) { - journals.add(s); + protected void addJournal(String journalName) { + journals.add(journalName); } - protected void setLocalCopy(String s) { - localCopy = s; + protected void setLocalCopy(String contentsOfJstyleFile) { + localCopy = contentsOfJstyleFile; } - protected void setName(String s) { - name = s; + protected void setName(String nameOfTheStyle) { + name = nameOfTheStyle; } protected boolean getIsDefaultLayoutPresent() { return isDefaultLayoutPresent; } - protected void setIsDefaultLayoutPresent(boolean b) { - isDefaultLayoutPresent = b; + protected void setIsDefaultLayoutPresent(boolean isPresent) { + isDefaultLayoutPresent = isPresent; } - protected void setValid(boolean b) { - valid = b; + protected void setValid(boolean isValid) { + valid = isValid; } protected LayoutFormatterPreferences getPrefs() { return prefs; } - protected void setDefaultBibLayout(Layout l) { - defaultBibLayout = l; + protected void setDefaultBibLayout(Layout layout) { + defaultBibLayout = layout; } /** @@ -1270,9 +1270,9 @@ protected String getAuthorLastSeparator() { /* As getAuthorLastSeparator, for in-text citation. */ protected String getAuthorLastSeparatorInTextWithFallBack() { - String a = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT); - String b = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); - return Objects.requireNonNullElse(a, b); + String value1 = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT); + String value2 = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); + return Objects.requireNonNullElse(value1, value2); } protected String getPageInfoSeparator() { From 8e5ae38489dd5384eb1523a68634db2bff469854 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 09:14:43 +0200 Subject: [PATCH 1019/1068] some longer names in OOBibStyleGetCitationMarker.java --- .../style/OOBibStyleGetCitationMarker.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java index 4235841e426..deb1a306913 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java @@ -503,6 +503,9 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, return OOText.fromString(sb.toString()); } + /** + * Add / override methods for the purpose of creating a normalized citation marker. + */ private static class CitationMarkerNormEntryWrap implements CitationMarkerEntry { CitationMarkerNormEntry inner; @@ -538,7 +541,7 @@ public boolean getIsFirstAppearanceOfSource() { } /** - * @param cne A citation to process. + * @param normEntry A citation to process. * * @return A normalized citation marker for deciding which * citations need uniqueLetters. @@ -548,10 +551,10 @@ public boolean getIsFirstAppearanceOfSource() { * Note: now includes some markup. */ static OOText getNormalizedCitationMarker(OOBibStyle style, - CitationMarkerNormEntry cne, + CitationMarkerNormEntry normEntry, Optional maxAuthorsOverride) { boolean[] startsNewGroup = {true}; - CitationMarkerEntry entry = new CitationMarkerNormEntryWrap(cne); + CitationMarkerEntry entry = new CitationMarkerNormEntryWrap(normEntry); return getAuthorYearParenthesisMarker2(style, AuthorYearMarkerPurpose.NORMALIZED, Collections.singletonList(entry), @@ -566,10 +569,10 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, List normalizedMarkers = new ArrayList<>(citationMarkerEntries.size()); for (CitationMarkerEntry citationMarkerEntry : citationMarkerEntries) { - OOText nm = getNormalizedCitationMarker(style, - citationMarkerEntry, - maxAuthorsOverride); - normalizedMarkers.add(nm); + OOText normalized = getNormalizedCitationMarker(style, + citationMarkerEntry, + maxAuthorsOverride); + normalizedMarkers.add(normalized); } return normalizedMarkers; } From d57caa6213f5219136377ed1fcf44dc6f4bf87c0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 14:34:54 +0200 Subject: [PATCH 1020/1068] drop normalizePageInfos, use 'preferred' and 'fallback' in getAuthorLastSeparatorInTextWithFallBack --- .../logic/openoffice/style/OOBibStyle.java | 36 ++----------------- 1 file changed, 3 insertions(+), 33 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index c612f179540..e21804a2c86 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -42,8 +42,6 @@ import org.jabref.model.openoffice.style.CitationMarkerNumericBibEntry; import org.jabref.model.openoffice.style.CitationMarkerNumericEntry; import org.jabref.model.openoffice.style.NonUniqueCitationMarker; -import org.jabref.model.openoffice.style.PageInfo; -import org.jabref.model.openoffice.util.OOListUtil; import org.jabref.model.strings.StringUtil; import org.slf4j.Logger; @@ -1080,34 +1078,6 @@ public OOText getNumCitationMarkerForBibliography(CitationMarkerNumericBibEntry return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, entry); } - /** - * Make sure that (1) we have exactly one entry for each - * citation, (2) each entry is either Optional.empty or its content is not empty when trimmed. - * - * As a special case: pageInfos may be null. In this case - * the result is a list filled with Optional.empty() values. - */ - static List> - normalizePageInfos(List> pageInfos, int nCitations) { - - // translate null to all-empty - if (pageInfos == null) { - List> res = new ArrayList<>(nCitations); - for (int i = 0; i < nCitations; i++) { - res.add(Optional.empty()); - } - return res; - } - - // not null, check size - if (pageInfos.size() != nCitations) { - throw new IllegalArgumentException("normalizePageInfos: pageInfos.size() != nCitations"); - } - - // not null, normalize elementwise - return OOListUtil.map(pageInfos, PageInfo::normalizePageInfo); - } - public OOText getNormalizedCitationMarker(CitationMarkerNormEntry ce) { return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, ce, Optional.empty()); } @@ -1270,9 +1240,9 @@ protected String getAuthorLastSeparator() { /* As getAuthorLastSeparator, for in-text citation. */ protected String getAuthorLastSeparatorInTextWithFallBack() { - String value1 = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT); - String value2 = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); - return Objects.requireNonNullElse(value1, value2); + String preferred = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT); + String fallback = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); + return Objects.requireNonNullElse(preferred, fallback); } protected String getPageInfoSeparator() { From bed4893ea23675fe6f9bf9a029a4730cb17367aa Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 14:53:20 +0200 Subject: [PATCH 1021/1068] checkstyle --- src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index e21804a2c86..082d94a7fdf 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -1241,7 +1241,7 @@ protected String getAuthorLastSeparator() { /* As getAuthorLastSeparator, for in-text citation. */ protected String getAuthorLastSeparatorInTextWithFallBack() { String preferred = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR_IN_TEXT); - String fallback = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); + String fallback = getStringCitProperty(OOBibStyle.AUTHOR_LAST_SEPARATOR); return Objects.requireNonNullElse(preferred, fallback); } From 73a0a0e03efe38b33ab42fba99a59e8c76b2e33c Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 14:53:34 +0200 Subject: [PATCH 1022/1068] use putIfAbsent --- .../style/OOProcessAuthorYearMarkers.java | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index cbd03cd79c6..896e747913f 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -63,17 +63,10 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup String normCitMarker = OOText.toString(citedKey.getNormalizedCitationMarker().get()); String citationKey = citedKey.citationKey; - if (!normCitMarkerToClachingKeys.containsKey(normCitMarker)) { - // Found new normCitMarker - List clashingKeys = new ArrayList<>(1); - normCitMarkerToClachingKeys.put(normCitMarker, clashingKeys); + List clashingKeys = normCitMarkerToClachingKeys.putIfAbsent(normCitMarker, new ArrayList<>(1)); + if (!clashingKeys.contains(citationKey)) { + // First appearance of citationKey, add to list. clashingKeys.add(citationKey); - } else { - List clashingKeys = normCitMarkerToClachingKeys.get(normCitMarker); - if (!clashingKeys.contains(citationKey)) { - // First appearance of citationKey, add to list. - clashingKeys.add(citationKey); - } } } From 5ecbb9d7c1ccd9fdadccd61139366203e99c73c1 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 14:56:59 +0200 Subject: [PATCH 1023/1068] use "{}" with LOGGER --- .../java/org/jabref/logic/openoffice/style/StyleLoader.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java b/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java index 727db88cbc4..3dbdf766056 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java +++ b/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java @@ -92,9 +92,9 @@ private void loadExternalStyles() { } } catch (FileNotFoundException e) { // The file couldn't be found... should we tell anyone? - LOGGER.info("Cannot find external style file " + filename); + LOGGER.info("Cannot find external style file {}", filename); } catch (IOException e) { - LOGGER.info("Problem reading external style file " + filename, e); + LOGGER.info("Problem reading external style file {}", filename, e); } } } From 7c7e8abef01602bd643f2933946d37245cae7091 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 16:52:37 +0200 Subject: [PATCH 1024/1068] use Objects.hash and Objects.equals in CitationLookupResult --- .../openoffice/style/CitationLookupResult.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java b/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java index 86674583d1c..bfe6dc1debe 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java @@ -24,6 +24,11 @@ public CitationLookupResult(BibEntry entry, BibDatabase database) { * is equivalent to {@code this.database == that.database}. * * Since within each GUI call we use a fixed list of databases, it is OK. + * + * 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) { @@ -34,15 +39,11 @@ public boolean equals(Object otherObject) { return false; } CitationLookupResult that = (CitationLookupResult) otherObject; - return this.entry.equals(that.entry) && this.database.equals(that.database); + return Objects.equals(this.entry, that.entry) && Objects.equals(this.database, that.database); } @Override public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + entry.hashCode(); - result = prime * result + database.hashCode(); - return result; + return Objects.hash(entry, database); } } From 77fbf1eb170767a351cfb0e779ccd5b3a85f9474 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 17:05:17 +0200 Subject: [PATCH 1025/1068] simplified CitedKey.getBibEntry --- src/main/java/org/jabref/model/openoffice/style/CitedKey.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/style/CitedKey.java b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java index 785d828ce7e..5331204bd75 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitedKey.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitedKey.java @@ -52,9 +52,7 @@ public String getCitationKey() { @Override public Optional getBibEntry() { - return (db.isPresent() - ? Optional.of(db.get().entry) - : Optional.empty()); + return db.map(e -> e.entry); } /* From 8a04b8d653614f6a80e09db94996750c590b4c8d Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 18:11:28 +0200 Subject: [PATCH 1026/1068] more use of "{}" in LOGGER --- .../jabref/logic/openoffice/style/StyleLoader.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java b/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java index 3dbdf766056..3098e06233c 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java +++ b/src/main/java/org/jabref/logic/openoffice/style/StyleLoader.java @@ -61,19 +61,19 @@ public boolean addStyleIfValid(String filename) { try { OOBibStyle newStyle = new OOBibStyle(new File(filename), layoutFormatterPreferences, encoding); if (externalStyles.contains(newStyle)) { - LOGGER.info("External style file " + filename + " already existing."); + LOGGER.info("External style file {} already existing.", filename); } else if (newStyle.isValid()) { externalStyles.add(newStyle); storeExternalStyles(); return true; } else { - LOGGER.error(String.format("Style with filename %s is invalid", filename)); + LOGGER.error("Style with filename {} is invalid", filename); } } catch (FileNotFoundException e) { // The file couldn't be found... should we tell anyone? - LOGGER.info("Cannot find external style file " + filename, e); + LOGGER.info("Cannot find external style file {}", filename, e); } catch (IOException e) { - LOGGER.info("Problem reading external style file " + filename, e); + LOGGER.info("Problem reading external style file {}", filename, e); } return false; } @@ -88,7 +88,7 @@ private void loadExternalStyles() { if (style.isValid()) { // Problem! externalStyles.add(style); } else { - LOGGER.error(String.format("Style with filename %s is invalid", filename)); + LOGGER.error("Style with filename {} is invalid", filename); } } catch (FileNotFoundException e) { // The file couldn't be found... should we tell anyone? @@ -105,7 +105,7 @@ private void loadInternalStyles() { try { internalStyles.add(new OOBibStyle(filename, layoutFormatterPreferences)); } catch (IOException e) { - LOGGER.info("Problem reading internal style file " + filename, e); + LOGGER.info("Problem reading internal style file {}", filename, e); } } } From 9efc942dfd29a23c2aeaa02ae0d43f6a57061139 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 18:11:50 +0200 Subject: [PATCH 1027/1068] more use of "{}" in LOGGER --- .../logic/openoffice/backend/NamedRangeReferenceMark.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index 8eae0c922f2..a11e29aecd1 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -195,8 +195,7 @@ public Optional nrGetRawCursor(XTextDocument doc) Optional markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name); if (markAsTextContent.isEmpty()) { - String msg = String.format("nrGetRawCursor: markAsTextContent(%s).isEmpty()", name); - LOGGER.warn(msg); + LOGGER.warn("nrGetRawCursor: markAsTextContent({}).isEmpty()", name); } Optional full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()); @@ -334,7 +333,7 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) alpha.goRight(leftLength, true); LOGGER.debug("nrGetFillCursor: alpha(7) covers '{}', should be '{}'", alpha.getString(), left); omega.goLeft(rightLength, true); - LOGGER.debug("nrGetFillCursor: omega(8) covers '%s', should be '%s'%n", omega.getString(), right); + LOGGER.debug("nrGetFillCursor: omega(8) covers '{}', should be '{}'", omega.getString(), right); } } From 18ee9993d14c4e3a117adcd406da544c3dc36c60 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 18 Jul 2021 18:11:56 +0200 Subject: [PATCH 1028/1068] more use of "{}" in LOGGER --- .../logic/openoffice/frontend/UpdateCitationMarkers.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index ac497c49d8f..bd9b08f44fd 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -59,9 +59,8 @@ public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, OOB Optional marker = cg.getCitationMarker(); if (!marker.isPresent()) { - String msg = String.format("applyNewCitationMarkers: no marker for %s", - cg.cgid.citationGroupIdAsString()); - LOGGER.warn(msg); + LOGGER.warn("applyNewCitationMarkers: no marker for {}", + cg.cgid.citationGroupIdAsString()); continue; } From 4015e8d2d88eb5ad92cf50a2965a5b2d74a78533 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 25 Jul 2021 00:17:31 +0200 Subject: [PATCH 1029/1068] Citation.lookup: use streams --- .../model/openoffice/style/Citation.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/style/Citation.java b/src/main/java/org/jabref/model/openoffice/style/Citation.java index 9b71a1051b2..9b286029310 100644 --- a/src/main/java/org/jabref/model/openoffice/style/Citation.java +++ b/src/main/java/org/jabref/model/openoffice/style/Citation.java @@ -62,14 +62,18 @@ public Optional getBibEntry() { : Optional.empty()); } + public static Optional lookup(BibDatabase database, String key) { + return (database + .getEntryByCitationKey(key) + .map(bibEntry -> new CitationLookupResult(bibEntry, database))); + } + public static Optional lookup(List databases, String key) { - for (BibDatabase database : databases) { - Optional entry = database.getEntryByCitationKey(key); - if (entry.isPresent()) { - return Optional.of(new CitationLookupResult(entry.get(), database)); - } - } - return Optional.empty(); + return (databases.stream() + .map(database -> Citation.lookup(database, key)) + .filter(Optional::isPresent) + .findFirst() + .orElse(Optional.empty())); } public void lookupInDatabases(List databases) { From 8396620fabf4a8099dbbad739afbf19a3a1d71cc Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 25 Jul 2021 01:00:26 +0200 Subject: [PATCH 1030/1068] Citation.lookup: Optional::get before findFirst --- src/main/java/org/jabref/model/openoffice/style/Citation.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/style/Citation.java b/src/main/java/org/jabref/model/openoffice/style/Citation.java index 9b286029310..7bae4fd2548 100644 --- a/src/main/java/org/jabref/model/openoffice/style/Citation.java +++ b/src/main/java/org/jabref/model/openoffice/style/Citation.java @@ -72,8 +72,8 @@ public static Optional lookup(List databases, return (databases.stream() .map(database -> Citation.lookup(database, key)) .filter(Optional::isPresent) - .findFirst() - .orElse(Optional.empty())); + .map(Optional::get) + .findFirst()); } public void lookupInDatabases(List databases) { From 163394cb2c7e21df221ead711002f4c44d61e187 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 2 Aug 2021 13:31:59 +0200 Subject: [PATCH 1031/1068] removed catch RuntimeException around UnoCursor.getViewCursor Apparently cannot throw here. NoDocumentException is caught elsewhere, before we get here. com.sun.star.uno.RuntimeException is caught below, for cursor.getStart(); --- src/main/java/org/jabref/gui/openoffice/OOBibBase2.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index 48079ba5760..9be63f27538 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -196,15 +196,8 @@ final boolean testDialog(String title, OOVoidResult... results) { */ OOResult getUserCursorForTextInsertion(XTextDocument doc, String title) { - XTextCursor cursor; // Get the cursor positioned by the user. - try { - cursor = UnoCursor.getViewCursor(doc).orElse(null); - } catch (RuntimeException ex) { - return OOResult.error(new OOError(title, - Localization.lang("Could not get the cursor."), - ex)); - } + XTextCursor cursor = UnoCursor.getViewCursor(doc).orElse(null); // Check for crippled XTextViewCursor Objects.requireNonNull(cursor); From 6297879d3f1402b235d1795f453f8e80dd2ea0db Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 2 Aug 2021 14:16:37 +0200 Subject: [PATCH 1032/1068] drop unused message --- src/main/resources/l10n/JabRef_en.properties | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index ba0c601df21..431a2fc0a71 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1565,7 +1565,6 @@ Custom=Custom Export\ cited=Export cited Unable\ to\ generate\ new\ library=Unable to generate new library -Could\ not\ get\ the\ cursor.=Could not get the cursor. The\ cursor\ is\ in\ protected\ area.=The cursor is in protected area. JabRefException=JabRefException No\ bibliography\ database\ is\ open\ for\ citation.=No bibliography database is open for citation. From 8e4b2e2f53d26e98a71821eadcab692914dd4406 Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 2 Aug 2021 16:25:40 +0200 Subject: [PATCH 1033/1068] putIfAbsent returns null for new entry --- .../logic/openoffice/style/OOProcessAuthorYearMarkers.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index 896e747913f..306c0111a22 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -64,6 +64,9 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup String citationKey = citedKey.citationKey; List clashingKeys = normCitMarkerToClachingKeys.putIfAbsent(normCitMarker, new ArrayList<>(1)); + if (clashingKeys == null) { + clashingKeys = normCitMarkerToClachingKeys.get(normCitMarker); + } if (!clashingKeys.contains(citationKey)) { // First appearance of citationKey, add to list. clashingKeys.add(citationKey); From c5613e6ea4158926f4a82bf165456c53a79b3a17 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 3 Aug 2021 15:40:03 +0200 Subject: [PATCH 1034/1068] What is 52 in Backend52 --- .../java/org/jabref/logic/openoffice/backend/Backend52.java | 5 +++++ .../java/org/jabref/logic/openoffice/backend/Codec52.java | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 878571090f0..ddcedf42d98 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -36,6 +36,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * Backend52, Codec52 and OODataModel.JabRef52 refer to the mode of storage, encoding and + * what-is-stored in the document under JabRef version 5.2. These basically did not change up to + * JabRef 5.4. + */ public class Backend52 { private static final Logger LOGGER = LoggerFactory.getLogger(Backend52.class); public final OODataModel dataModel; diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index f6d2b12245e..ac563be66b4 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -12,7 +12,7 @@ import org.jabref.model.openoffice.style.CitationType; /** - * How and what is encoded in a mark names. + * How and what is encoded in reference mark names under JabRef 5.2. * * - pageInfo does not appear here. It is not encoded in the mark name. */ From e7675e2f95508ccd5fc34e605025f4f72d16b6ee Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 18 Aug 2021 11:40:59 +0200 Subject: [PATCH 1035/1068] using orElseThrow --- .../org/jabref/logic/openoffice/backend/Backend52.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index ddcedf42d98..5c9d362edd3 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -138,11 +138,10 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str NoDocumentException { Optional optionalParsed = Codec52.parseMarkName(refMarkName); - if (optionalParsed.isEmpty()) { + Codec52.ParsedMarkName parsed = optionalParsed.orElseThrow( throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" - + " found unparsable referenceMarkName"); - } - Codec52.ParsedMarkName parsed = optionalParsed.get(); + + " found unparsable referenceMarkName")); + List citations = (parsed.citationKeys.stream() .map(Citation::new) .collect(Collectors.toList())); From ddb3c78d6cd14ad037a237071a1e1170820b8fa8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 18 Aug 2021 11:41:19 +0200 Subject: [PATCH 1036/1068] using StringBuilder --- .../jabref/logic/openoffice/backend/Backend52.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 5c9d362edd3..8b6cd0b1538 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -1,5 +1,6 @@ package org.jabref.logic.openoffice.backend; +import java.lang.StringBuilder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -106,11 +107,11 @@ public Optional healthReport(XTextDocument doc) if (pageInfoThrash.isEmpty()) { return Optional.empty(); // "Backend52: found no unused pageInfo data"; } - String msg = - "Backend52: found unused pageInfo data, with names listed below.\n" - + "In LibreOffice you may remove these in [File]/[Properties]/[Custom Properties]\n"; - msg += "" + String.join("\n", pageInfoThrash) + ""; - return Optional.of(msg); + + StringBuilder msg = new StringBuilder("Backend52: found unused pageInfo data, with names listed below.\n"); + msg.append("In LibreOffice you may remove these in [File]/[Properties]/[Custom Properties]\n"); + msg.append(String.join("\n", pageInfoThrash)); + return Optional.of(msg.toString()); } private static void setPageInfoInDataInitial(List citations, Optional pageInfo) { From 364dac56661ee7ceb3842aa401ad53f333e752de Mon Sep 17 00:00:00 2001 From: Antal K Date: Wed, 18 Aug 2021 12:14:22 +0200 Subject: [PATCH 1037/1068] refMarkName renamed to markName --- .../logic/openoffice/backend/Backend52.java | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 8b6cd0b1538..230cbd198cd 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -130,42 +130,41 @@ private static Optional getPageInfoFromData(CitationGroup cg) { } /** - * We have circular dependency here: backend uses - * class from ... + * @param markName Reference mark name */ - public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, String refMarkName) + public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, String markName) throws WrappedTargetException, NoDocumentException { - Optional optionalParsed = Codec52.parseMarkName(refMarkName); + Optional optionalParsed = Codec52.parseMarkName(markName); Codec52.ParsedMarkName parsed = optionalParsed.orElseThrow( throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" - + " found unparsable referenceMarkName")); + + " found unparsable reference mark name")); List citations = (parsed.citationKeys.stream() .map(Citation::new) .collect(Collectors.toList())); - Optional pageInfo = (UnoUserDefinedProperty.getStringValue(doc, refMarkName) + Optional pageInfo = (UnoUserDefinedProperty.getStringValue(doc, markName) .map(OOText::fromString)); pageInfo = PageInfo.normalizePageInfo(pageInfo); setPageInfoInDataInitial(citations, pageInfo); - Optional namedRange = citationStorageManager.nrmGetFromDocument(doc, refMarkName); + Optional namedRange = citationStorageManager.nrmGetFromDocument(doc, markName); if (namedRange.isEmpty()) { throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" - + " referenceMarkName is not in the document"); + + " reference mark name is not in the document"); } - CitationGroupId cgid = new CitationGroupId(refMarkName); + CitationGroupId cgid = new CitationGroupId(markName); CitationGroup cg = new CitationGroup(OODataModel.JabRef52, cgid, parsed.citationType, citations, - Optional.of(refMarkName)); + Optional.of(markName)); this.cgidToNamedRange.put(cgid, namedRange.get()); return cg; } From 3c6ef9853d3f92a571dcc2bd1359fd509dca2489 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 12:12:27 +0200 Subject: [PATCH 1038/1068] import StringBuilder is not needed --- src/main/java/org/jabref/logic/openoffice/backend/Backend52.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 230cbd198cd..1e9cafcff13 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -1,6 +1,5 @@ package org.jabref.logic.openoffice.backend; -import java.lang.StringBuilder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; From 4ca55aa78045306403be90a4e6372f9ad6ca09cc Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 12:13:28 +0200 Subject: [PATCH 1039/1068] orElseThrow correction (now without message) --- .../jabref/logic/openoffice/backend/Backend52.java | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 1e9cafcff13..057ddc43a41 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -136,10 +136,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str WrappedTargetException, NoDocumentException { - Optional optionalParsed = Codec52.parseMarkName(markName); - Codec52.ParsedMarkName parsed = optionalParsed.orElseThrow( - throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" - + " found unparsable reference mark name")); + Codec52.ParsedMarkName parsed = Codec52.parseMarkName(markName).orElseThrow(IllegalArgumentException::new); List citations = (parsed.citationKeys.stream() .map(Citation::new) @@ -151,12 +148,8 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str setPageInfoInDataInitial(citations, pageInfo); - Optional namedRange = citationStorageManager.nrmGetFromDocument(doc, markName); - - if (namedRange.isEmpty()) { - throw new IllegalArgumentException("readCitationGroupFromDocumentOrThrow:" - + " reference mark name is not in the document"); - } + Optional namedRange = (citationStorageManager.nrmGetFromDocument(doc, markName) + .orElseThrow(IllegalArgumentException::new)); CitationGroupId cgid = new CitationGroupId(markName); CitationGroup cg = new CitationGroup(OODataModel.JabRef52, From 7ace25ffb9a6cc8fee72a2daf2428305c193c5a5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 12:15:21 +0200 Subject: [PATCH 1040/1068] renamed cgid to groupId --- docs/openoffice/code-reorganization.md | 2 +- .../logic/openoffice/backend/Backend52.java | 18 ++++++++--------- .../logic/openoffice/frontend/OOFrontend.java | 8 ++++---- .../frontend/UpdateCitationMarkers.java | 2 +- .../style/OOFormatBibliography.java | 4 ++-- .../model/openoffice/style/CitationGroup.java | 6 +++--- .../openoffice/style/CitationGroups.java | 20 +++++++++---------- 7 files changed, 30 insertions(+), 30 deletions(-) diff --git a/docs/openoffice/code-reorganization.md b/docs/openoffice/code-reorganization.md index a9d45418690..35c3159a325 100644 --- a/docs/openoffice/code-reorganization.md +++ b/docs/openoffice/code-reorganization.md @@ -69,7 +69,7 @@ At the core, - each may have a `pageInfo` - A citation group (`CitationGroup`) has - a list of citations (`citationsInStorageOrder`) - - an identifier `CitationGroupId cgid` + - an identifier `CitationGroupId groupId` - this allows to refer to the group - also used to associate the group to its citation markers location (outside the style part, in [Backend](https://github.com/antalk2/jabref/blob/fed0952cbdaf7a76bcb09b3db5ac48f34f5ca388/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java#L46)) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 057ddc43a41..a75c4850c29 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -151,13 +151,13 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str Optional namedRange = (citationStorageManager.nrmGetFromDocument(doc, markName) .orElseThrow(IllegalArgumentException::new)); - CitationGroupId cgid = new CitationGroupId(markName); + CitationGroupId groupId = new CitationGroupId(markName); CitationGroup cg = new CitationGroup(OODataModel.JabRef52, - cgid, + groupId, parsed.citationType, citations, Optional.of(markName)); - this.cgidToNamedRange.put(cgid, namedRange.get()); + this.cgidToNamedRange.put(groupId, namedRange.get()); return cg; } @@ -195,7 +195,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, String xkey = (citationKeys.stream().collect(Collectors.joining(","))); String refMarkName = Codec52.getUniqueMarkName(usedNames, xkey, citationType); - CitationGroupId cgid = new CitationGroupId(refMarkName); + CitationGroupId groupId = new CitationGroupId(refMarkName); final int nCitations = citationKeys.size(); final int last = nCitations - 1; @@ -246,10 +246,10 @@ public CitationGroup createCitationGroup(XTextDocument doc, UnoUserDefinedProperty.removeIfExists(doc, refMarkName); } CitationGroup cg = new CitationGroup(OODataModel.JabRef52, - cgid, + groupId, citationType, citations, Optional.of(refMarkName)); - this.cgidToNamedRange.put(cgid, namedRange); + this.cgidToNamedRange.put(groupId, namedRange); return cg; default: throw new IllegalStateException("Backend52 requires JabRef52 dataModel"); @@ -303,7 +303,7 @@ public List> combinePageInfos(List joinableGroup } private NamedRange getNamedRangeOrThrow(CitationGroup cg) { - NamedRange namedRange = this.cgidToNamedRange.get(cg.cgid); + NamedRange namedRange = this.cgidToNamedRange.get(cg.groupId); if (namedRange == null) { throw new IllegalStateException("getNamedRange: could not lookup namedRange"); } @@ -319,7 +319,7 @@ public void removeCitationGroup(CitationGroup cg, XTextDocument doc) String refMarkName = namedRange.nrGetRangeName(); namedRange.nrRemoveFromDocument(doc); UnoUserDefinedProperty.removeIfExists(doc, refMarkName); - this.cgidToNamedRange.remove(cg.cgid); + this.cgidToNamedRange.remove(cg.groupId); } /** @@ -379,7 +379,7 @@ public List getCitationEntries(XTextDocument doc, CitationGroups // For DataModel.JabRef60 (Backend60) we need one context per Citation List citations = new ArrayList<>(cgs.numberOfCitationGroups()); for (CitationGroup cg : cgs.getCitationGroupsUnordered()) { - String name = cg.cgid.citationGroupIdAsString(); + String name = cg.groupId.citationGroupIdAsString(); XTextCursor cursor = (this .getRawCursorForCitationGroup(cg, doc) .orElseThrow(IllegalStateException::new)); diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index bd587bf9210..2638da6471b 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -83,7 +83,7 @@ public Optional healthReport(XTextDocument doc) Map citationGroups = new HashMap<>(); for (String name : citationGroupNames) { CitationGroup cg = backend.readCitationGroupFromDocumentOrThrow(doc, name); - citationGroups.put(cg.cgid, cg); + citationGroups.put(cg.groupId, cg); } return citationGroups; } @@ -318,9 +318,9 @@ public List> citationRanges(XTextDocument for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { XTextRange range = this.getMarkRange(doc, cg).orElseThrow(IllegalStateException::new); - String description = cg.cgid.citationGroupIdAsString(); + String description = cg.groupId.citationGroupIdAsString(); result.add(new RangeForOverlapCheck<>(range, - cg.cgid, + cg.groupId, RangeForOverlapCheck.REFERENCE_MARK_KIND, description)); } @@ -549,7 +549,7 @@ public void imposeGlobalOrder(XTextDocument doc, FunctionalTextViewCursor fcurso boolean mapFootnotesToFootnoteMarks = true; List sortedCitationGroups = getVisuallySortedCitationGroups(doc, mapFootnotesToFootnoteMarks, fcursor); - List sortedCitationGroupIds = OOListUtil.map(sortedCitationGroups, cg -> cg.cgid); + List sortedCitationGroupIds = OOListUtil.map(sortedCitationGroups, cg -> cg.groupId); citationGroups.setGlobalOrder(sortedCitationGroupIds); } } diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index bd9b08f44fd..b94e7c957a4 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -60,7 +60,7 @@ public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, OOB if (!marker.isPresent()) { LOGGER.warn("applyNewCitationMarkers: no marker for {}", - cg.cgid.citationGroupIdAsString()); + cg.groupId.citationGroupIdAsString()); continue; } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index 6c22c8abb09..eb2de1359ad 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -168,8 +168,8 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { List citationGroups = new ArrayList<>(); for (CitationPath p : ck.getCitationPaths()) { - CitationGroupId cgid = p.group; - Optional cg = cgs.getCitationGroup(cgid); + CitationGroupId groupId = p.group; + Optional cg = cgs.getCitationGroup(groupId); if (cg.isEmpty()) { throw new IllegalStateException(); } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java index 3b9021eb73f..90afb872d4f 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroup.java @@ -19,7 +19,7 @@ public class CitationGroup { /* * Identifies this citation group. */ - public final CitationGroupId cgid; + public final CitationGroupId groupId; /* * The core data, stored in the document: @@ -60,12 +60,12 @@ public class CitationGroup { private Optional citationMarker; public CitationGroup(OODataModel dataModel, - CitationGroupId cgid, + CitationGroupId groupId, CitationType citationType, List citationsInStorageOrder, Optional referenceMarkNameForLinking) { this.dataModel = dataModel; - this.cgid = cgid; + this.groupId = groupId; this.citationType = citationType; this.citationsInStorageOrder = Collections.unmodifiableList(citationsInStorageOrder); this.localOrder = OOListUtil.makeIndices(citationsInStorageOrder.size()); diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index 0bfe4a832d0..f49f38b542f 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -114,7 +114,7 @@ public List getCitationGroupsInGlobalOrder() { if (globalOrder.isEmpty()) { throw new IllegalStateException("getCitationGroupsInGlobalOrder: not ordered yet"); } - return OOListUtil.map(globalOrder.get(), cgid -> citationGroupsUnordered.get(cgid)); + return OOListUtil.map(globalOrder.get(), groupId -> citationGroupsUnordered.get(groupId)); } /** @@ -132,8 +132,8 @@ public void setGlobalOrder(List globalOrder) { // Propagate to each CitationGroup int i = 0; - for (CitationGroupId cgid : globalOrder) { - citationGroupsUnordered.get(cgid).setIndexInGlobalOrder(Optional.of(i)); + for (CitationGroupId groupId : globalOrder) { + citationGroupsUnordered.get(groupId).setIndexInGlobalOrder(Optional.of(i)); i++; } } @@ -161,7 +161,7 @@ public CitedKeys getCitedKeysUnordered() { int storageIndexInGroup = 0; for (Citation cit : cg.citationsInStorageOrder) { String key = cit.citationKey; - CitationPath path = new CitationPath(cg.cgid, storageIndexInGroup); + CitationPath path = new CitationPath(cg.groupId, storageIndexInGroup); if (res.containsKey(key)) { res.get(key).addPath(path, cit); } else { @@ -185,7 +185,7 @@ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { for (int i : cg.getLocalOrder()) { Citation cit = cg.citationsInStorageOrder.get(i); String citationKey = cit.citationKey; - CitationPath path = new CitationPath(cg.cgid, i); + CitationPath path = new CitationPath(cg.groupId, i); if (res.containsKey(citationKey)) { res.get(citationKey).addPath(path, cit); } else { @@ -257,8 +257,8 @@ public void createNumberedBibliographySortedByComparator(Comparator en * Query by CitationGroupId */ - public Optional getCitationGroup(CitationGroupId cgid) { - CitationGroup cg = citationGroupsUnordered.get(cgid); + public Optional getCitationGroup(CitationGroupId groupId) { + CitationGroup cg = citationGroupsUnordered.get(groupId); return Optional.ofNullable(cg); } @@ -279,15 +279,15 @@ public boolean citationGroupsProvideReferenceMarkNameForLinking() { */ public void afterCreateCitationGroup(CitationGroup cg) { - citationGroupsUnordered.put(cg.cgid, cg); + citationGroupsUnordered.put(cg.groupId, cg); globalOrder = Optional.empty(); bibliography = Optional.empty(); } public void afterRemoveCitationGroup(CitationGroup cg) { - citationGroupsUnordered.remove(cg.cgid); - globalOrder.map(l -> l.remove(cg.cgid)); + citationGroupsUnordered.remove(cg.groupId); + globalOrder.map(l -> l.remove(cg.groupId)); bibliography = Optional.empty(); } From 1a0a99147f9b8661f6ca04bba174620933c4abae Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 12:31:38 +0200 Subject: [PATCH 1041/1068] orElseThrow correction --- .../java/org/jabref/logic/openoffice/backend/Backend52.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index a75c4850c29..22d0e5e4e2d 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -148,8 +148,8 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str setPageInfoInDataInitial(citations, pageInfo); - Optional namedRange = (citationStorageManager.nrmGetFromDocument(doc, markName) - .orElseThrow(IllegalArgumentException::new)); + NamedRange namedRange = (citationStorageManager.nrmGetFromDocument(doc, markName) + .orElseThrow(IllegalArgumentException::new)); CitationGroupId groupId = new CitationGroupId(markName); CitationGroup cg = new CitationGroup(OODataModel.JabRef52, @@ -157,8 +157,8 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str parsed.citationType, citations, Optional.of(markName)); - this.cgidToNamedRange.put(groupId, namedRange.get()); return cg; + this.cgidToNamedRange.put(groupId, namedRange); } /** From cd67df5279b23e2cd8b1ff0753fce0938c7a16d5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 12:45:16 +0200 Subject: [PATCH 1042/1068] renamed cg to group --- .../logic/openoffice/action/EditMerge.java | 36 +++++----- .../logic/openoffice/action/EditSeparate.java | 10 +-- .../logic/openoffice/backend/Backend52.java | 66 +++++++++---------- .../logic/openoffice/frontend/OOFrontend.java | 62 ++++++++--------- .../frontend/UpdateCitationMarkers.java | 28 ++++---- .../style/OOFormatBibliography.java | 10 +-- .../style/OOProcessAuthorYearMarkers.java | 12 ++-- .../style/OOProcessCitationKeyMarkers.java | 6 +- .../style/OOProcessNumericMarkers.java | 6 +- .../openoffice/style/CitationGroups.java | 46 ++++++------- 10 files changed, 141 insertions(+), 141 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index ac5de38551f..43bdcd59e2d 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -62,7 +62,7 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBi List cgs = joinableGroupData.group; List newCitations = (cgs.stream() - .flatMap(cg -> cg.citationsInStorageOrder.stream()) + .flatMap(group -> group.citationsInStorageOrder.stream()) .collect(Collectors.toList())); CitationType citationType = cgs.get(0).citationType; @@ -145,15 +145,15 @@ void reset() { } /** - * Decide if cg could be added to state.currentGroup + * Decide if group could be added to state.currentGroup * - * @param cg The CitationGroup to test - * @param currentRange The XTextRange corresponding to cg. + * @param group The CitationGroup to test + * @param currentRange The XTextRange corresponding to group. * * @return false if cannot add, true if can. If returned true, then state.cursorBetween and * state.currentGroupCursor are expanded to end at the start of currentRange. */ - private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextRange currentRange) { + private static boolean checkAddToGroup(ScanState state, CitationGroup group, XTextRange currentRange) { if (state.currentGroup.isEmpty()) { return false; @@ -165,14 +165,14 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR Objects.requireNonNull(state.prevRange); // Only combine (Author 2000) type citations - if (cg.citationType != CitationType.AUTHORYEAR_PAR) { + if (group.citationType != CitationType.AUTHORYEAR_PAR) { return false; } if (state.prev != null) { // Even if we combine AUTHORYEAR_INTEXT citations, we would not mix them with AUTHORYEAR_PAR - if (cg.citationType != state.prev.citationType) { + if (group.citationType != state.prev.citationType) { return false; } @@ -247,12 +247,12 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup cg, XTextR } /** - * Add cg to state.currentGroup + * Add group to state.currentGroup * Set state.cursorBetween to start at currentRange.getEnd() * Expand state.currentGroupCursor to also cover currentRange - * Set state.prev to cg, state.prevRange to currentRange + * Set state.prev to group, state.prevRange to currentRange */ - private static void addToCurrentGroup(ScanState state, CitationGroup cg, XTextRange currentRange) { + private static void addToCurrentGroup(ScanState state, CitationGroup group, XTextRange currentRange) { final boolean isNewGroup = state.currentGroup.isEmpty(); if (!isNewGroup) { Objects.requireNonNull(state.currentGroupCursor); @@ -262,7 +262,7 @@ private static void addToCurrentGroup(ScanState state, CitationGroup cg, XTextRa } // Add the current entry to a group. - state.currentGroup.add(cg); + state.currentGroup.add(group); // Set up cursorBetween to start at currentRange.getEnd() XTextRange rangeEnd = currentRange.getEnd(); @@ -283,7 +283,7 @@ private static void addToCurrentGroup(ScanState state, CitationGroup cg, XTextRa } /* Store data about last entry in currentGroup */ - state.prev = cg; + state.prev = group; state.prevRange = currentRange; } @@ -303,22 +303,22 @@ private static List scan(XTextDocument doc, OOFrontend fr) ScanState state = new ScanState(); - for (CitationGroup cg : cgs) { + for (CitationGroup group : cgs) { - XTextRange currentRange = (fr.getMarkRange(doc, cg) + XTextRange currentRange = (fr.getMarkRange(doc, group) .orElseThrow(IllegalStateException::new)); /* - * Decide if we add cg to the group. False when the group is empty. + * Decide if we add group to the group. False when the group is empty. */ - boolean addToGroup = checkAddToGroup(state, cg, currentRange); + boolean addToGroup = checkAddToGroup(state, group, currentRange); /* * Even if we do not add it to an existing group, we might use it to start a new group. * * Can it start a new group? */ - boolean canStartGroup = (cg.citationType == CitationType.AUTHORYEAR_PAR); + boolean canStartGroup = (group.citationType == CitationType.AUTHORYEAR_PAR); if (!addToGroup) { // close currentGroup @@ -330,7 +330,7 @@ private static List scan(XTextDocument doc, OOFrontend fr) } if (addToGroup || canStartGroup) { - addToCurrentGroup(state, cg, currentRange); + addToCurrentGroup(state, group, currentRange); } } diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index 19e9e756d1b..fba50a93c6e 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -55,19 +55,19 @@ public static boolean separateCitations(XTextDocument doc, try { UnoScreenRefresh.lockControllers(doc); - for (CitationGroup cg : cgs) { + for (CitationGroup group : cgs) { XTextRange range1 = (fr - .getMarkRange(doc, cg) + .getMarkRange(doc, group) .orElseThrow(IllegalStateException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); - List cits = cg.citationsInStorageOrder; + List cits = group.citationsInStorageOrder; if (cits.size() <= 1) { continue; } - fr.removeCitationGroup(cg, doc); + fr.removeCitationGroup(group, doc); // Now we own the content of cits // Create a citation group for each citation. @@ -80,7 +80,7 @@ public static boolean separateCitations(XTextDocument doc, doc, List.of(cit.citationKey), List.of(cit.getPageInfo()), - cg.citationType, + group.citationType, OOText.fromString(cit.citationKey), textCursor, style, diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 22d0e5e4e2d..3e91d2bb173 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -120,8 +120,8 @@ private static void setPageInfoInDataInitial(List citations, Optional< } } - private static Optional getPageInfoFromData(CitationGroup cg) { - List citations = cg.getCitationsInLocalOrder(); + private static Optional getPageInfoFromData(CitationGroup group) { + List citations = group.getCitationsInLocalOrder(); if (citations.isEmpty()) { return Optional.empty(); } @@ -152,13 +152,13 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str .orElseThrow(IllegalArgumentException::new)); CitationGroupId groupId = new CitationGroupId(markName); - CitationGroup cg = new CitationGroup(OODataModel.JabRef52, - groupId, - parsed.citationType, - citations, - Optional.of(markName)); - return cg; + CitationGroup group = new CitationGroup(OODataModel.JabRef52, + groupId, + parsed.citationType, + citations, + Optional.of(markName)); this.cgidToNamedRange.put(groupId, namedRange); + return group; } /** @@ -245,12 +245,12 @@ public CitationGroup createCitationGroup(XTextDocument doc, // do not inherit from trash UnoUserDefinedProperty.removeIfExists(doc, refMarkName); } - CitationGroup cg = new CitationGroup(OODataModel.JabRef52, - groupId, - citationType, citations, - Optional.of(refMarkName)); + CitationGroup group = new CitationGroup(OODataModel.JabRef52, + groupId, + citationType, citations, + Optional.of(refMarkName)); this.cgidToNamedRange.put(groupId, namedRange); - return cg; + return group; default: throw new IllegalStateException("Backend52 requires JabRef52 dataModel"); } @@ -287,8 +287,8 @@ public CitationGroup createCitationGroup(XTextDocument doc, case JabRef60: return (joinableGroup.stream() - .flatMap(cg -> (cg.citationsInStorageOrder.stream() - .map(Citation::getPageInfo))) + .flatMap(group -> (group.citationsInStorageOrder.stream() + .map(Citation::getPageInfo))) .collect(Collectors.toList())); default: throw new IllegalArgumentException("unhandled dataModel here"); @@ -302,35 +302,35 @@ public List> combinePageInfos(List joinableGroup return combinePageInfosCommon(this.dataModel, joinableGroup); } - private NamedRange getNamedRangeOrThrow(CitationGroup cg) { - NamedRange namedRange = this.cgidToNamedRange.get(cg.groupId); + private NamedRange getNamedRangeOrThrow(CitationGroup group) { + NamedRange namedRange = this.cgidToNamedRange.get(group.groupId); if (namedRange == null) { throw new IllegalStateException("getNamedRange: could not lookup namedRange"); } return namedRange; } - public void removeCitationGroup(CitationGroup cg, XTextDocument doc) + public void removeCitationGroup(CitationGroup group, XTextDocument doc) throws WrappedTargetException, NoDocumentException, NotRemoveableException { - NamedRange namedRange = getNamedRangeOrThrow(cg); + NamedRange namedRange = getNamedRangeOrThrow(group); String refMarkName = namedRange.nrGetRangeName(); namedRange.nrRemoveFromDocument(doc); UnoUserDefinedProperty.removeIfExists(doc, refMarkName); - this.cgidToNamedRange.remove(cg.groupId); + this.cgidToNamedRange.remove(group.groupId); } /** * @return Optional.empty if the reference mark is missing. */ - public Optional getMarkRange(CitationGroup cg, XTextDocument doc) + public Optional getMarkRange(CitationGroup group, XTextDocument doc) throws NoDocumentException, WrappedTargetException { - NamedRange namedRange = getNamedRangeOrThrow(cg); + NamedRange namedRange = getNamedRangeOrThrow(group); return namedRange.nrGetMarkRange(doc); } @@ -338,33 +338,33 @@ public Optional getMarkRange(CitationGroup cg, XTextDocument doc) * Cursor for the reference marks as is: not prepared for filling, but does not need * cleanFillCursorForCitationGroup either. */ - public Optional getRawCursorForCitationGroup(CitationGroup cg, XTextDocument doc) + public Optional getRawCursorForCitationGroup(CitationGroup group, XTextDocument doc) throws NoDocumentException, WrappedTargetException { - NamedRange namedRange = getNamedRangeOrThrow(cg); + NamedRange namedRange = getNamedRangeOrThrow(group); return namedRange.nrGetRawCursor(doc); } /** * Must be followed by call to cleanFillCursorForCitationGroup */ - public XTextCursor getFillCursorForCitationGroup(CitationGroup cg, XTextDocument doc) + public XTextCursor getFillCursorForCitationGroup(CitationGroup group, XTextDocument doc) throws NoDocumentException, WrappedTargetException, CreationException { - NamedRange namedRange = getNamedRangeOrThrow(cg); + NamedRange namedRange = getNamedRangeOrThrow(group); return namedRange.nrGetFillCursor(doc); } /** To be called after getFillCursorForCitationGroup */ - public void cleanFillCursorForCitationGroup(CitationGroup cg, XTextDocument doc) + public void cleanFillCursorForCitationGroup(CitationGroup group, XTextDocument doc) throws NoDocumentException, WrappedTargetException { - NamedRange namedRange = getNamedRangeOrThrow(cg); + NamedRange namedRange = getNamedRangeOrThrow(group); namedRange.nrCleanFillCursor(doc); } @@ -378,14 +378,14 @@ public List getCitationEntries(XTextDocument doc, CitationGroups // One context per CitationGroup: Backend52 (DataModel.JabRef52) // For DataModel.JabRef60 (Backend60) we need one context per Citation List citations = new ArrayList<>(cgs.numberOfCitationGroups()); - for (CitationGroup cg : cgs.getCitationGroupsUnordered()) { - String name = cg.groupId.citationGroupIdAsString(); + for (CitationGroup group : cgs.getCitationGroupsUnordered()) { + String name = group.groupId.citationGroupIdAsString(); XTextCursor cursor = (this - .getRawCursorForCitationGroup(cg, doc) + .getRawCursorForCitationGroup(group, doc) .orElseThrow(IllegalStateException::new)); String context = GetContext.getCursorStringWithContext(cursor, 30, 30, true); - Optional pageInfo = (cg.numberOfCitations() > 0 - ? (getPageInfoFromData(cg) + Optional pageInfo = (group.numberOfCitations() > 0 + ? (getPageInfoFromData(group) .map(e -> OOText.toString(e))) : Optional.empty()); CitationEntry entry = new CitationEntry(name, context, pageInfo); diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 2638da6471b..3cf5e901abe 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -82,8 +82,8 @@ public Optional healthReport(XTextDocument doc) Map citationGroups = new HashMap<>(); for (String name : citationGroupNames) { - CitationGroup cg = backend.readCitationGroupFromDocumentOrThrow(doc, name); - citationGroups.put(cg.groupId, cg); + CitationGroup group = backend.readCitationGroupFromDocumentOrThrow(doc, name); + citationGroups.put(group.groupId, group); } return citationGroups; } @@ -111,11 +111,11 @@ public Optional healthReport(XTextDocument doc) WrappedTargetException { List> sortables = new ArrayList<>(); - for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { + for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) { XTextRange range = (this - .getMarkRange(doc, cg) + .getMarkRange(doc, group) .orElseThrow(IllegalStateException::new)); - sortables.add(new RangeSortEntry<>(range, 0, cg)); + sortables.add(new RangeSortEntry<>(range, 0, group)); } /* @@ -236,28 +236,28 @@ public CitationGroup createCitationGroup(XTextDocument doc, if (pageInfos.size() != citationKeys.size()) { throw new IllegalArgumentException("pageInfos.size != citationKeys.size"); } - CitationGroup cg = backend.createCitationGroup(doc, - citationKeys, - pageInfos, - citationType, - position, - insertSpaceAfter); - - this.citationGroups.afterCreateCitationGroup(cg); - return cg; + CitationGroup group = backend.createCitationGroup(doc, + citationKeys, + pageInfos, + citationType, + position, + insertSpaceAfter); + + this.citationGroups.afterCreateCitationGroup(group); + return group; } /** - * Remove {@code cg} both from the document and notify {@code citationGroups} + * Remove {@code group} both from the document and notify {@code citationGroups} */ - public void removeCitationGroup(CitationGroup cg, XTextDocument doc) + public void removeCitationGroup(CitationGroup group, XTextDocument doc) throws WrappedTargetException, NoDocumentException, NotRemoveableException { - backend.removeCitationGroup(cg, doc); - this.citationGroups.afterRemoveCitationGroup(cg); + backend.removeCitationGroup(group, doc); + this.citationGroups.afterRemoveCitationGroup(group); } public void removeCitationGroups(List cgs, XTextDocument doc) @@ -266,8 +266,8 @@ public void removeCitationGroups(List cgs, XTextDocument doc) NoDocumentException, NotRemoveableException { - for (CitationGroup cg : cgs) { - removeCitationGroup(cg, doc); + for (CitationGroup group : cgs) { + removeCitationGroup(group, doc); } } @@ -277,30 +277,30 @@ public void removeCitationGroups(List cgs, XTextDocument doc) * @return Optional.empty() if the reference mark is missing. * */ - public Optional getMarkRange(XTextDocument doc, CitationGroup cg) + public Optional getMarkRange(XTextDocument doc, CitationGroup group) throws NoDocumentException, WrappedTargetException { - return backend.getMarkRange(cg, doc); + return backend.getMarkRange(group, doc); } - public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGroup cg) + public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGroup group) throws NoDocumentException, WrappedTargetException, CreationException { - return backend.getFillCursorForCitationGroup(cg, doc); + return backend.getFillCursorForCitationGroup(group, doc); } /** * Remove brackets added by getFillCursorForCitationGroup. */ - public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroup cg) + public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroup group) throws NoDocumentException, WrappedTargetException { - backend.cleanFillCursorForCitationGroup(cg, doc); + backend.cleanFillCursorForCitationGroup(group, doc); } /** @@ -316,11 +316,11 @@ public List> citationRanges(XTextDocument List> result = new ArrayList<>(citationGroups.numberOfCitationGroups()); - for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { - XTextRange range = this.getMarkRange(doc, cg).orElseThrow(IllegalStateException::new); - String description = cg.groupId.citationGroupIdAsString(); + for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) { + XTextRange range = this.getMarkRange(doc, group).orElseThrow(IllegalStateException::new); + String description = group.groupId.citationGroupIdAsString(); result.add(new RangeForOverlapCheck<>(range, - cg.groupId, + group.groupId, RangeForOverlapCheck.REFERENCE_MARK_KIND, description)); } @@ -549,7 +549,7 @@ public void imposeGlobalOrder(XTextDocument doc, FunctionalTextViewCursor fcurso boolean mapFootnotesToFootnoteMarks = true; List sortedCitationGroups = getVisuallySortedCitationGroups(doc, mapFootnotesToFootnoteMarks, fcursor); - List sortedCitationGroupIds = OOListUtil.map(sortedCitationGroups, cg -> cg.groupId); + List sortedCitationGroupIds = OOListUtil.map(sortedCitationGroups, group -> group.groupId); citationGroups.setGlobalOrder(sortedCitationGroupIds); } } diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index b94e7c957a4..55f04775094 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -53,24 +53,24 @@ public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, OOB CitationGroups citationGroups = fr.citationGroups; - for (CitationGroup cg : citationGroups.getCitationGroupsUnordered()) { + for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) { - boolean withText = (cg.citationType != CitationType.INVISIBLE_CIT); - Optional marker = cg.getCitationMarker(); + boolean withText = (group.citationType != CitationType.INVISIBLE_CIT); + Optional marker = group.getCitationMarker(); if (!marker.isPresent()) { LOGGER.warn("applyNewCitationMarkers: no marker for {}", - cg.groupId.citationGroupIdAsString()); + group.groupId.citationGroupIdAsString()); continue; } if (withText && marker.isPresent()) { - XTextCursor cursor = fr.getFillCursorForCitationGroup(doc, cg); + XTextCursor cursor = fr.getFillCursorForCitationGroup(doc, group); fillCitationMarkInCursor(doc, cursor, marker.get(), withText, style); - fr.cleanFillCursorForCitationGroup(doc, cg); + fr.cleanFillCursorForCitationGroup(doc, group); } } @@ -140,21 +140,21 @@ public static void createAndFillCitationGroup(OOFrontend fr, if (pageInfos.size() != citationKeys.size()) { throw new IllegalArgumentException("pageInfos.size != citationKeys.size"); } - CitationGroup cg = fr.createCitationGroup(doc, - citationKeys, - pageInfos, - citationType, - position, - insertSpaceAfter); + CitationGroup group = fr.createCitationGroup(doc, + citationKeys, + pageInfos, + citationType, + position, + insertSpaceAfter); final boolean withText = citationType.withText(); if (withText) { - XTextCursor fillCursor = fr.getFillCursorForCitationGroup(doc, cg); + XTextCursor fillCursor = fr.getFillCursorForCitationGroup(doc, group); UpdateCitationMarkers.fillCitationMarkInCursor(doc, fillCursor, citationText, withText, style); - fr.cleanFillCursorForCitationGroup(doc, cg); + fr.cleanFillCursorForCitationGroup(doc, group); } position.collapseToEnd(); } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index eb2de1359ad..4bc3fac6191 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -169,11 +169,11 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { List citationGroups = new ArrayList<>(); for (CitationPath p : ck.getCitationPaths()) { CitationGroupId groupId = p.group; - Optional cg = cgs.getCitationGroup(groupId); - if (cg.isEmpty()) { + Optional group = cgs.getCitationGroup(groupId); + if (group.isEmpty()) { throw new IllegalStateException(); } - citationGroups.add(cg.get()); + citationGroups.add(group.get()); } // sort the citationGroups according to their indexInGlobalOrder @@ -184,11 +184,11 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { }); int i = 0; - for (CitationGroup cg : citationGroups) { + for (CitationGroup group : citationGroups) { if (i > 0) { sb.append(", "); } - String markName = cg.getReferenceMarkNameForLinking().orElseThrow(IllegalStateException::new); + String markName = group.getReferenceMarkNameForLinking().orElseThrow(IllegalStateException::new); OOText xref = OOFormat.formatReferenceToPageNumberOfReferenceMark(markName); sb.append(xref.toString()); i++; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index 306c0111a22..1aaeb538930 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -110,8 +110,8 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup */ private static void setIsFirstAppearanceOfSourceInCitations(CitationGroups cgs) { Set seenBefore = new HashSet<>(); - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { - for (Citation cit : cg.getCitationsInLocalOrder()) { + for (CitationGroup group : cgs.getCitationGroupsInGlobalOrder()) { + for (Citation cit : group.getCitationsInLocalOrder()) { String currentKey = cit.citationKey; if (!seenBefore.contains(currentKey)) { cit.setIsFirstAppearanceOfSource(true); @@ -145,17 +145,17 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { // Mark first appearance of each citationKey setIsFirstAppearanceOfSourceInCitations(cgs); - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { + for (CitationGroup group : cgs.getCitationGroupsInGlobalOrder()) { - final boolean inParenthesis = (cg.citationType == CitationType.AUTHORYEAR_PAR); + final boolean inParenthesis = (group.citationType == CitationType.AUTHORYEAR_PAR); final NonUniqueCitationMarker strictlyUnique = NonUniqueCitationMarker.THROWS; - List cits = cg.getCitationsInLocalOrder(); + List cits = group.getCitationsInLocalOrder(); List citationMarkerEntries = OOListUtil.map(cits, e -> e); OOText citMarker = style.createCitationMarker(citationMarkerEntries, inParenthesis, strictlyUnique); - cg.setCitationMarker(Optional.of(citMarker)); + group.setCitationMarker(Optional.of(citMarker)); } } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java index 9789d6c6caa..5329d9ca021 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessCitationKeyMarkers.java @@ -24,12 +24,12 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { cgs.createPlainBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { + for (CitationGroup group : cgs.getCitationGroupsInGlobalOrder()) { String citMarker = style.getCitationGroupMarkupBefore() - + String.join(",", OOListUtil.map(cg.getCitationsInLocalOrder(), Citation::getCitationKey)) + + String.join(",", OOListUtil.map(group.getCitationsInLocalOrder(), Citation::getCitationKey)) + style.getCitationGroupMarkupAfter(); - cg.setCitationMarker(Optional.of(OOText.fromString(citMarker))); + group.setCitationMarker(Optional.of(OOText.fromString(citMarker))); } } } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java index 589ebfb7a48..deddab66cca 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessNumericMarkers.java @@ -37,10 +37,10 @@ static void produceCitationMarkers(CitationGroups cgs, OOBibStyle style) { cgs.createNumberedBibliographySortedByComparator(OOProcess.AUTHOR_YEAR_TITLE_COMPARATOR); } - for (CitationGroup cg : cgs.getCitationGroupsInGlobalOrder()) { - List cits = OOListUtil.map(cg.getCitationsInLocalOrder(), e -> e); + for (CitationGroup group : cgs.getCitationGroupsInGlobalOrder()) { + List cits = OOListUtil.map(group.getCitationsInLocalOrder(), e -> e); OOText citMarker = style.getNumCitationMarker2(cits); - cg.setCitationMarker(Optional.of(citMarker)); + group.setCitationMarker(Optional.of(citMarker)); } } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index f49f38b542f..b03028b76ef 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -62,12 +62,12 @@ public void distributeToCitations(List where, T value) { for (CitationPath p : where) { - CitationGroup cg = citationGroupsUnordered.get(p.group); - if (cg == null) { + CitationGroup group = citationGroupsUnordered.get(p.group); + if (group == null) { LOGGER.warn("CitationGroups.distributeToCitations: group missing"); continue; } - Citation cit = cg.citationsInStorageOrder.get(p.storageIndexInGroup); + Citation cit = group.citationsInStorageOrder.get(p.storageIndexInGroup); fun.accept(new OOPair<>(cit, value)); } } @@ -96,8 +96,8 @@ public void lookupCitations(List databases) { // 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 cg : getCitationGroupsUnordered()) { - /// for (Citation cit : cg.citationsInStorageOrder) { + /// for (CitationGroup group : getCitationGroupsUnordered()) { + /// for (Citation cit : group.citationsInStorageOrder) { /// cit.lookupInDatabases(databases); /// } /// } @@ -146,8 +146,8 @@ public boolean hasGlobalOrder() { * Impose an order for citations within each group. */ public void imposeLocalOrder(Comparator entryComparator) { - for (CitationGroup cg : citationGroupsUnordered.values()) { - cg.imposeLocalOrder(entryComparator); + for (CitationGroup group : citationGroupsUnordered.values()) { + group.imposeLocalOrder(entryComparator); } } @@ -157,11 +157,11 @@ public void imposeLocalOrder(Comparator entryComparator) { */ public CitedKeys getCitedKeysUnordered() { LinkedHashMap res = new LinkedHashMap<>(); - for (CitationGroup cg : citationGroupsUnordered.values()) { + for (CitationGroup group : citationGroupsUnordered.values()) { int storageIndexInGroup = 0; - for (Citation cit : cg.citationsInStorageOrder) { + for (Citation cit : group.citationsInStorageOrder) { String key = cit.citationKey; - CitationPath path = new CitationPath(cg.groupId, storageIndexInGroup); + CitationPath path = new CitationPath(group.groupId, storageIndexInGroup); if (res.containsKey(key)) { res.get(key).addPath(path, cit); } else { @@ -181,11 +181,11 @@ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { throw new IllegalStateException("getSortedCitedKeys: no globalOrder"); } LinkedHashMap res = new LinkedHashMap<>(); - for (CitationGroup cg : getCitationGroupsInGlobalOrder()) { - for (int i : cg.getLocalOrder()) { - Citation cit = cg.citationsInStorageOrder.get(i); + for (CitationGroup group : getCitationGroupsInGlobalOrder()) { + for (int i : group.getLocalOrder()) { + Citation cit = group.citationsInStorageOrder.get(i); String citationKey = cit.citationKey; - CitationPath path = new CitationPath(cg.groupId, i); + CitationPath path = new CitationPath(group.groupId, i); if (res.containsKey(citationKey)) { res.get(citationKey).addPath(path, cit); } else { @@ -258,16 +258,16 @@ public void createNumberedBibliographySortedByComparator(Comparator en */ public Optional getCitationGroup(CitationGroupId groupId) { - CitationGroup cg = citationGroupsUnordered.get(groupId); - return Optional.ofNullable(cg); + CitationGroup group = citationGroupsUnordered.get(groupId); + return Optional.ofNullable(group); } /* * @return true if all citation groups have referenceMarkNameForLinking */ public boolean citationGroupsProvideReferenceMarkNameForLinking() { - for (CitationGroup cg : citationGroupsUnordered.values()) { - if (cg.getReferenceMarkNameForLinking().isEmpty()) { + for (CitationGroup group : citationGroupsUnordered.values()) { + if (group.getReferenceMarkNameForLinking().isEmpty()) { return false; } } @@ -278,16 +278,16 @@ public boolean citationGroupsProvideReferenceMarkNameForLinking() { * Callbacks. */ - public void afterCreateCitationGroup(CitationGroup cg) { - citationGroupsUnordered.put(cg.groupId, cg); + public void afterCreateCitationGroup(CitationGroup group) { + citationGroupsUnordered.put(group.groupId, group); globalOrder = Optional.empty(); bibliography = Optional.empty(); } - public void afterRemoveCitationGroup(CitationGroup cg) { - citationGroupsUnordered.remove(cg.groupId); - globalOrder.map(l -> l.remove(cg.groupId)); + public void afterRemoveCitationGroup(CitationGroup group) { + citationGroupsUnordered.remove(group.groupId); + globalOrder.map(l -> l.remove(group.groupId)); bibliography = Optional.empty(); } From 3762c9a0fc31deb86603333ea18f6e587006cc7e Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 15:53:05 +0200 Subject: [PATCH 1043/1068] drop message not understandable by end user --- .../java/org/jabref/logic/openoffice/backend/Backend52.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 3e91d2bb173..284d9ba962d 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -187,7 +187,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, Objects.requireNonNull(pageInfos); if (pageInfos.size() != citationKeys.size()) { - throw new IllegalArgumentException("pageInfos.size != citationKeys.size"); + throw new IllegalArgumentException(); } // Get a new refMarkName From b284c3e8d962b28b85a56d7f671050f44632b3e6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 16:00:15 +0200 Subject: [PATCH 1044/1068] reorganized reference mark name generation In Backend52: - use a single expression - expand comment - rename refMarkName to markName Collectors.joining(",") moved to Codec52.getUniqueMarkName --- .../logic/openoffice/backend/Backend52.java | 31 +++++++++++++------ .../logic/openoffice/backend/Codec52.java | 14 +++++---- 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 284d9ba962d..e835d9f889d 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -162,12 +162,19 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str } /** - * Create a reference mark with the given name, at the end of position. + * Create a reference mark at the end of {@code position} in the document. * * On return {@code position} is collapsed, and is after the inserted space, or at the end of * the reference mark. * + * @param citationKeys Keys to be cited. + * + * @param pageInfos An optional pageInfo for each citation key. + * Backend52 only uses and stores the last pageInfo, + * all others should be Optional.empty() + * * @param position Collapsed to its end. + * * @param insertSpaceAfter We insert a space after the mark, that carries on format of * characters from the original position. */ @@ -190,12 +197,16 @@ public CitationGroup createCitationGroup(XTextDocument doc, throw new IllegalArgumentException(); } - // Get a new refMarkName - Set usedNames = new HashSet<>(this.citationStorageManager.nrmGetUsedNames(doc)); - String xkey = (citationKeys.stream().collect(Collectors.joining(","))); - String refMarkName = Codec52.getUniqueMarkName(usedNames, xkey, citationType); + /* + * Backend52 uses reference marks to (1) mark the location of the citation in the text and (2) to encode + * the citation keys and citation type in the name of the reference mark. The name of the reference mark + * has to be unique in the document. + */ + String markName = Codec52.getUniqueMarkName(new HashSet<>(citationStorageManager.nrmGetUsedNames(doc)), + citationKeys, + citationType); - CitationGroupId groupId = new CitationGroupId(refMarkName); + CitationGroupId groupId = new CitationGroupId(markName); final int nCitations = citationKeys.size(); final int last = nCitations - 1; @@ -231,7 +242,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, */ boolean withoutBrackets = (citationType == CitationType.INVISIBLE_CIT); NamedRange namedRange = - this.citationStorageManager.nrmCreate(doc, refMarkName, position, insertSpaceAfter, + this.citationStorageManager.nrmCreate(doc, markName, position, insertSpaceAfter, withoutBrackets); switch (dataModel) { @@ -240,15 +251,15 @@ public CitationGroup createCitationGroup(XTextDocument doc, if (pageInfo.isPresent()) { String pageInfoString = OOText.toString(pageInfo.get()); - UnoUserDefinedProperty.setStringProperty(doc, refMarkName, pageInfoString); + UnoUserDefinedProperty.setStringProperty(doc, markName, pageInfoString); } else { // do not inherit from trash - UnoUserDefinedProperty.removeIfExists(doc, refMarkName); + UnoUserDefinedProperty.removeIfExists(doc, markName); } CitationGroup group = new CitationGroup(OODataModel.JabRef52, groupId, citationType, citations, - Optional.of(refMarkName)); + Optional.of(markName)); this.cgidToNamedRange.put(groupId, namedRange); return group; default: diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index ac563be66b4..938badfba58 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -77,25 +77,27 @@ private static int citationTypeToInt(CitationType i) { } /** - * Produce a reference mark name for JabRef for the given citation key and citationType that + * Produce a reference mark name for JabRef for the given citationType and list citation keys that * does not yet appear among the reference marks of the document. * - * @param bibtexKey The citation key. + * @param usedNames Reference mark names already in use. + * @param citationKeys Identifies the cited sources. * @param citationType Encodes the effect of withText and inParenthesis options. * - * The first occurrence of bibtexKey gets no serial number, the second gets 0, the third 1 ... + * The first occurrence of citationKeys gets no serial number, the second gets 0, the third 1 ... * * Or the first unused in this series, after removals. */ public static String getUniqueMarkName(Set usedNames, - String bibtexKey, + List citationKeys, CitationType citationType) { + String citationKeysPart = citationKeys.stream().collect(Collectors.joining(",")); int i = 0; int citTypeCode = citationTypeToInt(citationType); - String name = BIB_CITATION + '_' + citTypeCode + '_' + bibtexKey; + String name = BIB_CITATION + '_' + citTypeCode + '_' + citationKeysPart; while (usedNames.contains(name)) { - name = BIB_CITATION + i + '_' + citTypeCode + '_' + bibtexKey; + name = BIB_CITATION + i + '_' + citTypeCode + '_' + citationKeysPart; i++; } return name; From 632d9df7278ee433087723a18ecad5f012127bd5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 16:18:55 +0200 Subject: [PATCH 1045/1068] renamed nCitations to numberOfCitations and totalCitations --- .../logic/openoffice/backend/Backend52.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index e835d9f889d..f71cb9a575e 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -208,12 +208,12 @@ public CitationGroup createCitationGroup(XTextDocument doc, CitationGroupId groupId = new CitationGroupId(markName); - final int nCitations = citationKeys.size(); - final int last = nCitations - 1; + final int numberOfCitations = citationKeys.size(); + final int last = numberOfCitations - 1; // Build citations, add pageInfo to each citation - List citations = new ArrayList<>(nCitations); - for (int i = 0; i < nCitations; i++) { + List citations = new ArrayList<>(numberOfCitations); + for (int i = 0; i < numberOfCitations; i++) { Citation cit = new Citation(citationKeys.get(i)); citations.add(cit); @@ -288,13 +288,13 @@ public CitationGroup createCitationGroup(XTextDocument doc, .distinct() .collect(Collectors.joining("; "))); - int nCitations = (joinableGroup.stream() - .map(CitationGroup::numberOfCitations) - .mapToInt(Integer::intValue).sum()); + int totalCitations = (joinableGroup.stream() + .map(CitationGroup::numberOfCitations) + .mapToInt(Integer::intValue).sum()); if ("".equals(cgPageInfo)) { cgPageInfo = null; } - return OODataModel.fakePageInfos(cgPageInfo, nCitations); + return OODataModel.fakePageInfos(cgPageInfo, totalCitations); case JabRef60: return (joinableGroup.stream() From 9af060e9bdd1a3edf1ef6e7a0165aa552aa244c9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 16:21:57 +0200 Subject: [PATCH 1046/1068] format --- .../org/jabref/logic/openoffice/backend/Backend52.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index f71cb9a575e..c7e6b024de2 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -241,9 +241,11 @@ public CitationGroup createCitationGroup(XTextDocument doc, * Apply to document */ boolean withoutBrackets = (citationType == CitationType.INVISIBLE_CIT); - NamedRange namedRange = - this.citationStorageManager.nrmCreate(doc, markName, position, insertSpaceAfter, - withoutBrackets); + NamedRange namedRange = this.citationStorageManager.nrmCreate(doc, + markName, + position, + insertSpaceAfter, + withoutBrackets); switch (dataModel) { case JabRef52: From b17f0e2628de32e72fbc1410cb0d1c382bbd95e3 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 19:33:28 +0200 Subject: [PATCH 1047/1068] insert dummy case JabRef60: branch --- .../java/org/jabref/logic/openoffice/backend/Backend52.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index c7e6b024de2..a9ac30a6f03 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -264,8 +264,10 @@ public CitationGroup createCitationGroup(XTextDocument doc, Optional.of(markName)); this.cgidToNamedRange.put(groupId, namedRange); return group; + case JabRef60: + throw new IllegalStateException("createCitationGroup for JabRef60 is not implemented yet"); default: - throw new IllegalStateException("Backend52 requires JabRef52 dataModel"); + throw new IllegalStateException("Unhandled dataModel in Backend52.createCitationGroup"); } } From 0210909cf9bb75d2601e1d116e45ce670bc01aa6 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 20:30:48 +0200 Subject: [PATCH 1048/1068] indent case-label in model/style --- .../java/org/jabref/model/openoffice/style/CitationType.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationType.java b/src/main/java/org/jabref/model/openoffice/style/CitationType.java index 14189e903e3..567996ec56e 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationType.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationType.java @@ -11,8 +11,8 @@ public enum CitationType { public boolean inParenthesis() { return switch (this) { - case AUTHORYEAR_PAR, INVISIBLE_CIT -> true; - case AUTHORYEAR_INTEXT -> false; + case AUTHORYEAR_PAR, INVISIBLE_CIT -> true; + case AUTHORYEAR_INTEXT -> false; }; } From ef9645ab97458f7ab7c82174666a701a44fabe13 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 20:31:51 +0200 Subject: [PATCH 1049/1068] indent case-label in gui --- .../org/jabref/gui/openoffice/OOBibBase2.java | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index 9be63f27538..9832adb991d 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -368,18 +368,18 @@ private OOVoidResult checkStyleExistsInTheDocument(String familyName, if (internalName.isEmpty()) { String msg = switch (familyName) { - case UnoStyle.PARAGRAPH_STYLES -> - Localization.lang("The %0 paragraph style '%1' is missing from the document", - labelInJstyleFile, - styleName); - case UnoStyle.CHARACTER_STYLES -> - Localization.lang("The %0 character style '%1' is missing from the document", - labelInJstyleFile, - styleName); - default -> - throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES - + " or " + UnoStyle.PARAGRAPH_STYLES - + " for familyName"); + case UnoStyle.PARAGRAPH_STYLES -> + Localization.lang("The %0 paragraph style '%1' is missing from the document", + labelInJstyleFile, + styleName); + case UnoStyle.CHARACTER_STYLES -> + Localization.lang("The %0 character style '%1' is missing from the document", + labelInJstyleFile, + styleName); + default -> + throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES + + " or " + UnoStyle.PARAGRAPH_STYLES + + " for familyName"); } + "\n" + Localization.lang("Please create it in the document or change in the file:") @@ -391,20 +391,20 @@ private OOVoidResult checkStyleExistsInTheDocument(String familyName, if (!internalName.get().equals(styleName)) { String msg = switch (familyName) { - case UnoStyle.PARAGRAPH_STYLES -> - Localization.lang("The %0 paragraph style '%1' is a display name for '%2'.", - labelInJstyleFile, - styleName, - internalName.get()); - case UnoStyle.CHARACTER_STYLES -> - Localization.lang("The %0 character style '%1' is a display name for '%2'.", - labelInJstyleFile, - styleName, - internalName.get()); - default -> - throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES - + " or " + UnoStyle.PARAGRAPH_STYLES - + " for familyName"); + case UnoStyle.PARAGRAPH_STYLES -> + Localization.lang("The %0 paragraph style '%1' is a display name for '%2'.", + labelInJstyleFile, + styleName, + internalName.get()); + case UnoStyle.CHARACTER_STYLES -> + Localization.lang("The %0 character style '%1' is a display name for '%2'.", + labelInJstyleFile, + styleName, + internalName.get()); + default -> + throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES + + " or " + UnoStyle.PARAGRAPH_STYLES + + " for familyName"); } + "\n" + Localization.lang("Please use the latter in the style file below" From 4a35342d5d031ef1e216292a1d6a424d2ffe5e6e Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 20:32:17 +0200 Subject: [PATCH 1050/1068] indent case-label in logic/backend --- .../logic/openoffice/backend/Backend52.java | 196 +++++++++--------- .../logic/openoffice/backend/Codec52.java | 32 +-- 2 files changed, 114 insertions(+), 114 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index a9ac30a6f03..8407198523d 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -219,21 +219,21 @@ public CitationGroup createCitationGroup(XTextDocument doc, Optional pageInfo = PageInfo.normalizePageInfo(pageInfos.get(i)); switch (dataModel) { - case JabRef52: - if (i == last) { - cit.setPageInfo(pageInfo); - } else { - if (pageInfo.isPresent()) { - LOGGER.warn("dataModel JabRef52" - + " only supports pageInfo for the last citation of a group"); + case JabRef52: + if (i == last) { + cit.setPageInfo(pageInfo); + } else { + if (pageInfo.isPresent()) { + LOGGER.warn("dataModel JabRef52" + + " only supports pageInfo for the last citation of a group"); + } } - } - break; - case JabRef60: - cit.setPageInfo(pageInfo); - break; - default: - throw new IllegalStateException("Unhandled dataModel in Backend52.createCitationGroup"); + break; + case JabRef60: + cit.setPageInfo(pageInfo); + break; + default: + throw new IllegalStateException("Unhandled dataModel in Backend52.createCitationGroup"); } } @@ -248,26 +248,26 @@ public CitationGroup createCitationGroup(XTextDocument doc, withoutBrackets); switch (dataModel) { - case JabRef52: - Optional pageInfo = PageInfo.normalizePageInfo(pageInfos.get(last)); - - if (pageInfo.isPresent()) { - String pageInfoString = OOText.toString(pageInfo.get()); - UnoUserDefinedProperty.setStringProperty(doc, markName, pageInfoString); - } else { - // do not inherit from trash - UnoUserDefinedProperty.removeIfExists(doc, markName); - } - CitationGroup group = new CitationGroup(OODataModel.JabRef52, - groupId, - citationType, citations, - Optional.of(markName)); - this.cgidToNamedRange.put(groupId, namedRange); - return group; - case JabRef60: - throw new IllegalStateException("createCitationGroup for JabRef60 is not implemented yet"); - default: - throw new IllegalStateException("Unhandled dataModel in Backend52.createCitationGroup"); + case JabRef52: + Optional pageInfo = PageInfo.normalizePageInfo(pageInfos.get(last)); + + if (pageInfo.isPresent()) { + String pageInfoString = OOText.toString(pageInfo.get()); + UnoUserDefinedProperty.setStringProperty(doc, markName, pageInfoString); + } else { + // do not inherit from trash + UnoUserDefinedProperty.removeIfExists(doc, markName); + } + CitationGroup group = new CitationGroup(OODataModel.JabRef52, + groupId, + citationType, citations, + Optional.of(markName)); + this.cgidToNamedRange.put(groupId, namedRange); + return group; + case JabRef60: + throw new IllegalStateException("createCitationGroup for JabRef60 is not implemented yet"); + default: + throw new IllegalStateException("Unhandled dataModel in Backend52.createCitationGroup"); } } @@ -280,33 +280,33 @@ public CitationGroup createCitationGroup(XTextDocument doc, public static List> combinePageInfosCommon(OODataModel dataModel, List joinableGroup) { switch (dataModel) { - case JabRef52: - // collect to cgPageInfos - List> cgPageInfos = OOListUtil.map(joinableGroup, - Backend52::getPageInfoFromData); - - // Try to do something of the cgPageInfos. - String cgPageInfo = (cgPageInfos.stream() - .filter(pi -> pi.isPresent()) - .map(pi -> OOText.toString(pi.get())) - .distinct() - .collect(Collectors.joining("; "))); - - int totalCitations = (joinableGroup.stream() - .map(CitationGroup::numberOfCitations) - .mapToInt(Integer::intValue).sum()); - if ("".equals(cgPageInfo)) { - cgPageInfo = null; - } - return OODataModel.fakePageInfos(cgPageInfo, totalCitations); - - case JabRef60: - return (joinableGroup.stream() - .flatMap(group -> (group.citationsInStorageOrder.stream() - .map(Citation::getPageInfo))) - .collect(Collectors.toList())); - default: - throw new IllegalArgumentException("unhandled dataModel here"); + case JabRef52: + // collect to cgPageInfos + List> cgPageInfos = OOListUtil.map(joinableGroup, + Backend52::getPageInfoFromData); + + // Try to do something of the cgPageInfos. + String cgPageInfo = (cgPageInfos.stream() + .filter(pi -> pi.isPresent()) + .map(pi -> OOText.toString(pi.get())) + .distinct() + .collect(Collectors.joining("; "))); + + int totalCitations = (joinableGroup.stream() + .map(CitationGroup::numberOfCitations) + .mapToInt(Integer::intValue).sum()); + if ("".equals(cgPageInfo)) { + cgPageInfo = null; + } + return OODataModel.fakePageInfos(cgPageInfo, totalCitations); + + case JabRef60: + return (joinableGroup.stream() + .flatMap(group -> (group.citationsInStorageOrder.stream() + .map(Citation::getPageInfo))) + .collect(Collectors.toList())); + default: + throw new IllegalArgumentException("unhandled dataModel here"); } } @@ -389,29 +389,29 @@ public List getCitationEntries(XTextDocument doc, CitationGroups NoDocumentException { switch (dataModel) { - case JabRef52: - // One context per CitationGroup: Backend52 (DataModel.JabRef52) - // For DataModel.JabRef60 (Backend60) we need one context per Citation - List citations = new ArrayList<>(cgs.numberOfCitationGroups()); - for (CitationGroup group : cgs.getCitationGroupsUnordered()) { - String name = group.groupId.citationGroupIdAsString(); - XTextCursor cursor = (this - .getRawCursorForCitationGroup(group, doc) - .orElseThrow(IllegalStateException::new)); - String context = GetContext.getCursorStringWithContext(cursor, 30, 30, true); - Optional pageInfo = (group.numberOfCitations() > 0 - ? (getPageInfoFromData(group) - .map(e -> OOText.toString(e))) - : Optional.empty()); - CitationEntry entry = new CitationEntry(name, context, pageInfo); - citations.add(entry); - } - return citations; - case JabRef60: - // xx - throw new IllegalStateException("getCitationEntries for JabRef60 is not implemented yet"); - default: - throw new IllegalStateException("getCitationEntries: unhandled dataModel "); + case JabRef52: + // One context per CitationGroup: Backend52 (DataModel.JabRef52) + // For DataModel.JabRef60 (Backend60) we need one context per Citation + List citations = new ArrayList<>(cgs.numberOfCitationGroups()); + for (CitationGroup group : cgs.getCitationGroupsUnordered()) { + String name = group.groupId.citationGroupIdAsString(); + XTextCursor cursor = (this + .getRawCursorForCitationGroup(group, doc) + .orElseThrow(IllegalStateException::new)); + String context = GetContext.getCursorStringWithContext(cursor, 30, 30, true); + Optional pageInfo = (group.numberOfCitations() > 0 + ? (getPageInfoFromData(group) + .map(e -> OOText.toString(e))) + : Optional.empty()); + CitationEntry entry = new CitationEntry(name, context, pageInfo); + citations.add(entry); + } + return citations; + case JabRef60: + // xx + throw new IllegalStateException("getCitationEntries for JabRef60 is not implemented yet"); + default: + throw new IllegalStateException("getCitationEntries: unhandled dataModel "); } } @@ -426,21 +426,21 @@ public void applyCitationEntries(XTextDocument doc, List citation WrappedTargetException { switch (dataModel) { - case JabRef52: - for (CitationEntry entry : citationEntries) { - Optional pageInfo = entry.getPageInfo().map(OOText::fromString); - pageInfo = PageInfo.normalizePageInfo(pageInfo); - if (pageInfo.isPresent()) { - String name = entry.getRefMarkName(); - UnoUserDefinedProperty.setStringProperty(doc, name, pageInfo.get().toString()); + case JabRef52: + for (CitationEntry entry : citationEntries) { + Optional pageInfo = entry.getPageInfo().map(OOText::fromString); + pageInfo = PageInfo.normalizePageInfo(pageInfo); + if (pageInfo.isPresent()) { + String name = entry.getRefMarkName(); + UnoUserDefinedProperty.setStringProperty(doc, name, pageInfo.get().toString()); + } } - } - break; - case JabRef60: - // xx - throw new IllegalStateException("applyCitationEntries for JabRef60 is not implemented yet"); - default: - throw new IllegalStateException("applyCitationEntries: unhandled dataModel "); + break; + case JabRef60: + // xx + throw new IllegalStateException("applyCitationEntries for JabRef60 is not implemented yet"); + default: + throw new IllegalStateException("applyCitationEntries: unhandled dataModel "); } } diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index 938badfba58..171222c1413 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -52,27 +52,27 @@ public static class ParsedMarkName { */ private static CitationType citationTypeFromInt(int i) { switch (i) { - case 1: - return CitationType.AUTHORYEAR_PAR; - case 2: - return CitationType.AUTHORYEAR_INTEXT; - case 3: - return CitationType.INVISIBLE_CIT; - default: - throw new IllegalArgumentException("Invalid CitationType code"); + case 1: + return CitationType.AUTHORYEAR_PAR; + case 2: + return CitationType.AUTHORYEAR_INTEXT; + case 3: + return CitationType.INVISIBLE_CIT; + default: + throw new IllegalArgumentException("Invalid CitationType code"); } } private static int citationTypeToInt(CitationType i) { switch (i) { - case AUTHORYEAR_PAR: - return 1; - case AUTHORYEAR_INTEXT: - return 2; - case INVISIBLE_CIT: - return 3; - default: - throw new IllegalArgumentException("Invalid CitationType"); + case AUTHORYEAR_PAR: + return 1; + case AUTHORYEAR_INTEXT: + return 2; + case INVISIBLE_CIT: + return 3; + default: + throw new IllegalArgumentException("Invalid CitationType"); } } From b4b1ec02cfe2ad7e4b6ca143ca01beedb8e0a954 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 20:32:41 +0200 Subject: [PATCH 1051/1068] indent case-label in logic/frontend --- .../org/jabref/logic/openoffice/frontend/OOFrontend.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java index 3cf5e901abe..58057c382e7 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -418,9 +418,9 @@ static String rangeOverlapsToMessage(List Localization.lang("Found identical ranges"); - case OVERLAP -> Localization.lang("Found overlapping ranges"); - case TOUCH -> Localization.lang("Found touching ranges"); + case EQUAL_RANGE -> Localization.lang("Found identical ranges"); + case OVERLAP -> Localization.lang("Found overlapping ranges"); + case TOUCH -> Localization.lang("Found touching ranges"); }); msg.append(": "); msg.append(listOfRanges); From 4a085b6206175dfcb38f1813808d0ba3e7ea9cec Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 20:33:01 +0200 Subject: [PATCH 1052/1068] indent case-label in model/ootext --- .../model/openoffice/ootext/OOTextIntoOO.java | 248 +++++++++--------- 1 file changed, 124 insertions(+), 124 deletions(-) diff --git a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java index 6e61faed147..909b088b5b3 100644 --- a/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java +++ b/src/main/java/org/jabref/model/openoffice/ootext/OOTextIntoOO.java @@ -189,135 +189,135 @@ public static void write(XTextDocument doc, XTextCursor position, OOText ootext) // Handle tags: switch (tagName) { - case "b": - formatStack.pushLayer(setCharWeight(FontWeight.BOLD)); - expectEnd.push("/" + tagName); - break; - case "i": - case "em": - formatStack.pushLayer(setCharPosture(FontSlant.ITALIC)); - expectEnd.push("/" + tagName); - break; - case "smallcaps": - formatStack.pushLayer(setCharCaseMap(CaseMap.SMALLCAPS)); - expectEnd.push("/" + tagName); - break; - case "sup": - formatStack.pushLayer(setSuperScript(formatStack)); - expectEnd.push("/" + tagName); - break; - case "sub": - formatStack.pushLayer(setSubScript(formatStack)); - expectEnd.push("/" + tagName); - break; - case "u": - formatStack.pushLayer(setCharUnderline(FontUnderline.SINGLE)); - expectEnd.push("/" + tagName); - break; - case "s": - formatStack.pushLayer(setCharStrikeout(FontStrikeout.SINGLE)); - expectEnd.push("/" + tagName); - break; - case "/p": - // nop - break; - case "p": - insertParagraphBreak(text, cursor); - cursor.collapseToEnd(); - for (OOPair pair : attributes) { - String key = pair.a; - String value = pair.b; - switch (key) { - case "oo:ParaStyleName": - //

- if (StringUtil.isNullOrEmpty(value)) { - LOGGER.debug(String.format("oo:ParaStyleName inherited")); - } else { - if (setParagraphStyle(cursor, value)) { - // Presumably tested already: - LOGGER.debug(String.format("oo:ParaStyleName=\"%s\" failed", value)); - } + case "b": + formatStack.pushLayer(setCharWeight(FontWeight.BOLD)); + expectEnd.push("/" + tagName); + break; + case "i": + case "em": + formatStack.pushLayer(setCharPosture(FontSlant.ITALIC)); + expectEnd.push("/" + tagName); + break; + case "smallcaps": + formatStack.pushLayer(setCharCaseMap(CaseMap.SMALLCAPS)); + expectEnd.push("/" + tagName); + break; + case "sup": + formatStack.pushLayer(setSuperScript(formatStack)); + expectEnd.push("/" + tagName); + break; + case "sub": + formatStack.pushLayer(setSubScript(formatStack)); + expectEnd.push("/" + tagName); + break; + case "u": + formatStack.pushLayer(setCharUnderline(FontUnderline.SINGLE)); + expectEnd.push("/" + tagName); + break; + case "s": + formatStack.pushLayer(setCharStrikeout(FontStrikeout.SINGLE)); + expectEnd.push("/" + tagName); + break; + case "/p": + // nop + break; + case "p": + insertParagraphBreak(text, cursor); + cursor.collapseToEnd(); + for (OOPair pair : attributes) { + String key = pair.a; + String value = pair.b; + switch (key) { + case "oo:ParaStyleName": + //

+ if (StringUtil.isNullOrEmpty(value)) { + LOGGER.debug(String.format("oo:ParaStyleName inherited")); + } else { + if (setParagraphStyle(cursor, value)) { + // Presumably tested already: + LOGGER.debug(String.format("oo:ParaStyleName=\"%s\" failed", value)); + } + } + break; + default: + LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); + break; } - break; - default: - LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); - break; } - } - break; - case "oo:referenceToPageNumberOfReferenceMark": - for (OOPair pair : attributes) { - String key = pair.a; - String value = pair.b; - switch (key) { - case "target": - UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); - break; - default: - LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); - break; + break; + case "oo:referenceToPageNumberOfReferenceMark": + for (OOPair pair : attributes) { + String key = pair.a; + String value = pair.b; + switch (key) { + case "target": + UnoCrossRef.insertReferenceToPageNumberOfReferenceMark(doc, value, cursor); + break; + default: + LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); + break; + } } - } - break; - case "tt": - // Note: "Example" names a character style in LibreOffice. - formatStack.pushLayer(setCharStyleName("Example")); - expectEnd.push("/" + tagName); - break; - case "span": - List> settings = new ArrayList<>(); - for (OOPair pair : attributes) { - String key = pair.a; - String value = pair.b; - switch (key) { - case "oo:CharStyleName": - // - settings.addAll(setCharStyleName(value)); - break; - case "lang": - // - // - settings.addAll(setCharLocale(value)); - break; - case "style": - // HTML-style small-caps - if ("font-variant: small-caps".equals(value)) { - settings.addAll(setCharCaseMap(CaseMap.SMALLCAPS)); - break; + break; + case "tt": + // Note: "Example" names a character style in LibreOffice. + formatStack.pushLayer(setCharStyleName("Example")); + expectEnd.push("/" + tagName); + break; + case "span": + List> settings = new ArrayList<>(); + for (OOPair pair : attributes) { + String key = pair.a; + String value = pair.b; + switch (key) { + case "oo:CharStyleName": + // + settings.addAll(setCharStyleName(value)); + break; + case "lang": + // + // + settings.addAll(setCharLocale(value)); + break; + case "style": + // HTML-style small-caps + if ("font-variant: small-caps".equals(value)) { + settings.addAll(setCharCaseMap(CaseMap.SMALLCAPS)); + break; + } + LOGGER.warn(String.format("Unexpected value %s for attribute '%s' for <%s>", + value, key, tagName)); + break; + default: + LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); + break; } - LOGGER.warn(String.format("Unexpected value %s for attribute '%s' for <%s>", - value, key, tagName)); - break; - default: - LOGGER.warn(String.format("Unexpected attribute '%s' for <%s>", key, tagName)); - break; } - } - formatStack.pushLayer(settings); - expectEnd.push("/" + tagName); - break; - case "/b": - case "/i": - case "/em": - case "/tt": - case "/smallcaps": - case "/sup": - case "/sub": - case "/u": - case "/s": - case "/span": - formatStack.popLayer(); - String expected = expectEnd.pop(); - if (!tagName.equals(expected)) { - LOGGER.warn(String.format("expected '<%s>', found '<%s>' after '%s'", - expected, - tagName, - currentSubstring)); - } - break; - default: - LOGGER.warn(String.format("ignoring unknown tag '<%s>'", tagName)); - break; + formatStack.pushLayer(settings); + expectEnd.push("/" + tagName); + break; + case "/b": + case "/i": + case "/em": + case "/tt": + case "/smallcaps": + case "/sup": + case "/sub": + case "/u": + case "/s": + case "/span": + formatStack.popLayer(); + String expected = expectEnd.pop(); + if (!tagName.equals(expected)) { + LOGGER.warn(String.format("expected '<%s>', found '<%s>' after '%s'", + expected, + tagName, + currentSubstring)); + } + break; + default: + LOGGER.warn(String.format("ignoring unknown tag '<%s>'", tagName)); + break; } piv = tagMatcher.end(); From 88f8e0ba251309ba404f9af0d0860bbf5d52d16f Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 20:38:13 +0200 Subject: [PATCH 1053/1068] rname cgPageInfos tro pageInfos --- .../org/jabref/logic/openoffice/backend/Backend52.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 8407198523d..8869a934499 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -281,12 +281,12 @@ public CitationGroup createCitationGroup(XTextDocument doc, combinePageInfosCommon(OODataModel dataModel, List joinableGroup) { switch (dataModel) { case JabRef52: - // collect to cgPageInfos - List> cgPageInfos = OOListUtil.map(joinableGroup, - Backend52::getPageInfoFromData); + // collect to pageInfos + List> pageInfos = OOListUtil.map(joinableGroup, + Backend52::getPageInfoFromData); - // Try to do something of the cgPageInfos. - String cgPageInfo = (cgPageInfos.stream() + // Try to do something of the pageInfos. + String cgPageInfo = (pageInfos.stream() .filter(pi -> pi.isPresent()) .map(pi -> OOText.toString(pi.get())) .distinct() From 17b314bc8af48e5671d333038821fb0d8fb3dda8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 20:40:28 +0200 Subject: [PATCH 1054/1068] renamed cgPageInfo to singlePageInfo --- .../logic/openoffice/backend/Backend52.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 8869a934499..cc37f4eb766 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -286,19 +286,19 @@ public CitationGroup createCitationGroup(XTextDocument doc, Backend52::getPageInfoFromData); // Try to do something of the pageInfos. - String cgPageInfo = (pageInfos.stream() - .filter(pi -> pi.isPresent()) - .map(pi -> OOText.toString(pi.get())) - .distinct() - .collect(Collectors.joining("; "))); + String singlePageInfo = (pageInfos.stream() + .filter(pi -> pi.isPresent()) + .map(pi -> OOText.toString(pi.get())) + .distinct() + .collect(Collectors.joining("; "))); int totalCitations = (joinableGroup.stream() .map(CitationGroup::numberOfCitations) .mapToInt(Integer::intValue).sum()); - if ("".equals(cgPageInfo)) { - cgPageInfo = null; + if ("".equals(singlePageInfo)) { + singlePageInfo = null; } - return OODataModel.fakePageInfos(cgPageInfo, totalCitations); + return OODataModel.fakePageInfos(singlePageInfo, totalCitations); case JabRef60: return (joinableGroup.stream() From b3c53f496db2a688f395e5a1fd359661ba0c1c10 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 20:48:23 +0200 Subject: [PATCH 1055/1068] replace Collectors.toSet() with new HashSet<>() --- .../java/org/jabref/logic/openoffice/backend/Backend52.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index cc37f4eb766..f0992362b47 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -79,7 +79,7 @@ private List findUnusedJabrefPropertyNames(XTextDocument doc, List citationGroupNames) { // Collect unused jabrefPropertyNames - Set citationGroupNamesSet = citationGroupNames.stream().collect(Collectors.toSet()); + Set citationGroupNamesSet = new HashSet<>(citationGroupNames); List pageInfoThrash = new ArrayList<>(); List jabrefPropertyNames = From d86eb42780000b9aea0027555c49ed1fa3fefab0 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 20:49:16 +0200 Subject: [PATCH 1056/1068] use method reference --- .../java/org/jabref/logic/openoffice/backend/Backend52.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index f0992362b47..6d870e12635 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -287,7 +287,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, // Try to do something of the pageInfos. String singlePageInfo = (pageInfos.stream() - .filter(pi -> pi.isPresent()) + .filter(Optional::isPresent) .map(pi -> OOText.toString(pi.get())) .distinct() .collect(Collectors.joining("; "))); From 0bd35877cc0c467dab77a067b56dc50c2873a0a5 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 20:49:41 +0200 Subject: [PATCH 1057/1068] drop two comments --- .../java/org/jabref/logic/openoffice/backend/Backend52.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 6d870e12635..c7c8178d4e8 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -78,7 +78,6 @@ public List getJabRefReferenceMarkNames(XTextDocument doc) private List findUnusedJabrefPropertyNames(XTextDocument doc, List citationGroupNames) { - // Collect unused jabrefPropertyNames Set citationGroupNamesSet = new HashSet<>(citationGroupNames); List pageInfoThrash = new ArrayList<>(); @@ -104,7 +103,7 @@ public Optional healthReport(XTextDocument doc) List pageInfoThrash = this.findUnusedJabrefPropertyNames(doc, this.getJabRefReferenceMarkNames(doc)); if (pageInfoThrash.isEmpty()) { - return Optional.empty(); // "Backend52: found no unused pageInfo data"; + return Optional.empty(); } StringBuilder msg = new StringBuilder("Backend52: found unused pageInfo data, with names listed below.\n"); From 7821283492daf2079b44f10a00b331d2d7d1cf02 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 21:52:13 +0200 Subject: [PATCH 1058/1068] use String.join --- src/main/java/org/jabref/logic/openoffice/backend/Codec52.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index 171222c1413..3f9faaf7285 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -92,7 +92,8 @@ public static String getUniqueMarkName(Set usedNames, List citationKeys, CitationType citationType) { - String citationKeysPart = citationKeys.stream().collect(Collectors.joining(",")); + String citationKeysPart = String.join(",", citationKeys); + int i = 0; int citTypeCode = citationTypeToInt(citationType); String name = BIB_CITATION + '_' + citTypeCode + '_' + citationKeysPart; From dd4fe78645fda339b4883bc8475408cb183f1dd9 Mon Sep 17 00:00:00 2001 From: Antal K Date: Thu, 19 Aug 2021 22:55:58 +0200 Subject: [PATCH 1059/1068] remove nr/nrm prefixes from NamedRange and NamedRangeManager methods --- .../logic/openoffice/backend/Backend52.java | 28 +++---- .../logic/openoffice/backend/Codec52.java | 34 +++----- .../NamedRangeManagerReferenceMark.java | 14 ++-- .../backend/NamedRangeReferenceMark.java | 79 +++++++++---------- .../model/openoffice/backend/NamedRange.java | 25 ++++-- .../openoffice/backend/NamedRangeManager.java | 14 ++-- 6 files changed, 97 insertions(+), 97 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index c7c8178d4e8..0016e5e4510 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -64,7 +64,7 @@ public Backend52() { public List getJabRefReferenceMarkNames(XTextDocument doc) throws NoDocumentException { - List allNames = this.citationStorageManager.nrmGetUsedNames(doc); + List allNames = this.citationStorageManager.getUsedNames(doc); return Codec52.filterIsJabRefReferenceMarkName(allNames); } @@ -147,7 +147,7 @@ public CitationGroup readCitationGroupFromDocumentOrThrow(XTextDocument doc, Str setPageInfoInDataInitial(citations, pageInfo); - NamedRange namedRange = (citationStorageManager.nrmGetFromDocument(doc, markName) + NamedRange namedRange = (citationStorageManager.getNamedRangeFromDocument(doc, markName) .orElseThrow(IllegalArgumentException::new)); CitationGroupId groupId = new CitationGroupId(markName); @@ -201,7 +201,7 @@ public CitationGroup createCitationGroup(XTextDocument doc, * the citation keys and citation type in the name of the reference mark. The name of the reference mark * has to be unique in the document. */ - String markName = Codec52.getUniqueMarkName(new HashSet<>(citationStorageManager.nrmGetUsedNames(doc)), + String markName = Codec52.getUniqueMarkName(new HashSet<>(citationStorageManager.getUsedNames(doc)), citationKeys, citationType); @@ -240,11 +240,11 @@ public CitationGroup createCitationGroup(XTextDocument doc, * Apply to document */ boolean withoutBrackets = (citationType == CitationType.INVISIBLE_CIT); - NamedRange namedRange = this.citationStorageManager.nrmCreate(doc, - markName, - position, - insertSpaceAfter, - withoutBrackets); + NamedRange namedRange = this.citationStorageManager.createNamedRange(doc, + markName, + position, + insertSpaceAfter, + withoutBrackets); switch (dataModel) { case JabRef52: @@ -330,8 +330,8 @@ public void removeCitationGroup(CitationGroup group, XTextDocument doc) NoDocumentException, NotRemoveableException { NamedRange namedRange = getNamedRangeOrThrow(group); - String refMarkName = namedRange.nrGetRangeName(); - namedRange.nrRemoveFromDocument(doc); + String refMarkName = namedRange.getRangeName(); + namedRange.removeFromDocument(doc); UnoUserDefinedProperty.removeIfExists(doc, refMarkName); this.cgidToNamedRange.remove(group.groupId); } @@ -345,7 +345,7 @@ public Optional getMarkRange(CitationGroup group, XTextDocument doc) WrappedTargetException { NamedRange namedRange = getNamedRangeOrThrow(group); - return namedRange.nrGetMarkRange(doc); + return namedRange.getMarkRange(doc); } /** @@ -357,7 +357,7 @@ public Optional getRawCursorForCitationGroup(CitationGroup group, X NoDocumentException, WrappedTargetException { NamedRange namedRange = getNamedRangeOrThrow(group); - return namedRange.nrGetRawCursor(doc); + return namedRange.getRawCursor(doc); } /** @@ -370,7 +370,7 @@ public XTextCursor getFillCursorForCitationGroup(CitationGroup group, XTextDocum CreationException { NamedRange namedRange = getNamedRangeOrThrow(group); - return namedRange.nrGetFillCursor(doc); + return namedRange.getFillCursor(doc); } /** To be called after getFillCursorForCitationGroup */ @@ -379,7 +379,7 @@ public void cleanFillCursorForCitationGroup(CitationGroup group, XTextDocument d NoDocumentException, WrappedTargetException { NamedRange namedRange = getNamedRangeOrThrow(group); - namedRange.nrCleanFillCursor(doc); + namedRange.cleanFillCursor(doc); } public List getCitationEntries(XTextDocument doc, CitationGroups cgs) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index 3f9faaf7285..1b6fd3704f8 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -51,29 +51,21 @@ public static class ParsedMarkName { * Integer representation was written into the document in JabRef52, keep it for compatibility. */ private static CitationType citationTypeFromInt(int i) { - switch (i) { - case 1: - return CitationType.AUTHORYEAR_PAR; - case 2: - return CitationType.AUTHORYEAR_INTEXT; - case 3: - return CitationType.INVISIBLE_CIT; - default: - throw new IllegalArgumentException("Invalid CitationType code"); - } + return switch (i) { + case 1 -> CitationType.AUTHORYEAR_PAR; + case 2 -> CitationType.AUTHORYEAR_INTEXT; + case 3 -> CitationType.INVISIBLE_CIT; + default -> throw new IllegalArgumentException("Invalid CitationType code"); + }; } private static int citationTypeToInt(CitationType i) { - switch (i) { - case AUTHORYEAR_PAR: - return 1; - case AUTHORYEAR_INTEXT: - return 2; - case INVISIBLE_CIT: - return 3; - default: - throw new IllegalArgumentException("Invalid CitationType"); - } + return switch (i) { + case AUTHORYEAR_PAR -> 1; + case AUTHORYEAR_INTEXT -> 2; + case INVISIBLE_CIT -> 3; + default -> throw new IllegalArgumentException("Invalid CitationType"); + }; } /** @@ -92,7 +84,7 @@ public static String getUniqueMarkName(Set usedNames, List citationKeys, CitationType citationType) { - String citationKeysPart = String.join(",", citationKeys); + String citationKeysPart = String.join(",", citationKeys); int i = 0; int citTypeCode = citationTypeToInt(citationType); diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java index d82ad08378e..93ad6d12908 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeManagerReferenceMark.java @@ -16,25 +16,25 @@ public class NamedRangeManagerReferenceMark implements NamedRangeManager { @Override - public NamedRange nrmCreate(XTextDocument doc, - String refMarkName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) + public NamedRange createNamedRange(XTextDocument doc, + String refMarkName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException { return NamedRangeReferenceMark.create(doc, refMarkName, position, insertSpaceAfter, withoutBrackets); } @Override - public List nrmGetUsedNames(XTextDocument doc) + public List getUsedNames(XTextDocument doc) throws NoDocumentException { return UnoReferenceMark.getListOfNames(doc); } @Override - public Optional nrmGetFromDocument(XTextDocument doc, String refMarkName) + public Optional getNamedRangeFromDocument(XTextDocument doc, String refMarkName) throws NoDocumentException, WrappedTargetException { diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index a11e29aecd1..cfabb1e2de0 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -141,43 +141,42 @@ static Optional getFromDocument(XTextDocument doc, Stri .map(e -> new NamedRangeReferenceMark(refMarkName))); } - /* + /** * Remove it from the document. * * See: removeCitationGroups */ @Override - public void nrRemoveFromDocument(XTextDocument doc) + public void removeFromDocument(XTextDocument doc) throws WrappedTargetException, NoDocumentException { - UnoReferenceMark.removeIfExists(doc, this.nrGetRangeName()); + UnoReferenceMark.removeIfExists(doc, this.getRangeName()); } @Override - public String nrGetRangeName() { + public String getRangeName() { return id; } - /* - * ranges controlled by citation groups should not overlap with each other. + /** * * @return Optional.empty if the reference mark is missing. * * See: UnoReferenceMark.getAnchor */ @Override - public Optional nrGetMarkRange(XTextDocument doc) + public Optional getMarkRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - String name = this.nrGetRangeName(); + String name = this.getRangeName(); return UnoReferenceMark.getAnchor(doc, name); } /** * Cursor for the reference marks as is, not prepared for filling, but does not need - * nrCleanFillCursor either. + * cleanFillCursor either. * * @return Optional.empty() if reference mark is missing from the document, * otherwise an XTextCursor for getMarkRange @@ -185,22 +184,22 @@ public Optional nrGetMarkRange(XTextDocument doc) * See: getRawCursorForCitationGroup */ @Override - public Optional nrGetRawCursor(XTextDocument doc) + public Optional getRawCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - String name = this.nrGetRangeName(); + String name = this.getRangeName(); Optional markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name); if (markAsTextContent.isEmpty()) { - LOGGER.warn("nrGetRawCursor: markAsTextContent({}).isEmpty()", name); + LOGGER.warn("getRawCursor: markAsTextContent({}).isEmpty()", name); } Optional full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()); if (full.isEmpty()) { - LOGGER.warn("nrGetRawCursor: full.isEmpty()"); + LOGGER.warn("getRawCursor: full.isEmpty()"); return Optional.empty(); } return full; @@ -210,13 +209,13 @@ public Optional nrGetRawCursor(XTextDocument doc) * See: getFillCursorForCitationGroup */ @Override - public XTextCursor nrGetFillCursor(XTextDocument doc) + public XTextCursor getFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, CreationException { - String name = this.nrGetRangeName(); + String name = this.getRangeName(); final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; @@ -228,31 +227,31 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) Optional markAsTextContent = UnoReferenceMark.getAsTextContent(doc, name); if (markAsTextContent.isEmpty()) { - String msg = String.format("nrGetFillCursor: markAsTextContent(%s).isEmpty (attempt %d)", name, i); + String msg = String.format("getFillCursor: markAsTextContent(%s).isEmpty (attempt %d)", name, i); throw new IllegalStateException(msg); } full = UnoCursor.getTextCursorOfTextContentAnchor(markAsTextContent.get()).orElse(null); if (full == null) { - String msg = String.format("nrGetFillCursor: full == null (attempt %d)", i); + String msg = String.format("getFillCursor: full == null (attempt %d)", i); throw new IllegalStateException(msg); } fullText = full.getString(); - LOGGER.debug("nrGetFillCursor: fulltext = '{}'", fullText); + LOGGER.debug("getFillCursor: fulltext = '{}'", fullText); if (fullText.length() >= 2) { - LOGGER.debug("nrGetFillCursor: (attempt: {}) fulltext.length() >= 2, break loop%n", i); + LOGGER.debug("getFillCursor: (attempt: {}) fulltext.length() >= 2, break loop%n", i); break; } else { // (fullText.length() < 2) if (i == 2) { - String msg = String.format("nrGetFillCursor: (fullText.length() < 2) (attempt %d)", i); + String msg = String.format("getFillCursor: (fullText.length() < 2) (attempt %d)", i); throw new IllegalStateException(msg); } // too short, recreate - LOGGER.warn("nrGetFillCursor: too short, recreate"); + LOGGER.warn("getFillCursor: too short, recreate"); full.setString(""); UnoReferenceMark.removeIfExists(doc, name); @@ -264,27 +263,27 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) } if (full == null) { - throw new IllegalStateException("nrGetFillCursorFor: full == null (after loop)"); + throw new IllegalStateException("getFillCursorFor: full == null (after loop)"); } if (fullText == null) { - throw new IllegalStateException("nrGetFillCursor: fullText == null (after loop)"); + throw new IllegalStateException("getFillCursor: fullText == null (after loop)"); } fullText = full.getString(); if (fullText.length() < 2) { - throw new IllegalStateException("nrGetFillCursor: fullText.length() < 2 (after loop)'%n"); + throw new IllegalStateException("getFillCursor: fullText.length() < 2 (after loop)'%n"); } XTextCursor beta = full.getText().createTextCursorByRange(full); beta.collapseToStart(); beta.goRight((short) 1, false); beta.goRight((short) (fullText.length() - 2), true); - LOGGER.debug("nrGetFillCursor: beta(1) covers '{}'", beta.getString()); + LOGGER.debug("getFillCursor: beta(1) covers '{}'", beta.getString()); final short rightLength = (short) right.length(); if (fullText.startsWith(left) && fullText.endsWith(right)) { beta.setString(""); } else { - LOGGER.debug("nrGetFillCursor: recreating brackets for '{}'", fullText); + LOGGER.debug("getFillCursor: recreating brackets for '{}'", fullText); // we have at least two characters inside XTextCursor alpha = full.getText().createTextCursorByRange(full); @@ -299,41 +298,41 @@ public XTextCursor nrGetFillCursor(XTextDocument doc) String paddingy = "y"; String paddingz = "z"; beta.setString(paddingx + left + paddingy + right + paddingz); - LOGGER.debug("nrGetFillCursor: beta(2) covers '{}'", beta.getString()); + LOGGER.debug("getFillCursor: beta(2) covers '{}'", beta.getString()); // move beta to before the right bracket beta.collapseToEnd(); beta.goLeft((short) (rightLength + 1), false); // remove middle padding beta.goLeft((short) 1, true); - LOGGER.debug("nrGetFillCursor: beta(3) covers '{}'", beta.getString()); + LOGGER.debug("getFillCursor: beta(3) covers '{}'", beta.getString()); // only drop paddingy later: beta.setString(""); // drop the initial character and paddingx alpha.collapseToStart(); alpha.goRight((short) (1 + 1), true); - LOGGER.debug("nrGetFillCursor: alpha(4) covers '{}'", alpha.getString()); + LOGGER.debug("getFillCursor: alpha(4) covers '{}'", alpha.getString()); alpha.setString(""); // drop the last character and paddingz omega.collapseToEnd(); omega.goLeft((short) (1 + 1), true); - LOGGER.debug("nrGetFillCursor: omega(5) covers '{}'", omega.getString()); + LOGGER.debug("getFillCursor: omega(5) covers '{}'", omega.getString()); omega.setString(""); // drop paddingy now - LOGGER.debug("nrGetFillCursor: beta(6) covers '{}'", beta.getString()); + LOGGER.debug("getFillCursor: beta(6) covers '{}'", beta.getString()); beta.setString(""); // should be OK now. if (debugThisFun) { final short leftLength = (short) left.length(); alpha.goRight(leftLength, true); - LOGGER.debug("nrGetFillCursor: alpha(7) covers '{}', should be '{}'", alpha.getString(), left); + LOGGER.debug("getFillCursor: alpha(7) covers '{}', should be '{}'", alpha.getString(), left); omega.goLeft(rightLength, true); - LOGGER.debug("nrGetFillCursor: omega(8) covers '{}', should be '{}'", omega.getString(), right); + LOGGER.debug("getFillCursor: omega(8) covers '{}', should be '{}'", omega.getString(), right); } } @@ -384,13 +383,13 @@ public static void checkFillCursor(XTextCursor cursor) { * See: cleanFillCursorForCitationGroup */ @Override - public void nrCleanFillCursor(XTextDocument doc) + public void cleanFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException { // alwaysRemoveBrackets : full compatibility with JabRef 5.2: brackets are temporary, only - // exist between nrGetFillCursor and nrCleanFillCursor. + // exist between getFillCursor and cleanFillCursor. final boolean alwaysRemoveBrackets = false; // removeBracketsFromEmpty is intended to force removal if we are working on an "Empty citation" (INVISIBLE_CIT). @@ -401,25 +400,25 @@ public void nrCleanFillCursor(XTextDocument doc) final short leftLength = (short) left.length(); final short rightLength = (short) right.length(); - String name = this.nrGetRangeName(); + String name = this.getRangeName(); - XTextCursor full = this.nrGetRawCursor(doc).orElseThrow(IllegalStateException::new); + XTextCursor full = this.getRawCursor(doc).orElseThrow(IllegalStateException::new); final String fullText = full.getString(); final int fullTextLength = fullText.length(); if (!fullText.startsWith(left)) { - String msg = String.format("nrCleanFillCursor: (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", name); + String msg = String.format("cleanFillCursor: (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", name); throw new IllegalStateException(msg); } if (!fullText.endsWith(right)) { - String msg = String.format("nrCleanFillCursor: (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", name); + String msg = String.format("cleanFillCursor: (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", name); throw new IllegalStateException(msg); } final int contentLength = (fullTextLength - (leftLength + rightLength)); if (contentLength < 0) { - String msg = String.format("nrCleanFillCursor: length(%s) < 0", name); + String msg = String.format("cleanFillCursor: length(%s) < 0", name); throw new IllegalStateException(msg); } diff --git a/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java b/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java index aa09f36edef..63981ceba70 100644 --- a/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java +++ b/src/main/java/org/jabref/model/openoffice/backend/NamedRange.java @@ -10,23 +10,32 @@ import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; +/** + * NamedRange (with NamedRangeManager) attempts to provide a common interface for working with + * reference mark based and bookmark based text ranges to be used as locations to fill with citation + * markers. LibreOffice supports name-based lookup and listing names for both (hence the name). + * + * Note: currently only implemented for refence marks (in NamedRangeReferenceMark and + * NamedRangeManagerReferenceMark). + * + */ public interface NamedRange { - String nrGetRangeName(); + String getRangeName(); /** * @return Optional.empty if the mark is missing from the document. */ - Optional nrGetMarkRange(XTextDocument doc) + Optional getMarkRange(XTextDocument doc) throws NoDocumentException, WrappedTargetException; /** * Cursor for the reference marks as is, not prepared for filling, but does not need - * nrCleanFillCursor either. + * cleanFillCursor either. */ - Optional nrGetRawCursor(XTextDocument doc) + Optional getRawCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException; @@ -34,9 +43,9 @@ Optional nrGetRawCursor(XTextDocument doc) /** * Get a cursor for filling in text. * - * Must be followed by nrCleanFillCursor() + * Must be followed by cleanFillCursor() */ - XTextCursor nrGetFillCursor(XTextDocument doc) + XTextCursor getFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException, @@ -47,7 +56,7 @@ XTextCursor nrGetFillCursor(XTextDocument doc) * single character, leave the left bracket. * */ - void nrCleanFillCursor(XTextDocument doc) + void cleanFillCursor(XTextDocument doc) throws NoDocumentException, WrappedTargetException; @@ -55,7 +64,7 @@ void nrCleanFillCursor(XTextDocument doc) /** * Note: create is in NamedRangeManager */ - void nrRemoveFromDocument(XTextDocument doc) + void removeFromDocument(XTextDocument doc) throws WrappedTargetException, NoDocumentException; diff --git a/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java b/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java index 536871b5c34..9bbcc752350 100644 --- a/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java +++ b/src/main/java/org/jabref/model/openoffice/backend/NamedRangeManager.java @@ -12,19 +12,19 @@ public interface NamedRangeManager { - NamedRange nrmCreate(XTextDocument doc, - String markName, - XTextCursor position, - boolean insertSpaceAfter, - boolean withoutBrackets) + NamedRange createNamedRange(XTextDocument doc, + String markName, + XTextCursor position, + boolean insertSpaceAfter, + boolean withoutBrackets) throws CreationException; - List nrmGetUsedNames(XTextDocument doc) + List getUsedNames(XTextDocument doc) throws NoDocumentException; - Optional nrmGetFromDocument(XTextDocument doc, String markName) + Optional getNamedRangeFromDocument(XTextDocument doc, String markName) throws NoDocumentException, WrappedTargetException; From cb132566f32cba17af24b41d037446a96a90dc16 Mon Sep 17 00:00:00 2001 From: Antal K Date: Fri, 20 Aug 2021 11:39:39 +0200 Subject: [PATCH 1060/1068] align dots --- .../java/org/jabref/logic/openoffice/backend/Codec52.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index 1b6fd3704f8..f567a3e459e 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -130,9 +130,8 @@ public static boolean isJabRefReferenceMarkName(String name) { * @param names The list to be filtered. */ public static List filterIsJabRefReferenceMarkName(List names) { - return (names - .stream() - .filter(Codec52::isJabRefReferenceMarkName) - .collect(Collectors.toList())); + return (names.stream() + .filter(Codec52::isJabRefReferenceMarkName) + .collect(Collectors.toList())); } } From 76b21b975b115aa95c179c76244f6a3337021ece Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 22 Aug 2021 15:11:10 +0200 Subject: [PATCH 1061/1068] add config/emacs/lsp-java --- .gitignore | 4 ++ config/emacs/lsp-java/Makefile | 12 +++++ config/emacs/lsp-java/README.md | 20 ++++++++ config/emacs/lsp-java/eclipse-jdt.classpath | 51 +++++++++++++++++++ config/emacs/lsp-java/eclipse-jdt.project | 34 +++++++++++++ .../org.eclipse.buildship.core.prefs | 13 +++++ .../org.eclipse.jdt.core.prefs | 4 ++ 7 files changed, 138 insertions(+) create mode 100644 config/emacs/lsp-java/Makefile create mode 100644 config/emacs/lsp-java/README.md create mode 100644 config/emacs/lsp-java/eclipse-jdt.classpath create mode 100644 config/emacs/lsp-java/eclipse-jdt.project create mode 100644 config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.buildship.core.prefs create mode 100644 config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.jdt.core.prefs diff --git a/.gitignore b/.gitignore index fd187d3f735..25e0600022b 100644 --- a/.gitignore +++ b/.gitignore @@ -70,6 +70,10 @@ local.properties .loadpath .recommenders +# config/emacs/lsp-java/Makefile will create a symlink named .settings +# Also exclude that, for consistency. +.settings + # External tool builders .externalToolBuilders/ diff --git a/config/emacs/lsp-java/Makefile b/config/emacs/lsp-java/Makefile new file mode 100644 index 00000000000..2bbf1eaddf2 --- /dev/null +++ b/config/emacs/lsp-java/Makefile @@ -0,0 +1,12 @@ + +# Toplevel directory of jabref +TOP = ../../.. + +# lsp-java files +SYMLINK_TARGETS = .classpath .project .settings + +all: + @echo "use make setup to create symnlinks to these files" + +setup: + for f in $(SYMLINK_TARGETS) ; do ln -sf config/emacs/lsp-java/eclipse-jdt$$f $(TOP)/$$f ; done diff --git a/config/emacs/lsp-java/README.md b/config/emacs/lsp-java/README.md new file mode 100644 index 00000000000..70c09c61e9d --- /dev/null +++ b/config/emacs/lsp-java/README.md @@ -0,0 +1,20 @@ + +Emacs with lsp-java needs some setup. + +`.classpath` is needed for finding JARs and sources + +`.project` and `.settings` were autogenerated by lsp-java + + +These name however appear in .gitignore excluding them from git. + +So I moved them here and provided a Makefile, so that +`make setup` +will establish symlinks to these. + +However, these names happen to be ignored recursively. +To avoid more changes to .gitignore, I prefixed them here with eclips-jdt. + + + + diff --git a/config/emacs/lsp-java/eclipse-jdt.classpath b/config/emacs/lsp-java/eclipse-jdt.classpath new file mode 100644 index 00000000000..e25b3170033 --- /dev/null +++ b/config/emacs/lsp-java/eclipse-jdt.classpath @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/emacs/lsp-java/eclipse-jdt.project b/config/emacs/lsp-java/eclipse-jdt.project new file mode 100644 index 00000000000..94975ef7827 --- /dev/null +++ b/config/emacs/lsp-java/eclipse-jdt.project @@ -0,0 +1,34 @@ + + + JabRef + Project jabref created by Buildship. + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.buildship.core.gradleprojectnature + + + + 1622997329481 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|.metadata|archetype-resources|META-INF/maven|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.buildship.core.prefs b/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.buildship.core.prefs new file mode 100644 index 00000000000..2b6d83b978b --- /dev/null +++ b/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.buildship.core.prefs @@ -0,0 +1,13 @@ +arguments= +auto.sync=false +build.scans.enabled=false +connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER) +connection.project.dir= +eclipse.preferences.version=1 +gradle.user.home= +java.home=/usr/lib/jvm/java-11-openjdk-amd64 +jvm.arguments= +offline.mode=false +override.workspace.settings=true +show.console.view=true +show.executions.view=true diff --git a/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.jdt.core.prefs b/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000000..99b7c05044a --- /dev/null +++ b/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=14 +org.eclipse.jdt.core.compiler.compliance=14 +org.eclipse.jdt.core.compiler.source=14 From eed6be1411c9148712a3ec839bc4c4668b1c9e1a Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 22 Aug 2021 15:53:58 +0200 Subject: [PATCH 1062/1068] make PMD happier with longer names --- .../openoffice/ConnectionLostException.java | 4 +- .../org/jabref/gui/openoffice/OOBibBase2.java | 54 +++++++++---------- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java b/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java index 36fc16e5e3f..df0264be0de 100644 --- a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java +++ b/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java @@ -5,7 +5,7 @@ */ class ConnectionLostException extends RuntimeException { - public ConnectionLostException(String s) { - super(s); + public ConnectionLostException(String msg) { + super(msg); } } diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index 9832adb991d..d1793bd5507 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -151,12 +151,12 @@ public Optional getCurrentDocumentTitle() { * * ******************************************************/ - void showDialog(OOError ex) { - ex.showErrorDialog(dialogService); + void showDialog(OOError err) { + err.showErrorDialog(dialogService); } - void showDialog(String title, OOError ex) { - ex.setTitle(title).showErrorDialog(dialogService); + void showDialog(String title, OOError err) { + err.setTitle(title).showErrorDialog(dialogService); } OOVoidResult collectResults(String title, List> results) { @@ -185,8 +185,8 @@ boolean testDialog(String title, List> results) { @SafeVarargs final boolean testDialog(String title, OOVoidResult... results) { - List> rs = Arrays.asList(results); - return testDialog(collectResults(title, rs)); + List> resultList = Arrays.asList(results); + return testDialog(collectResults(title, resultList)); } /* @@ -232,16 +232,16 @@ OOResult getFunctionalTextViewCursor(XTextDoc return result.mapError(detail -> new OOError(title, messageOnFailureToObtain)); } - private static OOVoidResult checkRangeOverlaps(XTextDocument doc, OOFrontend fr) { + private static OOVoidResult checkRangeOverlaps(XTextDocument doc, OOFrontend fontend) { final String title = "checkRangeOverlaps"; boolean requireSeparation = false; int maxReportedOverlaps = 10; try { - return (fr.checkRangeOverlaps(doc, - new ArrayList<>(), - requireSeparation, - maxReportedOverlaps) - .mapError(OOError::from)); + return (fontend.checkRangeOverlaps(doc, + new ArrayList<>(), + requireSeparation, + maxReportedOverlaps) + .mapError(OOError::from)); } catch (NoDocumentException ex) { return OOVoidResult.error(OOError.from(ex).setTitle(title)); } catch (WrappedTargetException ex) { @@ -249,18 +249,18 @@ private static OOVoidResult checkRangeOverlaps(XTextDocument doc, OOFro } } - private static OOVoidResult checkRangeOverlapsWithCursor(XTextDocument doc, OOFrontend fr) { + private static OOVoidResult checkRangeOverlapsWithCursor(XTextDocument doc, OOFrontend fontend) { final String title = "checkRangeOverlapsWithCursor"; List> userRanges; - userRanges = fr.viewCursorRanges(doc); + userRanges = fontend.viewCursorRanges(doc); boolean requireSeparation = false; OOVoidResult res; try { - res = fr.checkRangeOverlapsWithCursor(doc, - userRanges, - requireSeparation); + res = fontend.checkRangeOverlapsWithCursor(doc, + userRanges, + requireSeparation); } catch (NoDocumentException ex) { return OOVoidResult.error(OOError.from(ex).setTitle(title)); } catch (WrappedTargetException ex) { @@ -592,14 +592,14 @@ public void guiActionInsertEntry(List entries, if (testDialog(title, ofr.asVoidResult())) { return; } - OOFrontend fr = ofr.get(); + OOFrontend fontend = ofr.get(); OOResult cursor = getUserCursorForTextInsertion(doc, title); if (testDialog(title, cursor.asVoidResult())) { return; } - if (testDialog(title, checkRangeOverlapsWithCursor(doc, fr))) { + if (testDialog(title, checkRangeOverlapsWithCursor(doc, fontend))) { return; } @@ -635,7 +635,7 @@ public void guiActionInsertEntry(List entries, UnoUndo.enterUndoContext(doc, "Insert citation"); EditInsert.insertCitationGroup(doc, - fr, + fontend, cursor.get(), entries, database, @@ -695,8 +695,8 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle try { UnoUndo.enterUndoContext(doc, "Merge citations"); - OOFrontend fr = new OOFrontend(doc); - boolean madeModifications = EditMerge.mergeCitationGroups(doc, fr, style); + OOFrontend fontend = new OOFrontend(doc); + boolean madeModifications = EditMerge.mergeCitationGroups(doc, fontend, style); if (madeModifications) { UnoCrossRef.refresh(doc); Update.SyncOptions syncOptions = new Update.SyncOptions(databases); @@ -752,8 +752,8 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s try { UnoUndo.enterUndoContext(doc, "Separate citations"); - OOFrontend fr = new OOFrontend(doc); - boolean madeModifications = EditSeparate.separateCitations(doc, fr, databases, style); + OOFrontend fontend = new OOFrontend(doc); + boolean madeModifications = EditSeparate.separateCitations(doc, fontend, databases, style); if (madeModifications) { UnoCrossRef.refresh(doc); Update.SyncOptions syncOptions = new Update.SyncOptions(databases); @@ -881,8 +881,8 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl return; } - OOFrontend fr = new OOFrontend(doc); - if (testDialog(title, checkRangeOverlaps(doc, fr))) { + OOFrontend fontend = new OOFrontend(doc); + if (testDialog(title, checkRangeOverlaps(doc, fontend))) { return; } @@ -895,7 +895,7 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl .setUpdateBibliography(true) .setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages); - unresolvedKeys = Update.synchronizeDocument(doc, fr, style, fcursor.get(), syncOptions); + unresolvedKeys = Update.synchronizeDocument(doc, fontend, style, fcursor.get(), syncOptions); } finally { UnoUndo.leaveUndoContext(doc); From f2b86a55585026751bb9ad974a39de5af797f662 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 22 Aug 2021 16:06:20 +0200 Subject: [PATCH 1063/1068] fontend -> frontend --- .../org/jabref/gui/openoffice/OOBibBase2.java | 35 +++++++++---------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index d1793bd5507..817b3f854e8 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -232,15 +232,15 @@ OOResult getFunctionalTextViewCursor(XTextDoc return result.mapError(detail -> new OOError(title, messageOnFailureToObtain)); } - private static OOVoidResult checkRangeOverlaps(XTextDocument doc, OOFrontend fontend) { + private static OOVoidResult checkRangeOverlaps(XTextDocument doc, OOFrontend frontend) { final String title = "checkRangeOverlaps"; boolean requireSeparation = false; int maxReportedOverlaps = 10; try { - return (fontend.checkRangeOverlaps(doc, - new ArrayList<>(), - requireSeparation, - maxReportedOverlaps) + return (frontend.checkRangeOverlaps(doc, + new ArrayList<>(), + requireSeparation, + maxReportedOverlaps) .mapError(OOError::from)); } catch (NoDocumentException ex) { return OOVoidResult.error(OOError.from(ex).setTitle(title)); @@ -249,16 +249,16 @@ private static OOVoidResult checkRangeOverlaps(XTextDocument doc, OOFro } } - private static OOVoidResult checkRangeOverlapsWithCursor(XTextDocument doc, OOFrontend fontend) { + private static OOVoidResult checkRangeOverlapsWithCursor(XTextDocument doc, OOFrontend frontend) { final String title = "checkRangeOverlapsWithCursor"; List> userRanges; - userRanges = fontend.viewCursorRanges(doc); + userRanges = frontend.viewCursorRanges(doc); boolean requireSeparation = false; OOVoidResult res; try { - res = fontend.checkRangeOverlapsWithCursor(doc, + res = frontend.checkRangeOverlapsWithCursor(doc, userRanges, requireSeparation); } catch (NoDocumentException ex) { @@ -592,14 +592,13 @@ public void guiActionInsertEntry(List entries, if (testDialog(title, ofr.asVoidResult())) { return; } - OOFrontend fontend = ofr.get(); OOResult cursor = getUserCursorForTextInsertion(doc, title); if (testDialog(title, cursor.asVoidResult())) { return; } - if (testDialog(title, checkRangeOverlapsWithCursor(doc, fontend))) { + if (testDialog(title, checkRangeOverlapsWithCursor(doc, ofr.get()))) { return; } @@ -635,7 +634,7 @@ public void guiActionInsertEntry(List entries, UnoUndo.enterUndoContext(doc, "Insert citation"); EditInsert.insertCitationGroup(doc, - fontend, + frontend, cursor.get(), entries, database, @@ -695,8 +694,8 @@ public void guiActionMergeCitationGroups(List databases, OOBibStyle try { UnoUndo.enterUndoContext(doc, "Merge citations"); - OOFrontend fontend = new OOFrontend(doc); - boolean madeModifications = EditMerge.mergeCitationGroups(doc, fontend, style); + OOFrontend frontend = new OOFrontend(doc); + boolean madeModifications = EditMerge.mergeCitationGroups(doc, frontend, style); if (madeModifications) { UnoCrossRef.refresh(doc); Update.SyncOptions syncOptions = new Update.SyncOptions(databases); @@ -752,8 +751,8 @@ public void guiActionSeparateCitations(List databases, OOBibStyle s try { UnoUndo.enterUndoContext(doc, "Separate citations"); - OOFrontend fontend = new OOFrontend(doc); - boolean madeModifications = EditSeparate.separateCitations(doc, fontend, databases, style); + OOFrontend frontend = new OOFrontend(doc); + boolean madeModifications = EditSeparate.separateCitations(doc, frontend, databases, style); if (madeModifications) { UnoCrossRef.refresh(doc); Update.SyncOptions syncOptions = new Update.SyncOptions(databases); @@ -881,8 +880,8 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl return; } - OOFrontend fontend = new OOFrontend(doc); - if (testDialog(title, checkRangeOverlaps(doc, fontend))) { + OOFrontend frontend = new OOFrontend(doc); + if (testDialog(title, checkRangeOverlaps(doc, frontend))) { return; } @@ -895,7 +894,7 @@ public void guiActionUpdateDocument(List databases, OOBibStyle styl .setUpdateBibliography(true) .setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages); - unresolvedKeys = Update.synchronizeDocument(doc, fontend, style, fcursor.get(), syncOptions); + unresolvedKeys = Update.synchronizeDocument(doc, frontend, style, fcursor.get(), syncOptions); } finally { UnoUndo.leaveUndoContext(doc); From ae9abcc1781a6e4919117edfb2a9e66a0ac275d8 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 22 Aug 2021 18:33:03 +0200 Subject: [PATCH 1064/1068] ignore some PMD output --- Makefile | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 4629a6494f8..41c8a6a60b4 100644 --- a/Makefile +++ b/Makefile @@ -92,4 +92,22 @@ PMD = pmd -f text -R ../tools/pmd/pmd-java-rules.xml -cache /tmp/pmd-jabref-cach pmd: # $(PMD) -d src/main/java/org/jabref/model/openoffice # $(PMD) -d src/main/java/org/jabref/logic/openoffice - $(PMD) -d src/main/java/org/jabref/gui/openoffice +# +# +# - Ignore problems in old files (OOBibBase, Bootstrap, DetectOpenOfficeInstallation). +# - Ignore @FXML initalize UnusedPrivateMethod +# +# - Ignore IdenticalCatchBranches : PMD seems to ignore that textually +# identical branches can lead to different code based on type of the +# exception. +# +# + $(PMD) -d src/main/java/org/jabref/gui/openoffice \ + | egrep -v 'src/main/java/org/jabref/gui/openoffice/OOBibBase.java' \ + | egrep -v 'src/main/java/org/jabref/gui/openoffice/Bootstrap.java' \ + | egrep -v 'src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java' \ + | egrep -v 'src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java' \ + | egrep -v "UnusedPrivateMethod.*initialize" \ + | egrep -v '\sIdenticalCatchBranches:\s' \ + + From 3de1a6e75ed1e1d30e6d76ec857b8ef733404f01 Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 22 Aug 2021 21:09:11 +0200 Subject: [PATCH 1065/1068] rename ofr to frontend --- src/main/java/org/jabref/gui/openoffice/OOBibBase2.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java index 817b3f854e8..d8523f0cd77 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase2.java @@ -588,8 +588,8 @@ public void guiActionInsertEntry(List entries, } XTextDocument doc = odoc.get(); - OOResult ofr = getFrontend(doc); - if (testDialog(title, ofr.asVoidResult())) { + OOResult frontend = getFrontend(doc); + if (testDialog(title, frontend.asVoidResult())) { return; } @@ -598,7 +598,7 @@ public void guiActionInsertEntry(List entries, return; } - if (testDialog(title, checkRangeOverlapsWithCursor(doc, ofr.get()))) { + if (testDialog(title, checkRangeOverlapsWithCursor(doc, frontend.get()))) { return; } @@ -634,7 +634,7 @@ public void guiActionInsertEntry(List entries, UnoUndo.enterUndoContext(doc, "Insert citation"); EditInsert.insertCitationGroup(doc, - frontend, + frontend.get(), cursor.get(), entries, database, From 9a8c4a3f9a138a1caf922056fddb86fd648b238e Mon Sep 17 00:00:00 2001 From: Antal K Date: Sun, 22 Aug 2021 21:14:25 +0200 Subject: [PATCH 1066/1068] drop config/emacs/lsp-java/ --- config/emacs/lsp-java/Makefile | 12 ----- config/emacs/lsp-java/README.md | 20 -------- config/emacs/lsp-java/eclipse-jdt.classpath | 51 ------------------- config/emacs/lsp-java/eclipse-jdt.project | 34 ------------- .../org.eclipse.buildship.core.prefs | 13 ----- .../org.eclipse.jdt.core.prefs | 4 -- 6 files changed, 134 deletions(-) delete mode 100644 config/emacs/lsp-java/Makefile delete mode 100644 config/emacs/lsp-java/README.md delete mode 100644 config/emacs/lsp-java/eclipse-jdt.classpath delete mode 100644 config/emacs/lsp-java/eclipse-jdt.project delete mode 100644 config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.buildship.core.prefs delete mode 100644 config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.jdt.core.prefs diff --git a/config/emacs/lsp-java/Makefile b/config/emacs/lsp-java/Makefile deleted file mode 100644 index 2bbf1eaddf2..00000000000 --- a/config/emacs/lsp-java/Makefile +++ /dev/null @@ -1,12 +0,0 @@ - -# Toplevel directory of jabref -TOP = ../../.. - -# lsp-java files -SYMLINK_TARGETS = .classpath .project .settings - -all: - @echo "use make setup to create symnlinks to these files" - -setup: - for f in $(SYMLINK_TARGETS) ; do ln -sf config/emacs/lsp-java/eclipse-jdt$$f $(TOP)/$$f ; done diff --git a/config/emacs/lsp-java/README.md b/config/emacs/lsp-java/README.md deleted file mode 100644 index 70c09c61e9d..00000000000 --- a/config/emacs/lsp-java/README.md +++ /dev/null @@ -1,20 +0,0 @@ - -Emacs with lsp-java needs some setup. - -`.classpath` is needed for finding JARs and sources - -`.project` and `.settings` were autogenerated by lsp-java - - -These name however appear in .gitignore excluding them from git. - -So I moved them here and provided a Makefile, so that -`make setup` -will establish symlinks to these. - -However, these names happen to be ignored recursively. -To avoid more changes to .gitignore, I prefixed them here with eclips-jdt. - - - - diff --git a/config/emacs/lsp-java/eclipse-jdt.classpath b/config/emacs/lsp-java/eclipse-jdt.classpath deleted file mode 100644 index e25b3170033..00000000000 --- a/config/emacs/lsp-java/eclipse-jdt.classpath +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/config/emacs/lsp-java/eclipse-jdt.project b/config/emacs/lsp-java/eclipse-jdt.project deleted file mode 100644 index 94975ef7827..00000000000 --- a/config/emacs/lsp-java/eclipse-jdt.project +++ /dev/null @@ -1,34 +0,0 @@ - - - JabRef - Project jabref created by Buildship. - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.buildship.core.gradleprojectbuilder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.buildship.core.gradleprojectnature - - - - 1622997329481 - - 30 - - org.eclipse.core.resources.regexFilterMatcher - node_modules|.metadata|archetype-resources|META-INF/maven|__CREATED_BY_JAVA_LANGUAGE_SERVER__ - - - - diff --git a/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.buildship.core.prefs b/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.buildship.core.prefs deleted file mode 100644 index 2b6d83b978b..00000000000 --- a/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.buildship.core.prefs +++ /dev/null @@ -1,13 +0,0 @@ -arguments= -auto.sync=false -build.scans.enabled=false -connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER) -connection.project.dir= -eclipse.preferences.version=1 -gradle.user.home= -java.home=/usr/lib/jvm/java-11-openjdk-amd64 -jvm.arguments= -offline.mode=false -override.workspace.settings=true -show.console.view=true -show.executions.view=true diff --git a/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.jdt.core.prefs b/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 99b7c05044a..00000000000 --- a/config/emacs/lsp-java/eclipse-jdt.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=14 -org.eclipse.jdt.core.compiler.compliance=14 -org.eclipse.jdt.core.compiler.source=14 From 771e8d3605f0503ff9a3909c3e0dfeeace513a5d Mon Sep 17 00:00:00 2001 From: Antal K Date: Mon, 23 Aug 2021 16:38:53 +0200 Subject: [PATCH 1067/1068] follow some PMD suggestions --- Makefile | 22 ++- .../org/jabref/gui/openoffice/OOError.java | 24 +-- .../org/jabref/logic/openoffice/OOUtil.java | 15 +- .../logic/openoffice/action/EditInsert.java | 4 +- .../logic/openoffice/action/EditMerge.java | 20 +-- .../logic/openoffice/action/EditSeparate.java | 14 +- .../logic/openoffice/action/ExportCited.java | 4 +- .../openoffice/action/ManageCitations.java | 8 +- .../logic/openoffice/action/Update.java | 22 +-- .../logic/openoffice/backend/Backend52.java | 22 +-- .../logic/openoffice/backend/Codec52.java | 26 ++-- .../backend/NamedRangeReferenceMark.java | 27 ++-- .../frontend/UpdateBibliography.java | 8 +- .../frontend/UpdateCitationMarkers.java | 28 ++-- .../logic/openoffice/style/OOBibStyle.java | 140 +++++++++--------- .../style/OOBibStyleGetCitationMarker.java | 90 +++++------ .../style/OOBibStyleGetNumCitationMarker.java | 62 ++++---- .../style/OOFormatBibliography.java | 58 ++++---- .../style/OOProcessAuthorYearMarkers.java | 4 +- .../model/openoffice/CitationEntry.java | 8 +- .../openoffice/style/CitationGroupId.java | 8 +- .../openoffice/style/CitationGroups.java | 5 +- .../model/openoffice/style/CitedKeys.java | 6 +- .../model/openoffice/style/PageInfo.java | 2 +- .../model/openoffice/uno/UnoCursor.java | 4 +- .../jabref/model/openoffice/uno/UnoStyle.java | 4 +- .../jabref/model/openoffice/uno/UnoUndo.java | 12 +- .../uno/UnoUserDefinedProperty.java | 4 +- .../model/openoffice/util/OOListUtil.java | 16 +- 29 files changed, 338 insertions(+), 329 deletions(-) diff --git a/Makefile b/Makefile index 41c8a6a60b4..98e43fa75c2 100644 --- a/Makefile +++ b/Makefile @@ -95,19 +95,37 @@ pmd: # # # - Ignore problems in old files (OOBibBase, Bootstrap, DetectOpenOfficeInstallation). -# - Ignore @FXML initalize UnusedPrivateMethod +# - Ignore UnusedPrivateMethod for @FXML initalize / addStyleFile # # - Ignore IdenticalCatchBranches : PMD seems to ignore that textually # identical branches can lead to different code based on type of the # exception. # +# - Ignore some warnings in OOBibStyle.java for old stuff to be removed # - $(PMD) -d src/main/java/org/jabref/gui/openoffice \ + $(PMD) -d src/main/java/org/jabref/logic/openoffice \ | egrep -v 'src/main/java/org/jabref/gui/openoffice/OOBibBase.java' \ | egrep -v 'src/main/java/org/jabref/gui/openoffice/Bootstrap.java' \ | egrep -v 'src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java' \ | egrep -v 'src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java' \ + | egrep -v 'src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java' \ + | egrep -v 'src/main/java/org/jabref/logic/openoffice/OpenOfficePreferences.java' \ + | egrep -v 'src/main/java/org/jabref/logic/openoffice/style/OOPreFormatter.java' \ | egrep -v "UnusedPrivateMethod.*initialize" \ + | egrep -v 'UnusedPrivateMethod:.*addStyleFile' \ | egrep -v '\sIdenticalCatchBranches:\s' \ + | egrep -v '\sPreserveStackTrace:\s' \ + | egrep -v '\sUseUtilityClass:\s' \ + | egrep -v 'ShortVariable: Avoid variables with short names like (a|b|db|aa|bb)$$' \ + | egrep -v 'model/openoffice/style/CitedKeys.java:.*LooseCoupling:.*Avoid.*LinkedHashMap' \ + | egrep -v 'OOBibStyle.java.*names like (i1|al|to|j)$$' \ + | egrep -v 'OOBibStyle.java.*UseVarargs:' \ + | egrep -v 'OOBibStyleGetCitationMarker.java.*PrematureDeclaration:' \ + | egrep -v 'OOBibStyleGetCitationMarker.java.*SimplifiedTernary:' \ + | egrep -v 'OOBibStyleGetCitationMarker.java.*ShortVariable:.*like (j)$$' \ + | egrep -v 'OOBibStyleGetNumCitationMarker.java.*ShortVariable:.*like (na|nb)$$' \ + | egrep -v 'OOBibStyleGetNumCitationMarker.java.*(PrematureDeclaration|EmptyIfStmt):' \ + | egrep -v 'NamedRangeReferenceMark.java.*PrematureDeclaration:' \ + | egrep -v 'OOFormatBibliography.java.*(EmptyIfStmt|PrematureDeclaration):' diff --git a/src/main/java/org/jabref/gui/openoffice/OOError.java b/src/main/java/org/jabref/gui/openoffice/OOError.java index 44e70b3e975..b296ffe30c0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOError.java +++ b/src/main/java/org/jabref/gui/openoffice/OOError.java @@ -39,50 +39,50 @@ public void showErrorDialog(DialogService dialogService) { * Conversions from exception caught */ - public static OOError from(JabRefException ex) { + public static OOError from(JabRefException err) { return new OOError( Localization.lang("JabRefException"), - ex.getLocalizedMessage(), - ex); + err.getLocalizedMessage(), + err); } // For DisposedException - public static OOError from(DisposedException ex) { + public static OOError from(DisposedException err) { return new OOError( Localization.lang("Connection lost"), Localization.lang("Connection to OpenOffice/LibreOffice has been lost." + " Please make sure OpenOffice/LibreOffice is running," + " and try to reconnect."), - ex); + err); } // For NoDocumentException - public static OOError from(NoDocumentException ex) { + public static OOError from(NoDocumentException err) { return new OOError( Localization.lang("Not connected to document"), Localization.lang("Not connected to any Writer document." + " Please make sure a document is open," + " and use the 'Select Writer document' button" + " to connect to it."), - ex); + err); } // For NoDocumentFoundException - public static OOError from(NoDocumentFoundException ex) { + public static OOError from(NoDocumentFoundException err) { return new OOError( Localization.lang("No Writer documents found"), Localization.lang("Could not connect to any Writer document." + " Please make sure a document is open" + " before using the 'Select Writer document' button" + " to connect to it."), - ex); + err); } - public static OOError fromMisc(Exception ex) { + public static OOError fromMisc(Exception err) { return new OOError( "Exception", - ex.getMessage(), - ex); + err.getMessage(), + err); } /* diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 9efab82773c..a5976cb3342 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -127,13 +127,13 @@ public static void insertOOFormattedTextAtCurrentLocation(XText text, XTextCurso List formatting = new ArrayList<>(); // We need to extract formatting. Use a simple regexp search iteration: int piv = 0; - Matcher m = OOUtil.HTML_TAG.matcher(lText); - while (m.find()) { - String currentSubstring = lText.substring(piv, m.start()); + Matcher matcher = OOUtil.HTML_TAG.matcher(lText); + while (matcher.find()) { + String currentSubstring = lText.substring(piv, matcher.start()); if (!currentSubstring.isEmpty()) { OOUtil.insertTextAtCurrentLocation(text, cursor, currentSubstring, formatting); } - String tag = m.group(); + String tag = matcher.group(); // Handle tags: if ("".equals(tag)) { formatting.add(Formatting.BOLD); @@ -169,7 +169,7 @@ public static void insertOOFormattedTextAtCurrentLocation(XText text, XTextCurso formatting.remove(Formatting.STRIKEOUT); } - piv = m.end(); + piv = matcher.end(); } if (piv < lText.length()) { @@ -276,10 +276,9 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S cursor.collapseToEnd(); } - public static Object getProperty(Object o, String property) + public static Object getProperty(Object object, String property) throws UnknownPropertyException, WrappedTargetException { - XPropertySet props = UnoRuntime.queryInterface( - XPropertySet.class, o); + XPropertySet props = UnoRuntime.queryInterface(XPropertySet.class, object); return props.getPropertyValue(property); } } diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index 81491bd8590..375d3c1637a 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -56,7 +56,7 @@ private static String insertEntryGetCitationKey(BibEntry entry) { * @param pageInfo A single pageInfo for a list of entries. This is what we get from the GUI. */ public static void insertCitationGroup(XTextDocument doc, - OOFrontend fr, + OOFrontend frontend, XTextCursor cursor, List entries, BibDatabase database, @@ -98,7 +98,7 @@ public static void insertCitationGroup(XTextDocument doc, try { UnoScreenRefresh.lockControllers(doc); - UpdateCitationMarkers.createAndFillCitationGroup(fr, + UpdateCitationMarkers.createAndFillCitationGroup(frontend, doc, citationKeys, pageInfos, diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index 43bdcd59e2d..6fa19e2d344 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -40,7 +40,7 @@ private EditMerge() { /* * @return true if modified document */ - public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBibStyle style) + public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend frontend, OOBibStyle style) throws CreationException, IllegalArgumentException, @@ -50,12 +50,12 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBi PropertyVetoException, WrappedTargetException { - boolean madeModifications = false; + boolean madeModifications; try { UnoScreenRefresh.lockControllers(doc); - List joinableGroups = EditMerge.scan(doc, fr); + List joinableGroups = EditMerge.scan(doc, frontend); for (JoinableGroupData joinableGroupData : joinableGroups) { @@ -66,9 +66,9 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBi .collect(Collectors.toList())); CitationType citationType = cgs.get(0).citationType; - List> pageInfos = fr.backend.combinePageInfos(cgs); + List> pageInfos = frontend.backend.combinePageInfos(cgs); - fr.removeCitationGroups(cgs, doc); + frontend.removeCitationGroups(cgs, doc); XTextCursor textCursor = joinableGroupData.groupCursor; textCursor.setString(""); // Also remove the spaces between. @@ -76,7 +76,7 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend fr, OOBi /* insertSpaceAfter: no, it is already there (or could be) */ boolean insertSpaceAfter = false; - UpdateCitationMarkers.createAndFillCitationGroup(fr, + UpdateCitationMarkers.createAndFillCitationGroup(frontend, doc, citationKeys, pageInfos, @@ -226,7 +226,7 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup group, XTe couldExpand = thisCharCursor.goRight((short) 1, true); String thisChar = thisCharCursor.getString(); thisCharCursor.collapseToEnd(); - if (thisChar.isEmpty() || thisChar.equals("\n") || !thisChar.trim().isEmpty()) { + if (thisChar.isEmpty() || "\n".equals(thisChar) || !thisChar.trim().isEmpty()) { couldExpand = false; if (!thisChar.isEmpty()) { thisCharCursor.goLeft((short) 1, false); @@ -290,13 +290,13 @@ private static void addToCurrentGroup(ScanState state, CitationGroup group, XTex /** * Scan the document for joinable groups. Return those found. */ - private static List scan(XTextDocument doc, OOFrontend fr) + private static List scan(XTextDocument doc, OOFrontend frontend) throws NoDocumentException, WrappedTargetException { List result = new ArrayList<>(); - List cgs = fr.getCitationGroupsSortedWithinPartitions(doc, false /* mapFootnotesToFootnoteMarks */); + List cgs = frontend.getCitationGroupsSortedWithinPartitions(doc, false /* mapFootnotesToFootnoteMarks */); if (cgs.isEmpty()) { return result; } @@ -305,7 +305,7 @@ private static List scan(XTextDocument doc, OOFrontend fr) for (CitationGroup group : cgs) { - XTextRange currentRange = (fr.getMarkRange(doc, group) + XTextRange currentRange = (frontend.getMarkRange(doc, group) .orElseThrow(IllegalStateException::new)); /* diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index fba50a93c6e..409969b213f 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -29,7 +29,7 @@ private EditSeparate() { } public static boolean separateCitations(XTextDocument doc, - OOFrontend fr, + OOFrontend frontend, List databases, OOBibStyle style) throws @@ -47,17 +47,17 @@ public static boolean separateCitations(XTextDocument doc, // decide the visually last Citation in the group. Unless the // style changed since refresh this is the last on the screen // as well. - fr.citationGroups.lookupCitations(databases); - fr.citationGroups.imposeLocalOrder(OOProcess.comparatorForMulticite(style)); + frontend.citationGroups.lookupCitations(databases); + frontend.citationGroups.imposeLocalOrder(OOProcess.comparatorForMulticite(style)); - List cgs = fr.citationGroups.getCitationGroupsUnordered(); + List cgs = frontend.citationGroups.getCitationGroupsUnordered(); try { UnoScreenRefresh.lockControllers(doc); for (CitationGroup group : cgs) { - XTextRange range1 = (fr + XTextRange range1 = (frontend .getMarkRange(doc, group) .orElseThrow(IllegalStateException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); @@ -67,7 +67,7 @@ public static boolean separateCitations(XTextDocument doc, continue; } - fr.removeCitationGroup(group, doc); + frontend.removeCitationGroup(group, doc); // Now we own the content of cits // Create a citation group for each citation. @@ -76,7 +76,7 @@ public static boolean separateCitations(XTextDocument doc, boolean insertSpaceAfter = (i != last); Citation cit = cits.get(i); - UpdateCitationMarkers.createAndFillCitationGroup(fr, + UpdateCitationMarkers.createAndFillCitationGroup(frontend, doc, List.of(cit.citationKey), List.of(cit.getPageInfo()), diff --git a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java index 26ed654de21..ba806426051 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java @@ -51,8 +51,8 @@ public static GenerateDatabaseResult generateDatabase(XTextDocument doc, List unresolvedKeys = new ArrayList<>(); diff --git a/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java b/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java index 9782261f612..c8234df9ca0 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ManageCitations.java @@ -21,8 +21,8 @@ public static List getCitationEntries(XTextDocument doc) throws NoDocumentException, WrappedTargetException { - OOFrontend fr = new OOFrontend(doc); - return fr.getCitationEntries(doc); + OOFrontend frontend = new OOFrontend(doc); + return frontend.getCitationEntries(doc); } public static void applyCitationEntries(XTextDocument doc, List citationEntries) @@ -32,7 +32,7 @@ public static void applyCitationEntries(XTextDocument doc, List c IllegalTypeException, WrappedTargetException, IllegalArgumentException { - OOFrontend fr = new OOFrontend(doc); - fr.applyCitationEntries(doc, citationEntries); + OOFrontend frontend = new OOFrontend(doc); + frontend.applyCitationEntries(doc, citationEntries); } } diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index 49f79d6d2e7..ba840e88b70 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -29,7 +29,7 @@ private Update() { * @return the list of unresolved citation keys */ private static List updateDocument(XTextDocument doc, - OOFrontend fr, + OOFrontend frontend, List databases, OOBibStyle style, FunctionalTextViewCursor fcursor, @@ -43,25 +43,25 @@ private static List updateDocument(XTextDocument doc, final boolean useLockControllers = true; - fr.imposeGlobalOrder(doc, fcursor); - OOProcess.produceCitationMarkers(fr.citationGroups, databases, style); + frontend.imposeGlobalOrder(doc, fcursor); + OOProcess.produceCitationMarkers(frontend.citationGroups, databases, style); try { if (useLockControllers) { UnoScreenRefresh.lockControllers(doc); } - UpdateCitationMarkers.applyNewCitationMarkers(doc, fr, style); + UpdateCitationMarkers.applyNewCitationMarkers(doc, frontend, style); if (doUpdateBibliography) { UpdateBibliography.rebuildBibTextSection(doc, - fr, - fr.citationGroups.getBibliography().get(), + frontend, + frontend.citationGroups.getBibliography().get(), style, alwaysAddCitedOnPages); } - return fr.citationGroups.getUnresolvedKeys(); + return frontend.citationGroups.getUnresolvedKeys(); } finally { if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { UnoScreenRefresh.unlockControllers(doc); @@ -93,7 +93,7 @@ public SyncOptions setAlwaysAddCitedOnPages(boolean value) { } public static List synchronizeDocument(XTextDocument doc, - OOFrontend fr, + OOFrontend frontend, OOBibStyle style, FunctionalTextViewCursor fcursor, SyncOptions syncOptions) @@ -104,7 +104,7 @@ public static List synchronizeDocument(XTextDocument doc, com.sun.star.lang.IllegalArgumentException { return Update.updateDocument(doc, - fr, + frontend, syncOptions.databases, style, fcursor, @@ -125,9 +125,9 @@ public static List resyncDocument(XTextDocument doc, WrappedTargetException, com.sun.star.lang.IllegalArgumentException { - OOFrontend fr = new OOFrontend(doc); + OOFrontend frontend = new OOFrontend(doc); - return Update.synchronizeDocument(doc, fr, style, fcursor, syncOptions); + return Update.synchronizeDocument(doc, frontend, style, fcursor, syncOptions); } } diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 0016e5e4510..4a0d8d05e0e 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -196,17 +196,6 @@ public CitationGroup createCitationGroup(XTextDocument doc, throw new IllegalArgumentException(); } - /* - * Backend52 uses reference marks to (1) mark the location of the citation in the text and (2) to encode - * the citation keys and citation type in the name of the reference mark. The name of the reference mark - * has to be unique in the document. - */ - String markName = Codec52.getUniqueMarkName(new HashSet<>(citationStorageManager.getUsedNames(doc)), - citationKeys, - citationType); - - CitationGroupId groupId = new CitationGroupId(markName); - final int numberOfCitations = citationKeys.size(); final int last = numberOfCitations - 1; @@ -236,6 +225,17 @@ public CitationGroup createCitationGroup(XTextDocument doc, } } + /* + * Backend52 uses reference marks to (1) mark the location of the citation in the text and (2) to encode + * the citation keys and citation type in the name of the reference mark. The name of the reference mark + * has to be unique in the document. + */ + final String markName = Codec52.getUniqueMarkName(new HashSet<>(citationStorageManager.getUsedNames(doc)), + citationKeys, + citationType); + + final CitationGroupId groupId = new CitationGroupId(markName); + /* * Apply to document */ diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index f567a3e459e..45f3bd3ca04 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -32,16 +32,16 @@ private Codec52() { */ public static class ParsedMarkName { /** "", "0", "1" ... */ - public final String i; + public final String index; /** in-text-citation type */ public final CitationType citationType; /** Citation keys embedded in the reference mark. */ public final List citationKeys; - ParsedMarkName(String i, CitationType citationType, List citationKeys) { - Objects.requireNonNull(i); + ParsedMarkName(String index, CitationType citationType, List citationKeys) { + Objects.requireNonNull(index); Objects.requireNonNull(citationKeys); - this.i = i; + this.index = index; this.citationType = citationType; this.citationKeys = citationKeys; } @@ -50,8 +50,8 @@ public static class ParsedMarkName { /** * Integer representation was written into the document in JabRef52, keep it for compatibility. */ - private static CitationType citationTypeFromInt(int i) { - return switch (i) { + private static CitationType citationTypeFromInt(int code) { + return switch (code) { case 1 -> CitationType.AUTHORYEAR_PAR; case 2 -> CitationType.AUTHORYEAR_INTEXT; case 3 -> CitationType.INVISIBLE_CIT; @@ -59,8 +59,8 @@ private static CitationType citationTypeFromInt(int i) { }; } - private static int citationTypeToInt(CitationType i) { - return switch (i) { + private static int citationTypeToInt(CitationType type) { + return switch (type) { case AUTHORYEAR_PAR -> 1; case AUTHORYEAR_INTEXT -> 2; case INVISIBLE_CIT -> 3; @@ -86,12 +86,12 @@ public static String getUniqueMarkName(Set usedNames, String citationKeysPart = String.join(",", citationKeys); - int i = 0; + int index = 0; int citTypeCode = citationTypeToInt(citationType); String name = BIB_CITATION + '_' + citTypeCode + '_' + citationKeysPart; while (usedNames.contains(name)) { - name = BIB_CITATION + i + '_' + citTypeCode + '_' + citationKeysPart; - i++; + name = BIB_CITATION + index + '_' + citTypeCode + '_' + citationKeysPart; + index++; } return name; } @@ -110,10 +110,10 @@ public static Optional parseMarkName(String refMarkName) { } List keys = Arrays.asList(citeMatcher.group(3).split(",")); - String i = citeMatcher.group(1); + String index = citeMatcher.group(1); int citTypeCode = Integer.parseInt(citeMatcher.group(2)); CitationType citationType = citationTypeFromInt(citTypeCode); - return (Optional.of(new Codec52.ParsedMarkName(i, citationType, keys))); + return (Optional.of(new Codec52.ParsedMarkName(index, citationType, keys))); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index cfabb1e2de0..324b984377c 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -35,14 +35,14 @@ class NamedRangeReferenceMark implements NamedRange { private static final Logger LOGGER = LoggerFactory.getLogger(NamedRangeReferenceMark.class); - private String id; /* reference mark name */ + private String rangeId; /* reference mark name */ - private NamedRangeReferenceMark(String id) { - this.id = id; + private NamedRangeReferenceMark(String rangeId) { + this.rangeId = rangeId; } String getId() { - return id; + return rangeId; } /** @@ -156,7 +156,7 @@ public void removeFromDocument(XTextDocument doc) @Override public String getRangeName() { - return id; + return rangeId; } /** @@ -217,8 +217,6 @@ public XTextCursor getFillCursor(XTextDocument doc) String name = this.getRangeName(); - final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; - final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; final boolean debugThisFun = false; XTextCursor full = null; @@ -279,6 +277,8 @@ public XTextCursor getFillCursor(XTextDocument doc) beta.goRight((short) (fullText.length() - 2), true); LOGGER.debug("getFillCursor: beta(1) covers '{}'", beta.getString()); + final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; + final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; final short rightLength = (short) right.length(); if (fullText.startsWith(left) && fullText.endsWith(right)) { beta.setString(""); @@ -345,7 +345,6 @@ public XTextCursor getFillCursor(XTextDocument doc) */ public static void checkFillCursor(XTextCursor cursor) { final String left = REFERENCE_MARK_LEFT_BRACKET; - final String right = REFERENCE_MARK_RIGHT_BRACKET; XTextCursor alpha = cursor.getText().createTextCursorByRange(cursor); alpha.collapseToStart(); @@ -364,6 +363,7 @@ public static void checkFillCursor(XTextCursor cursor) { } } + final String right = REFERENCE_MARK_RIGHT_BRACKET; final short rightLength = (short) right.length(); if (rightLength > 0) { omega.goRight(rightLength, true); @@ -395,27 +395,26 @@ public void cleanFillCursor(XTextDocument doc) // removeBracketsFromEmpty is intended to force removal if we are working on an "Empty citation" (INVISIBLE_CIT). final boolean removeBracketsFromEmpty = false; - final String left = REFERENCE_MARK_LEFT_BRACKET; - final String right = REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); - String name = this.getRangeName(); XTextCursor full = this.getRawCursor(doc).orElseThrow(IllegalStateException::new); final String fullText = full.getString(); - final int fullTextLength = fullText.length(); + final String left = REFERENCE_MARK_LEFT_BRACKET; if (!fullText.startsWith(left)) { String msg = String.format("cleanFillCursor: (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", name); throw new IllegalStateException(msg); } + final String right = REFERENCE_MARK_RIGHT_BRACKET; if (!fullText.endsWith(right)) { String msg = String.format("cleanFillCursor: (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", name); throw new IllegalStateException(msg); } + final int fullTextLength = fullText.length(); + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); final int contentLength = (fullTextLength - (leftLength + rightLength)); if (contentLength < 0) { String msg = String.format("cleanFillCursor: length(%s) < 0", name); diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java index f7b3d14def6..ebda8359ba5 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java @@ -40,7 +40,7 @@ public static Optional getBibliographyRange(XTextDocument doc) * Rebuilds the bibliography. */ public static void rebuildBibTextSection(XTextDocument doc, - OOFrontend fr, + OOFrontend frontend, CitedKeys bibliography, OOBibStyle style, boolean alwaysAddCitedOnPages) @@ -52,7 +52,7 @@ public static void rebuildBibTextSection(XTextDocument doc, clearBibTextSectionContent2(doc); populateBibTextSection(doc, - fr, + frontend, bibliography, style, alwaysAddCitedOnPages); @@ -105,7 +105,7 @@ private static void clearBibTextSectionContent2(XTextDocument doc) * Assumes the section named BIB_SECTION_NAME exists. */ private static void populateBibTextSection(XTextDocument doc, - OOFrontend fr, + OOFrontend frontend, CitedKeys bibliography, OOBibStyle style, boolean alwaysAddCitedOnPages) @@ -121,7 +121,7 @@ private static void populateBibTextSection(XTextDocument doc, // emit the title of the bibliography OOTextIntoOO.removeDirectFormatting(cursor); - OOText bibliographyText = OOFormatBibliography.formatBibliography(fr.citationGroups, + OOText bibliographyText = OOFormatBibliography.formatBibliography(frontend.citationGroups, bibliography, style, alwaysAddCitedOnPages); diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java index 55f04775094..834fce1d0ce 100644 --- a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -40,18 +40,18 @@ private UpdateCitationMarkers() { * After each fillCitationMarkInCursor call check if we lost the * BIB_SECTION_NAME bookmark and recreate it if we did. * - * @param fr + * @param frontend * * @param style Bibliography style to use. * */ - public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, OOBibStyle style) + public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend frontend, OOBibStyle style) throws NoDocumentException, CreationException, WrappedTargetException { - CitationGroups citationGroups = fr.citationGroups; + CitationGroups citationGroups = frontend.citationGroups; for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) { @@ -66,11 +66,11 @@ public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend fr, OOB if (withText && marker.isPresent()) { - XTextCursor cursor = fr.getFillCursorForCitationGroup(doc, group); + XTextCursor cursor = frontend.getFillCursorForCitationGroup(doc, group); fillCitationMarkInCursor(doc, cursor, marker.get(), withText, style); - fr.cleanFillCursorForCitationGroup(doc, group); + frontend.cleanFillCursorForCitationGroup(doc, group); } } @@ -118,7 +118,7 @@ public static void fillCitationMarkInCursor(XTextDocument doc, * coming after. But is not wanted when we recreate a * reference mark. */ - public static void createAndFillCitationGroup(OOFrontend fr, + public static void createAndFillCitationGroup(OOFrontend frontend, XTextDocument doc, List citationKeys, List> pageInfos, @@ -140,21 +140,21 @@ public static void createAndFillCitationGroup(OOFrontend fr, if (pageInfos.size() != citationKeys.size()) { throw new IllegalArgumentException("pageInfos.size != citationKeys.size"); } - CitationGroup group = fr.createCitationGroup(doc, - citationKeys, - pageInfos, - citationType, - position, - insertSpaceAfter); + CitationGroup group = frontend.createCitationGroup(doc, + citationKeys, + pageInfos, + citationType, + position, + insertSpaceAfter); final boolean withText = citationType.withText(); if (withText) { - XTextCursor fillCursor = fr.getFillCursorForCitationGroup(doc, group); + XTextCursor fillCursor = frontend.getFillCursorForCitationGroup(doc, group); UpdateCitationMarkers.fillCitationMarkInCursor(doc, fillCursor, citationText, withText, style); - fr.cleanFillCursorForCitationGroup(doc, group); + frontend.cleanFillCursorForCitationGroup(doc, group); } position.collapseToEnd(); } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index 082d94a7fdf..5108c94c8b3 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -291,20 +291,20 @@ private boolean isUpToDate() { } } - private void readFormatFile(Reader in) throws IOException { + private void readFormatFile(Reader input) throws IOException { // First read all the contents of the file: - StringBuilder sb = new StringBuilder(); - int c; - while ((c = in.read()) != -1) { - sb.append((char) c); + StringBuilder stringBuilder = new StringBuilder(); + int chr; + while ((chr = input.read()) != -1) { + stringBuilder.append((char) chr); } // Store a local copy for viewing - localCopy = sb.toString(); + localCopy = stringBuilder.toString(); // Break into separate lines: - String[] lines = sb.toString().split("\n"); + String[] lines = stringBuilder.toString().split("\n"); BibStyleMode mode = BibStyleMode.NONE; for (String line1 : lines) { @@ -386,11 +386,12 @@ private void handleStructureLine(String line) { if ((index > 0) && (index < (line.length() - 1))) { try { - String formatString = line.substring(index + 1); + final String typeName = line.substring(0, index); + final String formatString = line.substring(index + 1); Layout layout = new LayoutHelper(new StringReader(formatString), this.prefs).getLayoutFromText(); - EntryType type = EntryTypeFactory.parse(line.substring(0, index)); + EntryType type = EntryTypeFactory.parse(typeName); - if (!isDefaultLayoutPresent && line.substring(0, index).equals(OOBibStyle.DEFAULT_MARK)) { + if (!isDefaultLayoutPresent && OOBibStyle.DEFAULT_MARK.equals(typeName)) { isDefaultLayoutPresent = true; defaultBibLayout = layout; } else { @@ -437,11 +438,11 @@ private void handleJournalsLine(String line) { } public Layout getReferenceFormat(EntryType type) { - Layout l = bibLayout.get(type); - if (l == null) { + Layout layout = bibLayout.get(type); + if (layout == null) { return defaultBibLayout; } else { - return l; + return layout; } } @@ -464,7 +465,7 @@ public String getNumCitationMarker(List number, int minGroupingCount, b // Sort the numbers: List lNum = new ArrayList<>(number); Collections.sort(lNum); - StringBuilder sb = new StringBuilder(bracketBefore); + StringBuilder stringBuilder = new StringBuilder(bracketBefore); int combineFrom = -1; int written = 0; for (int i = 0; i < lNum.size(); i++) { @@ -476,9 +477,9 @@ public String getNumCitationMarker(List number, int minGroupingCount, b } else { // Add single entry: if (i > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); + stringBuilder.append(getStringCitProperty(CITATION_SEPARATOR)); } - sb.append(lNum.get(i) > 0 ? String.valueOf(lNum.get(i)) : OOBibStyle.UNDEFINED_CITATION_MARKER); + stringBuilder.append(lNum.get(i) > 0 ? String.valueOf(lNum.get(i)) : OOBibStyle.UNDEFINED_CITATION_MARKER); written++; } } else { @@ -486,20 +487,20 @@ public String getNumCitationMarker(List number, int minGroupingCount, b // Check if it ends here: if ((i == (lNum.size() - 1)) || (lNum.get(i + 1) != (i1 + 1))) { if (written > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); + stringBuilder.append(getStringCitProperty(CITATION_SEPARATOR)); } if ((minGroupingCount > 0) && (((i1 + 1) - combineFrom) >= minGroupingCount)) { - sb.append(combineFrom); - sb.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); - sb.append(i1); + stringBuilder.append(combineFrom); + stringBuilder.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); + stringBuilder.append(i1); written++; } else { // Either we should never group, or there aren't enough // entries in this case to group. Output all: for (int jj = combineFrom; jj <= i1; jj++) { - sb.append(jj); + stringBuilder.append(jj); if (jj < i1) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); + stringBuilder.append(getStringCitProperty(CITATION_SEPARATOR)); } written++; } @@ -509,8 +510,8 @@ public String getNumCitationMarker(List number, int minGroupingCount, b // If it doesn't end here, just keep iterating. } } - sb.append(bracketAfter); - return sb.toString(); + stringBuilder.append(bracketAfter); + return stringBuilder.toString(); } /* end_old */ @@ -591,13 +592,13 @@ public String getCitationMarker(List entries, Map entries, String[] uniquefiers, int from, int to) { String separator = getStringCitProperty(UNIQUEFIER_SEPARATOR); - StringBuilder sb = new StringBuilder(uniquefiers[from]); + StringBuilder stringBuilder = new StringBuilder(uniquefiers[from]); for (int i = from + 1; i <= to; i++) { - sb.append(separator); - sb.append(uniquefiers[i]); + stringBuilder.append(separator); + stringBuilder.append(uniquefiers[i]); entries.set(i, null); } - uniquefiers[from] = sb.toString(); + uniquefiers[from] = stringBuilder.toString(); } /* end_old */ @@ -622,7 +623,7 @@ private String getAuthorYearParenthesisMarker(List entries, Map entries, Map 0) { - sb.append(citationSeparator); + stringBuilder.append(citationSeparator); } BibDatabase currentDatabase = database.get(currentEntry); @@ -641,17 +642,17 @@ private String getAuthorYearParenthesisMarker(List entries, Map entries, Map entries, Map 0 ? unlimA : maxA; if (i > 0) { - sb.append(citationSeparator); + stringBuilder.append(citationSeparator); } String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); String authorString = createAuthorList(author, maxAuthors, andString, yearSep); - sb.append(authorString); - sb.append(startBrace); + stringBuilder.append(authorString); + stringBuilder.append(startBrace); String year = getCitationMarkerField(currentEntry, currentDatabase, yearField); if (year != null) { - sb.append(year); + stringBuilder.append(year); } if ((uniquefiers != null) && (uniquefiers[i] != null)) { - sb.append(uniquefiers[i]); + stringBuilder.append(uniquefiers[i]); } - sb.append(endBrace); + stringBuilder.append(endBrace); } - return sb.toString(); + return stringBuilder.toString(); } /* end_old */ @@ -757,15 +758,15 @@ private String getCitationMarkerField(BibEntry entry, BibDatabase database, Stri * @return The author name, or an empty String if inapplicable. */ private String getAuthorLastName(AuthorList al, int number) { - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); if (al.getNumberOfAuthors() > number) { Author a = al.getAuthor(number); - a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> sb.append(von).append(' ')); - sb.append(a.getLast().orElse("")); + a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> stringBuilder.append(von).append(' ')); + stringBuilder.append(a.getLast().orElse("")); } - return sb.toString(); + return stringBuilder.toString(); } /* end_old */ @@ -896,12 +897,12 @@ public int compareTo(OOBibStyle other) { } @Override - public boolean equals(Object o) { - if (this == o) { + public boolean equals(Object object) { + if (this == object) { return true; } - if (o instanceof OOBibStyle) { - OOBibStyle otherStyle = (OOBibStyle) o; + if (object instanceof OOBibStyle) { + OOBibStyle otherStyle = (OOBibStyle) object; return Objects.equals(path, otherStyle.path) && Objects.equals(name, otherStyle.name) && Objects.equals(citProperties, otherStyle.citProperties) @@ -923,28 +924,28 @@ private String createAuthorList(String author, int maxAuthors, String andString, String etAlString = getStringCitProperty(ET_AL_STRING); // The String to represent authors that are not mentioned, e.g. " et al." String authorSep = getStringCitProperty(AUTHOR_SEPARATOR); // The String to add between author names except the last two, e.g. ", ". String oxfordComma = getStringCitProperty(OXFORD_COMMA); // The String to put after the second to last author in case of three or more authors - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); AuthorList al = AuthorList.parse(author); if (!al.isEmpty()) { - sb.append(getAuthorLastName(al, 0)); + stringBuilder.append(getAuthorLastName(al, 0)); } if ((al.getNumberOfAuthors() > 1) && ((al.getNumberOfAuthors() <= maxAuthors) || (maxAuthors < 0))) { int j = 1; while (j < (al.getNumberOfAuthors() - 1)) { - sb.append(authorSep); - sb.append(getAuthorLastName(al, j)); + stringBuilder.append(authorSep); + stringBuilder.append(getAuthorLastName(al, j)); j++; } if (al.getNumberOfAuthors() > 2) { - sb.append(oxfordComma); + stringBuilder.append(oxfordComma); } - sb.append(andString); - sb.append(getAuthorLastName(al, al.getNumberOfAuthors() - 1)); + stringBuilder.append(andString); + stringBuilder.append(getAuthorLastName(al, al.getNumberOfAuthors() - 1)); } else if (al.getNumberOfAuthors() > maxAuthors) { - sb.append(etAlString); + stringBuilder.append(etAlString); } - sb.append(yearSep); - return sb.toString(); + stringBuilder.append(yearSep); + return stringBuilder.toString(); } /* end_old */ @@ -1078,8 +1079,8 @@ public OOText getNumCitationMarkerForBibliography(CitationMarkerNumericBibEntry return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, entry); } - public OOText getNormalizedCitationMarker(CitationMarkerNormEntry ce) { - return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, ce, Optional.empty()); + public OOText getNormalizedCitationMarker(CitationMarkerNormEntry entry) { + return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, entry, Optional.empty()); } /** @@ -1158,10 +1159,6 @@ public String getGroupedNumbersSeparator() { return getStringCitProperty(OOBibStyle.GROUPED_NUMBERS_SEPARATOR); } - private boolean getBooleanProperty(String propName) { - return (Boolean) properties.get(propName); - } - private String getStringProperty(String propName) { return (String) properties.get(propName); } @@ -1308,12 +1305,9 @@ public OOText getFormattedBibliographyTitle() { OOBibStyle style = this; OOText title = style.getReferenceHeaderText(); String parStyle = style.getReferenceHeaderParagraphFormat(); - if (parStyle != null) { - title = OOFormat.paragraph(title, parStyle); - } else { - title = OOFormat.paragraph(title); - } - return title; + return (parStyle == null + ? OOFormat.paragraph(title) + : OOFormat.paragraph(title, parStyle)); } } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java index deb1a306913..2e5227d080e 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java @@ -38,21 +38,21 @@ private OOBibStyleGetCitationMarker() { * @return The author name, or an empty String if inapplicable. */ private static String getAuthorLastName(AuthorList authorList, int number) { - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); if (authorList.getNumberOfAuthors() > number) { Author author = authorList.getAuthor(number); // "von " if von exists Optional von = author.getVon(); if (von.isPresent() && !von.get().isEmpty()) { - sb.append(von.get()); - sb.append(' '); + stringBuilder.append(von.get()); + stringBuilder.append(' '); } // last name if it exists - sb.append(author.getLast().orElse("")); + stringBuilder.append(author.getLast().orElse("")); } - return sb.toString(); + return stringBuilder.toString(); } private static String markupAuthorName(OOBibStyle style, String name) { @@ -127,7 +127,7 @@ private static String formatAuthorList(OOBibStyle style, // of three or more authors: (A, B[,] and C) String oxfordComma = style.getOxfordComma(); - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); final int nAuthors = authorList.getNumberOfAuthors(); @@ -149,11 +149,11 @@ private static String formatAuthorList(OOBibStyle style, : Math.min(maxAuthorsBeforeEtAl, nAuthors)); if (nAuthorsToEmit >= 1) { - sb.append(style.getAuthorsPartMarkupBefore()); - sb.append(style.getAuthorNamesListMarkupBefore()); + stringBuilder.append(style.getAuthorsPartMarkupBefore()); + stringBuilder.append(style.getAuthorNamesListMarkupBefore()); // The first author String name = getAuthorLastName(authorList, 0); - sb.append(markupAuthorName(style, name)); + stringBuilder.append(markupAuthorName(style, name)); } if (nAuthors >= 2) { @@ -162,19 +162,19 @@ private static String formatAuthorList(OOBibStyle style, // Emit last names, except for the last author int j = 1; while (j < (nAuthors - 1)) { - sb.append(authorSep); + stringBuilder.append(authorSep); String name = getAuthorLastName(authorList, j); - sb.append(markupAuthorName(style, name)); + stringBuilder.append(markupAuthorName(style, name)); j++; } // oxfordComma if at least 3 authors if (nAuthors >= 3) { - sb.append(oxfordComma); + stringBuilder.append(oxfordComma); } // Emit " and "+"LastAuthor" - sb.append(andString); + stringBuilder.append(andString); String name = getAuthorLastName(authorList, nAuthors - 1); - sb.append(markupAuthorName(style, name)); + stringBuilder.append(markupAuthorName(style, name)); } else { // Emit last names up to nAuthorsToEmit. @@ -185,9 +185,9 @@ private static String formatAuthorList(OOBibStyle style, if (maxAuthorsBeforeEtAl > 1) { int j = 1; while (j < nAuthorsToEmit) { - sb.append(authorSep); + stringBuilder.append(authorSep); String name = getAuthorLastName(authorList, j); - sb.append(markupAuthorName(style, name)); + stringBuilder.append(markupAuthorName(style, name)); j++; } } @@ -195,15 +195,15 @@ private static String formatAuthorList(OOBibStyle style, } if (nAuthorsToEmit >= 1) { - sb.append(style.getAuthorNamesListMarkupAfter()); + stringBuilder.append(style.getAuthorNamesListMarkupAfter()); } if (nAuthors >= 2 && !emitAllAuthors) { - sb.append(etAlString); + stringBuilder.append(etAlString); } - sb.append(style.getAuthorsPartMarkupAfter()); - return sb.toString(); + stringBuilder.append(style.getAuthorsPartMarkupAfter()); + return stringBuilder.toString(); } /** @@ -279,15 +279,15 @@ private static String getCitationMarkerField(OOBibStyle style, return ""; } - FieldAndContent fc = optionalFieldAndContent.get(); - String result = style.getFieldFormatter().format(fc.content); + FieldAndContent fieldAndContent = optionalFieldAndContent.get(); + String result = style.getFieldFormatter().format(fieldAndContent.content); // If the field we found is mentioned in authorFieldNames and // content has a pair of braces around it, we add a pair of // braces around the result, so that AuthorList.parse does not split // the content. final OrFields fieldsToRebrace = style.getAuthorFieldNames(); - if (fieldsToRebrace.contains(fc.field) && StringUtil.isInCurlyBrackets(fc.content)) { + if (fieldsToRebrace.contains(fieldAndContent.field) && StringUtil.isInCurlyBrackets(fieldAndContent.content)) { result = "{" + result + "}"; } return result; @@ -406,11 +406,11 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, String pageInfoSeparator = style.getPageInfoSeparator(); String uniquefierSeparator = style.getUniquefierSeparator(); - StringBuilder sb = new StringBuilder(); - sb.append(style.getCitationGroupMarkupBefore()); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(style.getCitationGroupMarkupBefore()); if (inParenthesis) { - sb.append(startBrace); // shared parenthesis + stringBuilder.append(startBrace); // shared parenthesis } for (int j = 0; j < entries.size(); j++) { @@ -422,19 +422,19 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, // Just add our uniqueLetter String uniqueLetter = entry.getUniqueLetter().orElse(null); if (uniqueLetter != null) { - sb.append(uniquefierSeparator); - sb.append(uniqueLetter); + stringBuilder.append(uniquefierSeparator); + stringBuilder.append(uniqueLetter); } // And close the brace, if we are the last in the group. if (!inParenthesis && endingAGroup) { - sb.append(endBrace); + stringBuilder.append(endBrace); } continue; } if (j > 0) { - sb.append(citationSeparator); + stringBuilder.append(citationSeparator); } StringBuilder pageInfoPart = new StringBuilder(""); @@ -449,9 +449,9 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, final boolean isUnresolved = entry.getLookupResult().isEmpty(); if (isUnresolved) { - sb.append(String.format("Unresolved(%s)", entry.getCitationKey())); + stringBuilder.append(String.format("Unresolved(%s)", entry.getCitationKey())); if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { - sb.append(pageInfoPart); + stringBuilder.append(pageInfoPart); } } else { @@ -467,40 +467,40 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, AuthorList authorList = getAuthorList(style, db); String authorString = formatAuthorList(style, authorList, maxAuthors, andString); - sb.append(authorString); - sb.append(yearSep); + stringBuilder.append(authorString); + stringBuilder.append(yearSep); if (!inParenthesis) { - sb.append(startBrace); // parenthesis before year + stringBuilder.append(startBrace); // parenthesis before year } String year = getCitationMarkerField(style, db, yearFieldNames); if (year != null) { - sb.append(year); + stringBuilder.append(year); } if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { String uniqueLetter = entry.getUniqueLetter().orElse(null); if (uniqueLetter != null) { - sb.append(uniqueLetter); + stringBuilder.append(uniqueLetter); } } if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { - sb.append(pageInfoPart); + stringBuilder.append(pageInfoPart); } if (!inParenthesis && endingAGroup) { - sb.append(endBrace); // parenthesis after year + stringBuilder.append(endBrace); // parenthesis after year } } } // for j if (inParenthesis) { - sb.append(endBrace); // shared parenthesis + stringBuilder.append(endBrace); // shared parenthesis } - sb.append(style.getCitationGroupMarkupAfter()); - return OOText.fromString(sb.toString()); + stringBuilder.append(style.getCitationGroupMarkupAfter()); + return OOText.fromString(stringBuilder.toString()); } /** @@ -638,9 +638,9 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, int[] nAuthorsToEmitRevised = new int[nEntries]; for (int i = 0; i < nEntries; i++) { CitationMarkerEntry entry = citationMarkerEntries.get(i); - int n = calculateNAuthorsToEmit(style, entry); - nAuthorsToEmit[i] = n; - nAuthorsToEmitRevised[i] = n; + int nAuthors = calculateNAuthorsToEmit(style, entry); + nAuthorsToEmit[i] = nAuthors; + nAuthorsToEmitRevised[i] = nAuthors; } boolean[] startsNewGroup = new boolean[nEntries]; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java index 5dce4e8caa1..60b5222cf5b 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java @@ -53,23 +53,23 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, // prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST String bracketBefore = style.getBracketBeforeInListWithFallBack(); String bracketAfter = style.getBracketAfterInListWithFallBack(); - StringBuilder sb = new StringBuilder(); - sb.append(style.getCitationGroupMarkupBefore()); - sb.append(bracketBefore); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(style.getCitationGroupMarkupBefore()); + stringBuilder.append(bracketBefore); final Optional current = entry.getNumber(); - sb.append(current.isPresent() + stringBuilder.append(current.isPresent() ? String.valueOf(current.get()) : (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey())); - sb.append(bracketAfter); - sb.append(style.getCitationGroupMarkupAfter()); - return OOText.fromString(sb.toString()); + stringBuilder.append(bracketAfter); + stringBuilder.append(style.getCitationGroupMarkupAfter()); + return OOText.fromString(stringBuilder.toString()); } /* * emitBlock : a helper for getNumCitationMarker2 * * Given a block containing either a single entry or two or more - * entries that are joinable into an "i-j" form, append to {@code sb} the + * entries that are joinable into an "i-j" form, append to {@code stringBuilder} the * formatted text. * * Assumes: @@ -91,7 +91,7 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, private static void emitBlock(List block, OOBibStyle style, int minGroupingCount, - StringBuilder sb) { + StringBuilder stringBuilder) { final int blockSize = block.size(); if (blockSize == 0) { @@ -102,14 +102,14 @@ private static void emitBlock(List block, // Add single entry: CitationMarkerNumericEntry entry = block.get(0); final Optional num = entry.getNumber(); - sb.append(num.isEmpty() - ? (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey()) - : String.valueOf(num.get())); + stringBuilder.append(num.isEmpty() + ? (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey()) + : String.valueOf(num.get())); // Emit pageInfo Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { - sb.append(style.getPageInfoSeparator()); - sb.append(OOText.toString(pageInfo.get())); + stringBuilder.append(style.getPageInfoSeparator()); + stringBuilder.append(OOText.toString(pageInfo.get())); } return; } @@ -146,17 +146,17 @@ private static void emitBlock(List block, } // Emit: "first-last" - sb.append(first); - sb.append(style.getGroupedNumbersSeparator()); - sb.append(last); + stringBuilder.append(first); + stringBuilder.append(style.getGroupedNumbersSeparator()); + stringBuilder.append(last); } else { // Emit: first, first+1,..., last for (int j = 0; j < blockSize; j++) { if (j > 0) { - sb.append(style.getCitationSeparator()); + stringBuilder.append(style.getCitationSeparator()); } - sb.append(block.get(j).getNumber().get()); + stringBuilder.append(block.get(j).getNumber().get()); } } return; @@ -194,15 +194,15 @@ public static OOText getNumCitationMarker2(OOBibStyle style, final boolean joinIsDisabled = (minGroupingCount <= 0); final int nCitations = entries.size(); - String bracketBefore = style.getBracketBefore(); - String bracketAfter = style.getBracketAfter(); + final String bracketBefore = style.getBracketBefore(); + final String bracketAfter = style.getBracketAfter(); // Sort a copy of entries List sorted = OOListUtil.map(entries, e -> e); sorted.sort(OOBibStyleGetNumCitationMarker::compareCitationMarkerNumericEntry); // "[" - StringBuilder sb = new StringBuilder(bracketBefore); + StringBuilder stringBuilder = new StringBuilder(bracketBefore); /* * Original: @@ -248,12 +248,12 @@ public static OOText getNumCitationMarker2(OOBibStyle style, } } - if (nextBlock.size() > 0) { + if (!nextBlock.isEmpty()) { // emit current block if (blocksEmitted) { - sb.append(style.getCitationSeparator()); + stringBuilder.append(style.getCitationSeparator()); } - emitBlock(currentBlock, style, minGroupingCount, sb); + emitBlock(currentBlock, style, minGroupingCount, stringBuilder); blocksEmitted = true; currentBlock = nextBlock; nextBlock = new ArrayList<>(); @@ -261,21 +261,21 @@ public static OOText getNumCitationMarker2(OOBibStyle style, } - if (nextBlock.size() != 0) { + if (!nextBlock.isEmpty()) { throw new IllegalStateException("impossible: (nextBlock.size() != 0) after loop"); } - if (currentBlock.size() > 0) { + if (!currentBlock.isEmpty()) { // We are emitting a block if (blocksEmitted) { - sb.append(style.getCitationSeparator()); + stringBuilder.append(style.getCitationSeparator()); } - emitBlock(currentBlock, style, minGroupingCount, sb); + emitBlock(currentBlock, style, minGroupingCount, stringBuilder); } // Emit: "]" - sb.append(bracketAfter); - return OOText.fromString(sb.toString()); + stringBuilder.append(bracketAfter); + return OOText.fromString(stringBuilder.toString()); } } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index 4bc3fac6191..ea311193068 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -49,8 +49,8 @@ public static OOText formatBibliographyBody(CitationGroups cgs, StringBuilder stringBuilder = new StringBuilder(); - for (CitedKey ck : bibliography.values()) { - OOText entryText = formatBibliographyEntry(cgs, ck, style, alwaysAddCitedOnPages); + for (CitedKey citedKey : bibliography.values()) { + OOText entryText = formatBibliographyEntry(cgs, citedKey, style, alwaysAddCitedOnPages); stringBuilder.append(entryText.toString()); } @@ -61,29 +61,29 @@ public static OOText formatBibliographyBody(CitationGroups cgs, * @return A paragraph. Includes label and "Cited on pages". */ public static OOText formatBibliographyEntry(CitationGroups cgs, - CitedKey ck, + CitedKey citedKey, OOBibStyle style, boolean alwaysAddCitedOnPages) { - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); // insert marker "[1]" if (style.isNumberEntries()) { - sb.append(style.getNumCitationMarkerForBibliography(ck).toString()); + stringBuilder.append(style.getNumCitationMarkerForBibliography(citedKey).toString()); } else { // !style.isNumberEntries() : emit no prefix // Note: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); } // Add entry body - sb.append(formatBibliographyEntryBody(ck, style).toString()); + stringBuilder.append(formatBibliographyEntryBody(citedKey, style).toString()); // Add "Cited on pages" - if (ck.getLookupResult().isEmpty() || alwaysAddCitedOnPages) { - sb.append(formatCitedOnPages(cgs, ck).toString()); + if (citedKey.getLookupResult().isEmpty() || alwaysAddCitedOnPages) { + stringBuilder.append(formatCitedOnPages(cgs, citedKey).toString()); } // Add paragraph - OOText entryText = OOText.fromString(sb.toString()); + OOText entryText = OOText.fromString(stringBuilder.toString()); String parStyle = style.getReferenceParagraphFormat(); return OOFormat.paragraph(entryText, parStyle); } @@ -91,20 +91,20 @@ public static OOText formatBibliographyEntry(CitationGroups cgs, /** * @return just the body of a bibliography entry. No label, "Cited on pages" or paragraph. */ - public static OOText formatBibliographyEntryBody(CitedKey ck, OOBibStyle style) { - if (ck.getLookupResult().isEmpty()) { + public static OOText formatBibliographyEntryBody(CitedKey citedKey, OOBibStyle style) { + if (citedKey.getLookupResult().isEmpty()) { // Unresolved entry - return OOText.fromString(String.format("Unresolved(%s)", ck.citationKey)); + return OOText.fromString(String.format("Unresolved(%s)", citedKey.citationKey)); } else { // Resolved entry, use the layout engine - BibEntry bibentry = ck.getLookupResult().get().entry; + BibEntry bibentry = citedKey.getLookupResult().get().entry; Layout layout = style.getReferenceFormat(bibentry.getType()); layout.setPostFormatter(POSTFORMATTER); return formatFullReferenceOfBibEntry(layout, bibentry, - ck.getLookupResult().get().database, - ck.getUniqueLetter().orElse(null)); + citedKey.getLookupResult().get().database, + citedKey.getUniqueLetter().orElse(null)); } } @@ -147,27 +147,27 @@ private static OOText formatFullReferenceOfBibEntry(Layout layout, } /** - * Format links to citations of the source (ck). + * Format links to citations of the source (citedKey). * * Requires reference marks for the citation groups. * * - The links are created as references that show page numbers of the reference marks. * - We do not control the text shown, that is provided by OpenOffice. */ - private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { + private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey citedKey) { if (!cgs.citationGroupsProvideReferenceMarkNameForLinking()) { return OOText.fromString(""); } - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); - String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); - String suffix = ")"; - sb.append(prefix); + final String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); + final String suffix = ")"; + stringBuilder.append(prefix); List citationGroups = new ArrayList<>(); - for (CitationPath p : ck.getCitationPaths()) { + for (CitationPath p : citedKey.getCitationPaths()) { CitationGroupId groupId = p.group; Optional group = cgs.getCitationGroup(groupId); if (group.isEmpty()) { @@ -183,18 +183,18 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { return (aa.compareTo(bb)); }); - int i = 0; + int index = 0; for (CitationGroup group : citationGroups) { - if (i > 0) { - sb.append(", "); + if (index > 0) { + stringBuilder.append(", "); } String markName = group.getReferenceMarkNameForLinking().orElseThrow(IllegalStateException::new); OOText xref = OOFormat.formatReferenceToPageNumberOfReferenceMark(markName); - sb.append(xref.toString()); - i++; + stringBuilder.append(xref.toString()); + index++; } - sb.append(suffix); - return OOText.fromString(sb.toString()); + stringBuilder.append(suffix); + return OOText.fromString(stringBuilder.toString()); } } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index 1aaeb538930..affbc7584ae 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -88,8 +88,8 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup // according to their order in clashingKeys. int nextUniqueLetter = 'a'; for (String citationKey : clashingKeys) { - String ul = String.valueOf((char) nextUniqueLetter); - sortedCitedKeys.get(citationKey).setUniqueLetter(Optional.of(ul)); + String uniqueLetter = String.valueOf((char) nextUniqueLetter); + sortedCitedKeys.get(citationKey).setUniqueLetter(Optional.of(uniqueLetter)); nextUniqueLetter++; } } diff --git a/src/main/java/org/jabref/model/openoffice/CitationEntry.java b/src/main/java/org/jabref/model/openoffice/CitationEntry.java index 219e71eb0d1..0d702c860ab 100644 --- a/src/main/java/org/jabref/model/openoffice/CitationEntry.java +++ b/src/main/java/org/jabref/model/openoffice/CitationEntry.java @@ -37,12 +37,12 @@ public int compareTo(CitationEntry other) { } @Override - public boolean equals(Object o) { - if (this == o) { + public boolean equals(Object object) { + if (this == object) { return true; } - if (o instanceof CitationEntry) { - CitationEntry other = (CitationEntry) o; + if (object instanceof CitationEntry) { + CitationEntry other = (CitationEntry) object; return Objects.equals(this.refMarkName, other.refMarkName); } return false; diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java index 6ba6b760cb6..baaa931214c 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java @@ -4,15 +4,15 @@ * Identifies a citation group in a document. */ public class CitationGroupId { - String id; - public CitationGroupId(String id) { - this.id = id; + 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 id; + return groupId; } } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index b03028b76ef..e5e642fa652 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -131,10 +131,9 @@ public void setGlobalOrder(List globalOrder) { this.globalOrder = Optional.of(globalOrder); // Propagate to each CitationGroup - int i = 0; - for (CitationGroupId groupId : globalOrder) { + for (int i = 0; i < globalOrder.size(); i++) { + CitationGroupId groupId = globalOrder.get(i); citationGroupsUnordered.get(groupId).setIndexInGlobalOrder(Optional.of(i)); - i++; } } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java b/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java index 898fadbebe9..059c1b6123a 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java @@ -45,11 +45,11 @@ void sortByComparator(Comparator entryComparator) { } void numberCitedKeysInCurrentOrder() { - int i = 1; + int index = 1; for (CitedKey ck : data.values()) { if (ck.getLookupResult().isPresent()) { - ck.setNumber(Optional.of(i)); - i++; + ck.setNumber(Optional.of(index)); + index++; } else { // Unresolved citations do not get a number. ck.setNumber(Optional.empty()); diff --git a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java index ec3a8436dcf..1ff87569a3b 100644 --- a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java +++ b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java @@ -19,7 +19,7 @@ public static Optional normalizePageInfo(Optional optionalText) } String str = OOText.toString(optionalText.get()); String trimmed = str.trim(); - if (trimmed.equals("")) { + if ("".equals(trimmed)) { return Optional.empty(); } return Optional.of(OOText.fromString(trimmed)); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java index 1770b6957c5..e761a56e12f 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java @@ -39,7 +39,7 @@ public static Optional getTextCursorOfTextContentAnchor(XTextConten return Optional.of(markAnchor.getText().createTextCursorByRange(markAnchor)); } - public static XTextCursor createTextCursorByRange(XTextRange r) { - return r.getText().createTextCursorByRange(r); + public static XTextCursor createTextCursorByRange(XTextRange range) { + return range.getText().createTextCursorByRange(range); } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java index dece8978713..cd4065ba8b3 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java @@ -25,10 +25,10 @@ private static Optional getStyleFromFamily(XTextDocument doc, String fam WrappedTargetException { XStyleFamiliesSupplier fss = UnoCast.cast(XStyleFamiliesSupplier.class, doc).get(); - XNameAccess fs = UnoCast.cast(XNameAccess.class, fss.getStyleFamilies()).get(); + XNameAccess families = UnoCast.cast(XNameAccess.class, fss.getStyleFamilies()).get(); XNameContainer xFamily; try { - xFamily = UnoCast.cast(XNameContainer.class, fs.getByName(familyName)).get(); + 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); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java index b75bee17f3e..4f08bb0ed5c 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java @@ -25,17 +25,17 @@ public static Optional getXUndoManager(XTextDocument doc) { * document's undo stack is left in an inconsistent state. */ public static void enterUndoContext(XTextDocument doc, String title) { - Optional um = getXUndoManager(doc); - if (um.isPresent()) { - um.get().enterUndoContext(title); + Optional undoManager = getXUndoManager(doc); + if (undoManager.isPresent()) { + undoManager.get().enterUndoContext(title); } } public static void leaveUndoContext(XTextDocument doc) { - Optional um = getXUndoManager(doc); - if (um.isPresent()) { + Optional undoManager = getXUndoManager(doc); + if (undoManager.isPresent()) { try { - um.get().leaveUndoContext(); + undoManager.get().leaveUndoContext(); } catch (InvalidStateException ex) { throw new IllegalStateException("leaveUndoContext reported InvalidStateException"); } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java index 634edb0c57b..f5ec43f3211 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java @@ -61,8 +61,8 @@ public static Optional getStringValue(XTextDocument doc, String property throw new java.lang.IllegalArgumentException("getting UserDefinedProperties as XPropertySet failed"); } try { - String v = propertySet.get().getPropertyValue(property).toString(); - return Optional.ofNullable(v); + String value = propertySet.get().getPropertyValue(property).toString(); + return Optional.ofNullable(value); } catch (UnknownPropertyException ex) { return Optional.empty(); } diff --git a/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java b/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java index 1fe617ed99a..59295c798fe 100644 --- a/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java @@ -13,19 +13,19 @@ public static List map(List list, Function fun) { return list.stream().map(e -> fun.apply(e)).collect(Collectors.toList()); } - /** Integers 0..(n-1) */ - public static List makeIndices(int n) { - return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); + /** Integers 0..(len-1) */ + public static List 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 List order(List list, Comparator comparator) { - List ii = makeIndices(list.size()); - Collections.sort(ii, new Comparator() { - @Override public int compare(final Integer o1, final Integer o2) { - return comparator.compare((U) list.get(o1), (U) list.get(o2)); + List indices = makeIndices(list.size()); + Collections.sort(indices, new Comparator() { + @Override public int compare(final Integer a, final Integer b) { + return comparator.compare((U) list.get(a), (U) list.get(b)); } }); - return ii; + return indices; } } From 2b91d2b6fdd473206ae2f62f5388949a1b132657 Mon Sep 17 00:00:00 2001 From: Antal K Date: Tue, 9 Nov 2021 12:20:28 +0100 Subject: [PATCH 1068/1068] apply suggested changes --- .../logic/openoffice/action/EditInsert.java | 25 +++++++++-------- .../logic/openoffice/action/EditMerge.java | 28 +++++++++---------- .../logic/openoffice/action/EditSeparate.java | 22 +++++++-------- .../logic/openoffice/action/ExportCited.java | 14 +++++----- .../logic/openoffice/action/Update.java | 8 +++--- 5 files changed, 50 insertions(+), 47 deletions(-) diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java index 375d3c1637a..0004d3fe6db 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditInsert.java @@ -20,6 +20,7 @@ import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.uno.UnoScreenRefresh; import org.jabref.model.openoffice.util.OOListUtil; +import org.jabref.model.strings.StringUtil; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; @@ -73,11 +74,11 @@ public static void insertCitationGroup(XTextDocument doc, List citationKeys = OOListUtil.map(entries, EditInsert::insertEntryGetCitationKey); - final int nEntries = entries.size(); - List> pageInfos = OODataModel.fakePageInfos(pageInfo, nEntries); + final int totalEntries = entries.size(); + List> pageInfos = OODataModel.fakePageInfos(pageInfo, totalEntries); - List citations = new ArrayList<>(nEntries); - for (int i = 0; i < nEntries; i++) { + List citations = new ArrayList<>(totalEntries); + for (int i = 0; i < totalEntries; i++) { Citation cit = new Citation(citationKeys.get(i)); cit.lookupInDatabases(Collections.singletonList(database)); cit.setPageInfo(pageInfos.get(i)); @@ -85,14 +86,16 @@ public static void insertCitationGroup(XTextDocument doc, } // The text we insert - OOText citeText = - (style.isNumberEntries() - ? OOText.fromString("[-]") // A dash only. Only refresh later. - : style.createCitationMarker(citations, - citationType.inParenthesis(), - NonUniqueCitationMarker.FORGIVEN)); + OOText citeText = null; + if (style.isNumberEntries()) { + citeText = OOText.fromString("[-]"); // A dash only. Only refresh later. + } else { + citeText = style.createCitationMarker(citations, + citationType.inParenthesis(), + NonUniqueCitationMarker.FORGIVEN); + } - if ("".equals(OOText.toString(citeText))) { + if (StringUtil.isBlank(OOText.toString(citeText))) { citeText = OOText.fromString("[?]"); } diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java index 6fa19e2d344..f91e8aec93d 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditMerge.java @@ -59,16 +59,16 @@ public static boolean mergeCitationGroups(XTextDocument doc, OOFrontend frontend for (JoinableGroupData joinableGroupData : joinableGroups) { - List cgs = joinableGroupData.group; + List groups = joinableGroupData.group; - List newCitations = (cgs.stream() + List newCitations = (groups.stream() .flatMap(group -> group.citationsInStorageOrder.stream()) .collect(Collectors.toList())); - CitationType citationType = cgs.get(0).citationType; - List> pageInfos = frontend.backend.combinePageInfos(cgs); + CitationType citationType = groups.get(0).citationType; + List> pageInfos = frontend.backend.combinePageInfos(groups); - frontend.removeCitationGroups(cgs, doc); + frontend.removeCitationGroups(groups, doc); XTextCursor textCursor = joinableGroupData.groupCursor; textCursor.setString(""); // Also remove the spaces between. @@ -206,8 +206,8 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup group, XTe // assume: currentGroupCursor.getEnd() == cursorBetween.getEnd() if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { - String msg = ("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end"); - throw new IllegalStateException(msg); + LOGGER.warn("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end"); + throw new IllegalStateException("MergeCitationGroups failed"); } /* @@ -238,8 +238,8 @@ private static boolean checkAddToGroup(ScanState state, CitationGroup group, XTe // These two should move in sync: if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { - String msg = ("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end (during expand)"); - throw new IllegalStateException(msg); + LOGGER.warn("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end (during expand)"); + throw new IllegalStateException("MergeCitationGroups failed"); } } @@ -278,8 +278,8 @@ private static void addToCurrentGroup(ScanState state, CitationGroup group, XTex state.currentGroupCursor.goRight((short) (currentRange.getString().length()), true); if (UnoTextRange.compareEnds(state.cursorBetween, state.currentGroupCursor) != 0) { - String msg = ("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end"); - throw new IllegalStateException(msg); + LOGGER.warn("MergeCitationGroups: cursorBetween.end != currentGroupCursor.end"); + throw new IllegalStateException("MergeCitationGroups failed"); } /* Store data about last entry in currentGroup */ @@ -296,14 +296,14 @@ private static List scan(XTextDocument doc, OOFrontend fronte WrappedTargetException { List result = new ArrayList<>(); - List cgs = frontend.getCitationGroupsSortedWithinPartitions(doc, false /* mapFootnotesToFootnoteMarks */); - if (cgs.isEmpty()) { + List groups = frontend.getCitationGroupsSortedWithinPartitions(doc, false /* mapFootnotesToFootnoteMarks */); + if (groups.isEmpty()) { return result; } ScanState state = new ScanState(); - for (CitationGroup group : cgs) { + for (CitationGroup group : groups) { XTextRange currentRange = (frontend.getMarkRange(doc, group) .orElseThrow(IllegalStateException::new)); diff --git a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java index 409969b213f..66630a6f8d0 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java +++ b/src/main/java/org/jabref/logic/openoffice/action/EditSeparate.java @@ -50,38 +50,38 @@ public static boolean separateCitations(XTextDocument doc, frontend.citationGroups.lookupCitations(databases); frontend.citationGroups.imposeLocalOrder(OOProcess.comparatorForMulticite(style)); - List cgs = frontend.citationGroups.getCitationGroupsUnordered(); + List groups = frontend.citationGroups.getCitationGroupsUnordered(); try { UnoScreenRefresh.lockControllers(doc); - for (CitationGroup group : cgs) { + for (CitationGroup group : groups) { XTextRange range1 = (frontend .getMarkRange(doc, group) .orElseThrow(IllegalStateException::new)); XTextCursor textCursor = range1.getText().createTextCursorByRange(range1); - List cits = group.citationsInStorageOrder; - if (cits.size() <= 1) { + List citations = group.citationsInStorageOrder; + if (citations.size() <= 1) { continue; } frontend.removeCitationGroup(group, doc); - // Now we own the content of cits + // Now we own the content of citations // Create a citation group for each citation. - final int last = cits.size() - 1; - for (int i = 0; i < cits.size(); i++) { + final int last = citations.size() - 1; + for (int i = 0; i < citations.size(); i++) { boolean insertSpaceAfter = (i != last); - Citation cit = cits.get(i); + Citation citation = citations.get(i); UpdateCitationMarkers.createAndFillCitationGroup(frontend, doc, - List.of(cit.citationKey), - List.of(cit.getPageInfo()), + List.of(citation.citationKey), + List.of(citation.getPageInfo()), group.citationType, - OOText.fromString(cit.citationKey), + OOText.fromString(citation.citationKey), textCursor, style, insertSpaceAfter); diff --git a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java index ba806426051..c38cd4fd4cc 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java +++ b/src/main/java/org/jabref/logic/openoffice/action/ExportCited.java @@ -52,8 +52,8 @@ public static GenerateDatabaseResult generateDatabase(XTextDocument doc, List unresolvedKeys = new ArrayList<>(); BibDatabase resultDatabase = new BibDatabase(); @@ -61,13 +61,13 @@ public static GenerateDatabaseResult generateDatabase(XTextDocument doc, List entriesToInsert = new ArrayList<>(); Set seen = new HashSet<>(); // Only add crossReference once. - for (CitedKey ck : cks.values()) { - if (ck.getLookupResult().isEmpty()) { - unresolvedKeys.add(ck.citationKey); + for (CitedKey citation : citationKeys.values()) { + if (citation.getLookupResult().isEmpty()) { + unresolvedKeys.add(citation.citationKey); continue; } else { - BibEntry entry = ck.getLookupResult().get().entry; - BibDatabase loopDatabase = ck.getLookupResult().get().database; + BibEntry entry = citation.getLookupResult().get().entry; + BibDatabase loopDatabase = citation.getLookupResult().get().database; // If entry found BibEntry clonedEntry = (BibEntry) entry.clone(); diff --git a/src/main/java/org/jabref/logic/openoffice/action/Update.java b/src/main/java/org/jabref/logic/openoffice/action/Update.java index ba840e88b70..80263833aec 100644 --- a/src/main/java/org/jabref/logic/openoffice/action/Update.java +++ b/src/main/java/org/jabref/logic/openoffice/action/Update.java @@ -21,6 +21,8 @@ */ public class Update { + static final boolean USE_LOCK_CONTROLLERS = true; + private Update() { /**/ } @@ -41,13 +43,11 @@ private static List updateDocument(XTextDocument doc, WrappedTargetException, com.sun.star.lang.IllegalArgumentException { - final boolean useLockControllers = true; - frontend.imposeGlobalOrder(doc, fcursor); OOProcess.produceCitationMarkers(frontend.citationGroups, databases, style); try { - if (useLockControllers) { + if (USE_LOCK_CONTROLLERS) { UnoScreenRefresh.lockControllers(doc); } @@ -63,7 +63,7 @@ private static List updateDocument(XTextDocument doc, return frontend.citationGroups.getUnresolvedKeys(); } finally { - if (useLockControllers && UnoScreenRefresh.hasControllersLocked(doc)) { + if (USE_LOCK_CONTROLLERS && UnoScreenRefresh.hasControllersLocked(doc)) { UnoScreenRefresh.unlockControllers(doc); } }